Compare commits

..

No commits in common. "dev" and "tci" have entirely different histories.
dev ... tci

228 changed files with 4054 additions and 21938 deletions

1
.gitignore vendored
View file

@ -1,3 +1,2 @@
/target /target
/apb/target /apb/target
/web/dist

10
.tci
View file

@ -1,19 +1,13 @@
#!/bin/bash #!/bin/bash
echo "building release binary" echo "building release binary"
cargo build --release --all-features -j 4 cargo build --release --all-features
echo "stopping service" echo "stopping service"
systemctl --user stop upub systemctl --user stop upub
echo "installing new binary" echo "installing new binary"
cp ./target/release/upub /opt/bin/upub cp ./target/release/upub /opt/bin/upub
echo "migrating database" echo "migrating database"
/opt/bin/upub -c /etc/upub/config.toml migrate /opt/bin/upub --db "sqlite:///srv/tci/upub.db" --domain https://feditest.alemi.dev migrate
echo "restarting service" echo "restarting service"
systemctl --user start upub systemctl --user start upub
echo "rebuilding frontend"
cd web
CARGO_BUILD_JOBS=4 /opt/bin/trunk build --release --public-url 'https://dev.upub.social/web'
echo "deploying frontend"
rm /srv/http/upub/dev/web/*
mv ./dist/* /srv/http/upub/dev/web/
echo "done" echo "done"

5521
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,20 +1,9 @@
[workspace] [workspace]
members = [ members = ["apb"]
"apb",
"upub/core",
"upub/cli",
"upub/migrations",
"upub/routes",
"upub/worker",
"web",
"utils/httpsign",
"utils/mdhtml",
"utils/uriproxy",
]
[package] [package]
name = "upub-bin" name = "upub"
version = "0.3.0" version = "0.1.0"
edition = "2021" edition = "2021"
authors = [ "alemi <me@alemi.dev>" ] authors = [ "alemi <me@alemi.dev>" ]
description = "Traits and types to handle ActivityPub objects" description = "Traits and types to handle ActivityPub objects"
@ -23,30 +12,38 @@ keywords = ["activitypub", "activitystreams", "json"]
repository = "https://git.alemi.dev/upub.git" repository = "https://git.alemi.dev/upub.git"
readme = "README.md" readme = "README.md"
[[bin]] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
name = "upub"
path = "main.rs"
[dependencies] [dependencies]
toml = "0.8" thiserror = "1"
rand = "0.8"
sha256 = "1.5"
openssl = "0.10" # TODO handle pubkeys with a smaller crate
base64 = "0.22"
chrono = { version = "0.4", features = ["serde"] }
uuid = { version = "1.8", features = ["v4"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
jrd = "0.1"
tracing = "0.1" tracing = "0.1"
tracing-subscriber = "0.3" tracing-subscriber = "0.3"
clap = { version = "4.5", features = ["derive"] } clap = { version = "4.5", features = ["derive"] }
signal-hook = "0.3" tokio = { version = "1.35", features = ["full"] } # TODO slim this down
signal-hook-tokio = { version = "0.3", features = ["futures-v0_3"] } sea-orm = { version = "0.12", features = ["macros", "sqlx-sqlite", "runtime-tokio-rustls"] }
tokio = { version = "1.40", features = ["full"] } # TODO slim this down reqwest = { version = "0.12", features = ["json"] }
sea-orm = { version = "1.0", features = ["sqlx-sqlite", "sqlx-postgres", "runtime-tokio-rustls"] } axum = "0.7"
futures = "0.3" apb = { path = "apb", features = ["unstructured", "fetch", "orm"] }
# nodeinfo = "0.0.2" # the version on crates.io doesn't re-export necessary types to build the struct!!!
upub = { path = "upub/core" } nodeinfo = { git = "https://codeberg.org/thefederationinfo/nodeinfo-rs", rev = "e865094804" }
upub-cli = { path = "upub/cli", optional = true } http-signature-normalization = "0.7.0"
upub-migrations = { path = "upub/migrations", optional = true } # migrations
upub-routes = { path = "upub/routes", optional = true } sea-orm-migration = { version = "0.12", optional = true }
upub-worker = { path = "upub/worker", optional = true } # mastodon
mastodon-async-entities = { version = "1.1.0", optional = true }
time = { version = "0.3", features = ["serde"], optional = true }
[features] [features]
default = ["serve", "migrate", "cli", "worker"] default = ["faker", "migrations", "mastodon"]
serve = ["dep:upub-routes"] faker = []
migrate = ["dep:upub-migrations"] migrations = ["dep:sea-orm-migration"]
cli = ["dep:upub-cli"] mastodon = ["dep:mastodon-async-entities", "dep:time"]
worker = ["dep:upub-worker"]

675
LICENSE
View file

@ -1,675 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<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 General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

102
README.md
View file

@ -1,73 +1,13 @@
# μpub # μpub
> [micro social network, federated](https://join.upub.social) > micro social network, federated
![screenshot of upub simple frontend](https://cdn.alemi.dev/proj/upub/fe/20240704.png) μpub aims to be a fast, lightweight and secure [ActivityPub](https://www.w3.org/TR/activitypub/) server
μpub aims to be a private, lightweight, modular and **secure** [ActivityPub](https://www.w3.org/TR/activitypub/) server μpub is currently being developed and can do some basic things, like posting notes, follows and likes
* follow development [in the dedicated matrix room](https://matrix.to/#/#upub:alemi.dev) all interactions must happen with ActivityPub's client-server methods (basically POST your activities to your outbox)
μpub is usable as a very simple ActivityPub project: it has a home and server timeline, it allows to browse threads, star notes and leave replies, it renders remote media of any kind and can be used to browse and follow remote users a test instance is _usually_ available at [feditest.alemi.dev](https://feditest.alemi.dev)
all interactions happen with ActivityPub's client-server methods (basically POST your activities to your outbox), with [appropriate extensions](https://ns.alemi.dev/as): **μpub doesn't want to invent another API**!
development is still active, so expect more stuff to come! since most fediverse software uses Mastodon's API, μpub plans to implement it as an optional feature, becoming eventually compatible with most existing frontends and mobile applications, but focus right now is on producing something specific to μpub needs
a test instance is available at [dev.upub.social](https://dev.upub.social)
## about the database schema
im going to be very real i tried to do migrations but its getting super messy so until further notice assume db to be volatile. next change may be a migration (easy!) or a whole db rebuild (aaaaaaaaaa...), so if you're not comfortable with either manually exporting/importing or dropping and starting from scratch, **you really shouldn't put upub in prod yet**!
## about security
most activitypub implementations don't really validate fetches: knowing an activity/object id will allow anyone to resolve it on most fedi software. this is of course unacceptable: "security through obscurity" just doesn't work
μpub correctly and rigorously implements and enforces access control on each object based on its addressing
most instances will have "authorized fetch" which kind of makes the issue less bad, but anyone can host an actor, have any server download their pubkey and then start fetching
μpub may be considered to have "authorized fetch" permanently on, except it depends on each post:
* all posts marked public (meaning, addressed to "https://www.w3.org/ns/activitystreams#Public"), will be fetchable without any authorization
* all posts not public will require explicit addressing and authentication: for example if post A is addressed to example.net/actor
* anonymous fetchers will receive 404 on GET /posts/A
* local users must authenticate and will be given said post only if it's addressed to them
* remote servers will be given access to all posts from any of their users once they have authenticated themselves (with http signing)
note that followers get expanded: addressing to example.net/actor/followers will address to anyone following actor that the server knows of, at that time
## media caching
μpub doesn't download remote media to both minimize local resources requirement and avoid storing media that remotes want gone. to prevent leaking local user ip addresses, all media links are cloaked and proxied.
while this just works for small instances, larger servers should set up aggressive caching on `/proxy/...` path
for example, on `nginx`:
```nginx
proxy_cache_path /tmp/upub/cache levels=1:2 keys_zone=upub_cache:100m max_size=50g inactive=168h use_temp_path=off;
server {
location /proxy/ {
# use our configured cache
slice 1m;
proxy_set_header Range $slice_range;
chunked_transfer_encoding on;
proxy_ignore_client_abort on;
proxy_buffering on;
proxy_cache upub_cache;
proxy_cache_key $host$uri$is_args$args$slice_range;
proxy_cache_valid 200 206 301 304 168h;
proxy_cache_lock on;
proxy_pass http://127.0.0.1/;
}
}
```
## contributing
all help is extremely welcome! development mostly happens on [moonlit.technology](https://moonlit.technology/alemi/upub.git), but there's a [github mirror](https://github.com/alemidev/upub) available too
if you prefer a forge-less development you can browse the repo on [my cgit](https://git.alemi.dev/upub.git), and send me patches on any contact listed on [my site](https://alemi.dev/about/contacts)
don't hesitate to get in touch, i'd be thrilled to showcase the project to you!
## progress ## progress
@ -78,27 +18,11 @@ don't hesitate to get in touch, i'd be thrilled to showcase the project to you!
- [x] process barebones inbox - [x] process barebones inbox
- [x] process barebones outbox - [x] process barebones outbox
- [x] http signatures - [x] http signatures
- [x] privacy, targets, scopes - [ ] privacy, targets, scopes
- [x] simple web client - [ ] client api (mastodon/pleroma)
- [x] announce (boosts) - [ ] hashtags, discovery
- [x] threads - [ ] a custom frontend maybe?
- [x] remote media - [ ] more optimized database schema
- [x] editing via api
- [x] advanced composer ## what about the name?
- [x] api for fetching μpub, sometimes stylyzed `upub`, is pronounced `mu-pub` (the `μ` stands for [micro](https://en.wikipedia.org/wiki/International_System_of_Units#Prefixes))
- [x] like, share, reply via frontend
- [x] backend config
- [x] frontend config
- [x] optimize `addressing` database schema
- [x] mentions, notifications
- [x] hashtags
- [x] remote media proxy
- [x] user fields
- [ ] better editing via web frontend
- [ ] upload media
- [ ] public vs unlisted for discovery
- [ ] mastodon-like search bar
- [ ] polls
- [ ] lists
- [ ] full mastodon api
- [ ] get rid of internal ids from code

View file

@ -1,12 +1,12 @@
[package] [package]
name = "apb" name = "apb"
version = "0.2.2" version = "0.1.1"
edition = "2021" edition = "2021"
authors = [ "alemi <me@alemi.dev>" ] authors = [ "alemi <me@alemi.dev>" ]
description = "Traits and types to handle ActivityPub objects" description = "Traits and types to handle ActivityPub objects"
license = "MIT" license = "MIT"
keywords = ["activitypub", "activitystreams", "json"] keywords = ["activitypub", "activitystreams", "json"]
repository = "https://moonlit.technology/alemi/upub" repository = "https://git.alemi.dev/upub.git"
readme = "README.md" readme = "README.md"
[lib] [lib]
@ -18,27 +18,14 @@ chrono = { version = "0.4", features = ["serde"] }
thiserror = "1" thiserror = "1"
paste = "1.0" paste = "1.0"
tracing = "0.1" tracing = "0.1"
async-trait = "0.1"
serde_json = { version = "1", optional = true } serde_json = { version = "1", optional = true }
sea-orm = { version = "1.0", optional = true, default-features = false } sea-orm = { version = "0.12", optional = true }
reqwest = { version = "0.12", features = ["json"], optional = true } reqwest = { version = "0.12", features = ["json"], optional = true }
[features] [features]
default = ["activitypub-miscellaneous-terms", "send", "shortcuts"] default = []
# extensions
activitypub-miscellaneous-terms = [] # https://swicg.github.io/miscellany/
activitypub-counters = [] # https://ns.alemi.dev/as/counters/#
activitypub-fe = [] # https://ns.alemi.dev/as/fe/#
ostatus = [] # https://ostatus.org# , but it redirects and 403??? just need this for conversation
toot = [] # http://joinmastodon.org/ns# , mastodon is weird tho??
litepub = [] # incomplete, https://litepub.social/
did-core = [] # incomplete, may be cool to support all of this: https://www.w3.org/TR/did-core/
# full jsonld utilities
jsonld = []
# builtin utils
send = []
orm = ["dep:sea-orm"] orm = ["dep:sea-orm"]
fetch = ["dep:reqwest"] fetch = ["dep:reqwest"]
shortcuts = []
# providers
unstructured = ["dep:serde_json"] unstructured = ["dep:serde_json"]
#TODO eventually also make a structured base? # TODO eventually also make a structured base?

View file

@ -1,5 +0,0 @@
#[derive(Debug, thiserror::Error)]
#[error("missing field '{0}'")]
pub struct FieldErr(pub &'static str);
pub type Field<T> = Result<T, FieldErr>;

View file

@ -1,50 +0,0 @@
use crate::Object;
pub trait LD {
fn ld_context(self) -> Self;
}
impl LD for serde_json::Value {
fn ld_context(mut self) -> Self {
let o_type = self.object_type();
if let Some(obj) = self.as_object_mut() {
let mut ctx = serde_json::Map::new();
ctx.insert("sensitive".to_string(), serde_json::Value::String("as:sensitive".into()));
ctx.insert("quoteUrl".to_string(), serde_json::Value::String("as:quoteUrl".into()));
match o_type {
Ok(crate::ObjectType::Actor(_)) => {
ctx.insert("counters".to_string(), serde_json::Value::String("https://ns.alemi.dev/as/counters/#".into()));
ctx.insert("followingCount".to_string(), serde_json::Value::String("counters:followingCount".into()));
ctx.insert("followersCount".to_string(), serde_json::Value::String("counters:followersCount".into()));
ctx.insert("statusesCount".to_string(), serde_json::Value::String("counters:statusesCount".into()));
ctx.insert("fe".to_string(), serde_json::Value::String("https://ns.alemi.dev/as/fe/#".into()));
ctx.insert("followingMe".to_string(), serde_json::Value::String("fe:followingMe".into()));
ctx.insert("followedByMe".to_string(), serde_json::Value::String("fe:followedByMe".into()));
},
Ok(
crate::ObjectType::Note
| crate::ObjectType::Article
| crate::ObjectType::Event
| crate::ObjectType::Document(crate::DocumentType::Page) // TODO why Document lemmyyyyyy
) => {
ctx.insert("fe".to_string(), serde_json::Value::String("https://ns.alemi.dev/as/fe/#".into()));
ctx.insert("likedByMe".to_string(), serde_json::Value::String("fe:likedByMe".into()));
ctx.insert("ostatus".to_string(), serde_json::Value::String("http://ostatus.org#".into()));
ctx.insert("conversation".to_string(), serde_json::Value::String("ostatus:conversation".into()));
},
_ => {},
}
obj.insert(
"@context".to_string(),
serde_json::Value::Array(vec![
serde_json::Value::String("https://www.w3.org/ns/activitystreams".into()),
serde_json::Value::String("https://w3id.org/security/v1".into()),
serde_json::Value::Object(ctx),
]),
);
} else {
tracing::warn!("cannot add @context to json value different than object");
}
self
}
}

View file

@ -1,32 +1,32 @@
// TODO technically this is not part of ActivityStreams // TODO technically this is not part of ActivityStreams
pub trait PublicKey : super::Base { pub trait PublicKey : super::Base {
fn owner(&self) -> crate::Field<String> { Err(crate::FieldErr("owner")) } fn owner(&self) -> Option<&str> { None }
fn public_key_pem(&self) -> String; fn public_key_pem(&self) -> &str;
} }
pub trait PublicKeyMut : super::BaseMut { pub trait PublicKeyMut : super::BaseMut {
fn set_owner(self, val: Option<String>) -> Self; fn set_owner(self, val: Option<&str>) -> Self;
fn set_public_key_pem(self, val: String) -> Self; fn set_public_key_pem(self, val: &str) -> Self;
} }
#[cfg(feature = "unstructured")] #[cfg(feature = "unstructured")]
impl PublicKey for serde_json::Value { impl PublicKey for serde_json::Value {
crate::getter! { owner -> String } crate::getter! { owner -> &str }
fn public_key_pem(&self) -> String { fn public_key_pem(&self) -> &str {
self.get("publicKeyPem").and_then(|x| x.as_str()).unwrap_or_default().to_string() self.get("publicKeyPem").unwrap().as_str().unwrap()
} }
} }
#[cfg(feature = "unstructured")] #[cfg(feature = "unstructured")]
impl PublicKeyMut for serde_json::Value { impl PublicKeyMut for serde_json::Value {
crate::setter! { owner -> String } crate::setter! { owner -> &str }
fn set_public_key_pem(mut self, val: String) -> Self { fn set_public_key_pem(mut self, val: &str) -> Self {
self.as_object_mut().unwrap().insert( self.as_object_mut().unwrap().insert(
"publicKeyPem".to_string(), "publicKeyPem".to_string(),
serde_json::Value::String(val), serde_json::Value::String(val.to_string()),
); );
self self
} }

View file

@ -88,33 +88,17 @@
mod macros; mod macros;
pub(crate) use macros::strenum; pub(crate) use macros::{strenum, getter, setter};
#[cfg(feature = "unstructured")]
pub(crate) use macros::{getter, setter};
mod node; mod node;
pub use node::Node; pub use node::Node;
pub mod server;
pub mod target; pub mod target;
mod key; mod key;
pub use key::{PublicKey, PublicKeyMut}; pub use key::{PublicKey, PublicKeyMut};
pub mod field;
pub use field::{Field, FieldErr};
#[cfg(feature = "shortcuts")]
pub mod shortcuts;
#[cfg(feature = "shortcuts")]
pub use shortcuts::Shortcuts;
#[cfg(feature = "jsonld")]
mod jsonld;
#[cfg(feature = "jsonld")]
pub use jsonld::LD;
mod types; mod types;
pub use types::{ pub use types::{
base::{Base, BaseMut, BaseType}, base::{Base, BaseMut, BaseType},
@ -129,20 +113,15 @@ pub use types::{
offer::{Offer, OfferMut, OfferType}, offer::{Offer, OfferMut, OfferType},
reject::{Reject, RejectMut, RejectType}, reject::{Reject, RejectMut, RejectType},
}, },
actor::{Actor, ActorMut, ActorType, Endpoints, EndpointsMut}, actor::{Actor, ActorMut, ActorType},
collection::{ collection::{
Collection, CollectionMut, CollectionType, Collection, CollectionMut, CollectionType,
page::{CollectionPage, CollectionPageMut} page::{CollectionPage, CollectionPageMut}
}, },
document::{Document, DocumentMut, DocumentType}, document::{Document, DocumentMut, DocumentType},
place::{Place, PlaceMut}, place::{Place, PlaceMut},
profile::Profile, // profile::Profile,
relationship::{Relationship, RelationshipMut}, relationship::{Relationship, RelationshipMut},
tombstone::{Tombstone, TombstoneMut}, tombstone::{Tombstone, TombstoneMut},
}, },
}; };
#[cfg(feature = "unstructured")]
pub fn new() -> serde_json::Value {
serde_json::Value::Object(serde_json::Map::default())
}

View file

@ -1,15 +1,3 @@
#[cfg(feature = "send")]
pub trait MaybeSend : Send {}
#[cfg(feature = "send")]
impl<T : Send> MaybeSend for T {}
#[cfg(not(feature = "send"))]
pub trait MaybeSend {}
#[cfg(not(feature = "send"))]
impl<T> MaybeSend for T {}
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
#[error("invalid type value")] #[error("invalid type value")]
pub struct TypeValueError; pub struct TypeValueError;
@ -38,12 +26,6 @@ macro_rules! strenum {
$($deep($inner),)* $($deep($inner),)*
} }
impl std::fmt::Display for $enum_name {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.as_ref())
}
}
impl AsRef<str> for $enum_name { impl AsRef<str> for $enum_name {
fn as_ref(&self) -> &str { fn as_ref(&self) -> &str {
match self { match self {
@ -97,7 +79,7 @@ macro_rules! strenum {
} }
fn column_type() -> sea_orm::sea_query::ColumnType { fn column_type() -> sea_orm::sea_query::ColumnType {
sea_orm::sea_query::ColumnType::String(sea_orm::sea_query::table::StringLen::N(24)) sea_orm::sea_query::ColumnType::String(Some(24))
} }
} }
@ -114,110 +96,108 @@ macro_rules! strenum {
pub(crate) use strenum; pub(crate) use strenum;
#[cfg(feature = "unstructured")]
macro_rules! getter { macro_rules! getter {
($name:ident -> type $t:ty) => { ($name:ident -> type $t:ty) => {
paste::paste! { fn $name(&self) -> Option<$t> {
fn [< $name:snake >] (&self) -> $crate::Field<$t> { self.get("type")?.as_str()?.try_into().ok()
self.get("type")
.and_then(|x| x.as_str())
.and_then(|x| x.try_into().ok())
.ok_or($crate::FieldErr("type"))
}
} }
}; };
($name:ident -> bool) => { ($name:ident -> bool) => {
paste::paste! { fn $name(&self) -> Option<bool> {
fn [< $name:snake >](&self) -> $crate::Field<bool> { self.get(stringify!($name))?.as_bool()
self.get(stringify!($name))
.and_then(|x| x.as_bool())
.ok_or($crate::FieldErr(stringify!($name)))
}
} }
}; };
($name:ident -> String) => { ($name:ident -> &str) => {
paste::paste! { fn $name(&self) -> Option<&str> {
fn [< $name:snake >](&self) -> $crate::Field<String> { self.get(stringify!($name))?.as_str()
self.get(stringify!($name))
.and_then(|x| x.as_str())
.map(|x| x.to_string())
.ok_or($crate::FieldErr(stringify!($name)))
} }
};
($name:ident::$rename:ident -> &str) => {
fn $name(&self) -> Option<&str> {
self.get(stringify!($rename))?.as_str()
} }
}; };
($name:ident -> f64) => { ($name:ident -> f64) => {
paste::paste! { fn $name(&self) -> Option<f64> {
fn [< $name:snake >](&self) -> $crate::Field<f64> { self.get(stringify!($name))?.as_f64()
self.get(stringify!($name))
.and_then(|x| x.as_f64())
.ok_or($crate::FieldErr(stringify!($name)))
} }
};
($name:ident::$rename:ident -> f64) => {
fn $name(&self) -> Option<f64> {
self.get(stringify!($rename))?.as_f64()
} }
}; };
($name:ident -> u64) => { ($name:ident -> u64) => {
paste::paste! { fn $name(&self) -> Option<u64> {
fn [< $name:snake >](&self) -> $crate::Field<u64> { self.get(stringify!($name))?.as_u64()
self.get(stringify!($name))
.and_then(|x| x.as_u64())
.ok_or($crate::FieldErr(stringify!($name)))
}
} }
}; };
($name:ident -> i64) => { ($name:ident::$rename:ident -> u64) => {
paste::paste! { fn $name(&self) -> Option<u64> {
fn [< $name:snake >](&self) -> $crate::Field<i64> { self.get(stringify!($rename))?.as_u64()
self.get(stringify!($name))
.and_then(|x| x.as_i64())
.ok_or($crate::FieldErr(stringify!($name)))
}
} }
}; };
($name:ident -> chrono::DateTime<chrono::Utc>) => { ($name:ident -> chrono::DateTime<chrono::Utc>) => {
paste::paste! { fn $name(&self) -> Option<chrono::DateTime<chrono::Utc>> {
fn [< $name:snake >](&self) -> $crate::Field<chrono::DateTime<chrono::Utc>> { Some(
Ok(
chrono::DateTime::parse_from_rfc3339( chrono::DateTime::parse_from_rfc3339(
self self
.get(stringify!($name)) .get(stringify!($name))?
.and_then(|x| x.as_str()) .as_str()?
.ok_or($crate::FieldErr(stringify!($name)))?
) )
.map_err(|e| { .ok()?
tracing::warn!("invalid time string ({e}), ignoring");
$crate::FieldErr(stringify!($name))
})?
.with_timezone(&chrono::Utc) .with_timezone(&chrono::Utc)
) )
} }
};
($name:ident::$rename:ident -> chrono::DateTime<chrono::Utc>) => {
fn $name(&self) -> Option<chrono::DateTime<chrono::Utc>> {
Some(
chrono::DateTime::parse_from_rfc3339(
self
.get(stringify!($rename))?
.as_str()?
)
.ok()?
.with_timezone(&chrono::Utc)
)
} }
}; };
($name:ident -> node $t:ty) => { ($name:ident -> node $t:ty) => {
paste::paste! { fn $name(&self) -> $crate::Node<$t> {
fn [< $name:snake >](&self) -> $crate::Node<$t> {
match self.get(stringify!($name)) { match self.get(stringify!($name)) {
Some(x) => $crate::Node::from(x.clone()), Some(x) => $crate::Node::from(x.clone()),
None => $crate::Node::Empty, None => $crate::Node::Empty,
} }
} }
};
($name:ident::$rename:ident -> node $t:ty) => {
fn $name(&self) -> $crate::Node<$t> {
match self.get(stringify!($rename)) {
Some(x) => $crate::Node::from(x.clone()),
None => $crate::Node::Empty,
}
} }
}; };
} }
#[cfg(feature = "unstructured")]
pub(crate) use getter; pub(crate) use getter;
#[cfg(feature = "unstructured")]
macro_rules! setter { macro_rules! setter {
($name:ident -> bool) => { ($name:ident -> bool) => {
paste::item! { paste::item! {
fn [< set_$name:snake >](mut self, val: Option<bool>) -> Self { fn [< set_$name >](mut self, val: Option<bool>) -> Self {
$crate::macros::set_maybe_value( $crate::macros::set_maybe_value(
&mut self, stringify!($name), val.map(|x| serde_json::Value::Bool(x)) &mut self, stringify!($name), val.map(|x| serde_json::Value::Bool(x))
); );
@ -226,11 +206,22 @@ macro_rules! setter {
} }
}; };
($name:ident -> String) => { ($name:ident -> &str) => {
paste::item! { paste::item! {
fn [< set_$name:snake >](mut self, val: Option<String>) -> Self { fn [< set_$name >](mut self, val: Option<&str>) -> Self {
$crate::macros::set_maybe_value( $crate::macros::set_maybe_value(
&mut self, stringify!($name), val.map(|x| serde_json::Value::String(x)) &mut self, stringify!($name), val.map(|x| serde_json::Value::String(x.to_string()))
);
self
}
}
};
($name:ident::$rename:ident -> &str) => {
paste::item! {
fn [< set_$name >](mut self, val: Option<&str>) -> Self {
$crate::macros::set_maybe_value(
&mut self, stringify!($rename), val.map(|x| serde_json::Value::String(x.to_string()))
); );
self self
} }
@ -239,7 +230,7 @@ macro_rules! setter {
($name:ident -> u64) => { ($name:ident -> u64) => {
paste::item! { paste::item! {
fn [< set_$name:snake >](mut self, val: Option<u64>) -> Self { fn [< set_$name >](mut self, val: Option<u64>) -> Self {
$crate::macros::set_maybe_value( $crate::macros::set_maybe_value(
&mut self, stringify!($name), val.map(|x| serde_json::Value::Number(serde_json::Number::from(x))) &mut self, stringify!($name), val.map(|x| serde_json::Value::Number(serde_json::Number::from(x)))
); );
@ -248,11 +239,11 @@ macro_rules! setter {
} }
}; };
($name:ident -> i64) => { ($name:ident::$rename:ident -> u64) => {
paste::item! { paste::item! {
fn [< set_$name:snake >](mut self, val: Option<i64>) -> Self { fn [< set_$name >](mut self, val: Option<u64>) -> Self {
$crate::macros::set_maybe_value( $crate::macros::set_maybe_value(
&mut self, stringify!($name), val.map(|x| serde_json::Value::Number(serde_json::Number::from(x))) &mut self, stringify!($rename), val.map(|x| serde_json::Value::Number(serde_json::Number::from(x)))
); );
self self
} }
@ -261,7 +252,7 @@ macro_rules! setter {
($name:ident -> chrono::DateTime<chrono::Utc>) => { ($name:ident -> chrono::DateTime<chrono::Utc>) => {
paste::item! { paste::item! {
fn [< set_$name:snake >](mut self, val: Option<chrono::DateTime<chrono::Utc>>) -> Self { fn [< set_$name >](mut self, val: Option<chrono::DateTime<chrono::Utc>>) -> Self {
$crate::macros::set_maybe_value( $crate::macros::set_maybe_value(
&mut self, stringify!($name), val.map(|x| serde_json::Value::String(x.to_rfc3339())) &mut self, stringify!($name), val.map(|x| serde_json::Value::String(x.to_rfc3339()))
); );
@ -270,9 +261,20 @@ macro_rules! setter {
} }
}; };
($name:ident::$rename:ident -> chrono::DateTime<chrono::Utc>) => {
paste::item! {
fn [< set_$name >](mut self, val: Option<chrono::DateTime<chrono::Utc>>) -> Self {
$crate::macros::set_maybe_value(
&mut self, stringify!($rename), val.map(|x| serde_json::Value::String(x.to_rfc3339()))
);
self
}
}
};
($name:ident -> node $t:ty ) => { ($name:ident -> node $t:ty ) => {
paste::item! { paste::item! {
fn [< set_$name:snake >](mut self, val: $crate::Node<$t>) -> Self { fn [< set_$name >](mut self, val: $crate::Node<$t>) -> Self {
$crate::macros::set_maybe_node( $crate::macros::set_maybe_node(
&mut self, stringify!($name), val &mut self, stringify!($name), val
); );
@ -283,7 +285,7 @@ macro_rules! setter {
($name:ident::$rename:ident -> node $t:ty ) => { ($name:ident::$rename:ident -> node $t:ty ) => {
paste::item! { paste::item! {
fn [< set_$name:snake >](mut self, val: $crate::Node<$t>) -> Self { fn [< set_$name >](mut self, val: $crate::Node<$t>) -> Self {
$crate::macros::set_maybe_node( $crate::macros::set_maybe_node(
&mut self, stringify!($rename), val &mut self, stringify!($rename), val
); );
@ -294,7 +296,7 @@ macro_rules! setter {
($name:ident -> type $t:ty ) => { ($name:ident -> type $t:ty ) => {
paste::item! { paste::item! {
fn [< set_$name:snake >](mut self, val: Option<$t>) -> Self { fn [< set_$name >](mut self, val: Option<$t>) -> Self {
$crate::macros::set_maybe_value( $crate::macros::set_maybe_value(
&mut self, "type", val.map(|x| serde_json::Value::String(x.as_ref().to_string())) &mut self, "type", val.map(|x| serde_json::Value::String(x.as_ref().to_string()))
); );
@ -304,15 +306,31 @@ macro_rules! setter {
}; };
} }
#[cfg(feature = "unstructured")]
pub(crate) use setter; pub(crate) use setter;
#[cfg(feature = "unstructured")] #[cfg(feature = "unstructured")]
pub fn set_maybe_node(obj: &mut serde_json::Value, key: &str, node: crate::Node<serde_json::Value>) { pub fn set_maybe_node(obj: &mut serde_json::Value, key: &str, node: crate::Node<serde_json::Value>) {
if node.is_empty() { match node {
set_maybe_value(obj, key, None) crate::Node::Object(x) => {
} else { set_maybe_value(
set_maybe_value(obj, key, Some(node.into_value())) obj, key, Some(*x),
);
},
crate::Node::Link(l) => {
set_maybe_value(
obj, key, Some(serde_json::Value::String(l.href().to_string())),
);
},
crate::Node::Array(_) => {
set_maybe_value(
obj, key, Some(serde_json::Value::Array(node.into_iter().collect())),
);
},
crate::Node::Empty => {
set_maybe_value(
obj, key, None,
);
},
} }
} }
@ -327,3 +345,67 @@ pub fn set_maybe_value(obj: &mut serde_json::Value, key: &str, value: Option<ser
tracing::error!("error setting '{key}' on json Value: not an object"); tracing::error!("error setting '{key}' on json Value: not an object");
} }
} }
#[cfg(feature = "unstructured")]
pub(crate) trait InsertValue {
fn insert_node(&mut self, k: &str, v: crate::Node<serde_json::Value>);
fn insert_str(&mut self, k: &str, v: Option<&str>);
fn insert_float(&mut self, k: &str, f: Option<f64>);
fn insert_timestr(&mut self, k: &str, t: Option<chrono::DateTime<chrono::Utc>>);
}
#[cfg(feature = "unstructured")]
impl InsertValue for serde_json::Map<String, serde_json::Value> {
fn insert_node(&mut self, k: &str, node: crate::Node<serde_json::Value>) {
match node {
crate::Node::Object(x) => {
self.insert(
k.to_string(),
*x,
);
},
crate::Node::Array(ref _arr) => {
self.insert(
k.to_string(),
serde_json::Value::Array(node.into_iter().collect()),
);
},
crate::Node::Link(l) => {
self.insert(
k.to_string(),
serde_json::Value::String(l.href().to_string()),
);
},
crate::Node::Empty => {},
};
}
fn insert_str(&mut self, k: &str, v: Option<&str>) {
if let Some(v) = v {
self.insert(
k.to_string(),
serde_json::Value::String(v.to_string()),
);
}
}
fn insert_float(&mut self, k: &str, v: Option<f64>) {
if let Some(v) = v {
if let Some(n) = serde_json::Number::from_f64(v) {
self.insert(
k.to_string(),
serde_json::Value::Number(n),
);
}
}
}
fn insert_timestr(&mut self, k: &str, t: Option<chrono::DateTime<chrono::Utc>>) {
if let Some(published) = t {
self.insert(
k.to_string(),
serde_json::Value::String(published.to_rfc3339()),
);
}
}
}

View file

@ -1,37 +1,12 @@
/// ActivityPub object node, representing either nothing, something, a link to something or /// ActivityPub object node, representing either nothing, something, a link to something or
/// multiple things /// multiple things
pub enum Node<T : super::Base> { pub enum Node<T : super::Base> {
/// this document node holds multiple objects Array(Vec<T>), // TODO would be cool to make it Box<[T]> so that Node is just a ptr
Array(std::collections::VecDeque<Node<T>>), // TODO would be cool to make it Box<[T]> so that Node is just a ptr
/// this document node holds one object
Object(Box<T>), Object(Box<T>),
/// this document node holds a reference to an object Link(Box<dyn super::Link>),
Link(Box<dyn crate::Link + Sync + Send>), // TODO feature flag to toggle these maybe?
/// this document node is not present
Empty, Empty,
} }
impl<T: super::Base + std::fmt::Debug> std::fmt::Debug for Node<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if f.alternate() {
match self {
Self::Array(x) => write!(f, "Node(array: {x:#?})"),
Self::Link(x) => write!(f, "Node(link: {})", x.href().unwrap_or_default()),
Self::Object(x) => write!(f, "Node(object: {x:#?})"),
Self::Empty => write!(f, "Node(empty)"),
}
} else {
match self {
Self::Array(x) => write!(f, "Node(array: {x:?})"),
Self::Link(x) => write!(f, "Node(link: {})", x.href().unwrap_or_default()),
Self::Object(x) => write!(f, "Node(object: {x:?})"),
Self::Empty => write!(f, "Node(empty)"),
}
}
}
}
// TODO convert in a from_residual (iirc?) so that in rust nightly we can do ?
impl<T : super::Base> From<Option<T>> for Node<T> { impl<T : super::Base> From<Option<T>> for Node<T> {
fn from(value: Option<T>) -> Self { fn from(value: Option<T>) -> Self {
match value { match value {
@ -41,44 +16,37 @@ impl<T : super::Base> From<Option<T>> for Node<T> {
} }
} }
impl<T : super::Base + Clone> Iterator for Node<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
let x = match self {
Self::Empty => return None,
Self::Link(_) => return None,
Self::Array(arr) => return arr.pop(), // TODO weird that we iter in reverse
Self::Object(x) => *x.clone(), // TODO needed because next() on object can't get value without owning
};
*self = Self::Empty;
Some(x)
}
}
impl<T : super::Base> Node<T> { impl<T : super::Base> Node<T> {
/// return reference to embedded object (or first if many are present) /// return reference to embedded object (or last if many are present)
#[deprecated = "use .inner() instead"]
pub fn get(&self) -> Option<&T> { pub fn get(&self) -> Option<&T> {
match self { match self {
Node::Empty | Node::Link(_) => None, Node::Empty | Node::Link(_) => None,
Node::Object(x) => Some(x), Node::Object(x) => Some(x),
Node::Array(v) => v.iter().filter_map(|x| x.get()).next(), Node::Array(v) => v.last(), // TODO so it's coherent with next(), still weird tho!
} }
} }
/// return embedded object (or first if many are present) /// consume node and extract embedded object (or last if many are present)
#[deprecated = "use .into_inner() instead"]
pub fn extract(self) -> Option<T> { pub fn extract(self) -> Option<T> {
match self { match self {
Node::Empty | Node::Link(_) => None, Node::Empty | Node::Link(_) => None,
Node::Object(x) => Some(*x), Node::Object(x) => Some(*x),
Node::Array(mut v) => v.pop_front()?.extract(), Node::Array(mut v) => v.pop(), // TODO so it's coherent with next(), still weird tho!
}
}
/// return reference to embedded object (or first if many are present)
pub fn inner(&self) -> crate::Field<&T> {
match self {
Node::Empty => Err(crate::FieldErr("node is empty")),
Node::Link(_) => Err(crate::FieldErr("node has not been dereferenced")),
Node::Object(x) => Ok(x),
Node::Array(v) => v.iter().next().ok_or(crate::FieldErr("node contains no items"))?.inner(),
}
}
/// return embedded object (or first if many are present)
pub fn into_inner(self) -> crate::Field<T> {
match self {
Node::Empty => Err(crate::FieldErr("node is empty")),
Node::Link(_) => Err(crate::FieldErr("node has not been dereferenced")),
Node::Object(x) => Ok(*x),
Node::Array(v) => v.into_iter().next().ok_or(crate::FieldErr("node contains no items"))?.into_inner(),
} }
} }
@ -113,50 +81,17 @@ impl<T : super::Base> Node<T> {
} }
/// returns id of object: url for link, id for object, None if empty or array /// returns id of object: url for link, id for object, None if empty or array
pub fn id(&self) -> crate::Field<String> { pub fn id(&self) -> Option<String> {
match self { match self {
Node::Empty => Err(crate::FieldErr("id")), Node::Empty | Node::Array(_) => None,
Node::Link(uri) => uri.href(), Node::Link(uri) => Some(uri.href().to_string()),
Node::Object(obj) => obj.id(), Node::Object(obj) => obj.id().map(|x| x.to_string()),
Node::Array(arr) => arr.front().map(|x| x.id()).ok_or(crate::FieldErr("id"))?,
}
}
pub fn all_ids(&self) -> Vec<String> {
match self {
Node::Empty => vec![],
Node::Link(uri) => uri.href().map(|x| vec![x.to_string()]).unwrap_or_default(),
Node::Object(x) => x.id().map_or(vec![], |x| vec![x.to_string()]),
Node::Array(x) => x.iter().filter_map(|x| Some(x.id().ok()?.to_string())).collect()
}
}
pub fn flat(self) -> Vec<Node<T>> {
match self {
Node::Empty => vec![],
Node::Link(_) | Node::Object(_) => vec![self],
// i think AP disallows array of arrays so no need to make this recursive
Node::Array(arr) => arr.into()
} }
} }
} }
#[cfg(feature = "unstructured")] #[cfg(feature = "unstructured")]
impl Node<serde_json::Value> { impl Node<serde_json::Value> {
pub fn into_value(self) -> serde_json::Value {
match self {
Self::Object(x) => *x,
Self::Link(l) => serde_json::Value::String(l.href().unwrap_or_default().to_string()),
Self::Empty => serde_json::Value::Null,
Self::Array(arr) => serde_json::Value::Array(
arr
.into_iter()
.map(|x| x.into_value())
.collect()
),
}
}
pub fn link(uri: String) -> Self { pub fn link(uri: String) -> Self {
Node::Link(Box::new(uri)) Node::Link(Box::new(uri))
} }
@ -165,7 +100,7 @@ impl Node<serde_json::Value> {
Node::Array( Node::Array(
uris uris
.into_iter() .into_iter()
.map(Node::link) .map(serde_json::Value::String)
.collect() .collect()
) )
} }
@ -189,20 +124,7 @@ impl Node<serde_json::Value> {
} }
pub fn array(values: Vec<serde_json::Value>) -> Self { pub fn array(values: Vec<serde_json::Value>) -> Self {
Node::Array( Node::Array(values)
std::collections::VecDeque::from_iter(
values.into_iter()
.map(Node::object)
)
)
}
pub fn maybe_array(values: Vec<serde_json::Value>) -> Self {
if values.is_empty() {
Node::Empty
} else {
Node::array(values)
}
} }
#[cfg(feature = "fetch")] #[cfg(feature = "fetch")]
@ -241,20 +163,15 @@ impl From<&str> for Node<serde_json::Value> {
#[cfg(feature = "unstructured")] #[cfg(feature = "unstructured")]
impl From<serde_json::Value> for Node<serde_json::Value> { impl From<serde_json::Value> for Node<serde_json::Value> {
fn from(value: serde_json::Value) -> Self { fn from(value: serde_json::Value) -> Self {
use crate::Link;
match value { match value {
serde_json::Value::String(uri) => Node::Link(Box::new(uri)), serde_json::Value::String(uri) => Node::Link(Box::new(uri)),
serde_json::Value::Array(arr) => Node::Array( serde_json::Value::Array(arr) => Node::Array(arr),
std::collections::VecDeque::from_iter( serde_json::Value::Object(_) => match value.get("href") {
arr.into_iter() None => Node::Object(Box::new(value)),
.map(Node::from) Some(_) => Node::Link(Box::new(value)),
)
),
serde_json::Value::Object(_) => match value.link_type() {
Ok(_) => Node::Link(Box::new(value)),
Err(_) => Node::Object(Box::new(value)),
}, },
_ => Node::Empty, _ => Node::Empty,
} }
} }
} }

29
apb/src/server.rs Normal file
View file

@ -0,0 +1,29 @@
#[async_trait::async_trait]
pub trait Outbox {
type Object: crate::Object;
type Activity: crate::Activity;
type Error: std::error::Error;
async fn create_note(&self, uid: String, object: Self::Object) -> Result<String, Self::Error>;
async fn create(&self, uid: String, activity: Self::Activity) -> Result<String, Self::Error>;
async fn like(&self, uid: String, activity: Self::Activity) -> Result<String, Self::Error>;
async fn follow(&self, uid: String, activity: Self::Activity) -> Result<String, Self::Error>;
async fn accept(&self, uid: String, activity: Self::Activity) -> Result<String, Self::Error>;
async fn reject(&self, _uid: String, _activity: Self::Activity) -> Result<String, Self::Error>;
async fn undo(&self, uid: String, activity: Self::Activity) -> Result<String, Self::Error>;
}
#[async_trait::async_trait]
pub trait Inbox {
type Activity: crate::Activity;
type Error: std::error::Error;
async fn create(&self, activity: Self::Activity) -> Result<(), Self::Error>;
async fn like(&self, activity: Self::Activity) -> Result<(), Self::Error>;
async fn follow(&self, activity: Self::Activity) -> Result<(), Self::Error>;
async fn accept(&self, activity: Self::Activity) -> Result<(), Self::Error>;
async fn reject(&self, activity: Self::Activity) -> Result<(), Self::Error>;
async fn undo(&self, activity: Self::Activity) -> Result<(), Self::Error>;
async fn delete(&self, activity: Self::Activity) -> Result<(), Self::Error>;
async fn update(&self, activity: Self::Activity) -> Result<(), Self::Error>;
}

View file

@ -1,52 +0,0 @@
use crate::{Collection, Object};
pub trait Shortcuts: crate::Object {
fn likes_count(&self) -> crate::Field<i32> {
let x = self
.likes()
.inner()?
.total_items()?
.min(i32::MAX as u64)
as i32;
Ok(x)
}
fn shares_count(&self) -> crate::Field<i32> {
let x = self
.shares()
.inner()?
.total_items()?
.min(i32::MAX as u64)
as i32;
Ok(x)
}
fn replies_count(&self) -> crate::Field<i32> {
let x = self
.replies()
.inner()?
.total_items()?
.min(i32::MAX as u64)
as i32;
Ok(x)
}
fn image_url(&self) -> crate::Field<String> {
let image_node = self.image();
let image = image_node.inner()?;
let url = image.url();
let id = url.id()?;
Ok(id.to_string())
}
fn icon_url(&self) -> crate::Field<String> {
let icon_node = self.icon();
let icon = icon_node.inner()?;
let url = icon.url();
let id = url.id()?;
Ok(id.to_string())
}
}
impl<T: crate::Object> Shortcuts for T {}

View file

@ -1,101 +1,18 @@
use crate::Object; use crate::{Object, Link};
pub const PUBLIC : &str = "https://www.w3.org/ns/activitystreams#Public"; pub const PUBLIC : &str = "https://www.w3.org/ns/activitystreams#Public";
pub trait Addressed { pub trait Addressed : Object {
fn addressed(&self) -> Vec<String>; // TODO rename this? remate others? idk fn addressed(&self) -> Vec<String>;
fn mentioning(&self) -> Vec<String>;
// fn secondary_targets(&self) -> Vec<String>;
// fn public_targets(&self) -> Vec<String>;
// fn private_targets(&self) -> Vec<String>;
} }
impl<T: Object> Addressed for T { #[cfg(feature = "unstructured")]
impl Addressed for serde_json::Value {
fn addressed(&self) -> Vec<String> { fn addressed(&self) -> Vec<String> {
let mut to : Vec<String> = self.to().all_ids(); let mut to : Vec<String> = self.to().map(|x| x.href().to_string()).collect();
to.append(&mut self.bto().all_ids()); to.append(&mut self.bto().map(|x| x.href().to_string()).collect());
to.append(&mut self.cc().all_ids()); to.append(&mut self.cc().map(|x| x.href().to_string()).collect());
to.append(&mut self.bcc().all_ids()); to.append(&mut self.bcc().map(|x| x.href().to_string()).collect());
to to
} }
fn mentioning(&self) -> Vec<String> {
let mut to : Vec<String> = self.to().all_ids();
to.append(&mut self.bto().all_ids());
to
}
// fn secondary_targets(&self) -> Vec<String> {
// let mut to : Vec<String> = self.cc().ids();
// to.append(&mut self.bcc().ids());
// to
// }
// fn public_targets(&self) -> Vec<String> {
// let mut to : Vec<String> = self.to().ids();
// to.append(&mut self.cc().ids());
// to
// }
// fn private_targets(&self) -> Vec<String> {
// let mut to : Vec<String> = self.bto().ids();
// to.append(&mut self.bcc().ids());
// to
// }
}
#[cfg(test)]
mod test {
use super::Addressed;
#[test]
#[cfg(feature = "unstructured")]
fn addressed_trait_finds_all_targets_on_json_objects() {
let obj = serde_json::json!({
"id": "http://localhost:8080/obj/1",
"type": "Note",
"content": "hello world!",
"published": "2024-06-04T17:09:20+00:00",
"to": ["http://localhost:8080/usr/root/followers"],
"bto": ["https://localhost:8080/usr/secret"],
"cc": [crate::target::PUBLIC],
"bcc": [],
});
let addressed = obj.addressed();
assert_eq!(
addressed,
vec![
"http://localhost:8080/usr/root/followers".to_string(),
"https://localhost:8080/usr/secret".to_string(),
crate::target::PUBLIC.to_string(),
]
);
}
#[test]
#[cfg(feature = "unstructured")]
fn primary_targets_only_finds_to_and_bto() {
let obj = serde_json::json!({
"id": "http://localhost:8080/obj/1",
"type": "Note",
"content": "hello world!",
"published": "2024-06-04T17:09:20+00:00",
"to": ["http://localhost:8080/usr/root/followers"],
"bto": ["https://localhost:8080/usr/secret"],
"cc": [crate::target::PUBLIC],
"bcc": [],
});
let addressed = obj.mentioning();
assert_eq!(
addressed,
vec![
"http://localhost:8080/usr/root/followers".to_string(),
"https://localhost:8080/usr/secret".to_string(),
]
);
}
} }

View file

@ -8,55 +8,36 @@ crate::strenum! {
}; };
} }
pub trait Base : crate::macros::MaybeSend { pub trait Base {
fn id(&self) -> crate::Field<String> { Err(crate::FieldErr("id")) } fn id(&self) -> Option<&str> { None }
fn base_type(&self) -> crate::Field<BaseType> { Err(crate::FieldErr("type")) } fn base_type(&self) -> Option<BaseType> { None }
} }
pub trait BaseMut : crate::macros::MaybeSend { pub trait BaseMut {
fn set_id(self, val: Option<String>) -> Self; fn set_id(self, val: Option<&str>) -> Self;
fn set_base_type(self, val: Option<BaseType>) -> Self; fn set_base_type(self, val: Option<BaseType>) -> Self;
} }
impl Base for String { impl Base for String {
fn id(&self) -> crate::Field<String> { fn id(&self) -> Option<&str> {
Ok(self.clone()) Some(self)
} }
fn base_type(&self) -> crate::Field<BaseType> { fn base_type(&self) -> Option<BaseType> {
Ok(BaseType::Link(LinkType::Link)) Some(BaseType::Link(LinkType::Link))
} }
} }
#[cfg(feature = "unstructured")] #[cfg(feature = "unstructured")]
impl Base for serde_json::Value { impl Base for serde_json::Value {
fn base_type(&self) -> crate::Field<BaseType> { crate::getter! { id -> &str }
if self.is_string() { crate::getter! { base_type -> type BaseType }
Ok(BaseType::Link(LinkType::Link))
} else {
self.get("type")
.and_then(|x| x.as_str())
.and_then(|x| x.try_into().ok())
.ok_or(crate::FieldErr("type"))
}
}
fn id(&self) -> crate::Field<String> {
if self.is_string() {
Ok(self.as_str().ok_or(crate::FieldErr("id"))?.to_string())
} else {
self.get("id")
.and_then(|x| x.as_str())
.map(|x| x.to_string())
.ok_or(crate::FieldErr("id"))
}
}
} }
#[cfg(feature = "unstructured")] #[cfg(feature = "unstructured")]
impl BaseMut for serde_json::Value { impl BaseMut for serde_json::Value {
crate::setter! { id -> String } crate::setter! { id -> &str }
crate::setter! { base_type -> type BaseType } crate::setter! { base_type -> type BaseType }
} }

View file

@ -1,15 +1,3 @@
use crate::{Field, FieldErr};
#[cfg(feature = "activitypub-miscellaneous-terms")]
crate::strenum! {
pub enum LinkType {
Link,
Hashtag,
Mention;
};
}
#[cfg(not(feature = "activitypub-miscellaneous-terms"))]
crate::strenum! { crate::strenum! {
pub enum LinkType { pub enum LinkType {
Link, Link,
@ -18,83 +6,81 @@ crate::strenum! {
} }
pub trait Link : crate::Base { pub trait Link : crate::Base {
fn link_type(&self) -> Field<LinkType> { Err(FieldErr("type")) } fn href(&self) -> &str;
fn href(&self) -> Field<String>; fn rel(&self) -> Option<&str> { None }
fn rel(&self) -> Field<String> { Err(FieldErr("rel")) } fn link_media_type(&self) -> Option<&str> { None } // also in obj
fn media_type(&self) -> Field<String> { Err(FieldErr("mediaType")) } // also in obj fn link_name(&self) -> Option<&str> { None } // also in obj
fn name(&self) -> Field<String> { Err(FieldErr("name")) } // also in obj fn hreflang(&self) -> Option<&str> { None }
fn hreflang(&self) -> Field<String> { Err(FieldErr("hreflang")) } fn height(&self) -> Option<u64> { None }
fn height(&self) -> Field<u64> { Err(FieldErr("height")) } fn width(&self) -> Option<u64> { None }
fn width(&self) -> Field<u64> { Err(FieldErr("width")) } fn link_preview(&self) -> Option<&str> { None } // also in obj
fn preview(&self) -> Field<String> { Err(FieldErr("linkPreview")) } // also in obj
} }
pub trait LinkMut : crate::BaseMut { pub trait LinkMut : crate::BaseMut {
fn set_link_type(self, val: Option<LinkType>) -> Self; fn set_href(self, href: &str) -> Self;
fn set_href(self, href: Option<String>) -> Self; fn set_rel(self, val: Option<&str>) -> Self;
fn set_rel(self, val: Option<String>) -> Self; fn set_link_media_type(self, val: Option<&str>) -> Self; // also in obj
fn set_media_type(self, val: Option<String>) -> Self; // also in obj fn set_link_name(self, val: Option<&str>) -> Self; // also in obj
fn set_name(self, val: Option<String>) -> Self; // also in obj fn set_hreflang(self, val: Option<&str>) -> Self;
fn set_hreflang(self, val: Option<String>) -> Self;
fn set_height(self, val: Option<u64>) -> Self; fn set_height(self, val: Option<u64>) -> Self;
fn set_width(self, val: Option<u64>) -> Self; fn set_width(self, val: Option<u64>) -> Self;
fn set_preview(self, val: Option<String>) -> Self; // also in obj fn set_link_preview(self, val: Option<&str>) -> Self; // also in obj
} }
impl Link for String { impl Link for String {
fn href(&self) -> Field<String> { fn href(&self) -> &str {
Ok(self.to_string()) self
} }
} }
#[cfg(feature = "unstructured")] #[cfg(feature = "unstructured")]
impl Link for serde_json::Value { impl Link for serde_json::Value {
// TODO this can fail, but it should never do! // TODO this can fail, but it should never do!
fn href(&self) -> Field<String> { fn href(&self) -> &str {
if self.is_string() { match self {
self.as_str().map(|x| x.to_string()).ok_or(FieldErr("href")) serde_json::Value::String(x) => x,
} else { serde_json::Value::Object(map) =>
self.get("href") map.get("href")
.and_then(|x| x.as_str()) .map(|h| h.as_str().unwrap_or(""))
.map(|x| x.to_string()) .unwrap_or(""),
.ok_or(FieldErr("href")) _ => {
tracing::error!("failed getting href on invalid json Link object");
""
},
} }
} }
crate::getter! { link_type -> type LinkType } crate::getter! { rel -> &str }
crate::getter! { rel -> String } crate::getter! { link_media_type::mediaType -> &str }
crate::getter! { mediaType -> String } crate::getter! { link_name::name -> &str }
crate::getter! { name -> String } crate::getter! { hreflang -> &str }
crate::getter! { hreflang -> String }
crate::getter! { height -> u64 } crate::getter! { height -> u64 }
crate::getter! { width -> u64 } crate::getter! { width -> u64 }
crate::getter! { preview -> String } crate::getter! { link_preview::preview -> &str }
} }
#[cfg(feature = "unstructured")] #[cfg(feature = "unstructured")]
impl LinkMut for serde_json::Value { impl LinkMut for serde_json::Value {
fn set_href(mut self, href: Option<String>) -> Self { // TODO this can fail, but it should never do!
fn set_href(mut self, href: &str) -> Self {
match &mut self { match &mut self {
serde_json::Value::String(x) => *x = href.to_string(),
serde_json::Value::Object(map) => { serde_json::Value::Object(map) => {
match href { map.insert(
Some(href) => map.insert(
"href".to_string(), "href".to_string(),
serde_json::Value::String(href) serde_json::Value::String(href.to_string())
), );
None => map.remove("href"),
};
}, },
x => *x = serde_json::Value::String(href.unwrap_or_default()), _ => tracing::error!("failed setting href on invalid json Link object"),
} }
self self
} }
crate::setter! { link_type -> type LinkType } crate::setter! { rel -> &str }
crate::setter! { rel -> String } crate::setter! { link_media_type::mediaType -> &str }
crate::setter! { mediaType -> String } crate::setter! { link_name::name -> &str }
crate::setter! { name -> String } crate::setter! { hreflang -> &str }
crate::setter! { hreflang -> String }
crate::setter! { height -> u64 } crate::setter! { height -> u64 }
crate::setter! { width -> u64 } crate::setter! { width -> u64 }
crate::setter! { preview -> String } crate::setter! { link_preview::preview -> &str }
} }

View file

@ -8,7 +8,7 @@ strenum! {
} }
pub trait Accept : super::Activity { pub trait Accept : super::Activity {
fn accept_type(&self) -> crate::Field<AcceptType> { Err(crate::FieldErr("type")) } fn accept_type(&self) -> Option<AcceptType> { None }
} }
pub trait AcceptMut : super::ActivityMut { pub trait AcceptMut : super::ActivityMut {

View file

@ -8,7 +8,7 @@ strenum! {
} }
pub trait Ignore : super::Activity { pub trait Ignore : super::Activity {
fn ignore_type(&self) -> crate::Field<IgnoreType> { Err(crate::FieldErr("type")) } fn ignore_type(&self) -> Option<IgnoreType> { None }
} }
pub trait IgnoreMut : super::ActivityMut { pub trait IgnoreMut : super::ActivityMut {

View file

@ -10,7 +10,7 @@ strenum! {
} }
pub trait IntransitiveActivity : super::Activity { pub trait IntransitiveActivity : super::Activity {
fn intransitive_activity_type(&self) -> crate::Field<IntransitiveActivityType> { Err(crate::FieldErr("type")) } fn intransitive_activity_type(&self) -> Option<IntransitiveActivityType> { None }
} }
pub trait IntransitiveActivityMut : super::ActivityMut { pub trait IntransitiveActivityMut : super::ActivityMut {

View file

@ -4,45 +4,13 @@ pub mod intransitive;
pub mod offer; pub mod offer;
pub mod reject; pub mod reject;
use crate::{Field, FieldErr, Node, Object, ObjectMut}; use crate::{Node, Object, ObjectMut};
use accept::AcceptType; use accept::AcceptType;
use reject::RejectType; use reject::RejectType;
use offer::OfferType; use offer::OfferType;
use intransitive::IntransitiveActivityType; use intransitive::IntransitiveActivityType;
use ignore::IgnoreType; use ignore::IgnoreType;
#[cfg(feature = "litepub")]
crate::strenum! {
pub enum ActivityType {
Activity,
Add,
Announce,
Create,
Delete,
Dislike,
EmojiReact,
Flag,
Follow,
Join,
Leave,
Like,
Listen,
Move,
Read,
Remove,
Undo,
Update,
View;
IntransitiveActivity(IntransitiveActivityType),
Accept(AcceptType),
Ignore(IgnoreType),
Offer(OfferType),
Reject(RejectType)
};
}
#[cfg(not(feature = "litepub"))]
crate::strenum! { crate::strenum! {
pub enum ActivityType { pub enum ActivityType {
Activity, Activity,
@ -73,29 +41,13 @@ crate::strenum! {
} }
pub trait Activity : Object { pub trait Activity : Object {
fn activity_type(&self) -> Field<ActivityType> { Err(FieldErr("type")) } fn activity_type(&self) -> Option<ActivityType> { None }
/// Describes one or more entities that either performed or are expected to perform the activity.
/// Any single activity can have multiple actors. The actor MAY be specified using an indirect Link.
fn actor(&self) -> Node<Self::Actor> { Node::Empty } fn actor(&self) -> Node<Self::Actor> { Node::Empty }
/// Describes an object of any kind.
/// The Object type serves as the base type for most of the other kinds of objects defined in the Activity Vocabulary, including other Core types such as Activity, IntransitiveActivity, Collection and OrderedCollection.
fn object(&self) -> Node<Self::Object> { Node::Empty } fn object(&self) -> Node<Self::Object> { Node::Empty }
/// Describes the indirect object, or target, of the activity.
/// The precise meaning of the target is largely dependent on the type of action being described but will often be the object of the English preposition "to".
/// For instance, in the activity "John added a movie to his wishlist", the target of the activity is John's wishlist. An activity can have more than one target.
fn target(&self) -> Node<Self::Object> { Node::Empty } fn target(&self) -> Node<Self::Object> { Node::Empty }
/// Describes the result of the activity.
/// For instance, if a particular action results in the creation of a new resource, the result property can be used to describe that new resource.
fn result(&self) -> Node<Self::Object> { Node::Empty } fn result(&self) -> Node<Self::Object> { Node::Empty }
/// Describes an indirect object of the activity from which the activity is directed.
/// The precise meaning of the origin is the object of the English preposition "from".
/// For instance, in the activity "John moved an item to List B from List A", the origin of the activity is "List A".
fn origin(&self) -> Node<Self::Object> { Node::Empty } fn origin(&self) -> Node<Self::Object> { Node::Empty }
/// Identifies one or more objects used (or to be used) in the completion of an Activity.
fn instrument(&self) -> Node<Self::Object> { Node::Empty } fn instrument(&self) -> Node<Self::Object> { Node::Empty }
#[cfg(feature = "activitypub-fe")]
fn seen(&self) -> Field<bool> { Err(FieldErr("seen")) }
} }
pub trait ActivityMut : ObjectMut { pub trait ActivityMut : ObjectMut {
@ -106,9 +58,6 @@ pub trait ActivityMut : ObjectMut {
fn set_result(self, val: Node<Self::Object>) -> Self; fn set_result(self, val: Node<Self::Object>) -> Self;
fn set_origin(self, val: Node<Self::Object>) -> Self; fn set_origin(self, val: Node<Self::Object>) -> Self;
fn set_instrument(self, val: Node<Self::Object>) -> Self; fn set_instrument(self, val: Node<Self::Object>) -> Self;
#[cfg(feature = "activitypub-fe")]
fn set_seen(self, val: Option<bool>) -> Self;
} }
#[cfg(feature = "unstructured")] #[cfg(feature = "unstructured")]
@ -120,9 +69,6 @@ impl Activity for serde_json::Value {
crate::getter! { result -> node <Self as Object>::Object } crate::getter! { result -> node <Self as Object>::Object }
crate::getter! { origin -> node <Self as Object>::Object } crate::getter! { origin -> node <Self as Object>::Object }
crate::getter! { instrument -> node <Self as Object>::Object } crate::getter! { instrument -> node <Self as Object>::Object }
#[cfg(feature = "activitypub-fe")]
crate::getter! { seen -> bool }
} }
#[cfg(feature = "unstructured")] #[cfg(feature = "unstructured")]
@ -134,7 +80,4 @@ impl ActivityMut for serde_json::Value {
crate::setter! { result -> node <Self as Object>::Object } crate::setter! { result -> node <Self as Object>::Object }
crate::setter! { origin -> node <Self as Object>::Object } crate::setter! { origin -> node <Self as Object>::Object }
crate::setter! { instrument -> node <Self as Object>::Object } crate::setter! { instrument -> node <Self as Object>::Object }
#[cfg(feature = "activitypub-fe")]
crate::setter! { seen -> bool }
} }

View file

@ -8,7 +8,7 @@ strenum! {
} }
pub trait Offer : super::Activity { pub trait Offer : super::Activity {
fn offer_type(&self) -> crate::Field<OfferType> { Err(crate::FieldErr("type")) } fn offer_type(&self) -> Option<OfferType> { None }
} }
pub trait OfferMut : super::ActivityMut { pub trait OfferMut : super::ActivityMut {

View file

@ -8,7 +8,7 @@ strenum! {
} }
pub trait Reject : super::Activity { pub trait Reject : super::Activity {
fn reject_type(&self) -> crate::Field<RejectType> { Err(crate::FieldErr("type")) } fn reject_type(&self) -> Option<RejectType> { None }
} }
pub trait RejectMut : super::ActivityMut { pub trait RejectMut : super::ActivityMut {

View file

@ -1,245 +1,86 @@
use crate::{Field, FieldErr, Node, Object, ObjectMut}; use crate::Node;
use crate::{Object, ObjectMut, PublicKey};
crate::strenum! { crate::strenum! {
pub enum ActorType { pub enum ActorType {
Application, Application,
Group, Group,
Organization, Organization,
Person, Person;
Service;
}; };
} }
pub trait Actor : Object { pub trait Actor : Object {
type PublicKey : crate::PublicKey; type PublicKey : PublicKey;
type Endpoints : Endpoints;
fn actor_type(&self) -> Field<ActorType> { Err(FieldErr("type")) } fn actor_type(&self) -> Option<ActorType> { None }
/// A short username which may be used to refer to the actor, with no uniqueness guarantees. fn preferred_username(&self) -> Option<&str> { None }
fn preferred_username(&self) -> Field<String> { Err(FieldErr("preferredUsername")) }
/// A reference to an [ActivityStreams] OrderedCollection comprised of all the messages received by the actor; see 5.2 Inbox.
fn inbox(&self) -> Node<Self::Collection>; fn inbox(&self) -> Node<Self::Collection>;
/// An [ActivityStreams] OrderedCollection comprised of all the messages produced by the actor; see 5.1 Outbox.
fn outbox(&self) -> Node<Self::Collection>; fn outbox(&self) -> Node<Self::Collection>;
/// A link to an [ActivityStreams] collection of the actors that this actor is following; see 5.4 Following Collection
fn following(&self) -> Node<Self::Collection> { Node::Empty } fn following(&self) -> Node<Self::Collection> { Node::Empty }
/// A link to an [ActivityStreams] collection of the actors that follow this actor; see 5.3 Followers Collection.
fn followers(&self) -> Node<Self::Collection> { Node::Empty } fn followers(&self) -> Node<Self::Collection> { Node::Empty }
/// A link to an [ActivityStreams] collection of objects this actor has liked; see 5.5 Liked Collection.
fn liked(&self) -> Node<Self::Collection> { Node::Empty } fn liked(&self) -> Node<Self::Collection> { Node::Empty }
/// A list of supplementary Collections which may be of interest.
fn streams(&self) -> Node<Self::Collection> { Node::Empty } fn streams(&self) -> Node<Self::Collection> { Node::Empty }
/// A json object which maps additional (typically server/domain-wide) endpoints which may be useful either for this actor or someone referencing this actor. fn endpoints(&self) -> Node<Self::Object> { Node::Empty }
/// This mapping may be nested inside the actor document as the value or may be a link to a JSON-LD document with these properties. fn public_key(&self) -> Node<Self::PublicKey> { Node::Empty }
fn endpoints(&self) -> Node<Self::Endpoints> { Node::Empty } // idk about this? everyone has it but AP doesn't mention it
fn public_key(&self) -> Node<Self::PublicKey> { Node::Empty } // TODO hmmm where is this from?? fn discoverable(&self) -> Option<bool> { None }
#[cfg(feature = "activitypub-miscellaneous-terms")]
fn moved_to(&self) -> Node<Self::Actor> { Node::Empty }
#[cfg(feature = "activitypub-miscellaneous-terms")]
fn manually_approves_followers(&self) -> Field<bool> { Err(FieldErr("manuallyApprovesFollowers")) }
#[cfg(feature = "did-core")]
fn also_known_as(&self) -> Node<Self::Actor> { Node::Empty }
#[cfg(feature = "activitypub-fe")]
fn following_me(&self) -> Field<bool> { Err(FieldErr("followingMe")) }
#[cfg(feature = "activitypub-fe")]
fn followed_by_me(&self) -> Field<bool> { Err(FieldErr("followedByMe")) }
#[cfg(feature = "activitypub-fe")]
fn notifications(&self) -> Node<Self::Collection> { Node::Empty }
#[cfg(feature = "activitypub-counters")]
fn followers_count(&self) -> Field<u64> { Err(FieldErr("followersCount")) }
#[cfg(feature = "activitypub-counters")]
fn following_count(&self) -> Field<u64> { Err(FieldErr("followingCount")) }
#[cfg(feature = "activitypub-counters")]
fn statuses_count(&self) -> Field<u64> { Err(FieldErr("statusesCount")) }
#[cfg(feature = "toot")]
fn discoverable(&self) -> Field<bool> { Err(FieldErr("discoverable")) }
#[cfg(feature = "toot")]
fn featured(&self) -> Node<Self::Collection> { Node::Empty }
}
pub trait Endpoints : Object {
/// Endpoint URI so this actor's clients may access remote ActivityStreams objects which require authentication to access. To use this endpoint, the client posts an x-www-form-urlencoded id parameter with the value being the id of the requested ActivityStreams object.
fn proxy_url(&self) -> Field<String> { Err(FieldErr("proxyUrl")) }
/// If OAuth 2.0 bearer tokens [RFC6749] [RFC6750] are being used for authenticating client to server interactions, this endpoint specifies a URI at which a browser-authenticated user may obtain a new authorization grant.
fn oauth_authorization_endpoint(&self) -> Field<String> { Err(FieldErr("oauthAuthorizationEndpoint")) }
/// If OAuth 2.0 bearer tokens [RFC6749] [RFC6750] are being used for authenticating client to server interactions, this endpoint specifies a URI at which a client may acquire an access token.
fn oauth_token_endpoint(&self) -> Field<String> { Err(FieldErr("oauthTokenEndpoint")) }
/// If Linked Data Signatures and HTTP Signatures are being used for authentication and authorization, this endpoint specifies a URI at which browser-authenticated users may authorize a client's public key for client to server interactions.
fn provide_client_key(&self) -> Field<String> { Err(FieldErr("provideClientKey")) }
/// If Linked Data Signatures and HTTP Signatures are being used for authentication and authorization, this endpoint specifies a URI at which a client key may be signed by the actor's key for a time window to act on behalf of the actor in interacting with foreign servers.
fn sign_client_key(&self) -> Field<String> { Err(FieldErr("signClientKey")) }
/// An optional endpoint used for wide delivery of publicly addressed activities and activities sent to followers. sharedInbox endpoints SHOULD also be publicly readable OrderedCollection objects containing objects addressed to the Public special collection. Reading from the sharedInbox endpoint MUST NOT present objects which are not addressed to the Public endpoint.
fn shared_inbox(&self) -> Field<String> { Err(FieldErr("sharedInbox")) }
} }
pub trait ActorMut : ObjectMut { pub trait ActorMut : ObjectMut {
type PublicKey : crate::PublicKey; type PublicKey : PublicKey;
type Endpoints : Endpoints;
fn set_actor_type(self, val: Option<ActorType>) -> Self; fn set_actor_type(self, val: Option<ActorType>) -> Self;
fn set_preferred_username(self, val: Option<String>) -> Self; fn set_preferred_username(self, val: Option<&str>) -> Self;
fn set_inbox(self, val: Node<Self::Collection>) -> Self; fn set_inbox(self, val: Node<Self::Collection>) -> Self;
fn set_outbox(self, val: Node<Self::Collection>) -> Self; fn set_outbox(self, val: Node<Self::Collection>) -> Self;
fn set_following(self, val: Node<Self::Collection>) -> Self; fn set_following(self, val: Node<Self::Collection>) -> Self;
fn set_followers(self, val: Node<Self::Collection>) -> Self; fn set_followers(self, val: Node<Self::Collection>) -> Self;
fn set_liked(self, val: Node<Self::Collection>) -> Self; fn set_liked(self, val: Node<Self::Collection>) -> Self;
fn set_streams(self, val: Node<Self::Collection>) -> Self; fn set_streams(self, val: Node<Self::Collection>) -> Self;
fn set_endpoints(self, val: Node<Self::Endpoints>) -> Self; fn set_endpoints(self, val: Node<Self::Object>) -> Self; // TODO it's more complex than this!
fn set_public_key(self, val: Node<Self::PublicKey>) -> Self; fn set_public_key(self, val: Node<Self::PublicKey>) -> Self;
#[cfg(feature = "activitypub-miscellaneous-terms")]
fn set_moved_to(self, val: Node<Self::Actor>) -> Self;
#[cfg(feature = "activitypub-miscellaneous-terms")]
fn set_manually_approves_followers(self, val: Option<bool>) -> Self;
#[cfg(feature = "did-core")]
fn set_also_known_as(self, val: Node<Self::Actor>) -> Self;
#[cfg(feature = "activitypub-fe")]
fn set_following_me(self, val: Option<bool>) -> Self;
#[cfg(feature = "activitypub-fe")]
fn set_followed_by_me(self, val: Option<bool>) -> Self;
#[cfg(feature = "activitypub-fe")]
fn set_notifications(self, val: Node<Self::Collection>) -> Self;
#[cfg(feature = "activitypub-counters")]
fn set_followers_count(self, val: Option<u64>) -> Self;
#[cfg(feature = "activitypub-counters")]
fn set_following_count(self, val: Option<u64>) -> Self;
#[cfg(feature = "activitypub-counters")]
fn set_statuses_count(self, val: Option<u64>) -> Self;
#[cfg(feature = "toot")]
fn set_discoverable(self, val: Option<bool>) -> Self; fn set_discoverable(self, val: Option<bool>) -> Self;
#[cfg(feature = "toot")]
fn set_featured(self, val: Node<Self::Collection>) -> Self;
}
pub trait EndpointsMut : ObjectMut {
/// Endpoint URI so this actor's clients may access remote ActivityStreams objects which require authentication to access. To use this endpoint, the client posts an x-www-form-urlencoded id parameter with the value being the id of the requested ActivityStreams object.
fn set_proxy_url(self, val: Option<String>) -> Self;
/// If OAuth 2.0 bearer tokens [RFC6749] [RFC6750] are being used for authenticating client to server interactions, this endpoint specifies a URI at which a browser-authenticated user may obtain a new authorization grant.
fn set_oauth_authorization_endpoint(self, val: Option<String>) -> Self;
/// If OAuth 2.0 bearer tokens [RFC6749] [RFC6750] are being used for authenticating client to server interactions, this endpoint specifies a URI at which a client may acquire an access token.
fn set_oauth_token_endpoint(self, val: Option<String>) -> Self;
/// If Linked Data Signatures and HTTP Signatures are being used for authentication and authorization, this endpoint specifies a URI at which browser-authenticated users may authorize a client's public key for client to server interactions.
fn set_provide_client_key(self, val: Option<String>) -> Self;
/// If Linked Data Signatures and HTTP Signatures are being used for authentication and authorization, this endpoint specifies a URI at which a client key may be signed by the actor's key for a time window to act on behalf of the actor in interacting with foreign servers.
fn set_sign_client_key(self, val: Option<String>) -> Self;
/// An optional endpoint used for wide delivery of publicly addressed activities and activities sent to followers. sharedInbox endpoints SHOULD also be publicly readable OrderedCollection objects containing objects addressed to the Public special collection. Reading from the sharedInbox endpoint MUST NOT present objects which are not addressed to the Public endpoint.
fn set_shared_inbox(self, val: Option<String>) -> Self;
} }
#[cfg(feature = "unstructured")] #[cfg(feature = "unstructured")]
impl Actor for serde_json::Value { impl Actor for serde_json::Value {
type PublicKey = serde_json::Value; type PublicKey = serde_json::Value;
type Endpoints = serde_json::Value;
crate::getter! { actorType -> type ActorType } crate::getter! { actor_type -> type ActorType }
crate::getter! { preferredUsername -> String } crate::getter! { preferred_username::preferredUsername -> &str }
crate::getter! { inbox -> node Self::Collection } crate::getter! { inbox -> node Self::Collection }
crate::getter! { outbox -> node Self::Collection } crate::getter! { outbox -> node Self::Collection }
crate::getter! { following -> node Self::Collection } crate::getter! { following -> node Self::Collection }
crate::getter! { followers -> node Self::Collection } crate::getter! { followers -> node Self::Collection }
crate::getter! { liked -> node Self::Collection } crate::getter! { liked -> node Self::Collection }
crate::getter! { streams -> node Self::Collection } crate::getter! { streams -> node Self::Collection }
crate::getter! { publicKey -> node Self::PublicKey } crate::getter! { public_key::publicKey -> node Self::PublicKey }
crate::getter! { endpoints -> node Self::Endpoints }
#[cfg(feature = "activitypub-miscellaneous-terms")]
crate::getter! { movedTo -> node Self::Actor }
#[cfg(feature = "activitypub-miscellaneous-terms")]
crate::getter! { manuallyApprovesFollowers -> bool }
#[cfg(feature = "did-core")]
crate::getter! { alsoKnownAs -> node Self::Actor }
#[cfg(feature = "activitypub-fe")]
crate::getter! { followingMe -> bool }
#[cfg(feature = "activitypub-fe")]
crate::getter! { followedByMe -> bool }
#[cfg(feature = "activitypub-fe")]
crate::getter! { notifications -> node Self::Collection }
#[cfg(feature = "activitypub-counters")]
crate::getter! { followingCount -> u64 }
#[cfg(feature = "activitypub-counters")]
crate::getter! { followersCount -> u64 }
#[cfg(feature = "activitypub-counters")]
crate::getter! { statusesCount -> u64 }
#[cfg(feature = "toot")]
crate::getter! { discoverable -> bool } crate::getter! { discoverable -> bool }
#[cfg(feature = "toot")]
crate::getter! { featured -> node Self::Collection }
}
#[cfg(feature = "unstructured")] fn endpoints(&self) -> Node<<Self as Object>::Object> {
impl Endpoints for serde_json::Value { todo!()
crate::getter! { proxyUrl -> String } }
crate::getter! { oauthAuthorizationEndpoint -> String }
crate::getter! { oauthTokenEndpoint -> String }
crate::getter! { provideClientKey -> String }
crate::getter! { signClientKey -> String }
crate::getter! { sharedInbox -> String }
} }
#[cfg(feature = "unstructured")] #[cfg(feature = "unstructured")]
impl ActorMut for serde_json::Value { impl ActorMut for serde_json::Value {
type PublicKey = serde_json::Value; type PublicKey = serde_json::Value;
type Endpoints = serde_json::Value;
crate::setter! { actor_type -> type ActorType } crate::setter! { actor_type -> type ActorType }
crate::setter! { preferredUsername -> String } crate::setter! { preferred_username::preferredUsername -> &str }
crate::setter! { inbox -> node Self::Collection } crate::setter! { inbox -> node Self::Collection }
crate::setter! { outbox -> node Self::Collection } crate::setter! { outbox -> node Self::Collection }
crate::setter! { following -> node Self::Collection } crate::setter! { following -> node Self::Collection }
crate::setter! { followers -> node Self::Collection } crate::setter! { followers -> node Self::Collection }
crate::setter! { liked -> node Self::Collection } crate::setter! { liked -> node Self::Collection }
crate::setter! { streams -> node Self::Collection } crate::setter! { streams -> node Self::Collection }
crate::setter! { publicKey -> node Self::PublicKey } crate::setter! { public_key::publicKey -> node Self::PublicKey }
crate::setter! { endpoints -> node Self::Endpoints }
#[cfg(feature = "activitypub-miscellaneous-terms")]
crate::setter! { movedTo -> node Self::Actor }
#[cfg(feature = "activitypub-miscellaneous-terms")]
crate::setter! { manuallyApprovesFollowers -> bool }
#[cfg(feature = "did-core")]
crate::setter! { alsoKnownAs -> node Self::Actor }
#[cfg(feature = "activitypub-fe")]
crate::setter! { followingMe -> bool }
#[cfg(feature = "activitypub-fe")]
crate::setter! { followedByMe -> bool }
#[cfg(feature = "activitypub-fe")]
crate::setter! { notifications -> node Self::Collection }
#[cfg(feature = "activitypub-counters")]
crate::setter! { followingCount -> u64 }
#[cfg(feature = "activitypub-counters")]
crate::setter! { followersCount -> u64 }
#[cfg(feature = "activitypub-counters")]
crate::setter! { statusesCount -> u64 }
#[cfg(feature = "toot")]
crate::setter! { discoverable -> bool } crate::setter! { discoverable -> bool }
#[cfg(feature = "toot")]
crate::setter! { featured -> node Self::Collection }
}
#[cfg(feature = "unstructured")] fn set_endpoints(mut self, _val: Node<<Self as Object>::Object>) -> Self {
impl EndpointsMut for serde_json::Value { self.as_object_mut().unwrap().insert("endpoints".to_string(), serde_json::Value::Object(serde_json::Map::default()));
crate::setter! { proxyUrl -> String } self
crate::setter! { oauthAuthorizationEndpoint -> String } }
crate::setter! { oauthTokenEndpoint -> String }
crate::setter! { provideClientKey -> String }
crate::setter! { signClientKey -> String }
crate::setter! { sharedInbox -> String }
} }

View file

@ -1,7 +1,7 @@
pub mod page; pub mod page;
pub use page::CollectionPage; pub use page::CollectionPage;
use crate::{Field, FieldErr, Node, Object, ObjectMut}; use crate::{Node, Object, ObjectMut};
crate::strenum! { crate::strenum! {
pub enum CollectionType { pub enum CollectionType {
@ -15,20 +15,13 @@ crate::strenum! {
pub trait Collection : Object { pub trait Collection : Object {
type CollectionPage : CollectionPage; type CollectionPage : CollectionPage;
fn collection_type(&self) -> Field<CollectionType> { Err(FieldErr("type")) } fn collection_type(&self) -> Option<CollectionType> { None }
/// A non-negative integer specifying the total number of objects contained by the logical view of the collection. fn total_items(&self) -> Option<u64> { None }
/// This number might not reflect the actual number of items serialized within the Collection object instance.
fn total_items(&self) -> Field<u64> { Err(FieldErr("totalItems")) }
/// In a paged Collection, indicates the page that contains the most recently updated member items.
fn current(&self) -> Node<Self::CollectionPage> { Node::Empty } fn current(&self) -> Node<Self::CollectionPage> { Node::Empty }
/// In a paged Collection, indicates the furthest preceeding page of items in the collection.
fn first(&self) -> Node<Self::CollectionPage> { Node::Empty } fn first(&self) -> Node<Self::CollectionPage> { Node::Empty }
/// In a paged Collection, indicates the furthest proceeding page of the collection.
fn last(&self) -> Node<Self::CollectionPage> { Node::Empty } fn last(&self) -> Node<Self::CollectionPage> { Node::Empty }
/// Identifies the items contained in a collection. The items might be ordered or unordered.
fn items(&self) -> Node<Self::Object> { Node::Empty } fn items(&self) -> Node<Self::Object> { Node::Empty }
/// ??????????????? same as items but ordered?? spec just uses it without saying
fn ordered_items(&self) -> Node<Self::Object> { Node::Empty } fn ordered_items(&self) -> Node<Self::Object> { Node::Empty }
} }
@ -49,12 +42,12 @@ impl Collection for serde_json::Value {
type CollectionPage = serde_json::Value; type CollectionPage = serde_json::Value;
crate::getter! { collection_type -> type CollectionType } crate::getter! { collection_type -> type CollectionType }
crate::getter! { totalItems -> u64 } crate::getter! { total_items::totalItems -> u64 }
crate::getter! { current -> node Self::CollectionPage } crate::getter! { current -> node Self::CollectionPage }
crate::getter! { first -> node Self::CollectionPage } crate::getter! { first -> node Self::CollectionPage }
crate::getter! { last -> node Self::CollectionPage } crate::getter! { last -> node Self::CollectionPage }
crate::getter! { items -> node <Self as Object>::Object } crate::getter! { items -> node <Self as Object>::Object }
crate::getter! { orderedItems -> node <Self as Object>::Object } crate::getter! { ordered_items::orderedItems -> node <Self as Object>::Object }
} }
#[cfg(feature = "unstructured")] #[cfg(feature = "unstructured")]
@ -62,10 +55,10 @@ impl CollectionMut for serde_json::Value {
type CollectionPage = serde_json::Value; type CollectionPage = serde_json::Value;
crate::setter! { collection_type -> type CollectionType } crate::setter! { collection_type -> type CollectionType }
crate::setter! { totalItems -> u64 } crate::setter! { total_items::totalItems -> u64 }
crate::setter! { current -> node Self::CollectionPage } crate::setter! { current -> node Self::CollectionPage }
crate::setter! { first -> node Self::CollectionPage } crate::setter! { first -> node Self::CollectionPage }
crate::setter! { last -> node Self::CollectionPage } crate::setter! { last -> node Self::CollectionPage }
crate::setter! { items -> node <Self as Object>::Object } crate::setter! { items -> node <Self as Object>::Object }
crate::setter! { orderedItems -> node <Self as Object>::Object } crate::setter! { ordered_items::orderedItems -> node <Self as Object>::Object }
} }

View file

@ -14,14 +14,14 @@ pub trait CollectionPageMut : super::CollectionMut {
#[cfg(feature = "unstructured")] #[cfg(feature = "unstructured")]
impl CollectionPage for serde_json::Value { impl CollectionPage for serde_json::Value {
crate::getter! { partOf -> node Self::Collection } crate::getter! { part_of::partOf -> node Self::Collection }
crate::getter! { next -> node Self::CollectionPage } crate::getter! { next -> node Self::CollectionPage }
crate::getter! { prev -> node Self::CollectionPage } crate::getter! { prev -> node Self::CollectionPage }
} }
#[cfg(feature = "unstructured")] #[cfg(feature = "unstructured")]
impl CollectionPageMut for serde_json::Value { impl CollectionPageMut for serde_json::Value {
crate::setter! { partOf -> node Self::Collection } crate::setter! { part_of::partOf -> node Self::Collection }
crate::setter! { next -> node Self::CollectionPage } crate::setter! { next -> node Self::CollectionPage }
crate::setter! { prev -> node Self::CollectionPage } crate::setter! { prev -> node Self::CollectionPage }
} }

View file

@ -9,7 +9,7 @@ crate::strenum! {
} }
pub trait Document : super::Object { pub trait Document : super::Object {
fn document_type(&self) -> crate::Field<DocumentType> { Err(crate::FieldErr("type")) } fn document_type(&self) -> Option<DocumentType> { None }
} }
pub trait DocumentMut : super::ObjectMut { pub trait DocumentMut : super::ObjectMut {
@ -19,10 +19,10 @@ pub trait DocumentMut : super::ObjectMut {
#[cfg(feature = "unstructured")] #[cfg(feature = "unstructured")]
impl Document for serde_json::Value { impl Document for serde_json::Value {
crate::getter! { documentType -> type DocumentType } crate::getter! { document_type -> type DocumentType }
} }
#[cfg(feature = "unstructured")] #[cfg(feature = "unstructured")]
impl DocumentMut for serde_json::Value { impl DocumentMut for serde_json::Value {
crate::setter! { documentType -> type DocumentType } crate::setter! { document_type -> type DocumentType }
} }

View file

@ -7,12 +7,12 @@ pub mod place;
pub mod profile; pub mod profile;
pub mod relationship; pub mod relationship;
use crate::{Base, BaseMut, Field, FieldErr, Node}; use crate::{Base, BaseMut, Link, Node};
use actor::ActorType; use actor::{Actor, ActorType};
use document::DocumentType; use document::{Document, DocumentType};
use activity::ActivityType; use activity::ActivityType;
use collection::CollectionType; use collection::{Collection, CollectionType};
crate::strenum! { crate::strenum! {
pub enum ObjectType { pub enum ObjectType {
@ -33,119 +33,55 @@ crate::strenum! {
} }
pub trait Object : Base { pub trait Object : Base {
type Link : crate::Link; type Link : Link;
type Actor : crate::Actor; type Actor : Actor;
type Object : Object; type Object : Object;
type Collection : crate::Collection; type Collection : Collection;
type Document : crate::Document; type Document : Document;
type Activity : crate::Activity;
fn object_type(&self) -> Field<ObjectType> { Err(FieldErr("type")) } fn object_type(&self) -> Option<ObjectType> { None }
/// Identifies a resource attached or related to an object that potentially requires special handling
/// The intent is to provide a model that is at least semantically similar to attachments in email.
fn attachment(&self) -> Node<Self::Object> { Node::Empty } fn attachment(&self) -> Node<Self::Object> { Node::Empty }
/// Identifies one or more entities to which this object is attributed.
/// The attributed entities might not be Actors. For instance, an object might be attributed to the completion of another activity.
fn attributed_to(&self) -> Node<Self::Actor> { Node::Empty } fn attributed_to(&self) -> Node<Self::Actor> { Node::Empty }
/// Identifies one or more entities that represent the total population of entities for which the object can considered to be relevant fn audience(&self) -> Node<Self::Actor> { Node::Empty }
fn audience(&self) -> Node<Self::Object> { Node::Empty } fn content(&self) -> Option<&str> { None } // TODO handle language maps
/// The content or textual representation of the Object encoded as a JSON string. By default, the value of content is HTML
/// The mediaType property can be used in the object to indicate a different content type
/// The content MAY be expressed using multiple language-tagged values
fn content(&self) -> Field<String> { Err(FieldErr("content")) } // TODO handle language maps
/// Identifies the context within which the object exists or an activity was performed
/// The notion of "context" used is intentionally vague
/// The intended function is to serve as a means of grouping objects and activities that share a common originating context or purpose
/// An example could be all activities relating to a common project or event
fn context(&self) -> Node<Self::Object> { Node::Empty } fn context(&self) -> Node<Self::Object> { Node::Empty }
/// A simple, human-readable, plain-text name for the object. HTML markup MUST NOT be included. The name MAY be expressed using multiple language-tagged values fn name(&self) -> Option<&str> { None } // also in link // TODO handle language maps
fn name(&self) -> Field<String> { Err(FieldErr("name")) } // also in link // TODO handle language maps fn end_time(&self) -> Option<chrono::DateTime<chrono::Utc>> { None }
/// The date and time describing the actual or expected ending time of the object
/// When used with an Activity object, for instance, the endTime property specifies the moment the activity concluded or is expected to conclude.
fn end_time(&self) -> Field<chrono::DateTime<chrono::Utc>> { Err(FieldErr("endTime")) }
/// Identifies the entity (e.g. an application) that generated the object
fn generator(&self) -> Node<Self::Actor> { Node::Empty } fn generator(&self) -> Node<Self::Actor> { Node::Empty }
/// Indicates an entity that describes an icon for this object
/// The image should have an aspect ratio of one (horizontal) to one (vertical) and should be suitable for presentation at a small size
fn icon(&self) -> Node<Self::Document> { Node::Empty } fn icon(&self) -> Node<Self::Document> { Node::Empty }
/// Indicates an entity that describes an image for this object
/// Unlike the icon property, there are no aspect ratio or display size limitations assumed
fn image(&self) -> Node<Self::Document> { Node::Empty } fn image(&self) -> Node<Self::Document> { Node::Empty }
/// Indicates one or more entities for which this object is considered a response
fn in_reply_to(&self) -> Node<Self::Object> { Node::Empty } fn in_reply_to(&self) -> Node<Self::Object> { Node::Empty }
/// Indicates one or more physical or logical locations associated with the object
fn location(&self) -> Node<Self::Object> { Node::Empty } fn location(&self) -> Node<Self::Object> { Node::Empty }
/// Identifies an entity that provides a preview of this object
fn preview(&self) -> Node<Self::Object> { Node::Empty } // also in link fn preview(&self) -> Node<Self::Object> { Node::Empty } // also in link
/// The date and time at which the object was published fn published(&self) -> Option<chrono::DateTime<chrono::Utc>> { None }
fn published(&self) -> Field<chrono::DateTime<chrono::Utc>> { Err(FieldErr("published")) }
/// The date and time at which the object was updated
fn updated(&self) -> Field<chrono::DateTime<chrono::Utc>> { Err(FieldErr("updated")) }
/// Identifies a Collection containing objects considered to be responses to this object
fn replies(&self) -> Node<Self::Collection> { Node::Empty } fn replies(&self) -> Node<Self::Collection> { Node::Empty }
fn likes(&self) -> Node<Self::Collection> { Node::Empty } fn start_time(&self) -> Option<chrono::DateTime<chrono::Utc>> { None }
fn shares(&self) -> Node<Self::Collection> { Node::Empty } fn summary(&self) -> Option<&str> { None }
/// The date and time describing the actual or expected starting time of the object. fn tag(&self) -> Node<Self::Object> { Node::Empty }
/// When used with an Activity object, for instance, the startTime property specifies the moment the activity began or is scheduled to begin. fn updated(&self) -> Option<chrono::DateTime<chrono::Utc>> { None }
fn start_time(&self) -> Field<chrono::DateTime<chrono::Utc>> { Err(FieldErr("startTime")) }
/// A natural language summarization of the object encoded as HTML. Multiple language tagged summaries MAY be provided
fn summary(&self) -> Field<String> { Err(FieldErr("summary")) }
/// One or more "tags" that have been associated with an objects. A tag can be any kind of Object
/// The key difference between attachment and tag is that the former implies association by inclusion, while the latter implies associated by reference
// TODO technically this is an object? but spec says that it works my reference, idk
fn tag(&self) -> Node<Self::Link> { Node::Empty }
/// Identifies one or more links to representations of the object
fn url(&self) -> Node<Self::Link> { Node::Empty } fn url(&self) -> Node<Self::Link> { Node::Empty }
/// Identifies an entity considered to be part of the public primary audience of an Object
fn to(&self) -> Node<Self::Link> { Node::Empty } fn to(&self) -> Node<Self::Link> { Node::Empty }
/// Identifies an Object that is part of the private primary audience of this Object
fn bto(&self) -> Node<Self::Link> { Node::Empty } fn bto(&self) -> Node<Self::Link> { Node::Empty }
/// Identifies an Object that is part of the public secondary audience of this Object
fn cc(&self) -> Node<Self::Link> { Node::Empty } fn cc(&self) -> Node<Self::Link> { Node::Empty }
/// Identifies one or more Objects that are part of the private secondary audience of this Object
fn bcc(&self) -> Node<Self::Link> { Node::Empty } fn bcc(&self) -> Node<Self::Link> { Node::Empty }
/// When used on a Link, identifies the MIME media type of the referenced resource. fn media_type(&self) -> Option<&str> { None } // also in link
/// When used on an Object, identifies the MIME media type of the value of the content property. fn duration(&self) -> Option<&str> { None } // TODO how to parse xsd:duration ?
/// If not specified, the content property is assumed to contain text/html content.
fn media_type(&self) -> Field<String> { Err(FieldErr("mediaType")) } // also in link
/// When the object describes a time-bound resource, such as an audio or video, a meeting, etc, the duration property indicates the object's approximate duration.
/// The value MUST be expressed as an xsd:duration as defined by [ xmlschema11-2], section 3.3.6 (e.g. a period of 5 seconds is represented as "PT5S").
fn duration(&self) -> Field<String> { Err(FieldErr("duration")) } // TODO how to parse xsd:duration ?
#[cfg(feature = "activitypub-miscellaneous-terms")]
fn sensitive(&self) -> Field<bool> { Err(FieldErr("sensitive")) }
#[cfg(feature = "activitypub-miscellaneous-terms")]
fn quote_url(&self) -> Node<Self::Object> { Node::Empty }
#[cfg(feature = "activitypub-fe")]
fn liked_by_me(&self) -> Field<bool> { Err(FieldErr("likedByMe")) }
#[cfg(feature = "ostatus")]
fn conversation(&self) -> Node<Self::Object> { Node::Empty }
fn as_activity(&self) -> Result<&Self::Activity, FieldErr> { Err(FieldErr("type")) }
fn as_actor(&self) -> Result<&Self::Actor, FieldErr> { Err(FieldErr("type")) }
fn as_collection(&self) -> Result<&Self::Collection, FieldErr> { Err(FieldErr("type")) }
fn as_document(&self) -> Result<&Self::Document, FieldErr> { Err(FieldErr("type")) }
#[cfg(feature = "did-core")] // TODO this isn't from did-core actually!?!?!?!?!
fn value(&self) -> Field<String> { Err(FieldErr("value")) }
} }
pub trait ObjectMut : BaseMut { pub trait ObjectMut : BaseMut {
type Link : crate::Link; type Link : Link;
type Actor : crate::Actor; type Actor : Actor;
type Object : Object; type Object : Object;
type Collection : crate::Collection; type Collection : Collection;
type Document : crate::Document; type Document : Document;
fn set_object_type(self, val: Option<ObjectType>) -> Self; fn set_object_type(self, val: Option<ObjectType>) -> Self;
fn set_attachment(self, val: Node<Self::Object>) -> Self; fn set_attachment(self, val: Node<Self::Object>) -> Self;
fn set_attributed_to(self, val: Node<Self::Actor>) -> Self; fn set_attributed_to(self, val: Node<Self::Actor>) -> Self;
fn set_audience(self, val: Node<Self::Actor>) -> Self; fn set_audience(self, val: Node<Self::Actor>) -> Self;
fn set_content(self, val: Option<String>) -> Self; // TODO handle language maps fn set_content(self, val: Option<&str>) -> Self; // TODO handle language maps
fn set_context(self, val: Node<Self::Object>) -> Self; fn set_context(self, val: Node<Self::Object>) -> Self;
fn set_name(self, val: Option<String>) -> Self; // also in link // TODO handle language maps fn set_name(self, val: Option<&str>) -> Self; // also in link // TODO handle language maps
fn set_end_time(self, val: Option<chrono::DateTime<chrono::Utc>>) -> Self; fn set_end_time(self, val: Option<chrono::DateTime<chrono::Utc>>) -> Self;
fn set_generator(self, val: Node<Self::Actor>) -> Self; fn set_generator(self, val: Node<Self::Actor>) -> Self;
fn set_icon(self, val: Node<Self::Document>) -> Self; fn set_icon(self, val: Node<Self::Document>) -> Self;
@ -154,34 +90,18 @@ pub trait ObjectMut : BaseMut {
fn set_location(self, val: Node<Self::Object>) -> Self; fn set_location(self, val: Node<Self::Object>) -> Self;
fn set_preview(self, val: Node<Self::Object>) -> Self; // also in link fn set_preview(self, val: Node<Self::Object>) -> Self; // also in link
fn set_published(self, val: Option<chrono::DateTime<chrono::Utc>>) -> Self; fn set_published(self, val: Option<chrono::DateTime<chrono::Utc>>) -> Self;
fn set_updated(self, val: Option<chrono::DateTime<chrono::Utc>>) -> Self;
fn set_replies(self, val: Node<Self::Collection>) -> Self; fn set_replies(self, val: Node<Self::Collection>) -> Self;
fn set_likes(self, val: Node<Self::Collection>) -> Self;
fn set_shares(self, val: Node<Self::Collection>) -> Self;
fn set_start_time(self, val: Option<chrono::DateTime<chrono::Utc>>) -> Self; fn set_start_time(self, val: Option<chrono::DateTime<chrono::Utc>>) -> Self;
fn set_summary(self, val: Option<String>) -> Self; fn set_summary(self, val: Option<&str>) -> Self;
fn set_tag(self, val: Node<Self::Object>) -> Self; fn set_tag(self, val: Node<Self::Object>) -> Self;
fn set_updated(self, val: Option<chrono::DateTime<chrono::Utc>>) -> Self;
fn set_url(self, val: Node<Self::Link>) -> Self; fn set_url(self, val: Node<Self::Link>) -> Self;
fn set_to(self, val: Node<Self::Link>) -> Self; fn set_to(self, val: Node<Self::Link>) -> Self;
fn set_bto(self, val: Node<Self::Link>) -> Self; fn set_bto(self, val: Node<Self::Link>) -> Self;
fn set_cc(self, val: Node<Self::Link>) -> Self; fn set_cc(self, val: Node<Self::Link>) -> Self;
fn set_bcc(self, val: Node<Self::Link>) -> Self; fn set_bcc(self, val: Node<Self::Link>) -> Self;
fn set_media_type(self, val: Option<String>) -> Self; // also in link fn set_media_type(self, val: Option<&str>) -> Self; // also in link
fn set_duration(self, val: Option<String>) -> Self; // TODO how to parse xsd:duration ? fn set_duration(self, val: Option<&str>) -> Self; // TODO how to parse xsd:duration ?
#[cfg(feature = "activitypub-miscellaneous-terms")]
fn set_sensitive(self, val: Option<bool>) -> Self;
#[cfg(feature = "activitypub-miscellaneous-terms")]
fn set_quote_url(self, val: Node<Self::Object>) -> Self;
#[cfg(feature = "activitypub-fe")]
fn set_liked_by_me(self, val: Option<bool>) -> Self;
#[cfg(feature = "ostatus")]
fn set_conversation(self, val: Node<Self::Object>) -> Self;
#[cfg(feature = "did-core")] // TODO this isn't from did-core actually!?!?!?!?!
fn set_value(self, val: Option<String>) -> Self;
} }
#[cfg(feature = "unstructured")] #[cfg(feature = "unstructured")]
@ -191,78 +111,43 @@ impl Object for serde_json::Value {
type Object = serde_json::Value; type Object = serde_json::Value;
type Document = serde_json::Value; type Document = serde_json::Value;
type Collection = serde_json::Value; type Collection = serde_json::Value;
type Activity = serde_json::Value;
crate::getter! { objectType -> type ObjectType } crate::getter! { object_type -> type ObjectType }
crate::getter! { attachment -> node <Self as Object>::Object } crate::getter! { attachment -> node <Self as Object>::Object }
crate::getter! { attributedTo -> node Self::Actor } crate::getter! { attributed_to::attributedTo -> node Self::Actor }
crate::getter! { audience -> node Self::Actor } crate::getter! { audience -> node Self::Actor }
crate::getter! { content -> String } crate::getter! { content -> &str }
crate::getter! { context -> node <Self as Object>::Object } crate::getter! { name -> &str }
crate::getter! { name -> String } crate::getter! { end_time::endTime -> chrono::DateTime<chrono::Utc> }
crate::getter! { endTime -> chrono::DateTime<chrono::Utc> }
crate::getter! { generator -> node Self::Actor } crate::getter! { generator -> node Self::Actor }
crate::getter! { icon -> node Self::Document } crate::getter! { icon -> node Self::Document }
crate::getter! { image -> node Self::Document } crate::getter! { image -> node Self::Document }
crate::getter! { inReplyTo -> node <Self as Object>::Object } crate::getter! { in_reply_to::inReplyTo -> node <Self as Object>::Object }
crate::getter! { location -> node <Self as Object>::Object } crate::getter! { location -> node <Self as Object>::Object }
crate::getter! { preview -> node <Self as Object>::Object } crate::getter! { preview -> node <Self as Object>::Object }
crate::getter! { published -> chrono::DateTime<chrono::Utc> } crate::getter! { published -> chrono::DateTime<chrono::Utc> }
crate::getter! { updated -> chrono::DateTime<chrono::Utc> }
crate::getter! { replies -> node Self::Collection } crate::getter! { replies -> node Self::Collection }
crate::getter! { likes -> node Self::Collection } crate::getter! { start_time::startTime -> chrono::DateTime<chrono::Utc> }
crate::getter! { shares -> node Self::Collection } crate::getter! { summary -> &str }
crate::getter! { startTime -> chrono::DateTime<chrono::Utc> }
crate::getter! { summary -> String }
crate::getter! { tag -> node <Self as Object>::Object } crate::getter! { tag -> node <Self as Object>::Object }
crate::getter! { updated -> chrono::DateTime<chrono::Utc> }
crate::getter! { to -> node Self::Link } crate::getter! { to -> node Self::Link }
crate::getter! { bto -> node Self::Link } crate::getter! { bto -> node Self::Link }
crate::getter! { cc -> node Self::Link } crate::getter! { cc -> node Self::Link }
crate::getter! { bcc -> node Self::Link } crate::getter! { bcc -> node Self::Link }
crate::getter! { mediaType -> String } crate::getter! { media_type -> &str }
crate::getter! { duration -> String } crate::getter! { duration -> &str }
crate::getter! { url -> node Self::Link } crate::getter! { url -> node Self::Link }
#[cfg(feature = "activitypub-miscellaneous-terms")] // TODO Mastodon doesn't use a "context" field on the object but makes up a new one!!
crate::getter! { sensitive -> bool } fn context(&self) -> Node<<Self as Object>::Object> {
#[cfg(feature = "activitypub-miscellaneous-terms")] match self.get("context") {
crate::getter! { quoteUrl -> node <Self as Object>::Object } Some(x) => Node::from(x.clone()),
None => match self.get("conversation") {
#[cfg(feature = "activitypub-fe")] Some(x) => Node::from(x.clone()),
crate::getter! { likedByMe -> bool } None => Node::Empty,
#[cfg(feature = "ostatus")]
crate::getter! { conversation -> node <Self as Object>::Object }
#[cfg(feature = "did-core")] // TODO this isn't from did-core actually!?!?!?!?!
crate::getter! { value -> String }
fn as_activity(&self) -> Result<&Self::Activity, FieldErr> {
match self.object_type()? {
ObjectType::Activity(_) => Ok(self),
_ => Err(FieldErr("type")),
} }
} }
fn as_actor(&self) -> Result<&Self::Actor, FieldErr> {
match self.object_type()? {
ObjectType::Actor(_) => Ok(self),
_ => Err(FieldErr("type")),
}
}
fn as_collection(&self) -> Result<&Self::Collection, FieldErr> {
match self.object_type()? {
ObjectType::Collection(_) => Ok(self),
_ => Err(FieldErr("type")),
}
}
fn as_document(&self) -> Result<&Self::Document, FieldErr> {
match self.object_type()? {
ObjectType::Document(_) => Ok(self),
_ => Err(FieldErr("type")),
}
} }
} }
@ -276,45 +161,42 @@ impl ObjectMut for serde_json::Value {
crate::setter! { object_type -> type ObjectType } crate::setter! { object_type -> type ObjectType }
crate::setter! { attachment -> node <Self as Object>::Object } crate::setter! { attachment -> node <Self as Object>::Object }
crate::setter! { attributedTo -> node Self::Actor } crate::setter! { attributed_to::attributedTo -> node Self::Actor }
crate::setter! { audience -> node Self::Actor } crate::setter! { audience -> node Self::Actor }
crate::setter! { content -> String } crate::setter! { content -> &str }
crate::setter! { context -> node <Self as Object>::Object } crate::setter! { name -> &str }
crate::setter! { name -> String } crate::setter! { end_time::endTime -> chrono::DateTime<chrono::Utc> }
crate::setter! { endTime -> chrono::DateTime<chrono::Utc> }
crate::setter! { generator -> node Self::Actor } crate::setter! { generator -> node Self::Actor }
crate::setter! { icon -> node Self::Document } crate::setter! { icon -> node Self::Document }
crate::setter! { image -> node Self::Document } crate::setter! { image -> node Self::Document }
crate::setter! { inReplyTo -> node <Self as Object>::Object } crate::setter! { in_reply_to::inReplyTo -> node <Self as Object>::Object }
crate::setter! { location -> node <Self as Object>::Object } crate::setter! { location -> node <Self as Object>::Object }
crate::setter! { preview -> node <Self as Object>::Object } crate::setter! { preview -> node <Self as Object>::Object }
crate::setter! { published -> chrono::DateTime<chrono::Utc> } crate::setter! { published -> chrono::DateTime<chrono::Utc> }
crate::setter! { updated -> chrono::DateTime<chrono::Utc> }
crate::setter! { replies -> node Self::Collection } crate::setter! { replies -> node Self::Collection }
crate::setter! { likes -> node Self::Collection } crate::setter! { start_time::startTime -> chrono::DateTime<chrono::Utc> }
crate::setter! { shares -> node Self::Collection } crate::setter! { summary -> &str }
crate::setter! { startTime -> chrono::DateTime<chrono::Utc> }
crate::setter! { summary -> String }
crate::setter! { tag -> node <Self as Object>::Object } crate::setter! { tag -> node <Self as Object>::Object }
crate::setter! { updated -> chrono::DateTime<chrono::Utc> }
crate::setter! { to -> node Self::Link } crate::setter! { to -> node Self::Link }
crate::setter! { bto -> node Self::Link} crate::setter! { bto -> node Self::Link}
crate::setter! { cc -> node Self::Link } crate::setter! { cc -> node Self::Link }
crate::setter! { bcc -> node Self::Link } crate::setter! { bcc -> node Self::Link }
crate::setter! { mediaType -> String } crate::setter! { media_type -> &str }
crate::setter! { duration -> String } crate::setter! { duration -> &str }
crate::setter! { url -> node Self::Link } crate::setter! { url -> node Self::Link }
#[cfg(feature = "activitypub-miscellaneous-terms")] // TODO Mastodon doesn't use a "context" field on the object but makes up a new one!!
crate::setter! { sensitive -> bool } fn set_context(mut self, ctx: Node<<Self as Object>::Object>) -> Self {
#[cfg(feature = "activitypub-miscellaneous-terms")] if let Some(conversation) = ctx.id() {
crate::setter! { quoteUrl -> node <Self as Object>::Object } crate::macros::set_maybe_value(
&mut self, "conversation", Some(serde_json::Value::String(conversation)),
);
}
crate::macros::set_maybe_node(
&mut self, "context", ctx
);
self
}
#[cfg(feature = "activitypub-fe")]
crate::setter! { likedByMe -> bool }
#[cfg(feature = "ostatus")]
crate::setter! { conversation -> node <Self as Object>::Object }
#[cfg(feature = "did-core")] // TODO this isn't from did-core actually!?!?!?!?!
crate::setter! { value -> String }
} }

View file

@ -1,12 +1,10 @@
use crate::{Field, FieldErr};
pub trait Place : super::Object { pub trait Place : super::Object {
fn accuracy(&self) -> Field<f64> { Err(FieldErr("accuracy")) } fn accuracy(&self) -> Option<f64> { None }
fn altitude(&self) -> Field<f64> { Err(FieldErr("altitude")) } fn altitude(&self) -> Option<f64> { None }
fn latitude(&self) -> Field<f64> { Err(FieldErr("latitude")) } fn latitude(&self) -> Option<f64> { None }
fn longitude(&self) -> Field<f64> { Err(FieldErr("longitude")) } fn longitude(&self) -> Option<f64> { None }
fn radius(&self) -> Field<f64> { Err(FieldErr("radius")) } fn radius(&self) -> Option<f64> { None }
fn units(&self) -> Field<&str> { Err(FieldErr("units")) } fn units(&self) -> Option<&str> { None }
} }
pub trait PlaceMut : super::ObjectMut { pub trait PlaceMut : super::ObjectMut {

View file

@ -1,6 +1,6 @@
pub trait Tombstone : super::Object { pub trait Tombstone : super::Object {
fn former_type(&self) -> crate::Field<crate::BaseType> { Err(crate::FieldErr("formerType")) } fn former_type(&self) -> Option<crate::BaseType> { None }
fn deleted(&self) -> crate::Field<chrono::DateTime<chrono::Utc>> { Err(crate::FieldErr("deleted")) } fn deleted(&self) -> Option<chrono::DateTime<chrono::Utc>> { None }
} }
pub trait TombstoneMut : super::ObjectMut { pub trait TombstoneMut : super::ObjectMut {

284
main.rs
View file

@ -1,284 +0,0 @@
use std::path::PathBuf;
use clap::{Parser, Subcommand};
use sea_orm::{ConnectOptions, Database};
use signal_hook::consts::signal::*;
use signal_hook_tokio::Signals;
use futures::stream::StreamExt;
use upub::{context, ext::LoggableError};
#[cfg(feature = "cli")]
use upub_cli as cli;
#[cfg(feature = "migrate")]
use upub_migrations as migrations;
#[cfg(feature = "serve")]
use upub_routes as routes;
#[cfg(feature = "worker")]
use upub_worker as worker;
#[derive(Parser)]
/// all names were taken
struct Args {
#[clap(subcommand)]
/// command to run
command: Mode,
/// path to config file, leave empty to not use any
#[arg(short, long)]
config: Option<PathBuf>,
#[arg(long = "db")]
/// database connection uri, overrides config value
database: Option<String>,
#[arg(long)]
/// instance base domain, for AP ids, overrides config value
domain: Option<String>,
#[arg(long, default_value_t=false)]
/// run with debug level tracing
debug: bool,
#[arg(long)]
/// force set number of worker threads for async runtime, defaults to number of cores
threads: Option<usize>,
}
#[derive(Clone, Subcommand)]
enum Mode {
/// print current or default configuration
Config,
#[cfg(feature = "migrate")]
/// apply database migrations
Migrate,
#[cfg(feature = "cli")]
/// run maintenance CLI tasks
Cli {
#[clap(subcommand)]
/// task to run
command: cli::CliCommand,
},
#[cfg(all(feature = "serve", feature = "worker"))]
/// start both api routes and background workers
Monolith {
#[arg(short, long, default_value="127.0.0.1:3000")]
/// addr to bind and serve onto
bind: String,
#[arg(short, long, default_value_t = 4)]
/// how many concurrent jobs to process with this worker
tasks: usize,
#[arg(short, long, default_value_t = 20)]
/// interval for polling new tasks
poll: u64,
},
#[cfg(feature = "serve")]
/// start api routes server
Serve {
#[arg(short, long, default_value="127.0.0.1:3000")]
/// addr to bind and serve onto
bind: String,
},
#[cfg(feature = "worker")]
/// start background job worker
Work {
/// only run tasks of this type, run all if not given
filter: Filter,
/// how many concurrent jobs to process with this worker
#[arg(short, long, default_value_t = 4)]
tasks: usize,
#[arg(short, long, default_value_t = 20)]
/// interval for polling new tasks
poll: u64,
},
}
fn main() {
let args = Args::parse();
tracing_subscriber::fmt()
.compact()
.with_max_level(if args.debug { tracing::Level::DEBUG } else { tracing::Level::INFO })
.init();
let config = upub::Config::load(args.config.as_ref());
if matches!(args.command, Mode::Config) {
println!("{}", toml::to_string_pretty(&config).expect("failed serializing config"));
return;
}
let mut runtime = tokio::runtime::Builder::new_multi_thread();
if let Some(threads) = args.threads {
runtime.worker_threads(threads);
}
runtime
.enable_io()
.enable_time()
.thread_name("upub-worker")
.build()
.expect("failed creating tokio async runtime")
.block_on(async { init(args, config).await })
}
async fn init(args: Args, config: upub::Config) {
let database = args.database.unwrap_or(config.datasource.connection_string.clone());
let domain = args.domain.unwrap_or(config.instance.domain.clone());
// TODO can i do connectoptions.into() or .connect() and skip these ugly bindings?
let mut opts = ConnectOptions::new(&database);
opts
.sqlx_logging(true)
.sqlx_logging_level(tracing::log::LevelFilter::Debug)
.max_connections(config.datasource.max_connections)
.min_connections(config.datasource.min_connections)
.acquire_timeout(std::time::Duration::from_secs(config.datasource.acquire_timeout_seconds))
.connect_timeout(std::time::Duration::from_secs(config.datasource.connect_timeout_seconds))
.sqlx_slow_statements_logging_settings(
if config.datasource.slow_query_warn_enable { tracing::log::LevelFilter::Warn } else { tracing::log::LevelFilter::Debug },
std::time::Duration::from_secs(config.datasource.slow_query_warn_seconds)
);
let db = Database::connect(opts)
.await.expect("error connecting to db");
#[cfg(feature = "migrate")]
if matches!(args.command, Mode::Migrate) {
use migrations::MigratorTrait;
migrations::Migrator::up(&db, None)
.await
.expect("error applying migrations");
return;
}
let (tx_wake, rx_wake) = tokio::sync::mpsc::unbounded_channel();
let wake = WakeToken(rx_wake);
let ctx = upub::Context::new(db, domain, config.clone(), Some(Box::new(WakerToken(tx_wake))))
.await.expect("failed creating server context");
#[cfg(feature = "cli")]
if let Mode::Cli { command } = args.command {
cli::run(ctx, command)
.await.expect("failed running cli task");
return;
}
// register signal handler only for long-lasting modes, such as server or worker
let (tx, rx) = tokio::sync::watch::channel(false);
let signals = Signals::new([SIGTERM, SIGINT]).expect("failed registering signal handler");
let handle = signals.handle();
let signals_task = tokio::spawn(handle_signals(signals, tx));
let stop = CancellationToken(rx);
match args.command {
#[cfg(feature = "serve")]
Mode::Serve { bind } =>
routes::serve(ctx, bind, stop)
.await.expect("failed serving api routes"),
#[cfg(feature = "worker")]
Mode::Work { filter, tasks, poll } =>
worker::spawn(ctx, tasks, poll, filter.into(), stop, wake)
.await.expect("failed running worker"),
#[cfg(all(feature = "serve", feature = "worker"))]
Mode::Monolith { bind, tasks, poll } => {
worker::spawn(ctx.clone(), tasks, poll, None, stop.clone(), wake);
routes::serve(ctx, bind, stop)
.await.expect("failed serving api routes");
},
Mode::Config => unreachable!(),
#[cfg(feature = "migrate")]
Mode::Migrate => unreachable!(),
#[cfg(feature = "cli")]
Mode::Cli { .. } => unreachable!(),
}
handle.close();
signals_task.await.expect("failed joining signal handler task");
}
struct WakerToken(tokio::sync::mpsc::UnboundedSender<()>);
impl context::WakerToken for WakerToken {
fn wake(&self) {
self.0.send(()).warn_failed("failed waking up workers");
}
}
struct WakeToken(tokio::sync::mpsc::UnboundedReceiver<()>);
impl worker::WakeToken for WakeToken {
async fn wait(&mut self) {
let _ = self.0.recv().await;
}
}
#[derive(Clone)]
struct CancellationToken(tokio::sync::watch::Receiver<bool>);
impl worker::StopToken for CancellationToken {
fn stop(&self) -> bool {
*self.0.borrow()
}
}
impl routes::ShutdownToken for CancellationToken {
async fn event(mut self) {
self.0.changed().await.warn_failed("cancellation token channel closed, stopping...");
}
}
async fn handle_signals(
mut signals: signal_hook_tokio::Signals,
tx: tokio::sync::watch::Sender<bool>,
) {
while let Some(signal) = signals.next().await {
match signal {
SIGTERM | SIGINT => {
tracing::info!("received stop signal, closing tasks");
tx.send(true).info_failed("error sending stop signal to tasks")
},
_ => unreachable!(),
}
}
}
#[derive(Debug, Clone, clap::ValueEnum)]
enum Filter {
All,
Delivery,
Inbound,
Outbound,
}
impl From<Filter> for Option<upub::model::job::JobType> {
fn from(value: Filter) -> Self {
match value {
Filter::All => None,
Filter::Delivery => Some(upub::model::job::JobType::Delivery),
Filter::Inbound => Some(upub::model::job::JobType::Inbound),
Filter::Outbound => Some(upub::model::job::JobType::Outbound),
}
}
}

89
src/errors.rs Normal file
View file

@ -0,0 +1,89 @@
#[derive(Debug, thiserror::Error)]
pub enum UpubError {
#[error("database error: {0}")]
Database(#[from] sea_orm::DbErr),
#[error("api returned {0}")]
Status(axum::http::StatusCode),
#[error("missing field: {0}")]
Field(#[from] crate::model::FieldError),
#[error("openssl error: {0}")]
OpenSSL(#[from] openssl::error::ErrorStack),
#[error("invalid UTF8 in key: {0}")]
OpenSSLParse(#[from] std::str::Utf8Error),
#[error("fetch error: {0}")]
Reqwest(#[from] reqwest::Error),
}
impl UpubError {
pub fn bad_request() -> Self {
Self::Status(axum::http::StatusCode::BAD_REQUEST)
}
pub fn unprocessable() -> Self {
Self::Status(axum::http::StatusCode::UNPROCESSABLE_ENTITY)
}
pub fn not_found() -> Self {
Self::Status(axum::http::StatusCode::NOT_FOUND)
}
pub fn forbidden() -> Self {
Self::Status(axum::http::StatusCode::FORBIDDEN)
}
pub fn not_modified() -> Self {
Self::Status(axum::http::StatusCode::NOT_MODIFIED)
}
pub fn internal_server_error() -> Self {
Self::Status(axum::http::StatusCode::INTERNAL_SERVER_ERROR)
}
}
pub type UpubResult<T> = Result<T, UpubError>;
impl From<axum::http::StatusCode> for UpubError {
fn from(value: axum::http::StatusCode) -> Self {
UpubError::Status(value)
}
}
impl axum::response::IntoResponse for UpubError {
fn into_response(self) -> axum::response::Response {
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
self.to_string()
).into_response()
}
}
pub trait LoggableError {
fn info_failed(self, msg: &str);
fn warn_failed(self, msg: &str);
fn err_failed(self, msg: &str);
}
impl<T, E: std::error::Error> LoggableError for Result<T, E> {
fn info_failed(self, msg: &str) {
if let Err(e) = self {
tracing::info!("{} : {}", msg, e);
}
}
fn warn_failed(self, msg: &str) {
if let Err(e) = self {
tracing::warn!("{} : {}", msg, e);
}
}
fn err_failed(self, msg: &str) {
if let Err(e) = self {
tracing::error!("{} : {}", msg, e);
}
}
}

159
src/main.rs Normal file
View file

@ -0,0 +1,159 @@
pub mod server;
pub mod model;
pub mod routes;
pub mod tools;
pub mod errors;
#[cfg(feature = "migrations")]
mod migrations;
#[cfg(feature = "migrations")]
use sea_orm_migration::MigratorTrait;
use clap::{Parser, Subcommand};
use sea_orm::{ConnectOptions, Database, EntityTrait, IntoActiveModel};
pub use errors::UpubResult as Result;
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
#[derive(Parser)]
/// all names were taken
struct CliArgs {
#[clap(subcommand)]
/// command to run
command: CliCommand,
#[arg(short = 'd', long = "db", default_value = "sqlite://./upub.db")]
/// database connection uri
database: String,
#[arg(short = 'D', long, default_value = "http://localhost:3000")]
/// instance base domain, for AP ids
domain: String,
#[arg(long, default_value_t=false)]
/// run with debug level tracing
debug: bool,
}
#[derive(Clone, Subcommand)]
enum CliCommand {
/// run fediverse server
Serve ,
#[cfg(feature = "migrations")]
/// apply database migrations
Migrate,
#[cfg(feature = "faker")]
/// generate fake user, note and activity
Faker{
/// how many fake statuses to insert for root user
count: u64,
},
/// fetch a single AP object
Fetch {
/// object id, or uri, to fetch
uri: String,
#[arg(long, default_value_t = false)]
/// store fetched object in local db
save: bool,
},
}
#[tokio::main]
async fn main() {
let args = CliArgs::parse();
tracing_subscriber::fmt()
.compact()
.with_max_level(if args.debug { tracing::Level::DEBUG } else { tracing::Level::INFO })
.init();
// TODO can i do connectoptions.into() or .connect() and skip these ugly bindings?
let mut opts = ConnectOptions::new(&args.database);
opts
.sqlx_logging_level(tracing::log::LevelFilter::Debug);
let db = Database::connect(opts)
.await.expect("error connecting to db");
match args.command {
#[cfg(feature = "migrations")]
CliCommand::Migrate => migrations::Migrator::up(&db, None)
.await.expect("error applying migrations"),
#[cfg(feature = "faker")]
CliCommand::Faker { count } => model::faker::faker(&db, args.domain, count)
.await.expect("error creating fake entities"),
CliCommand::Fetch { uri, save } => fetch(&db, &uri, save)
.await.expect("error fetching object"),
CliCommand::Serve => {
let ctx = server::Context::new(db, args.domain)
.await.expect("failed creating server context");
use routes::activitypub::ActivityPubRouter;
use routes::mastodon::MastodonRouter;
let router = axum::Router::new()
.ap_routes()
.mastodon_routes() // no-op if mastodon feature is disabled
.with_state(ctx);
// run our app with hyper, listening locally on port 3000
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await.expect("could not bind tcp socket");
axum::serve(listener, router)
.await
.expect("failed serving application")
},
}
}
async fn fetch(db: &sea_orm::DatabaseConnection, uri: &str, save: bool) -> reqwest::Result<()> {
use apb::{Base, Object};
let mut node = apb::Node::from(uri);
tracing::info!("fetching object");
node.fetch().await?;
tracing::info!("fetched node");
let obj = node.get().expect("node still empty after fetch?");
tracing::info!("fetched object:{}, name:{}", obj.id().unwrap_or(""), obj.name().unwrap_or(""));
if save {
match obj.base_type() {
Some(apb::BaseType::Object(apb::ObjectType::Actor(_))) => {
model::user::Entity::insert(
model::user::Model::new(obj).unwrap().into_active_model()
).exec(db).await.unwrap();
},
Some(apb::BaseType::Object(apb::ObjectType::Activity(_))) => {
model::activity::Entity::insert(
model::activity::Model::new(obj).unwrap().into_active_model()
).exec(db).await.unwrap();
},
Some(apb::BaseType::Object(apb::ObjectType::Note)) => {
model::object::Entity::insert(
model::object::Model::new(obj).unwrap().into_active_model()
).exec(db).await.unwrap();
},
Some(apb::BaseType::Object(t)) => tracing::warn!("not implemented: {:?}", t),
Some(apb::BaseType::Link(_)) => tracing::error!("fetched another link?"),
None => tracing::error!("no type on object"),
}
}
Ok(())
}

3
src/migrations/README.md Normal file
View file

@ -0,0 +1,3 @@
# migrations
there are sea_orm migrations to apply to your database

View file

@ -0,0 +1,167 @@
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Users::Table)
.col(
ColumnDef::new(Users::Id)
.string()
.not_null()
.primary_key()
)
.col(ColumnDef::new(Users::ActorType).string().not_null())
.col(ColumnDef::new(Users::Domain).string().not_null())
.col(ColumnDef::new(Users::Name).string().not_null())
.col(ColumnDef::new(Users::Summary).string().null())
.col(ColumnDef::new(Users::Image).string().null())
.col(ColumnDef::new(Users::Icon).string().null())
.col(ColumnDef::new(Users::PreferredUsername).string().null())
.col(ColumnDef::new(Users::Inbox).string().null())
.col(ColumnDef::new(Users::SharedInbox).string().null())
.col(ColumnDef::new(Users::Outbox).string().null())
.col(ColumnDef::new(Users::Following).string().null())
.col(ColumnDef::new(Users::Followers).string().null())
.col(ColumnDef::new(Users::FollowingCount).integer().not_null().default(0))
.col(ColumnDef::new(Users::FollowersCount).integer().not_null().default(0))
.col(ColumnDef::new(Users::PublicKey).string().not_null())
.col(ColumnDef::new(Users::PrivateKey).string().null())
.col(ColumnDef::new(Users::Created).date_time().not_null())
.col(ColumnDef::new(Users::Updated).date_time().not_null())
.to_owned()
)
.await?;
manager
.create_table(
Table::create()
.table(Activities::Table)
.col(
ColumnDef::new(Activities::Id)
.string()
.not_null()
.primary_key()
)
.col(ColumnDef::new(Activities::ActivityType).string().not_null())
.col(ColumnDef::new(Activities::Actor).string().not_null())
.col(ColumnDef::new(Activities::Object).string().null())
.col(ColumnDef::new(Activities::Target).string().null())
.col(ColumnDef::new(Activities::To).json().null())
.col(ColumnDef::new(Activities::Bto).json().null())
.col(ColumnDef::new(Activities::Cc).json().null())
.col(ColumnDef::new(Activities::Bcc).json().null())
.col(ColumnDef::new(Activities::Published).date_time().not_null())
.to_owned()
).await?;
manager
.create_table(
Table::create()
.table(Objects::Table)
.col(
ColumnDef::new(Objects::Id)
.string()
.not_null()
.primary_key()
)
.col(ColumnDef::new(Objects::ObjectType).string().not_null())
.col(ColumnDef::new(Objects::AttributedTo).string().null())
.col(ColumnDef::new(Objects::Name).string().null())
.col(ColumnDef::new(Objects::Summary).string().null())
.col(ColumnDef::new(Objects::Content).string().null())
.col(ColumnDef::new(Objects::Likes).integer().not_null().default(0))
.col(ColumnDef::new(Objects::Shares).integer().not_null().default(0))
.col(ColumnDef::new(Objects::Comments).integer().not_null().default(0))
.col(ColumnDef::new(Objects::Context).string().null())
.col(ColumnDef::new(Objects::To).json().null())
.col(ColumnDef::new(Objects::Bto).json().null())
.col(ColumnDef::new(Objects::Cc).json().null())
.col(ColumnDef::new(Objects::Bcc).json().null())
.col(ColumnDef::new(Objects::Published).string().not_null())
.to_owned()
).await?;
Ok(())
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Users::Table).to_owned())
.await?;
manager
.drop_table(Table::drop().table(Activities::Table).to_owned())
.await?;
manager
.drop_table(Table::drop().table(Objects::Table).to_owned())
.await?;
Ok(())
}
}
#[derive(DeriveIden)]
enum Users {
Table,
Id,
Domain,
ActorType,
Name,
Summary,
Image,
Icon,
PreferredUsername,
Inbox,
SharedInbox,
Outbox,
Following,
FollowingCount,
Followers,
FollowersCount,
PublicKey,
PrivateKey,
Created,
Updated,
}
#[derive(DeriveIden)]
enum Activities {
Table,
Id,
ActivityType,
Actor,
Object,
Target,
Cc,
Bcc,
To,
Bto,
Published,
}
#[derive(DeriveIden)]
enum Objects {
Table,
Id,
ObjectType,
AttributedTo,
Name,
Summary,
Content,
Likes,
Shares,
Comments,
Context,
Cc,
Bcc,
To,
Bto,
Published,
}

View file

@ -0,0 +1,44 @@
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Relations::Table)
.col(
ColumnDef::new(Relations::Id)
.integer()
.auto_increment()
.not_null()
.primary_key()
)
.col(ColumnDef::new(Relations::Follower).string().not_null())
.col(ColumnDef::new(Relations::Following).string().not_null())
.to_owned()
)
.await?;
Ok(())
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Relations::Table).to_owned())
.await?;
Ok(())
}
}
#[derive(DeriveIden)]
enum Relations {
Table,
Id,
Follower,
Following,
}

View file

@ -0,0 +1,80 @@
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Likes::Table)
.col(
ColumnDef::new(Likes::Id)
.integer()
.auto_increment()
.not_null()
.primary_key()
)
.col(ColumnDef::new(Likes::Actor).string().not_null())
.col(ColumnDef::new(Likes::Likes).string().not_null())
.col(ColumnDef::new(Likes::Date).date_time().not_null())
.to_owned()
)
.await?;
manager
.create_table(
Table::create()
.table(Shares::Table)
.col(
ColumnDef::new(Shares::Id)
.integer()
.auto_increment()
.not_null()
.primary_key()
)
.col(ColumnDef::new(Shares::Actor).string().not_null())
.col(ColumnDef::new(Shares::Shares).string().not_null())
.col(ColumnDef::new(Shares::Date).date_time().not_null())
.to_owned()
)
.await?;
Ok(())
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Likes::Table).to_owned())
.await?;
manager
.drop_table(Table::drop().table(Shares::Table).to_owned())
.await?;
Ok(())
}
}
#[derive(DeriveIden)]
#[allow(clippy::enum_variant_names)]
enum Likes {
Table,
Id,
Actor,
Likes,
Date,
}
#[derive(DeriveIden)]
#[allow(clippy::enum_variant_names)]
enum Shares {
Table,
Id,
Actor,
Shares,
Date,
}

View file

@ -0,0 +1,176 @@
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_index(
Index::create()
.name("user-domain-index")
.table(Users::Table)
.col(Users::Domain)
.to_owned()
)
.await?;
manager
.create_index(
Index::create()
.name("activities-published-descending-index")
.table(Activities::Table)
.col((Activities::Published, IndexOrder::Desc))
.to_owned()
)
.await?;
manager
.create_index(
Index::create()
.name("activities-actor-index")
.table(Activities::Table)
.col(Activities::Actor)
.to_owned()
)
.await?;
manager
.create_index(
Index::create()
.name("activities-object-index")
.table(Activities::Table)
.col(Activities::Object)
.to_owned()
).await?;
manager
.create_index(
Index::create()
.name("objects-attributed-to-index")
.table(Objects::Table)
.col(Objects::AttributedTo)
.to_owned()
).await?;
manager
.create_index(
Index::create()
.name("shares-actor-index")
.table(Shares::Table)
.col(Shares::Actor)
.to_owned()
).await?;
manager
.create_index(
Index::create()
.name("shares-shares-index")
.table(Shares::Table)
.col(Shares::Shares)
.to_owned()
).await?;
manager
.create_index(
Index::create()
.name("likes-actor-index")
.table(Likes::Table)
.col(Likes::Actor)
.to_owned()
).await?;
manager
.create_index(
Index::create()
.name("likes-likes-index")
.table(Likes::Table)
.col(Likes::Likes)
.to_owned()
).await?;
manager
.create_index(
Index::create()
.name("likes-actor-likes-index")
.table(Likes::Table)
.col(Likes::Actor)
.col(Likes::Likes)
.unique()
.to_owned()
).await?;
Ok(())
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_index(Index::drop().name("user-domain-index").to_owned())
.await?;
manager
.drop_index(Index::drop().name("activities-published-descending-index").to_owned())
.await?;
manager
.drop_index(Index::drop().name("activities-actor-index").to_owned())
.await?;
manager
.drop_index(Index::drop().name("activities-object-index").to_owned())
.await?;
manager
.drop_index(Index::drop().name("objects-attributed-to-index").to_owned())
.await?;
manager
.drop_index(Index::drop().name("shares-actor-index").to_owned())
.await?;
manager
.drop_index(Index::drop().name("shares-shares-index").to_owned())
.await?;
manager
.drop_index(Index::drop().name("likes-actor-index").to_owned())
.await?;
manager
.drop_index(Index::drop().name("likes-likes-index").to_owned())
.await?;
manager
.drop_index(Index::drop().name("likes-actor-likes-index").to_owned())
.await?;
Ok(())
}
}
#[derive(DeriveIden)]
#[allow(clippy::enum_variant_names)]
enum Likes {
Table,
Actor,
Likes,
}
#[derive(DeriveIden)]
#[allow(clippy::enum_variant_names)]
enum Shares {
Table,
Actor,
Shares,
}
#[derive(DeriveIden)]
enum Users {
Table,
Domain,
}
#[derive(DeriveIden)]
enum Activities {
Table,
Actor,
Object,
Published,
}
#[derive(DeriveIden)]
enum Objects {
Table,
AttributedTo,
}

View file

@ -0,0 +1,49 @@
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Configs::Table)
.col(
ColumnDef::new(Configs::Id)
.string()
.not_null()
.primary_key()
)
.col(ColumnDef::new(Configs::AcceptFollowRequests).boolean().not_null())
.col(ColumnDef::new(Configs::ShowFollowersCount).boolean().not_null())
.col(ColumnDef::new(Configs::ShowFollowingCount).boolean().not_null())
.col(ColumnDef::new(Configs::ShowFollowers).boolean().not_null())
.col(ColumnDef::new(Configs::ShowFollowing).boolean().not_null())
.to_owned()
)
.await?;
Ok(())
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Configs::Table).to_owned())
.await?;
Ok(())
}
}
#[derive(DeriveIden)]
enum Configs {
Table,
Id,
AcceptFollowRequests,
ShowFollowersCount,
ShowFollowingCount,
ShowFollowers,
ShowFollowing,
}

View file

@ -0,0 +1,67 @@
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Credentials::Table)
.col(
ColumnDef::new(Credentials::Id)
.string()
.not_null()
.primary_key()
)
.col(ColumnDef::new(Credentials::Email).string().not_null())
.col(ColumnDef::new(Credentials::Password).string().not_null())
.to_owned()
)
.await?;
manager
.create_table(
Table::create()
.table(Sessions::Table)
.col(
ColumnDef::new(Sessions::Id)
.string()
.not_null()
.primary_key()
)
.col(ColumnDef::new(Sessions::Actor).string().not_null())
.col(ColumnDef::new(Sessions::Expires).date_time().not_null())
.to_owned()
)
.await?;
Ok(())
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Credentials::Table).to_owned())
.await?;
Ok(())
}
}
#[derive(DeriveIden)]
enum Credentials {
Table,
Id,
Email,
Password,
}
#[derive(DeriveIden)]
enum Sessions {
Table,
Id, // TODO here ID is the session "secret" but in Credentials it's the actor ID (String) ??? weird!!
Actor,
Expires,
}

View file

@ -0,0 +1,110 @@
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Addressing::Table)
.col(
ColumnDef::new(Addressing::Id)
.integer()
.not_null()
.auto_increment()
.primary_key()
)
.col(ColumnDef::new(Addressing::Actor).string().not_null())
.col(ColumnDef::new(Addressing::Server).string().not_null())
.col(ColumnDef::new(Addressing::Activity).string().not_null())
.col(ColumnDef::new(Addressing::Object).string().null())
.col(ColumnDef::new(Addressing::Published).date_time().not_null())
.to_owned()
)
.await?;
// TODO these indexes may not be ordered, killing out timeline query performance
// it may be necessary to include datetime in the index itself? or maybe specify
// some ordering to use another type of indes?
manager
.create_index(
Index::create()
.name("addressing-actor-index")
.table(Addressing::Table)
.col(Addressing::Actor)
.to_owned()
)
.await?;
manager
.create_index(
Index::create()
.name("addressing-server-index")
.table(Addressing::Table)
.col(Addressing::Server)
.to_owned()
)
.await?;
manager
.create_index(
Index::create()
.name("addressing-activity-index")
.table(Addressing::Table)
.col(Addressing::Activity)
.to_owned()
)
.await?;
manager
.create_index(
Index::create()
.name("addressing-object-index")
.table(Addressing::Table)
.col(Addressing::Object)
.to_owned()
)
.await?;
Ok(())
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Addressing::Table).to_owned())
.await?;
manager
.drop_index(Index::drop().name("addressing-actor-index").to_owned())
.await?;
manager
.drop_index(Index::drop().name("addressing-server-index").to_owned())
.await?;
manager
.drop_index(Index::drop().name("addressing-activity-index").to_owned())
.await?;
manager
.drop_index(Index::drop().name("addressing-object-index").to_owned())
.await?;
Ok(())
}
}
#[derive(DeriveIden)]
enum Addressing {
Table,
Id,
Actor,
Server,
Activity,
Object,
Published,
}

View file

@ -0,0 +1,66 @@
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Deliveries::Table)
.col(
ColumnDef::new(Deliveries::Id)
.integer()
.not_null()
.auto_increment()
.primary_key()
)
.col(ColumnDef::new(Deliveries::Actor).string().not_null())
.col(ColumnDef::new(Deliveries::Target).string().not_null())
.col(ColumnDef::new(Deliveries::Activity).string().not_null())
.col(ColumnDef::new(Deliveries::Created).date_time().not_null())
.col(ColumnDef::new(Deliveries::NotBefore).date_time().not_null())
.col(ColumnDef::new(Deliveries::Attempt).integer().not_null())
.to_owned()
)
.await?;
manager
.create_index(
Index::create()
.name("deliveries-notbefore-index")
.table(Deliveries::Table)
.col((Deliveries::NotBefore, IndexOrder::Asc))
.to_owned()
)
.await?;
Ok(())
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Deliveries::Table).to_owned())
.await?;
manager
.drop_index(Index::drop().name("deliveries-notbefore-index").to_owned())
.await?;
Ok(())
}
}
#[derive(DeriveIden)]
enum Deliveries {
Table,
Id,
Actor,
Target,
Activity,
Created,
NotBefore,
Attempt,
}

View file

@ -0,0 +1,46 @@
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Application::Table)
.col(
ColumnDef::new(Application::Id)
.integer()
.not_null()
.auto_increment()
.primary_key()
)
.col(ColumnDef::new(Application::PrivateKey).string().not_null())
.col(ColumnDef::new(Application::PublicKey).string().not_null())
.col(ColumnDef::new(Application::Created).date_time().not_null())
.to_owned()
)
.await?;
Ok(())
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Application::Table).to_owned())
.await?;
Ok(())
}
}
#[derive(DeriveIden)]
enum Application {
Table,
Id,
PrivateKey,
PublicKey,
Created,
}

30
src/migrations/mod.rs Normal file
View file

@ -0,0 +1,30 @@
use sea_orm_migration::prelude::*;
mod m20240316_000001_create_table;
mod m20240322_000001_create_relations;
mod m20240322_000002_add_likes_shares;
mod m20240322_000003_add_indexes;
mod m20240323_000001_add_user_configs;
mod m20240323_000002_add_simple_credentials;
mod m20240324_000001_add_addressing;
mod m20240325_000001_add_deliveries;
mod m20240325_000002_add_system_key;
pub struct Migrator;
#[async_trait::async_trait]
impl MigratorTrait for Migrator {
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
vec![
Box::new(m20240316_000001_create_table::Migration),
Box::new(m20240322_000001_create_relations::Migration),
Box::new(m20240322_000002_add_likes_shares::Migration),
Box::new(m20240322_000003_add_indexes::Migration),
Box::new(m20240323_000001_add_user_configs::Migration),
Box::new(m20240323_000002_add_simple_credentials::Migration),
Box::new(m20240324_000001_add_addressing::Migration),
Box::new(m20240325_000001_add_deliveries::Migration),
Box::new(m20240325_000002_add_system_key::Migration),
]
}
}

83
src/model/activity.rs Normal file
View file

@ -0,0 +1,83 @@
use sea_orm::entity::prelude::*;
use super::Audience;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "activities")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: String,
pub activity_type: apb::ActivityType,
pub actor: String,
pub object: Option<String>,
pub target: Option<String>, // TODO relates to USER maybe??
pub cc: Audience,
pub bcc: Audience,
pub to: Audience,
pub bto: Audience,
pub published: ChronoDateTimeUtc,
// TODO: origin, result, instrument
}
impl Model {
pub fn new(activity: &impl apb::Activity) -> Result<Self, super::FieldError> {
Ok(Model {
id: activity.id().ok_or(super::FieldError("id"))?.to_string(),
activity_type: activity.activity_type().ok_or(super::FieldError("type"))?,
actor: activity.actor().id().ok_or(super::FieldError("actor"))?,
object: activity.object().id(),
target: activity.target().id(),
published: activity.published().unwrap_or(chrono::Utc::now()),
to: activity.to().into(),
bto: activity.bto().into(),
cc: activity.cc().into(),
bcc: activity.bcc().into(),
})
}
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::user::Entity",
from = "Column::Actor",
to = "super::user::Column::Id"
)]
User,
#[sea_orm(
belongs_to = "super::object::Entity",
from = "Column::Object",
to = "super::object::Column::Id"
)]
Object,
#[sea_orm(has_many = "super::addressing::Entity")]
Addressing,
#[sea_orm(has_many = "super::delivery::Entity")]
Delivery,
}
impl Related<super::user::Entity> for Entity {
fn to() -> RelationDef {
Relation::User.def()
}
}
impl Related<super::object::Entity> for Entity {
fn to() -> RelationDef {
Relation::Object.def()
}
}
impl Related<super::addressing::Entity> for Entity {
fn to() -> RelationDef {
Relation::Addressing.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

57
src/model/addressing.rs Normal file
View file

@ -0,0 +1,57 @@
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "addressing")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub actor: String,
pub server: String,
pub activity: String,
pub object: Option<String>,
pub published: ChronoDateTimeUtc,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::user::Entity",
from = "Column::Actor",
to = "super::user::Column::Id"
)]
User,
#[sea_orm(
belongs_to = "super::activity::Entity",
from = "Column::Activity",
to = "super::activity::Column::Id"
)]
Activity,
#[sea_orm(
belongs_to = "super::object::Entity",
from = "Column::Object",
to = "super::object::Column::Id"
)]
Object,
}
impl Related<super::user::Entity> for Entity {
fn to() -> RelationDef {
Relation::User.def()
}
}
impl Related<super::activity::Entity> for Entity {
fn to() -> RelationDef {
Relation::Activity.def()
}
}
impl Related<super::object::Entity> for Entity {
fn to() -> RelationDef {
Relation::Object.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

18
src/model/application.rs Normal file
View file

@ -0,0 +1,18 @@
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "application")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub private_key: String,
pub public_key: String,
pub created: ChronoDateTimeUtc,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}

View file

@ -4,9 +4,7 @@ use sea_orm::entity::prelude::*;
#[sea_orm(table_name = "configs")] #[sea_orm(table_name = "configs")]
pub struct Model { pub struct Model {
#[sea_orm(primary_key)] #[sea_orm(primary_key)]
pub internal: i64, pub id: String,
#[sea_orm(unique)]
pub actor: String,
pub accept_follow_requests: bool, pub accept_follow_requests: bool,
pub show_followers_count: bool, pub show_followers_count: bool,
pub show_following_count: bool, pub show_following_count: bool,
@ -17,7 +15,7 @@ pub struct Model {
impl Default for Model { impl Default for Model {
fn default() -> Self { fn default() -> Self {
Model { Model {
internal: 0, actor: "".into(), id: "".to_string(),
accept_follow_requests: true, accept_follow_requests: true,
show_following_count: true, show_following_count: true,
show_following: true, show_following: true,
@ -30,18 +28,16 @@ impl Default for Model {
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation { pub enum Relation {
#[sea_orm( #[sea_orm(
belongs_to = "super::actor::Entity", belongs_to = "super::user::Entity",
from = "Column::Actor", from = "Column::Id",
to = "super::actor::Column::Id", to = "super::user::Column::Id"
on_update = "Cascade",
on_delete = "Cascade"
)] )]
Actors, User,
} }
impl Related<super::actor::Entity> for Entity { impl Related<super::user::Entity> for Entity {
fn to() -> RelationDef { fn to() -> RelationDef {
Relation::Actors.def() Relation::User.def()
} }
} }

View file

@ -4,29 +4,24 @@ use sea_orm::entity::prelude::*;
#[sea_orm(table_name = "credentials")] #[sea_orm(table_name = "credentials")]
pub struct Model { pub struct Model {
#[sea_orm(primary_key)] #[sea_orm(primary_key)]
pub internal: i64, pub id: String,
#[sea_orm(unique)] pub email: String,
pub actor: String,
pub login: String,
pub password: String, pub password: String,
pub active: bool,
} }
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation { pub enum Relation {
#[sea_orm( #[sea_orm(
belongs_to = "super::actor::Entity", belongs_to = "super::user::Entity",
from = "Column::Actor", from = "Column::Id",
to = "super::actor::Column::Id", to = "super::user::Column::Id"
on_update = "Cascade",
on_delete = "Cascade"
)] )]
Actors, User,
} }
impl Related<super::actor::Entity> for Entity { impl Related<super::user::Entity> for Entity {
fn to() -> RelationDef { fn to() -> RelationDef {
Relation::Actors.def() Relation::User.def()
} }
} }

50
src/model/delivery.rs Normal file
View file

@ -0,0 +1,50 @@
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "deliveries")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub actor: String,
pub target: String,
pub activity: String,
pub created: ChronoDateTimeUtc,
pub not_before: ChronoDateTimeUtc,
pub attempt: i32,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::activity::Entity",
from = "Column::Activity",
to = "super::activity::Column::Id"
)]
Activity,
}
impl Related<super::activity::Entity> for Entity {
fn to() -> RelationDef {
Relation::Activity.def()
}
}
impl ActiveModelBehavior for ActiveModel {}
impl Model {
pub fn next_delivery(&self) -> ChronoDateTimeUtc {
match self.attempt {
0 => chrono::Utc::now() + std::time::Duration::from_secs(10),
1 => chrono::Utc::now() + std::time::Duration::from_secs(60),
2 => chrono::Utc::now() + std::time::Duration::from_secs(5 * 60),
3 => chrono::Utc::now() + std::time::Duration::from_secs(20 * 60),
4 => chrono::Utc::now() + std::time::Duration::from_secs(60 * 60),
5 => chrono::Utc::now() + std::time::Duration::from_secs(12 * 60 * 60),
_ => chrono::Utc::now() + std::time::Duration::from_secs(24 * 60 * 60),
}
}
pub fn expired(&self) -> bool {
chrono::Utc::now() - self.created > chrono::Duration::days(7)
}
}

View file

@ -1,47 +1,39 @@
use upub::{ext::JsonVec, model::{activity, actor, addressing, config, credential, object}}; use crate::model::{config, credential};
use super::{activity, object, user, Audience};
use openssl::rsa::Rsa; use openssl::rsa::Rsa;
use sea_orm::{ActiveValue::NotSet, IntoActiveModel}; use sea_orm::IntoActiveModel;
pub async fn faker(ctx: upub::Context, count: i64) -> Result<(), sea_orm::DbErr> { pub async fn faker(db: &sea_orm::DatabaseConnection, domain: String, count: u64) -> Result<(), sea_orm::DbErr> {
use sea_orm::{EntityTrait, Set}; use sea_orm::{EntityTrait, Set};
let domain = ctx.domain();
let db = ctx.db();
let key = Rsa::generate(2048).unwrap(); let key = Rsa::generate(2048).unwrap();
let test_user = actor::Model { let test_user = super::user::Model {
internal: 42, id: format!("{domain}/users/test"),
id: format!("{domain}/actors/test"),
name: Some("μpub".into()), name: Some("μpub".into()),
domain: clean_domain(domain), domain: clean_domain(&domain),
preferred_username: "test".to_string(), preferred_username: "test".to_string(),
summary: Some("hello world! i'm manually generated but served dynamically from db! check progress at https://git.alemi.dev/upub.git".to_string()), summary: Some("hello world! i'm manually generated but served dynamically from db! check progress at https://git.alemi.dev/upub.git".to_string()),
following: None, following: None,
following_count: 0, following_count: 0,
followers: None, followers: None,
followers_count: 0, followers_count: 0,
statuses_count: count as i32,
fields: JsonVec::default(),
also_known_as: JsonVec::default(),
moved_to: None,
icon: Some("https://cdn.alemi.dev/social/circle-square.png".to_string()), icon: Some("https://cdn.alemi.dev/social/circle-square.png".to_string()),
image: Some("https://cdn.alemi.dev/social/someriver-xs.jpg".to_string()), image: Some("https://cdn.alemi.dev/social/someriver-xs.jpg".to_string()),
inbox: None, inbox: None,
shared_inbox: None, shared_inbox: None,
outbox: None, outbox: None,
actor_type: apb::ActorType::Person, actor_type: apb::ActorType::Person,
published: chrono::Utc::now(), created: chrono::Utc::now(),
updated: chrono::Utc::now(), updated: chrono::Utc::now(),
private_key: Some(std::str::from_utf8(&key.private_key_to_pem().unwrap()).unwrap().to_string()), private_key: Some(std::str::from_utf8(&key.private_key_to_pem().unwrap()).unwrap().to_string()),
// TODO generate a fresh one every time // TODO generate a fresh one every time
public_key: std::str::from_utf8(&key.public_key_to_pem().unwrap()).unwrap().to_string(), public_key: std::str::from_utf8(&key.public_key_to_pem().unwrap()).unwrap().to_string(),
}; };
actor::Entity::insert(test_user.clone().into_active_model()).exec(db).await?; user::Entity::insert(test_user.clone().into_active_model()).exec(db).await?;
config::Entity::insert(config::ActiveModel { config::Entity::insert(config::ActiveModel {
internal: NotSet, id: Set(test_user.id.clone()),
actor: Set(test_user.id.clone()),
accept_follow_requests: Set(true), accept_follow_requests: Set(true),
show_followers: Set(true), show_followers: Set(true),
show_following: Set(true), show_following: Set(true),
@ -50,11 +42,9 @@ pub async fn faker(ctx: upub::Context, count: i64) -> Result<(), sea_orm::DbErr>
}).exec(db).await?; }).exec(db).await?;
credential::Entity::insert(credential::ActiveModel { credential::Entity::insert(credential::ActiveModel {
internal: NotSet, id: Set(test_user.id.clone()),
actor: Set(test_user.id.clone()), email: Set("mail@example.net".to_string()),
login: Set("mail@example.net".to_string()),
password: Set(sha256::digest("very-strong-password")), password: Set(sha256::digest("very-strong-password")),
active: Set(true),
}).exec(db).await?; }).exec(db).await?;
let context = uuid::Uuid::new_v4().to_string(); let context = uuid::Uuid::new_v4().to_string();
@ -62,54 +52,35 @@ pub async fn faker(ctx: upub::Context, count: i64) -> Result<(), sea_orm::DbErr>
for i in (0..count).rev() { for i in (0..count).rev() {
let oid = uuid::Uuid::new_v4(); let oid = uuid::Uuid::new_v4();
let aid = uuid::Uuid::new_v4(); let aid = uuid::Uuid::new_v4();
addressing::Entity::insert(addressing::ActiveModel {
actor: Set(None),
instance: Set(None),
activity: Set(Some(42 + i)),
object: Set(Some(42 + i)),
published: Set(chrono::Utc::now()),
..Default::default()
}).exec(db).await?;
object::Entity::insert(object::ActiveModel { object::Entity::insert(object::ActiveModel {
internal: Set(42 + i),
id: Set(format!("{domain}/objects/{oid}")), id: Set(format!("{domain}/objects/{oid}")),
name: Set(None), name: Set(None),
object_type: Set(apb::ObjectType::Note), object_type: Set(apb::ObjectType::Note),
attributed_to: Set(Some(format!("{domain}/actors/test"))), attributed_to: Set(Some(format!("{domain}/users/test"))),
summary: Set(None), summary: Set(None),
context: Set(Some(context.clone())), context: Set(Some(context.clone())),
in_reply_to: Set(None),
quote: Set(None),
content: Set(Some(format!("[{i}] Tic(k). Quasiparticle of intensive multiplicity. Tics (or ticks) are intrinsically several components of autonomously numbering anorganic populations, propagating by contagion between segmentary divisions in the order of nature. Ticks - as nonqualitative differentially-decomposable counting marks - each designate a multitude comprehended as a singular variation in tic(k)-density."))), content: Set(Some(format!("[{i}] Tic(k). Quasiparticle of intensive multiplicity. Tics (or ticks) are intrinsically several components of autonomously numbering anorganic populations, propagating by contagion between segmentary divisions in the order of nature. Ticks - as nonqualitative differentially-decomposable counting marks - each designate a multitude comprehended as a singular variation in tic(k)-density."))),
image: Set(None), published: Set(chrono::Utc::now() - std::time::Duration::from_secs(60*i)),
published: Set(chrono::Utc::now() - std::time::Duration::from_secs(60*i as u64)), comments: Set(0),
updated: Set(chrono::Utc::now()),
replies: Set(0),
likes: Set(0), likes: Set(0),
announces: Set(0), shares: Set(0),
audience: Set(None), to: Set(Audience(vec![apb::target::PUBLIC.to_string()])),
to: Set(JsonVec(vec![apb::target::PUBLIC.to_string()])), bto: Set(Audience::default()),
bto: Set(JsonVec::default()), cc: Set(Audience(vec![])),
cc: Set(JsonVec(vec![])), bcc: Set(Audience::default()),
bcc: Set(JsonVec::default()),
url: Set(None),
sensitive: Set(false),
}).exec(db).await?; }).exec(db).await?;
activity::Entity::insert(activity::ActiveModel { activity::Entity::insert(activity::ActiveModel {
internal: Set(42 + i),
id: Set(format!("{domain}/activities/{aid}")), id: Set(format!("{domain}/activities/{aid}")),
activity_type: Set(apb::ActivityType::Create), activity_type: Set(apb::ActivityType::Create),
actor: Set(format!("{domain}/actors/test")), actor: Set(format!("{domain}/users/test")),
object: Set(Some(format!("{domain}/objects/{oid}"))), object: Set(Some(format!("{domain}/objects/{oid}"))),
target: Set(None), target: Set(None),
published: Set(chrono::Utc::now() - std::time::Duration::from_secs(60*i as u64)), published: Set(chrono::Utc::now() - std::time::Duration::from_secs(60*i)),
to: Set(JsonVec(vec![apb::target::PUBLIC.to_string()])), to: Set(Audience(vec![apb::target::PUBLIC.to_string()])),
bto: Set(JsonVec::default()), bto: Set(Audience::default()),
cc: Set(JsonVec(vec![])), cc: Set(Audience(vec![])),
bcc: Set(JsonVec::default()), bcc: Set(Audience::default()),
}).exec(db).await?; }).exec(db).await?;
} }

16
src/model/like.rs Normal file
View file

@ -0,0 +1,16 @@
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "likes")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub actor: String,
pub likes: String,
pub date: ChronoDateTimeUtc,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}

45
src/model/mod.rs Normal file
View file

@ -0,0 +1,45 @@
pub mod object;
pub mod activity;
pub mod user;
pub mod config;
pub mod relation;
pub mod addressing;
pub mod share;
pub mod like;
pub mod credential;
pub mod session;
pub mod delivery;
pub mod application;
#[cfg(feature = "faker")]
pub mod faker;
#[derive(Debug, Clone, thiserror::Error)]
#[error("missing required field: '{0}'")]
pub struct FieldError(pub &'static str);
impl From<FieldError> for axum::http::StatusCode {
fn from(value: FieldError) -> Self {
tracing::error!("bad request: {value}");
axum::http::StatusCode::BAD_REQUEST
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, sea_orm::FromJsonQueryResult)]
pub struct Audience(pub Vec<String>);
use apb::{Link, Node};
impl<T : Link> From<Node<T>> for Audience {
fn from(value: Node<T>) -> Self {
Audience(
match value {
Node::Empty => vec![],
Node::Link(l) => vec![l.href().to_string()],
Node::Object(o) => if let Some(id) = o.id() { vec![id.to_string()] } else { vec![] },
Node::Array(arr) => arr.into_iter().filter_map(|l| Some(l.id()?.to_string())).collect(),
}
)
}
}

82
src/model/object.rs Normal file
View file

@ -0,0 +1,82 @@
use sea_orm::entity::prelude::*;
use super::Audience;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "objects")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: String,
pub object_type: apb::ObjectType,
pub attributed_to: Option<String>,
pub name: Option<String>,
pub summary: Option<String>,
pub content: Option<String>,
pub likes: i64,
pub shares: i64,
pub comments: i64,
pub context: Option<String>,
pub cc: Audience,
pub bcc: Audience,
pub to: Audience,
pub bto: Audience,
pub published: ChronoDateTimeUtc,
}
impl Model {
pub fn new(object: &impl apb::Object) -> Result<Self, super::FieldError> {
Ok(Model {
id: object.id().ok_or(super::FieldError("id"))?.to_string(),
object_type: object.object_type().ok_or(super::FieldError("type"))?,
attributed_to: object.attributed_to().id(),
name: object.name().map(|x| x.to_string()),
summary: object.summary().map(|x| x.to_string()),
content: object.content().map(|x| x.to_string()),
context: object.context().id(),
published: object.published().ok_or(super::FieldError("published"))?,
comments: 0,
likes: 0,
shares: 0,
to: object.to().into(),
bto: object.bto().into(),
cc: object.cc().into(),
bcc: object.bcc().into(),
})
}
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::activity::Entity")]
Activity,
#[sea_orm(
belongs_to = "super::user::Entity",
from = "Column::AttributedTo",
to = "super::user::Column::Id",
)]
User,
#[sea_orm(has_many = "super::addressing::Entity")]
Addressing,
}
impl Related<super::activity::Entity> for Entity {
fn to() -> RelationDef {
Relation::Activity.def()
}
}
impl Related<super::user::Entity> for Entity {
fn to() -> RelationDef {
Relation::User.def()
}
}
impl Related<super::addressing::Entity> for Entity {
fn to() -> RelationDef {
Relation::Addressing.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

16
src/model/relation.rs Normal file
View file

@ -0,0 +1,16 @@
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "relations")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub follower: String,
pub following: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
// TODO how to represent this User-to-User relation in sea orm??
impl ActiveModelBehavior for ActiveModel {}

View file

@ -4,27 +4,24 @@ use sea_orm::entity::prelude::*;
#[sea_orm(table_name = "sessions")] #[sea_orm(table_name = "sessions")]
pub struct Model { pub struct Model {
#[sea_orm(primary_key)] #[sea_orm(primary_key)]
pub internal: i64, pub id: String,
pub actor: String, pub actor: String,
pub secret: String,
pub expires: ChronoDateTimeUtc, pub expires: ChronoDateTimeUtc,
} }
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation { pub enum Relation {
#[sea_orm( #[sea_orm(
belongs_to = "super::actor::Entity", belongs_to = "super::user::Entity",
from = "Column::Actor", from = "Column::Actor",
to = "super::actor::Column::Id", to = "super::user::Column::Id"
on_update = "Cascade",
on_delete = "Cascade"
)] )]
Actors, User,
} }
impl Related<super::actor::Entity> for Entity { impl Related<super::user::Entity> for Entity {
fn to() -> RelationDef { fn to() -> RelationDef {
Relation::Actors.def() Relation::User.def()
} }
} }

16
src/model/share.rs Normal file
View file

@ -0,0 +1,16 @@
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "shares")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub actor: String,
pub shares: String,
pub date: ChronoDateTimeUtc,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}

132
src/model/user.rs Normal file
View file

@ -0,0 +1,132 @@
use sea_orm::entity::prelude::*;
use apb::{Collection, Actor, PublicKey, ActorType};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "users")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: String,
pub domain: String,
pub actor_type: ActorType,
pub preferred_username: String,
pub name: Option<String>,
pub summary: Option<String>,
pub image: Option<String>,
pub icon: Option<String>,
pub inbox: Option<String>,
pub shared_inbox: Option<String>,
pub outbox: Option<String>,
pub following: Option<String>,
pub followers: Option<String>,
pub following_count: i64,
pub followers_count: i64,
pub public_key: String,
pub private_key: Option<String>,
pub created: ChronoDateTimeUtc,
pub updated: ChronoDateTimeUtc,
// TODO these are also suggested
// pub liked: Option<String>,
// pub streams: Option<String>,
}
impl Model {
pub fn new(object: &impl Actor) -> Result<Self, super::FieldError> {
let ap_id = object.id().ok_or(super::FieldError("id"))?.to_string();
let (domain, preferred_username) = split_user_id(&ap_id);
Ok(Model {
id: ap_id, preferred_username, domain,
actor_type: object.actor_type().ok_or(super::FieldError("type"))?,
name: object.name().map(|x| x.to_string()),
summary: object.summary().map(|x| x.to_string()),
icon: object.icon().id(),
image: object.image().id(),
inbox: object.inbox().id(),
outbox: object.inbox().id(),
shared_inbox: None, // TODO!!! parse endpoints
followers: object.followers().id(),
following: object.following().id(),
created: object.published().unwrap_or(chrono::Utc::now()),
updated: chrono::Utc::now(),
following_count: object.following().get().map(|f| f.total_items().unwrap_or(0)).unwrap_or(0) as i64,
followers_count: object.followers().get().map(|f| f.total_items().unwrap_or(0)).unwrap_or(0) as i64,
public_key: object.public_key().get().ok_or(super::FieldError("publicKey"))?.public_key_pem().to_string(),
private_key: None, // there's no way to transport privkey over AP json, must come from DB
})
}
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::activity::Entity")]
Activity,
#[sea_orm(has_many = "super::object::Entity")]
Object,
#[sea_orm(has_one = "super::config::Entity")]
Config,
#[sea_orm(has_one = "super::credential::Entity")]
Credential,
#[sea_orm(has_many = "super::session::Entity")]
Session,
#[sea_orm(has_many = "super::addressing::Entity")]
Addressing,
}
impl Related<super::activity::Entity> for Entity {
fn to() -> RelationDef {
Relation::Activity.def()
}
}
impl Related<super::object::Entity> for Entity {
fn to() -> RelationDef {
Relation::Object.def()
}
}
impl Related<super::config::Entity> for Entity {
fn to() -> RelationDef {
Relation::Config.def()
}
}
impl Related<super::credential::Entity> for Entity {
fn to() -> RelationDef {
Relation::Credential.def()
}
}
impl Related<super::session::Entity> for Entity {
fn to() -> RelationDef {
Relation::Session.def()
}
}
impl Related<super::addressing::Entity> for Entity {
fn to() -> RelationDef {
Relation::Addressing.def()
}
}
impl ActiveModelBehavior for ActiveModel {}
fn split_user_id(id: &str) -> (String, String) {
let clean = id
.replace("http://", "")
.replace("https://", "");
let mut splits = clean.split('/');
let first = splits.next().unwrap_or("");
let last = splits.last().unwrap_or(first);
(first.to_string(), last.to_string())
}

View file

@ -0,0 +1,43 @@
use axum::{extract::{Path, State}, http::StatusCode};
use sea_orm::EntityTrait;
use crate::{model::{self, activity, object}, server::Context};
use apb::{ActivityMut, ObjectMut, BaseMut, Node};
use super::{jsonld::LD, JsonLD};
pub fn ap_activity(activity: model::activity::Model) -> serde_json::Value {
serde_json::Value::new_object()
.set_id(Some(&activity.id))
.set_activity_type(Some(activity.activity_type))
.set_actor(Node::link(activity.actor))
.set_object(Node::maybe_link(activity.object))
.set_target(Node::maybe_link(activity.target))
.set_published(Some(activity.published))
.set_to(Node::links(activity.to.0.clone()))
.set_bto(Node::Empty)
.set_cc(Node::links(activity.cc.0.clone()))
.set_bcc(Node::Empty)
}
pub async fn view(State(ctx) : State<Context>, Path(id): Path<String>) -> Result<JsonLD<serde_json::Value>, StatusCode> {
match activity::Entity::find_by_id(ctx.aid(id))
.find_also_related(object::Entity)
.one(ctx.db())
.await
{
Ok(Some((activity, Some(object)))) => Ok(JsonLD(
ap_activity(activity)
.set_object(Node::object(super::object::ap_object(object)))
.ld_context()
)),
Ok(Some((activity, None))) => Ok(JsonLD(
ap_activity(activity).ld_context()
)),
Ok(None) => Err(StatusCode::NOT_FOUND),
Err(e) => {
tracing::error!("error querying for activity: {e}");
Err(StatusCode::INTERNAL_SERVER_ERROR)
},
}
}

View file

@ -0,0 +1,25 @@
use apb::{ActorMut, BaseMut, ObjectMut, PublicKeyMut};
use axum::{extract::State, http::StatusCode, Json};
use crate::{server::Context, url};
use super::jsonld::LD;
pub async fn view(State(ctx): State<Context>) -> Result<Json<serde_json::Value>, StatusCode> {
Ok(Json(
serde_json::Value::new_object()
.set_id(Some(&url!(ctx, "")))
.set_actor_type(Some(apb::ActorType::Application))
.set_name(Some("μpub"))
.set_summary(Some("micro social network, federated"))
.set_published(Some(ctx.app().created))
.set_public_key(apb::Node::object(
serde_json::Value::new_object()
.set_id(Some(&url!(ctx, "#main-key")))
.set_owner(Some(&url!(ctx, "")))
.set_public_key_pem(&ctx.app().public_key)
))
.ld_context()
))
}

View file

@ -0,0 +1,48 @@
use axum::{http::StatusCode, extract::State, Json};
use rand::Rng;
use sea_orm::{ColumnTrait, Condition, EntityTrait, QueryFilter};
use crate::{model, server::Context};
#[derive(Debug, Clone, serde::Deserialize)]
pub struct LoginForm {
email: String,
password: String,
}
pub async fn login(State(ctx): State<Context>, Json(login): Json<LoginForm>) -> Result<Json<serde_json::Value>, StatusCode> {
// TODO salt the pwd
match model::credential::Entity::find()
.filter(Condition::all()
.add(model::credential::Column::Email.eq(login.email))
.add(model::credential::Column::Password.eq(sha256::digest(login.password)))
)
.one(ctx.db())
.await
{
Ok(Some(x)) => {
// TODO should probably use crypto-safe rng
let token : String = rand::thread_rng()
.sample_iter(&rand::distributions::Alphanumeric)
.take(128)
.map(char::from)
.collect();
model::session::Entity::insert(
model::session::ActiveModel {
id: sea_orm::ActiveValue::Set(token.clone()),
actor: sea_orm::ActiveValue::Set(x.id),
expires: sea_orm::ActiveValue::Set(chrono::Utc::now() + std::time::Duration::from_secs(3600 * 6)),
}
)
.exec(ctx.db())
.await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(serde_json::Value::String(token)))
},
Ok(None) => Err(StatusCode::UNAUTHORIZED),
Err(e) => {
tracing::error!("error querying db for user credentials: {e}");
Err(StatusCode::INTERNAL_SERVER_ERROR)
}
}
}

View file

@ -0,0 +1,46 @@
use axum::{extract::{Query, State}, http::StatusCode};
use sea_orm::{ColumnTrait, Condition, EntityTrait, Order, QueryFilter, QueryOrder, QuerySelect};
use crate::{server::auth::{AuthIdentity, Identity}, errors::UpubError, model, server::Context, url};
use super::{activity::ap_activity, jsonld::LD, JsonLD, Pagination};
pub async fn get(
State(ctx): State<Context>,
) -> Result<JsonLD<serde_json::Value>, StatusCode> {
Ok(JsonLD(ctx.ap_collection(&url!(ctx, "/inbox"), None).ld_context()))
}
pub async fn page(
State(ctx): State<Context>,
AuthIdentity(auth): AuthIdentity,
Query(page): Query<Pagination>,
) -> Result<JsonLD<serde_json::Value>, UpubError> {
let limit = page.batch.unwrap_or(20).min(50);
let offset = page.offset.unwrap_or(0);
let mut condition = Condition::any()
.add(model::addressing::Column::Actor.eq(apb::target::PUBLIC));
if let Identity::Local(user) = auth {
condition = condition
.add(model::addressing::Column::Actor.eq(user));
}
let activities = model::addressing::Entity::find()
.filter(condition)
.order_by(model::addressing::Column::Published, Order::Asc)
.find_also_related(model::activity::Entity)
.limit(limit)
.offset(offset)
.all(ctx.db())
.await?;
Ok(JsonLD(
ctx.ap_collection_page(
&url!(ctx, "/inbox/page"),
offset, limit,
activities
.into_iter()
.filter_map(|(_, a)| Some(ap_activity(a?)))
.collect::<Vec<serde_json::Value>>()
).ld_context()
))
}

View file

@ -0,0 +1,36 @@
use axum::response::{IntoResponse, Response};
pub trait LD {
fn ld_context(self) -> Self;
fn new_object() -> serde_json::Value {
serde_json::Value::Object(serde_json::Map::default())
}
}
impl LD for serde_json::Value {
fn ld_context(mut self) -> Self {
if let Some(obj) = self.as_object_mut() {
obj.insert(
"@context".to_string(),
serde_json::Value::Array(vec![
serde_json::Value::String("https://www.w3.org/ns/activitystreams".into())
]),
);
} else {
tracing::warn!("cannot add @context to json value different than object");
}
self
}
}
// got this from https://github.com/kitsune-soc/kitsune/blob/b023a12b687dd9a274233a5a9950f2de5e192344/kitsune/src/http/responder.rs
// i was trying to do it with middlewares but this is way cleaner
pub struct JsonLD<T>(pub T);
impl<T: serde::Serialize> IntoResponse for JsonLD<T> {
fn into_response(self) -> Response {
(
[("Content-Type", "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"")],
axum::Json(self.0)
).into_response()
}
}

View file

@ -0,0 +1,72 @@
pub mod user;
pub mod inbox;
pub mod outbox;
pub mod object;
pub mod activity;
pub mod application;
pub mod auth;
pub mod well_known;
pub mod jsonld;
pub use jsonld::JsonLD;
use axum::{http::StatusCode, response::IntoResponse, routing::{get, post}, Router};
pub trait ActivityPubRouter {
fn ap_routes(self) -> Self;
}
impl ActivityPubRouter for Router<crate::server::Context> {
fn ap_routes(self) -> Self {
use crate::routes::activitypub as ap; // TODO use self ?
self
// core server inbox/outbox, maybe for feeds? TODO do we need these?
.route("/", get(ap::application::view))
// TODO shared inboxes and instance stream will come later, just use users *boxes for now
.route("/inbox", get(ap::inbox::get))
// .route("/inbox", post(ap::inbox::post))
// .route("/outbox", get(ap::outbox::get))
// .route("/outbox", get(ap::outbox::post))
// AUTH routes
.route("/auth", post(ap::auth::login))
// .well-known and discovery
.route("/.well-known/webfinger", get(ap::well_known::webfinger))
.route("/.well-known/host-meta", get(ap::well_known::host_meta))
.route("/.well-known/nodeinfo", get(ap::well_known::nodeinfo_discovery))
.route("/nodeinfo/:version", get(ap::well_known::nodeinfo))
// actor routes
.route("/users/:id", get(ap::user::view))
.route("/users/:id/inbox", post(ap::user::inbox::post))
.route("/users/:id/inbox", get(ap::user::inbox::get))
.route("/users/:id/inbox/page", get(ap::user::inbox::page))
.route("/users/:id/outbox", post(ap::user::outbox::post))
.route("/users/:id/outbox", get(ap::user::outbox::get))
.route("/users/:id/outbox/page", get(ap::user::outbox::page))
.route("/users/:id/followers", get(ap::user::following::get::<false>))
.route("/users/:id/followers/page", get(ap::user::following::page::<false>))
.route("/users/:id/following", get(ap::user::following::get::<true>))
.route("/users/:id/following/page", get(ap::user::following::page::<true>))
// specific object routes
.route("/activities/:id", get(ap::activity::view))
.route("/objects/:id", get(ap::object::view))
}
}
#[derive(Debug, serde::Deserialize)]
// TODO i don't really like how pleroma/mastodon do it actually, maybe change this?
pub struct Pagination {
pub offset: Option<u64>,
pub batch: Option<u64>,
}
pub struct CreationResult(pub String);
impl IntoResponse for CreationResult {
fn into_response(self) -> axum::response::Response {
(
StatusCode::CREATED,
[("Location", self.0.as_str())]
)
.into_response()
}
}

View file

@ -0,0 +1,34 @@
use axum::{extract::{Path, State}, http::StatusCode};
use sea_orm::EntityTrait;
use apb::{ObjectMut, BaseMut, Node};
use crate::{model::{self, object}, server::Context};
use super::{jsonld::LD, JsonLD};
pub fn ap_object(object: model::object::Model) -> serde_json::Value {
serde_json::Value::new_object()
.set_id(Some(&object.id))
.set_object_type(Some(object.object_type))
.set_attributed_to(Node::maybe_link(object.attributed_to))
.set_name(object.name.as_deref())
.set_summary(object.summary.as_deref())
.set_content(object.content.as_deref())
.set_context(Node::maybe_link(object.context.clone()))
.set_published(Some(object.published))
.set_to(Node::links(object.to.0.clone()))
.set_bto(Node::Empty)
.set_cc(Node::links(object.cc.0.clone()))
.set_bcc(Node::Empty)
}
pub async fn view(State(ctx) : State<Context>, Path(id): Path<String>) -> Result<JsonLD<serde_json::Value>, StatusCode> {
match object::Entity::find_by_id(ctx.oid(id)).one(ctx.db()).await {
Ok(Some(object)) => Ok(JsonLD(ap_object(object).ld_context())),
Ok(None) => Err(StatusCode::NOT_FOUND),
Err(e) => {
tracing::error!("error querying for object: {e}");
Err(StatusCode::INTERNAL_SERVER_ERROR)
},
}
}

View file

@ -0,0 +1,59 @@
use axum::{extract::{Path, Query, State}, http::StatusCode};
use sea_orm::{ColumnTrait, Condition, EntityTrait, PaginatorTrait, QueryFilter, QuerySelect, SelectColumns};
use crate::{routes::activitypub::{jsonld::LD, JsonLD, Pagination}, model, server::Context, url};
use model::relation::Column::{Following, Follower};
pub async fn get<const OUTGOING: bool>(
State(ctx): State<Context>,
Path(id): Path<String>,
) -> Result<JsonLD<serde_json::Value>, StatusCode> {
let follow___ = if OUTGOING { "following" } else { "followers" };
let count = model::relation::Entity::find()
.filter(Condition::all().add(if OUTGOING { Follower } else { Following }.eq(ctx.uid(id.clone()))))
.count(ctx.db()).await.unwrap_or_else(|e| {
tracing::error!("failed counting {follow___} for {id}: {e}");
0
});
Ok(JsonLD(
ctx.ap_collection(
&url!(ctx, "/users/{id}/{follow___}"),
Some(count)
).ld_context()
))
}
pub async fn page<const OUTGOING: bool>(
State(ctx): State<Context>,
Path(id): Path<String>,
Query(page): Query<Pagination>,
) -> Result<JsonLD<serde_json::Value>, StatusCode> {
let follow___ = if OUTGOING { "following" } else { "followers" };
let limit = page.batch.unwrap_or(20).min(50);
let offset = page.offset.unwrap_or(0);
match model::relation::Entity::find()
.filter(Condition::all().add(if OUTGOING { Follower } else { Following }.eq(ctx.uid(id.clone()))))
.select_only()
.select_column(if OUTGOING { Following } else { Follower })
.limit(limit)
.offset(page.offset.unwrap_or(0))
.into_tuple::<String>()
.all(ctx.db()).await
{
Err(e) => {
tracing::error!("error queriying {follow___} for {id}: {e}");
Err(StatusCode::INTERNAL_SERVER_ERROR)
},
Ok(following) => {
Ok(JsonLD(
ctx.ap_collection_page(
&url!(ctx, "/users/{id}/{follow___}"),
offset,
limit,
following.into_iter().map(serde_json::Value::String).collect()
).ld_context()
))
},
}
}

View file

@ -0,0 +1,128 @@
use axum::{extract::{Path, Query, State}, http::StatusCode, Json};
use sea_orm::{ColumnTrait, Condition, EntityTrait, JoinType, Order, QueryFilter, QueryOrder, QuerySelect, RelationTrait};
use apb::{server::Inbox, ActivityMut, ActivityType, Base, BaseType, ObjectType};
use crate::{errors::UpubError, model, routes::activitypub::{activity::ap_activity, jsonld::LD, object::ap_object, JsonLD, Pagination}, server::{auth::{AuthIdentity, Identity}, Context}, tools::ActivityWithObject, url};
pub async fn get(
State(ctx): State<Context>,
Path(id): Path<String>,
AuthIdentity(auth): AuthIdentity,
) -> Result<JsonLD<serde_json::Value>, StatusCode> {
match auth {
Identity::Anonymous => Err(StatusCode::FORBIDDEN),
Identity::Remote(_) => Err(StatusCode::FORBIDDEN),
Identity::Local(user) => if ctx.uid(id.clone()) == user {
Ok(JsonLD(ctx.ap_collection(&url!(ctx, "/users/{id}/inbox"), None).ld_context()))
} else {
Err(StatusCode::FORBIDDEN)
},
}
}
pub async fn page(
State(ctx): State<Context>,
Path(id): Path<String>,
AuthIdentity(auth): AuthIdentity,
Query(page): Query<Pagination>,
) -> crate::Result<JsonLD<serde_json::Value>> {
let uid = ctx.uid(id.clone());
match auth {
Identity::Anonymous => Err(StatusCode::FORBIDDEN.into()),
Identity::Remote(_) => Err(StatusCode::FORBIDDEN.into()),
Identity::Local(user) => if uid == user {
let limit = page.batch.unwrap_or(20).min(50);
let offset = page.offset.unwrap_or(0);
let select = model::addressing::Entity::find()
.filter(Condition::all().add(model::addressing::Column::Actor.eq(uid)))
.order_by(model::addressing::Column::Published, Order::Asc)
.select_only();
match crate::tools::Prefixer::new(select)
.add_columns(model::activity::Entity)
.add_columns(model::object::Entity)
.selector
.join(JoinType::LeftJoin, model::activity::Relation::Addressing.def().rev())
.join(JoinType::LeftJoin, model::object::Relation::Activity.def().rev())
.limit(limit)
.offset(offset)
.into_model::<crate::tools::ActivityWithObject>()
.all(ctx.db())
.await
{
Ok(activities) => {
Ok(JsonLD(
ctx.ap_collection_page(
&url!(ctx, "/users/{id}/inbox/page"),
offset, limit,
activities
.into_iter()
.map(|ActivityWithObject { activity, object }| {
ap_activity(activity)
.set_object(apb::Node::maybe_object(object.map(ap_object)))
})
.collect::<Vec<serde_json::Value>>()
).ld_context()
))
},
Err(e) => {
tracing::error!("failed paginating user inbox for {id}: {e}");
Err(StatusCode::INTERNAL_SERVER_ERROR.into())
},
}
} else {
Err(StatusCode::FORBIDDEN.into())
},
}
}
pub async fn post(
State(ctx): State<Context>,
Path(_id): Path<String>,
Json(activity): Json<serde_json::Value>
) -> Result<(), UpubError> {
match activity.base_type() {
None => { Err(StatusCode::BAD_REQUEST.into()) },
Some(BaseType::Link(_x)) => {
tracing::warn!("skipping remote activity: {}", serde_json::to_string_pretty(&activity).unwrap());
Err(StatusCode::UNPROCESSABLE_ENTITY.into()) // we could but not yet
},
Some(BaseType::Object(ObjectType::Activity(ActivityType::Activity))) => {
tracing::warn!("skipping unprocessable base activity: {}", serde_json::to_string_pretty(&activity).unwrap());
Err(StatusCode::UNPROCESSABLE_ENTITY.into()) // won't ingest useless stuff
},
Some(BaseType::Object(ObjectType::Activity(ActivityType::Delete))) =>
Ok(ctx.delete(activity).await?),
Some(BaseType::Object(ObjectType::Activity(ActivityType::Follow))) =>
Ok(ctx.follow(activity).await?),
Some(BaseType::Object(ObjectType::Activity(ActivityType::Accept(_)))) =>
Ok(ctx.accept(activity).await?),
Some(BaseType::Object(ObjectType::Activity(ActivityType::Reject(_)))) =>
Ok(ctx.reject(activity).await?),
Some(BaseType::Object(ObjectType::Activity(ActivityType::Like))) =>
Ok(ctx.like(activity).await?),
Some(BaseType::Object(ObjectType::Activity(ActivityType::Create))) =>
Ok(ctx.create(activity).await?),
Some(BaseType::Object(ObjectType::Activity(ActivityType::Update))) =>
Ok(ctx.update(activity).await?),
Some(BaseType::Object(ObjectType::Activity(_x))) => {
tracing::info!("received unimplemented activity on inbox: {}", serde_json::to_string_pretty(&activity).unwrap());
Err(StatusCode::NOT_IMPLEMENTED.into())
},
Some(_x) => {
tracing::warn!("ignoring non-activity object in inbox: {}", serde_json::to_string_pretty(&activity).unwrap());
Err(StatusCode::UNPROCESSABLE_ENTITY.into())
}
}
}

View file

@ -0,0 +1,72 @@
pub mod inbox;
pub mod outbox;
pub mod following;
use axum::{extract::{Path, State}, http::StatusCode};
use sea_orm::EntityTrait;
use apb::{PublicKeyMut, ActorMut, DocumentMut, DocumentType, ObjectMut, BaseMut, Node};
use crate::{model::{self, user}, server::Context, url};
use super::{jsonld::LD, JsonLD};
pub fn ap_user(user: model::user::Model) -> serde_json::Value {
serde_json::Value::new_object()
.set_id(Some(&user.id))
.set_actor_type(Some(user.actor_type))
.set_name(user.name.as_deref())
.set_summary(user.summary.as_deref())
.set_icon(Node::maybe_object(user.icon.map(|i|
serde_json::Value::new_object()
.set_document_type(Some(DocumentType::Image))
.set_url(Node::link(i.clone()))
)))
.set_image(Node::maybe_object(user.image.map(|i|
serde_json::Value::new_object()
.set_document_type(Some(DocumentType::Image))
.set_url(Node::link(i.clone()))
)))
.set_published(Some(user.created))
.set_preferred_username(Some(&user.preferred_username))
.set_inbox(Node::maybe_link(user.inbox))
.set_outbox(Node::maybe_link(user.outbox))
.set_following(Node::maybe_link(user.following))
.set_followers(Node::maybe_link(user.followers))
.set_public_key(Node::object(
serde_json::Value::new_object()
.set_id(Some(&format!("{}#main-key", user.id)))
.set_owner(Some(&user.id))
.set_public_key_pem(&user.public_key)
))
.set_discoverable(Some(true))
.set_endpoints(Node::Empty)
}
pub async fn view(State(ctx) : State<Context>, Path(id): Path<String>) -> Result<JsonLD<serde_json::Value>, StatusCode> {
match user::Entity::find_by_id(ctx.uid(id.clone()))
.find_also_related(model::config::Entity)
.one(ctx.db()).await
{
// local user
Ok(Some((user, Some(_cfg)))) => {
Ok(JsonLD(ap_user(user.clone()) // ew ugly clone TODO
.set_inbox(Node::link(url!(ctx, "/users/{id}/inbox")))
.set_outbox(Node::link(url!(ctx, "/users/{id}/outbox")))
.set_following(Node::link(url!(ctx, "/users/{id}/following")))
.set_followers(Node::link(url!(ctx, "/users/{id}/followers")))
// .set_public_key(user.public_key) // TODO
.ld_context()
))
},
// remote user
Ok(Some((user, None))) => Ok(JsonLD(ap_user(user).ld_context())),
Ok(None) => Err(StatusCode::NOT_FOUND),
Err(e) => {
tracing::error!("error querying for user: {e}");
Err(StatusCode::INTERNAL_SERVER_ERROR)
},
}
}

View file

@ -0,0 +1,108 @@
use axum::{extract::{Path, Query, State}, http::StatusCode, Json};
use sea_orm::{EntityTrait, Order, QueryOrder, QuerySelect};
use apb::{server::Outbox, AcceptType, ActivityMut, ActivityType, Base, BaseType, Node, ObjectType, RejectType};
use crate::{routes::activitypub::{jsonld::LD, CreationResult, JsonLD, Pagination}, server::auth::{AuthIdentity, Identity}, errors::UpubError, model, server::Context, url};
pub async fn get(
State(ctx): State<Context>,
Path(id): Path<String>,
) -> Result<JsonLD<serde_json::Value>, StatusCode> {
Ok(JsonLD(
ctx.ap_collection(&url!(ctx, "/users/{id}/outbox"), None).ld_context()
))
}
pub async fn page(
State(ctx): State<Context>,
Path(id): Path<String>,
Query(page): Query<Pagination>,
AuthIdentity(_auth): AuthIdentity,
) -> Result<JsonLD<serde_json::Value>, StatusCode> {
let limit = page.batch.unwrap_or(20).min(50);
let offset = page.offset.unwrap_or(0);
// let mut conditions = Condition::any()
// .add(model::addressing::Column::Actor.eq(PUBLIC_TARGET));
// if let Identity::User(ref x) = auth {
// conditions = conditions.add(model::addressing::Column::Actor.eq(x));
// }
// if let Identity::Server(ref x) = auth {
// conditions = conditions.add(model::addressing::Column::Server.eq(x));
// }
match model::activity::Entity::find()
.find_also_related(model::object::Entity)
.order_by(model::activity::Column::Published, Order::Desc)
.limit(limit)
.offset(offset)
.all(ctx.db()).await
{
Err(_e) => Err(StatusCode::INTERNAL_SERVER_ERROR),
Ok(items) => {
Ok(JsonLD(
ctx.ap_collection_page(
&url!(ctx, "/users/{id}/outbox/page"),
offset, limit,
items
.into_iter()
.map(|(a, o)| {
let oid = a.object.clone();
super::super::activity::ap_activity(a)
.set_object(match o {
Some(o) => Node::object(super::super::object::ap_object(o)),
None => Node::maybe_link(oid),
})
})
.collect()
).ld_context()
))
},
}
}
pub async fn post(
State(ctx): State<Context>,
Path(id): Path<String>,
AuthIdentity(auth): AuthIdentity,
Json(activity): Json<serde_json::Value>,
) -> Result<CreationResult, UpubError> {
match auth {
Identity::Anonymous => Err(StatusCode::UNAUTHORIZED.into()),
Identity::Remote(_) => Err(StatusCode::NOT_IMPLEMENTED.into()),
Identity::Local(uid) => if ctx.uid(id.clone()) == uid {
match activity.base_type() {
None => Err(StatusCode::BAD_REQUEST.into()),
Some(BaseType::Link(_)) => Err(StatusCode::UNPROCESSABLE_ENTITY.into()),
Some(BaseType::Object(ObjectType::Note)) =>
Ok(CreationResult(ctx.create_note(uid, activity).await?)),
Some(BaseType::Object(ObjectType::Activity(ActivityType::Create))) =>
Ok(CreationResult(ctx.create(uid, activity).await?)),
Some(BaseType::Object(ObjectType::Activity(ActivityType::Like))) =>
Ok(CreationResult(ctx.like(uid, activity).await?)),
Some(BaseType::Object(ObjectType::Activity(ActivityType::Follow))) =>
Ok(CreationResult(ctx.follow(uid, activity).await?)),
Some(BaseType::Object(ObjectType::Activity(ActivityType::Undo))) =>
Ok(CreationResult(ctx.undo(uid, activity).await?)),
Some(BaseType::Object(ObjectType::Activity(ActivityType::Accept(AcceptType::Accept)))) =>
Ok(CreationResult(ctx.accept(uid, activity).await?)),
Some(BaseType::Object(ObjectType::Activity(ActivityType::Reject(RejectType::Reject)))) =>
Ok(CreationResult(ctx.reject(uid, activity).await?)),
Some(_) => Err(StatusCode::NOT_IMPLEMENTED.into()),
}
} else {
Err(StatusCode::FORBIDDEN.into())
}
}
}

View file

@ -0,0 +1,146 @@
use axum::{extract::{Path, Query, State}, http::StatusCode, response::{IntoResponse, Response}, Json};
use jrd::{JsonResourceDescriptor, JsonResourceDescriptorLink};
use sea_orm::{EntityTrait, PaginatorTrait};
use crate::{model, server::Context, VERSION};
#[derive(serde::Serialize)]
pub struct NodeInfoDiscovery {
pub links: Vec<NodeInfoDiscoveryRel>,
}
#[derive(serde::Serialize)]
pub struct NodeInfoDiscoveryRel {
pub rel: String,
pub href: String,
}
pub async fn nodeinfo_discovery(State(ctx): State<Context>) -> Json<NodeInfoDiscovery> {
Json(NodeInfoDiscovery {
links: vec![
NodeInfoDiscoveryRel {
rel: "http://nodeinfo.diaspora.software/ns/schema/2.0".into(),
href: format!("{}/nodeinfo/2.0.json", ctx.base()),
},
NodeInfoDiscoveryRel {
rel: "http://nodeinfo.diaspora.software/ns/schema/2.1".into(),
href: format!("{}/nodeinfo/2.1.json", ctx.base()),
},
],
})
}
// TODO either vendor or fork nodeinfo-rs because it still represents "repository" and "homepage"
// even if None! technically leads to invalid nodeinfo 2.0
pub async fn nodeinfo(State(ctx): State<Context>, Path(version): Path<String>) -> Result<Json<nodeinfo::NodeInfoOwned>, StatusCode> {
// TODO it's unsustainable to count these every time, especially comments since it's a complex
// filter! keep these numbers caches somewhere, maybe db, so that we can just look them up
let total_users = model::user::Entity::find().count(ctx.db()).await.ok();
let total_posts = None;
let total_comments = None;
let (software, version) = match version.as_str() {
"2.0.json" | "2.0" => (
nodeinfo::types::Software {
name: "μpub".to_string(),
version: Some(VERSION.into()),
repository: None,
homepage: None,
},
"2.0".to_string()
),
"2.1.json" | "2.1" => (
nodeinfo::types::Software {
name: "μpub".to_string(),
version: Some(VERSION.into()),
repository: Some("https://git.alemi.dev/upub.git/".into()),
homepage: None,
},
"2.1".to_string()
),
_ => return Err(StatusCode::NOT_IMPLEMENTED),
};
Ok(Json(
nodeinfo::NodeInfoOwned {
version,
software,
open_registrations: false,
protocols: vec!["activitypub".into()],
services: nodeinfo::types::Services {
inbound: vec![],
outbound: vec![],
},
usage: nodeinfo::types::Usage {
local_posts: total_posts,
local_comments: total_comments,
users: Some(nodeinfo::types::Users {
active_month: None,
active_halfyear: None,
total: total_users.map(|x| x as i64),
}),
},
metadata: serde_json::Map::default(),
}
))
}
#[derive(Debug, serde::Deserialize)]
pub struct WebfingerQuery {
pub resource: String,
}
pub struct JsonRD<T>(pub T);
impl<T: serde::Serialize> IntoResponse for JsonRD<T> {
fn into_response(self) -> Response {
([("Content-Type", "application/jrd+json")], Json(self.0)).into_response()
}
}
pub async fn webfinger(State(ctx): State<Context>, Query(query): Query<WebfingerQuery>) -> Result<JsonRD<JsonResourceDescriptor>, StatusCode> {
if let Some((user, domain)) = query
.resource
.replace("acct:", "")
.split_once('@')
{
let uid = ctx.uid(user.to_string());
match model::user::Entity::find_by_id(uid)
.one(ctx.db())
.await
{
Ok(Some(x)) => Ok(JsonRD(JsonResourceDescriptor {
subject: format!("acct:{user}@{domain}"),
aliases: vec![x.id.clone()],
links: vec![
JsonResourceDescriptorLink {
rel: "self".to_string(),
link_type: Some("application/ld+json".to_string()),
href: Some(x.id),
properties: jrd::Map::default(),
titles: jrd::Map::default(),
},
],
expires: None,
properties: jrd::Map::default(),
})),
Ok(None) => Err(StatusCode::NOT_FOUND),
Err(e) => {
tracing::error!("error executing webfinger query: {e}");
Err(StatusCode::INTERNAL_SERVER_ERROR)
},
}
} else {
Err(StatusCode::UNPROCESSABLE_ENTITY)
}
}
// i don't even want to bother with XML, im just returning a formatted xml string
pub async fn host_meta(State(ctx): State<Context>) -> Response {
(
[("Content-Type", "application/xrd+xml")],
format!(r#"<?xml version="1.0" encoding="UTF-8"?>
<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">
<Link type="application/xrd+xml" template="{}{}/.well-known/webfinger?resource={{uri}}" rel="lrdd" />
</XRD>"#,
ctx.protocol(), ctx.base())
).into_response()
}

View file

@ -0,0 +1,43 @@
use axum::{extract::{Path, State}, http::StatusCode, Json};
use mastodon_async_entities::account::{Account, AccountId};
use sea_orm::EntityTrait;
use crate::{model, server::{auth::AuthIdentity, Context}};
pub async fn view(
State(ctx): State<Context>,
AuthIdentity(_auth): AuthIdentity,
Path(id): Path<String>
) -> Result<Json<Account>, StatusCode> {
match model::user::Entity::find_by_id(ctx.uid(id))
.find_also_related(model::config::Entity)
.one(ctx.db())
.await
{
Err(_e) => Err(StatusCode::INTERNAL_SERVER_ERROR),
Ok(None) => Err(StatusCode::NOT_FOUND),
Ok(Some((_x, None))) => Err(StatusCode::NOT_IMPLEMENTED), // TODO remote user
Ok(Some((x, Some(cfg)))) => Ok(Json(Account {
acct: x.preferred_username.clone(),
avatar: x.icon.as_deref().unwrap_or("").to_string(),
avatar_static: x.icon.unwrap_or_default(),
created_at: time::OffsetDateTime::from_unix_timestamp(x.created.timestamp()).unwrap(),
display_name: x.name.unwrap_or_default(),
// TODO hide these maybe
followers_count: x.followers_count as u64,
following_count: x.following_count as u64,
header: x.image.as_deref().unwrap_or("").to_string(),
header_static: x.image.unwrap_or_default(),
id: AccountId::new(x.id.clone()),
locked: !cfg.accept_follow_requests,
note: x.summary.unwrap_or_default(),
statuses_count: 0, // TODO keep track in each user
url: x.id,
username: x.preferred_username,
source: None,
moved: None,
fields: None, // TODO user fields
bot: None,
})),
}
}

View file

@ -1,5 +1,4 @@
pub mod accounts; pub mod accounts;
pub mod instance;
use axum::{http::StatusCode, routing::{delete, get, patch, post}, Router}; use axum::{http::StatusCode, routing::{delete, get, patch, post}, Router};
use crate::server::Context; use crate::server::Context;
@ -71,8 +70,6 @@ impl MastodonRouter for Router<Context> {
.route("/profile/avatar", delete(todo)) .route("/profile/avatar", delete(todo))
.route("/profile/header", delete(todo)) .route("/profile/header", delete(todo))
.route("/statuses", post(todo)) .route("/statuses", post(todo))
// ...
.route("/instance", get(mas::instance::get))
) )
} }
} }

16
src/routes/mod.rs Normal file
View file

@ -0,0 +1,16 @@
pub mod activitypub;
#[cfg(feature = "web")]
pub mod web;
#[cfg(feature = "mastodon")]
pub mod mastodon;
#[cfg(not(feature = "mastodon"))]
pub mod mastodon {
pub trait MastodonRouter {
fn mastodon_routes(self) -> Self { self }
}
impl MastodonRouter for axum::Router<crate::server::Context> {}
}

136
src/server/auth.rs Normal file
View file

@ -0,0 +1,136 @@
use std::collections::BTreeMap;
use axum::{extract::{FromRef, FromRequestParts}, http::{header, request::Parts, StatusCode}};
use openssl::hash::MessageDigest;
use sea_orm::{ColumnTrait, Condition, EntityTrait, QueryFilter};
use crate::{model, server::Context};
#[derive(Debug, Clone)]
pub enum Identity {
Anonymous,
Local(String),
Remote(String),
}
pub struct AuthIdentity(pub Identity);
#[axum::async_trait]
impl<S> FromRequestParts<S> for AuthIdentity
where
Context: FromRef<S>,
S: Send + Sync,
{
type Rejection = StatusCode;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let ctx = Context::from_ref(state);
let mut identity = Identity::Anonymous;
let auth_header = parts
.headers
.get(header::AUTHORIZATION)
.map(|v| v.to_str().unwrap_or(""))
.unwrap_or("");
if auth_header.starts_with("Bearer ") {
match model::session::Entity::find_by_id(auth_header.replace("Bearer ", ""))
.filter(Condition::all().add(model::session::Column::Expires.gt(chrono::Utc::now())))
.one(ctx.db())
.await
{
Ok(Some(x)) => identity = Identity::Local(x.actor),
Ok(None) => return Err(StatusCode::UNAUTHORIZED),
Err(e) => {
tracing::error!("failed querying user session: {e}");
return Err(StatusCode::INTERNAL_SERVER_ERROR)
},
}
}
// if let Some(sig) = parts
// .headers
// .get("Signature")
// .map(|v| v.to_str().unwrap_or(""))
// {
// let signature = HttpSignature::try_from(sig)?;
// let user_id = signature.key_id.split('#').next().unwrap_or("").to_string();
// let data : String = signature.headers.iter()
// .map(|header| {
// if header == "(request-target)" {
// format!("(request-target): {} {}", parts.method, parts.uri)
// } else {
// format!(
// "{header}: {}",
// parts.headers.get(header)
// .map(|h| h.to_str().unwrap_or(""))
// .unwrap_or("")
// )
// }
// })
// .collect::<Vec<String>>() // TODO can we avoid this unneeded allocation?
// .join("\n");
// let user = ctx.fetch().user(&user_id).await.map_err(|_e| StatusCode::UNAUTHORIZED)?;
// let pubkey = PKey::public_key_from_pem(user.public_key.as_bytes()).map_err(|_e| StatusCode::INTERNAL_SERVER_ERROR)?;
// let mut verifier = Verifier::new(signature.digest(), &pubkey).map_err(|_e| StatusCode::INTERNAL_SERVER_ERROR)?;
// verifier.update(data.as_bytes()).map_err(|_e| StatusCode::INTERNAL_SERVER_ERROR)?;
// if verifier.verify(signature.signature.as_bytes()).map_err(|_e| StatusCode::INTERNAL_SERVER_ERROR)? {
// identity = Identity::Remote(user_id);
// } else {
// return Err(StatusCode::FORBIDDEN);
// }
// }
Ok(AuthIdentity(identity))
}
}
#[allow(unused)] // TODO am i gonna reimplement http signatures for verification?
pub struct HttpSignature {
key_id: String,
algorithm: String,
headers: Vec<String>,
signature: String,
}
impl HttpSignature {
#[allow(unused)] // TODO am i gonna reimplement http signatures for verification?
pub fn digest(&self) -> MessageDigest {
match self.algorithm.as_str() {
"rsa-sha512" => MessageDigest::sha512(),
"rsa-sha384" => MessageDigest::sha384(),
"rsa-sha256" => MessageDigest::sha256(),
"rsa-sha1" => MessageDigest::sha1(),
_ => {
tracing::error!("unknown digest algorithm, trying with rsa-sha256");
MessageDigest::sha256()
}
}
}
}
impl TryFrom<&str> for HttpSignature {
type Error = StatusCode; // TODO: quite ad hoc...
fn try_from(value: &str) -> Result<Self, Self::Error> {
let parameters : BTreeMap<String, String> = value
.split(',')
.filter_map(|s| { // TODO kinda ugly, can be made nicer?
let (k, v) = s.split_once("=\"")?;
let (k, mut v) = (k.to_string(), v.to_string());
v.pop();
Some((k, v))
}).collect();
let sig = HttpSignature {
key_id: parameters.get("keyId").ok_or(StatusCode::BAD_REQUEST)?.to_string(),
algorithm: parameters.get("algorithm").ok_or(StatusCode::BAD_REQUEST)?.to_string(),
headers: parameters.get("headers").map(|x| x.split(' ').map(|x| x.to_string()).collect()).unwrap_or(vec!["date".to_string()]),
signature: parameters.get("signature").ok_or(StatusCode::BAD_REQUEST)?.to_string(),
};
Ok(sig)
}
}

229
src/server/context.rs Normal file
View file

@ -0,0 +1,229 @@
use std::sync::Arc;
use apb::{BaseMut, CollectionMut, CollectionPageMut};
use openssl::rsa::Rsa;
use sea_orm::{ColumnTrait, Condition, DatabaseConnection, EntityTrait, QueryFilter, QuerySelect, SelectColumns, Set};
use crate::{model, routes::activitypub::jsonld::LD};
use super::{dispatcher::Dispatcher, fetcher::Fetcher};
#[derive(Clone)]
pub struct Context(Arc<ContextInner>);
struct ContextInner {
db: DatabaseConnection,
domain: String,
protocol: String,
fetcher: Fetcher,
dispatcher: Dispatcher,
// TODO keep these pre-parsed
app: model::application::Model,
}
#[macro_export]
macro_rules! url {
($ctx:expr, $($args: tt)*) => {
format!("{}{}{}", $ctx.protocol(), $ctx.base(), format!($($args)*))
};
}
impl Context {
// TODO slim constructor down, maybe make a builder?
pub async fn new(db: DatabaseConnection, mut domain: String) -> crate::Result<Self> {
let protocol = if domain.starts_with("http://")
{ "http://" } else { "https://" }.to_string();
if domain.ends_with('/') {
domain.replace_range(domain.len()-1.., "");
}
if domain.starts_with("http") {
domain = domain.replace("https://", "").replace("http://", "");
}
let dispatcher = Dispatcher::new();
for _ in 0..1 { // TODO customize delivery workers amount
dispatcher.spawn(db.clone(), domain.clone(), 30); // TODO ew don't do it this deep and secretly!!
}
let app = match model::application::Entity::find().one(&db).await? {
Some(model) => model,
None => {
tracing::info!("generating application keys");
let rsa = Rsa::generate(2048)?;
let privk = std::str::from_utf8(&rsa.private_key_to_pem()?)?.to_string();
let pubk = std::str::from_utf8(&rsa.public_key_to_pem()?)?.to_string();
let system = model::application::ActiveModel {
id: sea_orm::ActiveValue::NotSet,
private_key: sea_orm::ActiveValue::Set(privk.clone()),
public_key: sea_orm::ActiveValue::Set(pubk.clone()),
created: sea_orm::ActiveValue::Set(chrono::Utc::now()),
};
model::application::Entity::insert(system).exec(&db).await?;
// sqlite doesn't resurn last inserted id so we're better off just querying again, it's just one time
model::application::Entity::find().one(&db).await?.expect("could not find app config just inserted")
}
};
let fetcher = Fetcher::new(db.clone(), domain.clone(), app.private_key.clone());
Ok(Context(Arc::new(ContextInner {
db, domain, protocol, app, fetcher, dispatcher,
})))
}
pub fn app(&self) -> &model::application::Model {
&self.0.app
}
pub fn db(&self) -> &DatabaseConnection {
&self.0.db
}
pub fn base(&self) -> &str {
&self.0.domain
}
pub fn protocol(&self) -> &str {
&self.0.protocol
}
pub fn uri(&self, entity: &str, id: String) -> String {
if id.starts_with("http") { id } else {
format!("{}{}/{}/{}", self.0.protocol, self.0.domain, entity, id)
}
}
pub fn fetch(&self) -> &Fetcher {
&self.0.fetcher
}
/// get full user id uri
pub fn uid(&self, id: String) -> String {
self.uri("users", id)
}
/// get full object id uri
pub fn oid(&self, id: String) -> String {
self.uri("objects", id)
}
/// get full activity id uri
pub fn aid(&self, id: String) -> String {
self.uri("activities", id)
}
/// get bare id, usually an uuid but unspecified
pub fn id(&self, id: String) -> String {
if id.starts_with(&self.0.domain) {
id.split('/').last().unwrap_or("").to_string()
} else {
id
}
}
pub fn server(id: &str) -> String {
id
.replace("https://", "")
.replace("http://", "")
.split('/')
.next()
.unwrap_or("")
.to_string()
}
pub async fn expand_addressing(&self, uid: &str, mut targets: Vec<String>) -> crate::Result<Vec<String>> {
let following_addr = format!("{uid}/followers");
if let Some(i) = targets.iter().position(|x| x == &following_addr) {
targets.remove(i);
model::relation::Entity::find()
.filter(Condition::all().add(model::relation::Column::Following.eq(uid.to_string())))
.select_only()
.select_column(model::relation::Column::Follower)
.into_tuple::<String>()
.all(self.db())
.await?
.into_iter()
.for_each(|x| targets.push(x));
}
Ok(targets)
}
pub async fn address_to(&self, aid: &str, oid: Option<&str>, targets: &[String]) -> crate::Result<()> {
let addressings : Vec<model::addressing::ActiveModel> = targets
.iter()
.filter(|to| !to.is_empty())
.filter(|to| !to.ends_with("/followers"))
.map(|to| model::addressing::ActiveModel {
id: sea_orm::ActiveValue::NotSet,
server: Set(Context::server(to)),
actor: Set(to.to_string()),
activity: Set(aid.to_string()),
object: Set(oid.map(|x| x.to_string())),
published: Set(chrono::Utc::now()),
})
.collect();
if !addressings.is_empty() {
model::addressing::Entity::insert_many(addressings)
.exec(self.db())
.await?;
}
Ok(())
}
pub async fn deliver_to(&self, aid: &str, from: &str, targets: &[String]) -> crate::Result<()> {
let deliveries : Vec<model::delivery::ActiveModel> = targets
.iter()
.filter(|to| !to.is_empty())
.filter(|to| Context::server(to) != self.base())
.filter(|to| to != &apb::target::PUBLIC)
.map(|to| model::delivery::ActiveModel {
id: sea_orm::ActiveValue::NotSet,
actor: Set(from.to_string()),
// TODO we should resolve each user by id and check its inbox because we can't assume
// it's /users/{id}/inbox for every software, but oh well it's waaaaay easier now
target: Set(format!("{}/inbox", to)),
activity: Set(aid.to_string()),
created: Set(chrono::Utc::now()),
not_before: Set(chrono::Utc::now()),
attempt: Set(0),
})
.collect();
if !deliveries.is_empty() {
model::delivery::Entity::insert_many(deliveries)
.exec(self.db())
.await?;
}
self.0.dispatcher.wakeup();
Ok(())
}
// TODO should probs not be here
pub fn ap_collection(&self, id: &str, total_items: Option<u64>) -> serde_json::Value {
serde_json::Value::new_object()
.set_id(Some(id))
.set_collection_type(Some(apb::CollectionType::OrderedCollection))
.set_first(apb::Node::link(format!("{id}/page")))
.set_total_items(total_items)
}
// TODO should probs not be here
pub fn ap_collection_page(&self, id: &str, offset: u64, limit: u64, items: Vec<serde_json::Value>) -> serde_json::Value {
serde_json::Value::new_object()
.set_id(Some(&format!("{id}?offset={offset}")))
.set_collection_type(Some(apb::CollectionType::OrderedCollectionPage))
.set_part_of(apb::Node::link(id.replace("/page", "")))
.set_next(apb::Node::link(format!("{id}?offset={}", offset+limit)))
.set_ordered_items(apb::Node::Array(items))
}
pub async fn dispatch(&self, uid: &str, activity_targets: Vec<String>, aid: &str, oid: Option<&str>) -> crate::Result<()> {
let addressed = self.expand_addressing(uid, activity_targets).await?;
self.address_to(aid, oid, &addressed).await?;
self.deliver_to(aid, uid, &addressed).await?;
Ok(())
}
}

171
src/server/dispatcher.rs Normal file
View file

@ -0,0 +1,171 @@
use base64::Engine;
use openssl::{hash::MessageDigest, pkey::{PKey, Private}, sign::Signer};
use reqwest::header::{CONTENT_TYPE, USER_AGENT};
use sea_orm::{ColumnTrait, Condition, DatabaseConnection, EntityTrait, Order, QueryFilter, QueryOrder};
use tokio::{sync::broadcast, task::JoinHandle};
use apb::{ActivityMut, Node};
use crate::{routes::activitypub::{activity::ap_activity, object::ap_object}, errors::UpubError, model, server::Context, VERSION};
pub struct Dispatcher {
waker: broadcast::Sender<()>,
}
impl Default for Dispatcher {
fn default() -> Self {
let (waker, _) = broadcast::channel(1);
Dispatcher { waker }
}
}
impl Dispatcher {
pub fn new() -> Self { Dispatcher::default() }
pub fn spawn(&self, db: DatabaseConnection, domain: String, poll_interval: u64) -> JoinHandle<()> {
let waker = self.waker.subscribe();
tokio::spawn(async move {
if let Err(e) = worker(db, domain, poll_interval, waker).await {
tracing::error!("delivery worker exited with error: {e}");
}
})
}
pub fn wakeup(&self) {
match self.waker.send(()) {
Err(_) => tracing::error!("no worker to wakeup"),
Ok(n) => tracing::debug!("woken {n} workers"),
}
}
}
async fn worker(db: DatabaseConnection, domain: String, poll_interval: u64, mut waker: broadcast::Receiver<()>) -> Result<(), UpubError> {
loop {
let Some(delivery) = model::delivery::Entity::find()
.filter(Condition::all().add(model::delivery::Column::NotBefore.lte(chrono::Utc::now())))
.order_by(model::delivery::Column::NotBefore, Order::Asc)
.one(&db)
.await?
else {
tokio::select! {
biased;
_ = waker.recv() => {},
_ = tokio::time::sleep(std::time::Duration::from_secs(poll_interval)) => {},
}
continue
};
let del_row = model::delivery::ActiveModel {
id: sea_orm::ActiveValue::Set(delivery.id),
..Default::default()
};
let del = model::delivery::Entity::delete(del_row)
.exec(&db)
.await?;
if del.rows_affected == 0 {
// another worker claimed this delivery
continue; // go back to the top
}
if delivery.expired() {
// try polling for another one
continue; // go back to top
}
tracing::info!("delivering {} to {}", delivery.activity, delivery.target);
let payload = match model::activity::Entity::find_by_id(&delivery.activity)
.find_also_related(model::object::Entity)
.one(&db)
.await? // TODO probably should not fail here and at least re-insert the delivery
{
Some((activity, Some(object))) => ap_activity(activity).set_object(Node::object(ap_object(object))),
Some((activity, None)) => ap_activity(activity),
None => {
tracing::warn!("skipping dispatch for deleted object {}", delivery.activity);
continue;
},
};
let Some(model::user::Model{ private_key: Some(key), .. }) = model::user::Entity::find_by_id(&delivery.actor)
.one(&db).await?
else {
tracing::error!("can not dispatch activity for user without private key: {}", delivery.actor);
continue;
};
let Ok(key) = PKey::private_key_from_pem(key.as_bytes())
else {
tracing::error!("failed parsing private key for user {}", delivery.actor);
continue;
};
if let Err(e) = deliver(&key, &delivery.target, &delivery.actor, payload, &domain).await {
tracing::warn!("failed delivery of {} to {} : {e}", delivery.activity, delivery.target);
let new_delivery = model::delivery::ActiveModel {
id: sea_orm::ActiveValue::NotSet,
not_before: sea_orm::ActiveValue::Set(delivery.next_delivery()),
actor: sea_orm::ActiveValue::Set(delivery.actor),
target: sea_orm::ActiveValue::Set(delivery.target),
activity: sea_orm::ActiveValue::Set(delivery.activity),
created: sea_orm::ActiveValue::Set(delivery.created),
attempt: sea_orm::ActiveValue::Set(delivery.attempt + 1),
};
model::delivery::Entity::insert(new_delivery).exec(&db).await?;
}
}
}
async fn deliver(key: &PKey<Private>, to: &str, from: &str, payload: serde_json::Value, domain: &str) -> Result<(), UpubError> {
let payload = serde_json::to_string(&payload).unwrap();
let digest = format!("sha-256={}", base64::prelude::BASE64_STANDARD.encode(openssl::sha::sha256(payload.as_bytes())));
let host = Context::server(to);
let date = chrono::Utc::now().format("%a, %d %b %Y %H:%M:%S GMT").to_string(); // lmao @ "GMT"
let path = to.replace("https://", "").replace("http://", "").replace(&host, "");
// let headers : BTreeMap<String, String> = [
// ("Host".to_string(), host.clone()),
// ("Date".to_string(), date.clone()),
// ("Digest".to_string(), digest.clone()),
// ].into();
// let signature_header = Config::new()
// .dont_use_created_field()
// .require_header("host")
// .require_header("date")
// .require_header("digest")
// .begin_sign("POST", &path, headers)
// .unwrap()
// .sign(format!("{from}#main-key"), |to_sign| {
// tracing::info!("signing '{to_sign}'");
// let mut signer = Signer::new(MessageDigest::sha256(), key)?;
// signer.update(to_sign.as_bytes())?;
// let signature = base64::prelude::BASE64_URL_SAFE.encode(signer.sign_to_vec()?);
// Ok(signature) as Result<_, UpubError>
// })
// .unwrap()
// .signature_header();
let signature_header = {
let to_sign = format!("(request-target): post {path}\nhost: {host}\ndate: {date}\ndigest: {digest}");
let mut signer = Signer::new(MessageDigest::sha256(), key)?;
signer.update(to_sign.as_bytes())?;
let signature = base64::prelude::BASE64_STANDARD.encode(signer.sign_to_vec()?);
format!("keyId=\"{from}#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target) host date digest\",signature=\"{signature}\"")
};
reqwest::Client::new()
.post(to)
.header("Host", host)
.header("Date", date)
.header("Digest", digest)
.header("Signature", signature_header)
.header(CONTENT_TYPE, "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"")
.header(USER_AGENT, format!("upub+{VERSION} ({domain})")) // TODO put instance admin email
.body(payload)
.send()
.await?
.error_for_status()?;
Ok(())
}

53
src/server/fetcher.rs Normal file
View file

@ -0,0 +1,53 @@
use openssl::pkey::{PKey, Private};
use reqwest::header::USER_AGENT;
use sea_orm::{DatabaseConnection, EntityTrait, IntoActiveModel};
use crate::{VERSION, model};
#[derive(Debug, thiserror::Error)]
pub enum FetchError {
#[error("could not dereference resource: {0}")]
Network(#[from] reqwest::Error),
#[error("error operating on database: {0}")]
Database(#[from] sea_orm::DbErr),
#[error("missing field when constructing object: {0}")]
Field(#[from] model::FieldError),
}
pub struct Fetcher {
db: DatabaseConnection,
_key: PKey<Private>, // TODO store pre-parsed
domain: String, // TODO merge directly with Context so we don't need to copy this
}
impl Fetcher {
pub fn new(db: DatabaseConnection, domain: String, key: String) -> Self {
Fetcher { db, domain, _key: PKey::private_key_from_pem(key.as_bytes()).unwrap() }
}
pub async fn user(&self, id: &str) -> Result<model::user::Model, FetchError> {
if let Some(x) = model::user::Entity::find_by_id(id).one(&self.db).await? {
return Ok(x); // already in db, easy
}
// TODO sign http fetches, we got the app key and db to get user keys just in case
tracing::info!("fetching {id}");
let user = reqwest::Client::new()
.get(id)
.header(USER_AGENT, format!("upub+{VERSION} ({})", self.domain)) // TODO put instance admin email
.send()
.await?
.json::<serde_json::Value>()
.await?;
let user_model = model::user::Model::new(&user)?;
model::user::Entity::insert(user_model.clone().into_active_model())
.exec(&self.db).await?;
Ok(user_model)
}
}

166
src/server/inbox.rs Normal file
View file

@ -0,0 +1,166 @@
use apb::{target::Addressed, Activity, Base, Object};
use sea_orm::{sea_query::Expr, ColumnTrait, EntityTrait, IntoActiveModel, QueryFilter, Set};
use crate::{errors::{LoggableError, UpubError}, model};
use super::Context;
#[axum::async_trait]
impl apb::server::Inbox for Context {
type Error = UpubError;
type Activity = serde_json::Value;
async fn create(&self, activity: serde_json::Value) -> crate::Result<()> {
let activity_model = model::activity::Model::new(&activity)?;
let activity_targets = activity.addressed();
let Some(object_node) = activity.object().extract() else {
// TODO we could process non-embedded activities or arrays but im lazy rn
tracing::error!("refusing to process activity without embedded object: {}", serde_json::to_string_pretty(&activity).unwrap());
return Err(UpubError::unprocessable());
};
let object_model = model::object::Model::new(&object_node)?;
let aid = activity_model.id.clone();
let oid = object_model.id.clone();
model::object::Entity::insert(object_model.into_active_model()).exec(self.db()).await?;
model::activity::Entity::insert(activity_model.into_active_model()).exec(self.db()).await?;
self.address_to(&aid, Some(&oid), &activity_targets).await?;
tracing::info!("{} posted {}", aid, oid);
Ok(())
}
async fn like(&self, activity: serde_json::Value) -> crate::Result<()> {
let aid = activity.actor().id().ok_or(UpubError::bad_request())?;
let oid = activity.object().id().ok_or(UpubError::bad_request())?;
let like = model::like::ActiveModel {
id: sea_orm::ActiveValue::NotSet,
actor: sea_orm::Set(aid.clone()),
likes: sea_orm::Set(oid.clone()),
date: sea_orm::Set(chrono::Utc::now()),
};
match model::like::Entity::insert(like).exec(self.db()).await {
Err(sea_orm::DbErr::RecordNotInserted) => Err(UpubError::not_modified()),
Err(sea_orm::DbErr::Exec(_)) => Err(UpubError::not_modified()), // bad fix for sqlite
Err(e) => {
tracing::error!("unexpected error procesing like from {aid} to {oid}: {e}");
Err(UpubError::internal_server_error())
}
Ok(_) => {
model::object::Entity::update_many()
.col_expr(model::object::Column::Likes, Expr::col(model::object::Column::Likes).add(1))
.filter(model::object::Column::Id.eq(oid.clone()))
.exec(self.db())
.await?;
tracing::info!("{} liked {}", aid, oid);
Ok(())
},
}
}
async fn follow(&self, activity: serde_json::Value) -> crate::Result<()> {
let activity_targets = activity.addressed();
let activity_model = model::activity::Model::new(&activity)?;
let aid = activity_model.id.clone();
tracing::info!("{} wants to follow {}", activity_model.actor, activity_model.object.as_deref().unwrap_or("<no-one???>"));
model::activity::Entity::insert(activity_model.into_active_model())
.exec(self.db()).await?;
self.address_to(&aid, None, &activity_targets).await?;
Ok(())
}
async fn accept(&self, activity: serde_json::Value) -> crate::Result<()> {
// TODO what about TentativeAccept
let activity_model = model::activity::Model::new(&activity)?;
let Some(follow_request_id) = activity_model.object else {
return Err(UpubError::bad_request());
};
let Some(follow_activity) = model::activity::Entity::find_by_id(follow_request_id)
.one(self.db()).await?
else {
return Err(UpubError::not_found());
};
if follow_activity.object.unwrap_or("".into()) != activity_model.actor {
return Err(UpubError::forbidden());
}
tracing::info!("{} accepted follow request by {}", activity_model.actor, follow_activity.actor);
model::relation::Entity::insert(
model::relation::ActiveModel {
follower: Set(follow_activity.actor),
following: Set(activity_model.actor),
..Default::default()
}
).exec(self.db()).await?;
self.address_to(&activity_model.id, None, &activity.addressed()).await?;
Ok(())
}
async fn reject(&self, activity: serde_json::Value) -> crate::Result<()> {
// TODO what about TentativeReject?
let activity_model = model::activity::Model::new(&activity)?;
let Some(follow_request_id) = activity_model.object else {
return Err(UpubError::bad_request());
};
let Some(follow_activity) = model::activity::Entity::find_by_id(follow_request_id)
.one(self.db()).await?
else {
return Err(UpubError::not_found());
};
if follow_activity.object.unwrap_or("".into()) != activity_model.actor {
return Err(UpubError::forbidden());
}
tracing::info!("{} rejected follow request by {}", activity_model.actor, follow_activity.actor);
self.address_to(&activity_model.id, None, &activity.addressed()).await?;
Ok(())
}
async fn delete(&self, activity: serde_json::Value) -> crate::Result<()> {
// TODO verify the signature before just deleting lmao
let oid = activity.object().id().ok_or(UpubError::bad_request())?;
// TODO maybe we should keep the tombstone?
model::user::Entity::delete_by_id(&oid).exec(self.db()).await.info_failed("failed deleting from users");
model::activity::Entity::delete_by_id(&oid).exec(self.db()).await.info_failed("failed deleting from activities");
model::object::Entity::delete_by_id(&oid).exec(self.db()).await.info_failed("failed deleting from objects");
Ok(())
}
async fn update(&self, activity: serde_json::Value) -> crate::Result<()> {
let activity_model = model::activity::Model::new(&activity)?;
let activity_targets = activity.addressed();
let Some(object_node) = activity.object().extract() else {
// TODO we could process non-embedded activities or arrays but im lazy rn
tracing::error!("refusing to process activity without embedded object: {}", serde_json::to_string_pretty(&activity).unwrap());
return Err(UpubError::unprocessable());
};
let aid = activity_model.id.clone();
let Some(oid) = object_node.id().map(|x| x.to_string()) else {
return Err(UpubError::bad_request());
};
model::activity::Entity::insert(activity_model.into_active_model()).exec(self.db()).await?;
match object_node.object_type() {
Some(apb::ObjectType::Actor(_)) => {
// TODO oof here is an example of the weakness of this model, we have to go all the way
// back up to serde_json::Value because impl Object != impl Actor
let actor_model = model::user::Model::new(&object_node)?;
model::user::Entity::update(actor_model.into_active_model())
.exec(self.db()).await?;
},
Some(apb::ObjectType::Note) => {
let object_model = model::object::Model::new(&object_node)?;
model::object::Entity::update(object_model.into_active_model())
.exec(self.db()).await?;
},
Some(t) => tracing::warn!("no side effects implemented for update type {t:?}"),
None => tracing::warn!("empty type on embedded updated object"),
}
self.address_to(&aid, Some(&oid), &activity_targets).await?;
tracing::info!("{} updated {}", aid, oid);
Ok(())
}
async fn undo(&self, _activity: serde_json::Value) -> crate::Result<()> {
todo!()
}
}

8
src/server/mod.rs Normal file
View file

@ -0,0 +1,8 @@
pub mod context;
pub mod dispatcher;
pub mod fetcher;
pub mod inbox;
pub mod outbox;
pub mod auth;
pub use context::Context;

224
src/server/outbox.rs Normal file
View file

@ -0,0 +1,224 @@
use apb::{target::Addressed, Activity, ActivityMut, BaseMut, Node, ObjectMut};
use sea_orm::{EntityTrait, IntoActiveModel, Set};
use crate::{errors::UpubError, model};
use super::Context;
#[axum::async_trait]
impl apb::server::Outbox for Context {
type Error = UpubError;
type Object = serde_json::Value;
type Activity = serde_json::Value;
async fn create_note(&self, uid: String, object: serde_json::Value) -> crate::Result<String> {
let oid = self.oid(uuid::Uuid::new_v4().to_string());
let aid = self.aid(uuid::Uuid::new_v4().to_string());
let activity_targets = object.addressed();
let object_model = model::object::Model::new(
&object
.set_id(Some(&oid))
.set_attributed_to(Node::link(uid.clone()))
.set_published(Some(chrono::Utc::now()))
)?;
let activity_model = model::activity::Model {
id: aid.clone(),
activity_type: apb::ActivityType::Create,
actor: uid.clone(),
object: Some(oid.clone()),
target: None,
cc: object_model.cc.clone(),
bcc: object_model.bcc.clone(),
to: object_model.to.clone(),
bto: object_model.bto.clone(),
published: object_model.published,
};
model::object::Entity::insert(object_model.into_active_model())
.exec(self.db()).await?;
model::activity::Entity::insert(activity_model.into_active_model())
.exec(self.db()).await?;
self.dispatch(&uid, activity_targets, &aid, Some(&oid)).await?;
Ok(aid)
}
async fn create(&self, uid: String, activity: serde_json::Value) -> crate::Result<String> {
let Some(object) = activity.object().extract() else {
return Err(UpubError::bad_request());
};
let oid = self.oid(uuid::Uuid::new_v4().to_string());
let aid = self.aid(uuid::Uuid::new_v4().to_string());
let activity_targets = activity.addressed();
let mut object_model = model::object::Model::new(
&object
.set_id(Some(&oid))
.set_attributed_to(Node::link(uid.clone()))
.set_published(Some(chrono::Utc::now()))
)?;
let mut activity_model = model::activity::Model::new(
&activity
.set_id(Some(&aid))
.set_actor(Node::link(uid.clone()))
.set_published(Some(chrono::Utc::now()))
)?;
object_model.to = activity_model.to.clone();
object_model.bto = activity_model.bto.clone();
object_model.cc = activity_model.cc.clone();
object_model.bcc = activity_model.bcc.clone();
activity_model.object = Some(oid.clone());
model::object::Entity::insert(object_model.into_active_model())
.exec(self.db()).await?;
model::activity::Entity::insert(activity_model.into_active_model())
.exec(self.db()).await?;
self.dispatch(&uid, activity_targets, &aid, Some(&oid)).await?;
Ok(aid)
}
async fn like(&self, uid: String, activity: serde_json::Value) -> crate::Result<String> {
let aid = self.aid(uuid::Uuid::new_v4().to_string());
let activity_targets = activity.addressed();
let Some(oid) = activity.object().id() else {
return Err(UpubError::bad_request());
};
let activity_model = model::activity::Model::new(
&activity
.set_id(Some(&aid))
.set_published(Some(chrono::Utc::now()))
.set_actor(Node::link(uid.clone()))
)?;
let like_model = model::like::ActiveModel {
actor: Set(uid.clone()),
likes: Set(oid),
date: Set(chrono::Utc::now()),
..Default::default()
};
model::like::Entity::insert(like_model).exec(self.db()).await?;
model::activity::Entity::insert(activity_model.into_active_model())
.exec(self.db()).await?;
self.dispatch(&uid, activity_targets, &aid, None).await?;
Ok(aid)
}
async fn follow(&self, uid: String, activity: serde_json::Value) -> crate::Result<String> {
let aid = self.aid(uuid::Uuid::new_v4().to_string());
let activity_targets = activity.addressed();
if activity.object().id().is_none() {
return Err(UpubError::bad_request());
}
let activity_model = model::activity::Model::new(
&activity
.set_id(Some(&aid))
.set_actor(Node::link(uid.clone()))
.set_published(Some(chrono::Utc::now()))
)?;
model::activity::Entity::insert(activity_model.into_active_model())
.exec(self.db()).await?;
self.dispatch(&uid, activity_targets, &aid, None).await?;
Ok(aid)
}
async fn accept(&self, uid: String, activity: serde_json::Value) -> crate::Result<String> {
let aid = self.aid(uuid::Uuid::new_v4().to_string());
let activity_targets = activity.addressed();
if activity.object().id().is_none() {
return Err(UpubError::bad_request());
}
let Some(accepted_id) = activity.object().id() else {
return Err(UpubError::bad_request());
};
let Some(accepted_activity) = model::activity::Entity::find_by_id(accepted_id)
.one(self.db()).await?
else {
return Err(UpubError::not_found());
};
match accepted_activity.activity_type {
apb::ActivityType::Follow => {
model::relation::Entity::insert(
model::relation::ActiveModel {
follower: Set(accepted_activity.actor), following: Set(uid.clone()),
..Default::default()
}
).exec(self.db()).await?;
},
t => tracing::warn!("no side effects implemented for accepting {t:?}"),
}
let activity_model = model::activity::Model::new(
&activity
.set_id(Some(&aid))
.set_actor(Node::link(uid.clone()))
.set_published(Some(chrono::Utc::now()))
)?;
model::activity::Entity::insert(activity_model.into_active_model())
.exec(self.db()).await?;
self.dispatch(&uid, activity_targets, &aid, None).await?;
Ok(aid)
}
async fn reject(&self, _uid: String, _activity: serde_json::Value) -> crate::Result<String> {
todo!()
}
async fn undo(&self, uid: String, activity: serde_json::Value) -> crate::Result<String> {
let aid = self.aid(uuid::Uuid::new_v4().to_string());
let activity_targets = activity.addressed();
{
let Some(old_aid) = activity.object().id() else {
return Err(UpubError::bad_request());
};
let Some(old_activity) = model::activity::Entity::find_by_id(old_aid)
.one(self.db()).await?
else {
return Err(UpubError::not_found());
};
if old_activity.actor != uid {
return Err(UpubError::forbidden());
}
match old_activity.activity_type {
apb::ActivityType::Like => {
model::like::Entity::delete(model::like::ActiveModel {
actor: Set(old_activity.actor), likes: Set(old_activity.object.unwrap_or("".into())),
..Default::default()
}).exec(self.db()).await?;
},
apb::ActivityType::Follow => {
model::relation::Entity::delete(model::relation::ActiveModel {
follower: Set(old_activity.actor), following: Set(old_activity.object.unwrap_or("".into())),
..Default::default()
}).exec(self.db()).await?;
},
t => tracing::warn!("extra side effects for activity {t:?} not implemented"),
}
}
let activity_model = model::activity::Model::new(
&activity
.set_id(Some(&aid))
.set_actor(Node::link(uid.clone()))
.set_published(Some(chrono::Utc::now()))
)?;
model::activity::Entity::insert(activity_model.into_active_model())
.exec(self.db())
.await?;
self.dispatch(&uid, activity_targets, &aid, None).await?;
Ok(aid)
}
}

41
src/tools.rs Normal file
View file

@ -0,0 +1,41 @@
// yanked from https://github.com/SeaQL/sea-orm/discussions/1502
use sea_orm::{prelude::*, FromQueryResult};
use sea_orm::sea_query::{Alias, IntoIden, SelectExpr, SelectStatement};
use sea_orm::{EntityTrait, QueryTrait};
pub struct Prefixer<S: QueryTrait<QueryStatement = SelectStatement>> {
pub selector: S,
}
impl<S: QueryTrait<QueryStatement = SelectStatement>> Prefixer<S> {
pub fn new(selector: S) -> Self {
Self { selector }
}
pub fn add_columns<T: EntityTrait>(mut self, entity: T) -> Self {
for col in <T::Column as sea_orm::entity::Iterable>::iter() {
let alias = format!("{}{}", entity.table_name(), col.to_string()); // we use entity.table_name() as prefix
self.selector.query().expr(SelectExpr {
expr: col.select_as(col.into_expr()),
alias: Some(Alias::new(&alias).into_iden()),
window: None,
});
}
self
}
}
// adapted from https://github.com/SeaQL/sea-orm/discussions/1502
#[derive(Debug)]
pub struct ActivityWithObject {
pub activity: crate::model::activity::Model,
pub object: Option<crate::model::object::Model>,
}
impl FromQueryResult for ActivityWithObject {
fn from_query_result(res: &sea_orm::QueryResult, _pre: &str) -> Result<Self, sea_orm::DbErr> {
let activity = crate::model::activity::Model::from_query_result(res, crate::model::activity::Entity.table_name())?;
let object = crate::model::object::Model::from_query_result(res, crate::model::object::Entity.table_name()).ok();
Ok(Self { activity, object })
}
}

View file

@ -1,26 +0,0 @@
[package]
name = "upub-cli"
version = "0.2.0"
edition = "2021"
authors = [ "alemi <me@alemi.dev>" ]
description = "cli maintenance tasks for upub"
license = "AGPL-3.0"
repository = "https://git.alemi.dev/upub.git"
readme = "README.md"
[lib]
[dependencies]
apb = { path = "../../apb/" }
upub = { path = "../core" }
tracing = "0.1"
serde_json = "1"
sha256 = "1.5"
uuid = { version = "1.10", features = ["v4"] }
chrono = { version = "0.4", features = ["serde"] }
openssl = "0.10" # TODO handle pubkeys with a smaller crate
clap = { version = "4.5", features = ["derive"] }
sea-orm = "1.0"
futures = "0.3"
mdhtml = { path = "../../utils/mdhtml/" }
reqwest = { version = "0.12", features = ["json"] }

View file

@ -1 +0,0 @@
# upub cli

View file

@ -1,115 +0,0 @@
use futures::TryStreamExt;
use sea_orm::{ActiveModelTrait, ActiveValue::{NotSet, Set, Unchanged}, ColumnTrait, Condition, EntityTrait, IntoActiveModel, QueryFilter, QuerySelect, SelectColumns};
use upub::traits::{fetch::RequestError, Cloaker};
pub async fn cloak(ctx: upub::Context, post_contents: bool, objects: bool, actors: bool) -> Result<(), RequestError> {
let local_base = format!("{}%", ctx.base());
{
let mut stream = upub::model::attachment::Entity::find()
.filter(upub::model::attachment::Column::Url.not_like(&local_base))
.stream(ctx.db())
.await?;
while let Some(attachment) = stream.try_next().await? {
tracing::info!("cloaking {}", attachment.url);
let (sig, url) = ctx.cloak(&attachment.url);
let mut model = attachment.into_active_model();
model.url = Set(upub::url!(ctx, "/proxy/{sig}/{url}"));
model.update(ctx.db()).await?;
}
}
if objects {
let mut stream = upub::model::object::Entity::find()
.filter(upub::model::object::Column::Image.is_not_null())
.filter(upub::model::object::Column::Image.not_like(&local_base))
.select_only()
.select_column(upub::model::object::Column::Internal)
.select_column(upub::model::object::Column::Image)
.into_tuple::<(i64, String)>()
.stream(ctx.db())
.await?;
while let Some((internal, image)) = stream.try_next().await? {
tracing::info!("cloaking object image {image}");
let model = upub::model::object::ActiveModel {
internal: Unchanged(internal),
image: Set(Some(ctx.cloaked(&image))),
..Default::default()
};
model.update(ctx.db()).await?;
}
}
if actors {
let mut stream = upub::model::actor::Entity::find()
.filter(
Condition::any()
.add(upub::model::actor::Column::Image.not_like(&local_base))
.add(upub::model::actor::Column::Icon.not_like(&local_base))
)
.select_only()
.select_column(upub::model::actor::Column::Internal)
.select_column(upub::model::actor::Column::Image)
.select_column(upub::model::actor::Column::Icon)
.into_tuple::<(i64, Option<String>, Option<String>)>()
.stream(ctx.db())
.await?;
while let Some((internal, image, icon)) = stream.try_next().await? {
tracing::info!("cloaking user #{internal}");
if image.is_none() && icon.is_none() { continue }
// TODO can this if/else/else be made nicer??
let image = if let Some(img) = image {
if !img.starts_with(ctx.base()) {
Set(Some(ctx.cloaked(&img)))
} else {
NotSet
}
} else {
NotSet
};
let icon = if let Some(icn) = icon {
if !icn.starts_with(ctx.base()) {
Set(Some(ctx.cloaked(&icn)))
} else {
NotSet
}
} else {
NotSet
};
let model = upub::model::actor::ActiveModel {
internal: Unchanged(internal),
image, icon,
..Default::default()
};
model.update(ctx.db()).await?;
}
}
if post_contents {
let mut stream = upub::model::object::Entity::find()
.filter(upub::model::object::Column::Content.like("%<img%"))
.select_only()
.select_column(upub::model::object::Column::Internal)
.select_column(upub::model::object::Column::Content)
.into_tuple::<(i64, String)>()
.stream(ctx.db())
.await?;
while let Some((internal, content)) = stream.try_next().await? {
let sanitized = ctx.sanitize(&content);
if sanitized != content {
tracing::info!("sanitizing object #{internal}");
let model = upub::model::object::ActiveModel {
internal: Unchanged(internal),
content: Set(Some(sanitized)),
..Default::default()
};
model.update(ctx.db()).await?;
}
}
}
Ok(())
}

View file

@ -1,65 +0,0 @@
use sea_orm::{EntityTrait, TransactionTrait};
use upub::traits::{fetch::RequestError, Addresser, Fetcher, Normalizer};
pub async fn fetch(ctx: upub::Context, uri: String, save: bool, actor: Option<String>) -> Result<(), RequestError> {
use apb::Base;
let mut pkey = ctx.pkey().to_string();
let mut from = ctx.base().to_string();
if let Some(actor) = actor {
let actor_model = upub::model::actor::Entity::find_by_ap_id(&actor)
.one(ctx.db())
.await?
.ok_or_else(|| sea_orm::DbErr::RecordNotFound(actor.clone()))?;
match actor_model.private_key {
None => tracing::error!("requested actor lacks a private key, fetching with server key instead"),
Some(x) => {
pkey = x;
from = actor.to_string();
},
}
}
let mut node = apb::Node::link(uri.to_string());
if let apb::Node::Link(ref uri) = node {
if let Ok(href) = uri.href() {
node = upub::Context::request(reqwest::Method::GET, &href, None, &from, &pkey, ctx.domain())
.await?
.json::<serde_json::Value>()
.await?
.into();
}
}
let obj = node.into_inner().expect("node still empty after fetch?");
println!("{}", serde_json::to_string_pretty(&obj).unwrap());
if save {
let tx = ctx.db().begin().await?;
match obj.base_type() {
Ok(apb::BaseType::Object(apb::ObjectType::Actor(_))) => {
upub::model::actor::Entity::insert(upub::AP::actor_q(&obj, None)?)
.exec(&tx)
.await?;
},
Ok(apb::BaseType::Object(apb::ObjectType::Activity(_))) => {
let act = ctx.insert_activity(obj, &tx).await?;
ctx.address(Some(&act), None, &tx).await?;
},
Ok(apb::BaseType::Object(apb::ObjectType::Note)) => {
let obj = ctx.insert_object(obj, &tx).await?;
ctx.address(None, Some(&obj), &tx).await?;
},
Ok(apb::BaseType::Object(t)) => tracing::warn!("not implemented: {:?}", t),
Ok(apb::BaseType::Link(_)) => tracing::error!("fetched another link?"),
Err(_) => tracing::error!("no type on object"),
}
tx.commit().await?;
}
Ok(())
}

View file

@ -1,79 +0,0 @@
use sea_orm::{ActiveModelTrait, EntityTrait};
pub async fn fix(ctx: upub::Context, likes: bool, shares: bool, replies: bool) -> Result<(), sea_orm::DbErr> {
use futures::TryStreamExt;
let db = ctx.db();
if likes {
tracing::info!("fixing likes...");
let mut store = std::collections::HashMap::new();
{
let mut stream = upub::model::like::Entity::find().stream(db).await?;
while let Some(like) = stream.try_next().await? {
store.insert(like.object, store.get(&like.object).unwrap_or(&0) + 1);
}
}
for (k, v) in store {
let m = upub::model::object::ActiveModel {
internal: sea_orm::Unchanged(k),
likes: sea_orm::Set(v),
..Default::default()
};
if let Err(e) = m.update(db).await {
tracing::warn!("record not updated ({k}): {e}");
}
}
}
if shares {
tracing::info!("fixing shares...");
let mut store = std::collections::HashMap::new();
{
let mut stream = upub::model::announce::Entity::find().stream(db).await?;
while let Some(share) = stream.try_next().await? {
store.insert(share.object, store.get(&share.object).unwrap_or(&0) + 1);
}
}
for (k, v) in store {
let m = upub::model::object::ActiveModel {
internal: sea_orm::Unchanged(k),
announces: sea_orm::Set(v),
..Default::default()
};
if let Err(e) = m.update(db).await {
tracing::warn!("record not updated ({k}): {e}");
}
}
}
if replies {
tracing::info!("fixing replies...");
let mut store = std::collections::HashMap::new();
{
let mut stream = upub::model::object::Entity::find().stream(db).await?;
while let Some(object) = stream.try_next().await? {
if let Some(reply) = object.in_reply_to {
let before = store.get(&reply).unwrap_or(&0);
store.insert(reply, before + 1);
}
}
}
for (k, v) in store {
let m = upub::model::object::ActiveModel {
id: sea_orm::Unchanged(k.clone()),
replies: sea_orm::Set(v),
..Default::default()
};
// TODO will update work with non-primary-key field??
if let Err(e) = m.update(db).await {
tracing::warn!("record not updated ({k}): {e}");
}
}
}
tracing::info!("done running fix tasks");
Ok(())
}

View file

@ -1,163 +0,0 @@
mod fix;
pub use fix::*;
mod fetch;
pub use fetch::*;
mod faker;
pub use faker::*;
mod relay;
pub use relay::*;
mod register;
pub use register::*;
mod update;
pub use update::*;
mod nuke;
pub use nuke::*;
mod thread;
pub use thread::*;
mod cloak;
pub use cloak::*;
#[derive(Debug, Clone, clap::Subcommand)]
pub enum CliCommand {
/// generate fake user, note and activity
Faker{
/// how many fake statuses to insert for root user
count: u64,
},
/// fetch a single AP object
Fetch {
/// object id, or uri, to fetch
uri: String,
#[arg(long, default_value_t = false)]
/// store fetched object in local db
save: bool,
#[arg(long)]
/// use this actor's private key to fetch
fetch_as: Option<String>,
},
/// act on remote relay actors at instance level
Relay {
#[clap(subcommand)]
/// action to take against this relay
action: RelayCommand,
},
/// run db maintenance tasks
Fix {
#[arg(long, default_value_t = false)]
/// fix likes counts for posts
likes: bool,
#[arg(long, default_value_t = false)]
/// fix shares counts for posts
shares: bool,
#[arg(long, default_value_t = false)]
/// fix replies counts for posts
replies: bool,
},
/// update remote actors
Update {
#[arg(long, short, default_value_t = 10)]
/// number of days after which actors should get updated
days: i64,
#[arg(long)]
/// stop after updating this many actors
limit: Option<u64>,
},
/// register a new local user
Register {
/// username for new user, must be unique locally and cannot be changed
username: String,
/// password for new user
// TODO get this with getpass rather than argv!!!!
password: String,
/// display name for new user
#[arg(long = "name")]
display_name: Option<String>,
/// summary text for new user
#[arg(long = "summary")]
summary: Option<String>,
/// url for avatar image of new user
#[arg(long = "avatar")]
avatar_url: Option<String>,
/// url for banner image of new user
#[arg(long = "banner")]
banner_url: Option<String>,
},
/// break all user relations so that instance can be shut down
Nuke {
/// unless this is set, nuke will be a dry run
#[arg(long, default_value_t = false)]
for_real: bool,
/// also send Delete activities for all local objects
#[arg(long, default_value_t = false)]
delete_objects: bool,
},
/// attempt to fix broken threads and completely gather their context
Thread {
},
/// replaces all attachment urls with proxied local versions (only useful for old instances)
Cloak {
/// also cloak objects image urls
#[arg(long, default_value_t = false)]
objects: bool,
/// also cloak actor images
#[arg(long, default_value_t = false)]
actors: bool,
/// also replace urls inside post contents
#[arg(long, default_value_t = false)]
contents: bool,
},
}
pub async fn run(ctx: upub::Context, command: CliCommand) -> Result<(), Box<dyn std::error::Error>> {
tracing::info!("running cli task: {command:?}");
match command {
CliCommand::Faker { count } =>
Ok(faker(ctx, count as i64).await?),
CliCommand::Fetch { uri, save, fetch_as } =>
Ok(fetch(ctx, uri, save, fetch_as).await?),
CliCommand::Relay { action } =>
Ok(relay(ctx, action).await?),
CliCommand::Fix { likes, shares, replies } =>
Ok(fix(ctx, likes, shares, replies).await?),
CliCommand::Update { days, limit } =>
Ok(update_users(ctx, days, limit).await?),
CliCommand::Register { username, password, display_name, summary, avatar_url, banner_url } =>
Ok(register(ctx, username, password, display_name, summary, avatar_url, banner_url).await?),
CliCommand::Nuke { for_real, delete_objects } =>
Ok(nuke(ctx, for_real, delete_objects).await?),
CliCommand::Thread { } =>
Ok(thread(ctx).await?),
CliCommand::Cloak { objects, actors, contents } =>
Ok(cloak(ctx, contents, objects, actors).await?),
}
}

View file

@ -1,137 +0,0 @@
use std::collections::HashSet;
use apb::{ActivityMut, BaseMut, ObjectMut};
use futures::TryStreamExt;
use sea_orm::{ActiveValue::{Set, NotSet}, ColumnTrait, EntityTrait, QueryFilter, QuerySelect, SelectColumns};
pub async fn nuke(ctx: upub::Context, for_real: bool, delete_posts: bool) -> Result<(), sea_orm::DbErr> {
if !for_real {
tracing::warn!("THIS IS A DRY RUN! pass --for-real to actually nuke this instance");
}
let mut to_undo = Vec::new();
// TODO rather expensive to find all local users with a LIKE query, should add an isLocal flag
let local_users_vec = upub::model::actor::Entity::find()
.filter(upub::model::actor::Column::Id.like(format!("{}%", ctx.base())))
.select_only()
.select_column(upub::model::actor::Column::Internal)
.into_tuple::<i64>()
.all(ctx.db())
.await?;
let local_users : HashSet<i64> = HashSet::from_iter(local_users_vec);
{
let mut stream = upub::model::relation::Entity::find().stream(ctx.db()).await?;
while let Some(like) = stream.try_next().await? {
if local_users.contains(&like.follower) {
to_undo.push(like.activity);
} else if local_users.contains(&like.following) {
if let Some(accept) = like.accept {
to_undo.push(accept);
}
}
}
}
for internal in to_undo {
let Some(activity) = upub::model::activity::Entity::find_by_id(internal)
.one(ctx.db())
.await?
else {
tracing::error!("could not load activity #{internal}");
continue;
};
let Some(ref oid) = activity.object
else {
tracing::error!("can't undo activity without object");
continue;
};
let (target, undone) = if matches!(activity.activity_type, apb::ActivityType::Follow) {
(oid.clone(), activity.clone().ap())
} else {
let follow_activity = upub::model::activity::Entity::find_by_ap_id(oid)
.one(ctx.db())
.await?
.ok_or(sea_orm::DbErr::RecordNotFound(oid.clone()))?;
(follow_activity.clone().object.unwrap_or_default(), follow_activity.ap())
};
let aid = ctx.aid(&upub::Context::new_id());
let undo_activity = apb::new()
.set_id(Some(aid.clone()))
.set_activity_type(Some(apb::ActivityType::Undo))
.set_actor(apb::Node::link(activity.actor.clone()))
.set_object(apb::Node::object(undone))
.set_to(apb::Node::links(vec![target]))
.set_published(Some(chrono::Utc::now()));
let job = upub::model::job::ActiveModel {
internal: NotSet,
activity: Set(aid),
job_type: Set(upub::model::job::JobType::Outbound),
actor: Set(activity.actor),
target: Set(None),
published: Set(chrono::Utc::now()),
not_before: Set(chrono::Utc::now()),
attempt: Set(0),
payload: Set(Some(undo_activity)),
error: Set(None),
};
tracing::info!("undoing {}", activity.id);
if for_real {
upub::model::job::Entity::insert(job).exec(ctx.db()).await?;
}
}
if delete_posts {
let mut stream = upub::model::object::Entity::find()
.filter(upub::model::object::Column::Id.like(format!("{}%", ctx.base())))
.stream(ctx.db())
.await?;
while let Some(object) = stream.try_next().await? {
let aid = ctx.aid(&upub::Context::new_id());
let actor = object.attributed_to.unwrap_or_else(|| ctx.domain().to_string());
let undo_activity = apb::new()
.set_id(Some(aid.clone()))
.set_activity_type(Some(apb::ActivityType::Delete))
.set_actor(apb::Node::link(actor.clone()))
.set_object(apb::Node::link(object.id.clone()))
.set_to(apb::Node::links(object.to.0))
.set_cc(apb::Node::links(object.cc.0))
.set_bto(apb::Node::links(object.bto.0))
.set_bcc(apb::Node::links(object.bcc.0))
.set_published(Some(chrono::Utc::now()));
let job = upub::model::job::ActiveModel {
internal: NotSet,
activity: Set(aid),
job_type: Set(upub::model::job::JobType::Outbound),
actor: Set(actor),
target: Set(None),
published: Set(chrono::Utc::now()),
not_before: Set(chrono::Utc::now()),
attempt: Set(0),
payload: Set(Some(undo_activity)),
error: Set(None),
};
tracing::info!("deleting {}", object.id);
if for_real {
upub::model::job::Entity::insert(job).exec(ctx.db()).await?;
}
}
}
Ok(())
}

View file

@ -1,24 +0,0 @@
use upub::traits::Administrable;
pub async fn register(
ctx: upub::Context,
username: String,
password: String,
display_name: Option<String>,
summary: Option<String>,
avatar_url: Option<String>,
banner_url: Option<String>,
) -> Result<(), sea_orm::DbErr> {
ctx.register_user(
username.clone(),
password,
display_name,
summary,
avatar_url,
banner_url,
).await?;
tracing::info!("registered new user: {username}");
Ok(())
}

View file

@ -1,204 +0,0 @@
use apb::{ActivityMut, BaseMut, ObjectMut};
use sea_orm::{ActiveValue::{NotSet, Set}, DbErr, EntityTrait, QueryFilter, ColumnTrait};
use upub::traits::{fetch::RequestError, Fetcher};
#[derive(Debug, Clone, clap::Subcommand)]
/// available actions to take on relays
pub enum RelayCommand {
/// get all current pending and accepted relays
Status,
/// request to follow a specific relay
Follow {
/// relay actor to follow (must be full AP id, like for pleroma)
actor: String,
},
/// accept a pending relay request
Accept {
/// relay actor to accept (must be full AP id, like for pleroma)
actor: String,
},
/// retract a follow relation to a relay, stopping receiving content
Unfollow {
/// relay actor to unfollow (must be full AP id, like for pleroma)
actor: String,
},
/// remove a follow relation from a relay, stopping sending content
Remove {
/// relay actor to unfollow (must be full AP id, like for pleroma)
actor: String,
},
}
pub async fn relay(ctx: upub::Context, action: RelayCommand) -> Result<(), RequestError> {
let my_internal = upub::model::actor::Entity::ap_to_internal(ctx.base(), ctx.db())
.await?
.ok_or_else(|| DbErr::RecordNotFound(ctx.base().to_string()))?;
let their_internal = match &action {
RelayCommand::Status => 0,
RelayCommand::Follow { actor }
| RelayCommand::Accept { actor }
| RelayCommand::Unfollow { actor }
| RelayCommand::Remove { actor }
=> ctx.fetch_user(actor, ctx.db()).await?.internal,
};
match action {
RelayCommand::Status => {
tracing::info!("active sinks:");
for sink in upub::Query::related(None, Some(my_internal), false)
.into_model::<upub::model::actor::Model>()
.all(ctx.db())
.await?
{
tracing::info!("[>>] {} {}", sink.name.unwrap_or_default(), sink.id);
}
tracing::info!("active sources:");
for source in upub::Query::related(Some(my_internal), None, false)
.into_model::<upub::model::actor::Model>()
.all(ctx.db())
.await?
{
tracing::info!("[<<] {} {}", source.name.unwrap_or_default(), source.id);
}
},
RelayCommand::Follow { actor } => {
let aid = ctx.aid(&upub::Context::new_id());
let payload = apb::new()
.set_id(Some(aid.clone()))
.set_activity_type(Some(apb::ActivityType::Follow))
.set_actor(apb::Node::link(ctx.base().to_string()))
.set_object(apb::Node::link(actor.clone()))
.set_to(apb::Node::links(vec![actor.clone()]))
.set_cc(apb::Node::links(vec![apb::target::PUBLIC.to_string()]))
.set_published(Some(chrono::Utc::now()));
let job = upub::model::job::ActiveModel {
internal: NotSet,
activity: Set(aid),
job_type: Set(upub::model::job::JobType::Outbound),
actor: Set(ctx.base().to_string()),
target: Set(None),
payload: Set(Some(payload)),
attempt: Set(0),
published: Set(chrono::Utc::now()),
not_before: Set(chrono::Utc::now()),
error: Set(None),
};
tracing::info!("following relay {actor}");
upub::model::job::Entity::insert(job).exec(ctx.db()).await?;
},
RelayCommand::Accept { actor } => {
let relation = upub::model::relation::Entity::find()
.filter(upub::model::relation::Column::Follower.eq(their_internal))
.filter(upub::model::relation::Column::Following.eq(my_internal))
.one(ctx.db())
.await?
.ok_or_else(|| DbErr::RecordNotFound(format!("relation-{their_internal}-{my_internal}")))?;
let activity = upub::model::activity::Entity::find_by_id(relation.activity)
.one(ctx.db())
.await?
.ok_or_else(|| DbErr::RecordNotFound(format!("activity#{}", relation.activity)))?;
let aid = ctx.aid(&upub::Context::new_id());
let payload = apb::new()
.set_id(Some(aid.clone()))
.set_activity_type(Some(apb::ActivityType::Accept(apb::AcceptType::Accept)))
.set_actor(apb::Node::link(ctx.base().to_string()))
.set_object(apb::Node::link(activity.id))
.set_to(apb::Node::links(vec![actor.clone()]))
.set_cc(apb::Node::links(vec![apb::target::PUBLIC.to_string()]))
.set_published(Some(chrono::Utc::now()));
let job = upub::model::job::ActiveModel {
internal: NotSet,
activity: Set(aid),
job_type: Set(upub::model::job::JobType::Outbound),
actor: Set(ctx.base().to_string()),
target: Set(None),
payload: Set(Some(payload)),
attempt: Set(0),
published: Set(chrono::Utc::now()),
not_before: Set(chrono::Utc::now()),
error: Set(None),
};
tracing::info!("accepting relay {actor}");
upub::model::job::Entity::insert(job).exec(ctx.db()).await?;
},
RelayCommand::Remove { actor } => {
let relation = upub::model::relation::Entity::find()
.filter(upub::model::relation::Column::Follower.eq(their_internal))
.filter(upub::model::relation::Column::Following.eq(my_internal))
.one(ctx.db())
.await?
.ok_or_else(|| DbErr::RecordNotFound(format!("relation-{their_internal}-{my_internal}")))?;
let accept_activity_id = relation.accept.ok_or(DbErr::RecordNotFound(format!("accept-{their_internal}-{my_internal}")))?;
let activity = upub::model::activity::Entity::find_by_id(accept_activity_id)
.one(ctx.db())
.await?
.ok_or_else(|| DbErr::RecordNotFound(format!("activity#{}", accept_activity_id)))?;
let aid = ctx.aid(&upub::Context::new_id());
let payload = apb::new()
.set_id(Some(aid.clone()))
.set_activity_type(Some(apb::ActivityType::Undo))
.set_actor(apb::Node::link(ctx.base().to_string()))
.set_object(apb::Node::object(activity.ap()))
.set_to(apb::Node::links(vec![actor.clone()]))
.set_cc(apb::Node::links(vec![apb::target::PUBLIC.to_string()]))
.set_published(Some(chrono::Utc::now()));
let job = upub::model::job::ActiveModel {
internal: NotSet,
activity: Set(aid),
job_type: Set(upub::model::job::JobType::Outbound),
actor: Set(ctx.base().to_string()),
target: Set(None),
payload: Set(Some(payload)),
attempt: Set(0),
published: Set(chrono::Utc::now()),
not_before: Set(chrono::Utc::now()),
error: Set(None),
};
tracing::info!("unfollowing relay {actor}");
upub::model::job::Entity::insert(job).exec(ctx.db()).await?;
},
RelayCommand::Unfollow { actor } => {
let relation = upub::model::relation::Entity::find()
.filter(upub::model::relation::Column::Follower.eq(my_internal))
.filter(upub::model::relation::Column::Following.eq(their_internal))
.one(ctx.db())
.await?
.ok_or_else(|| DbErr::RecordNotFound(format!("relation-{my_internal}-{their_internal}")))?;
let activity = upub::model::activity::Entity::find_by_id(relation.activity)
.one(ctx.db())
.await?
.ok_or_else(|| DbErr::RecordNotFound(format!("activity#{}", relation.activity)))?;
let aid = ctx.aid(&upub::Context::new_id());
let payload = apb::new()
.set_id(Some(aid.clone()))
.set_activity_type(Some(apb::ActivityType::Undo))
.set_actor(apb::Node::link(ctx.base().to_string()))
.set_object(apb::Node::object(activity.ap()))
.set_to(apb::Node::links(vec![actor.clone()]))
.set_cc(apb::Node::links(vec![apb::target::PUBLIC.to_string()]))
.set_published(Some(chrono::Utc::now()));
let job = upub::model::job::ActiveModel {
internal: NotSet,
activity: Set(aid),
job_type: Set(upub::model::job::JobType::Outbound),
actor: Set(ctx.base().to_string()),
target: Set(None),
payload: Set(Some(payload)),
attempt: Set(0),
published: Set(chrono::Utc::now()),
not_before: Set(chrono::Utc::now()),
error: Set(None),
};
tracing::info!("unfollowing relay {actor}");
upub::model::job::Entity::insert(job).exec(ctx.db()).await?;
},
}
Ok(())
}

View file

@ -1,34 +0,0 @@
use sea_orm::{ColumnTrait, EntityTrait, IntoActiveModel, QueryFilter};
use upub::traits::{fetch::RequestError, Fetcher};
pub async fn thread(ctx: upub::Context) -> Result<(), RequestError> {
use futures::TryStreamExt;
let db = ctx.db();
tracing::info!("fixing contexts...");
let mut stream = upub::model::object::Entity::find()
.filter(upub::model::object::Column::Context.is_null())
.stream(db)
.await?;
while let Some(mut object) = stream.try_next().await? {
match object.in_reply_to {
None => object.context = Some(object.id.clone()),
Some(ref in_reply_to) => {
let reply = ctx.fetch_object(in_reply_to, ctx.db()).await?;
if let Some(context) = reply.context {
object.context = Some(context);
} else {
continue;
}
},
}
tracing::info!("updating context of {}", object.id);
upub::model::object::Entity::update(object.into_active_model())
.exec(ctx.db())
.await?;
}
tracing::info!("done fixing contexts");
Ok(())
}

View file

@ -1,50 +0,0 @@
use futures::TryStreamExt;
use sea_orm::{ActiveModelTrait, ActiveValue::{Unchanged, Set}, ColumnTrait, EntityTrait, ModelTrait, QueryFilter, QueryOrder};
use upub::traits::Fetcher;
pub async fn update_users(ctx: upub::Context, days: i64, limit: Option<u64>) -> Result<(), sea_orm::DbErr> {
let mut count = 0;
let mut stream = upub::model::actor::Entity::find()
.filter(upub::model::actor::Column::Updated.lt(chrono::Utc::now() - chrono::Duration::days(days)))
.order_by_asc(upub::model::actor::Column::Updated)
.stream(ctx.db())
.await?;
while let Some(user) = stream.try_next().await? {
if ctx.is_local(&user.id) { continue }
if let Some(limit) = limit {
if count >= limit { break }
}
match ctx.pull(&user.id).await.and_then(|x| x.actor()) {
Err(upub::traits::fetch::RequestError::Fetch(status, msg)) => {
if status.as_u16() == 410 {
tracing::info!("user {} has been deleted", user.id);
user.delete(ctx.db()).await?;
}
else if status.as_u16() == 404 {
tracing::info!("user {} does not exist anymore", user.id);
user.delete(ctx.db()).await?;
}
else {
tracing::warn!("could not fetch user {}: failed with status {status} -- {msg}", user.id);
}
},
Err(e) => tracing::warn!("could not fetch user {}: {e}", user.id),
Ok(doc) => match ctx.resolve_user(doc, ctx.db()).await {
Ok(mut u) => {
tracing::info!("updating user {}", user.id);
u.internal = Unchanged(user.internal);
u.updated = Set(chrono::Utc::now());
u.update(ctx.db()).await?;
count += 1;
},
Err(e) => tracing::warn!("failed deserializing user '{}': {e}", user.id),
},
}
}
tracing::info!("updated {count} users");
Ok(())
}

View file

@ -1,38 +0,0 @@
[package]
name = "upub"
version = "0.3.0"
edition = "2021"
authors = [ "alemi <me@alemi.dev>" ]
description = "core inner workings of upub"
license = "AGPL-3.0"
repository = "https://git.alemi.dev/upub.git"
readme = "README.md"
[lib]
[dependencies]
thiserror = "1"
async-recursion = "1.1"
async-trait = "0.1"
sha256 = "1.5" # TODO get rid of this and use directly sha2!!
sha2 = "0.10"
hmac = "0.12"
openssl = "0.10" # TODO handle pubkeys with a smaller crate
base64 = "0.22"
chrono = { version = "0.4", features = ["serde"] }
uuid = { version = "1.10", features = ["v4"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
serde_default = "0.2"
serde-inline-default = "0.2"
toml = "0.8"
uriproxy = { path = "../../utils/uriproxy" }
httpsign = { path = "../../utils/httpsign/" }
mdhtml = { path = "../../utils/mdhtml/" }
jrd = "0.1"
tracing = "0.1"
sea-orm = { version = "1.0", features = ["macros"] }
reqwest = { version = "0.12", features = ["json"] }
apb = { path = "../../apb", features = ["unstructured", "orm", "did-core", "activitypub-miscellaneous-terms", "activitypub-fe", "activitypub-counters", "litepub", "ostatus", "toot"] }
# nodeinfo = "0.0.2" # the version on crates.io doesn't re-export necessary types to build the struct!!!
nodeinfo = { git = "https://codeberg.org/thefederationinfo/nodeinfo-rs", rev = "e865094804" }

View file

@ -1 +0,0 @@
# upub core

Some files were not shown because too many files have changed in this diff Show more