Compare commits

...

64 Commits

Author SHA1 Message Date
Mina Galić b596e77f03 remove redundant use statements 2020-05-25 20:00:57 +02:00
Mina Galić 41f97b01f0 unroll filter_map() to easier .await 2020-05-25 20:00:28 +02:00
Mina Galić a508a4150c remove redundant use statements 2020-05-25 19:18:24 +02:00
Mina Galić 25c40adf20 yet another dubious clippy warnings fix re returns 2020-05-25 19:17:32 +02:00
Mina Galić 7490567a21 fix warnings about unused doc comments
we do this by making the macro parse and generate doc comments
2020-05-25 15:44:32 +02:00
Mina Galić 492bbb1ba6 make clippy happy with a weird quirk wrt return
not happy about this lint or rust behaviour where the return statement
must not have a `;`
2020-05-25 15:23:55 +02:00
Mina Galić cf3708e1c6 make clippy happy by removing unused imports 2020-05-25 13:40:35 +02:00
Mina Galić df442002c2 replace .map().map_err() with a match
so we can .await without worries.
plus, it changes nothing about the code, other than making the intent
clearer at first sight.
2020-05-24 22:16:42 +02:00
Mina Galić 07036b5fad upgrade validator: it now uses types! in macros!! 2020-05-24 22:03:26 +02:00
Mina Galić 0726375859 add another async (and correctly convert followers_count) 2020-05-24 21:03:59 +02:00
Mina Galić cb1c260692 remove an experiment of disabling Send… it makes no sense 2020-05-24 21:03:02 +02:00
Mina Galić de6bfca084 removed a few unused imports 2020-05-24 21:01:16 +02:00
Mina Galić 7aabb9661e upgrade webfinger everywhere, and implement async 2020-05-24 20:27:39 +02:00
Mina Galić 18bb413011 add async/.await until all our errors are the same:
that our Connection is not Send-safe.
2020-05-24 19:40:02 +02:00
Mina Galić d2881ee3f7 add async/.await until all our errors are the same: that our Connection is not Send-safe. 2020-05-23 23:32:10 +02:00
Mina Galić 850b3c1337 add async/.await until all our errors are the same:
that our Connection is not Send-safe.
once we get there, we can start thinking about restructing the way we
pass along our connection, or consider using #[database].
2020-05-22 21:41:33 +02:00
Igor Galić 44ebce516c fix some, break some compiling by adding async/await in front of it
i forgot that we can't `Send` diesel connections over threads, so this
is going to require some rethinking.
2020-05-16 12:06:58 +02:00
Igor Galić 3c830ab0ce move towards using #[rocket::async_trait]
this also upgrades some dependencies
some of that fixes stuff, others breaks stuff.
2020-05-15 22:38:21 +02:00
Igor Galić 097d0ea9ce make plume-models async (again) 2020-05-06 22:33:10 +02:00
Igor Galić 6fe16c9f84 upgrade and use futures… then block_on .await in a trait? 2020-05-06 22:32:59 +02:00
Igor Galić 43cb9f700c update webfinger
as requested in https://github.com/Plume-org/webfinger/issues/8
and provided in https://github.com/Plume-org/webfinger/pull/9

```
meena@76ix ~/s/a/plume (go/async) [101]> cargo update --package webfinger
    Updating crates.io index
    Updating git repository `https://github.com/Plume-org/webfinger`
    Removing bytes v0.4.12
    Removing cookie v0.12.0
    Removing cookie_store v0.7.0
    Removing crossbeam-deque v0.7.2
    Removing crossbeam-epoch v0.8.0
    Removing crossbeam-queue v0.1.2
    Removing crossbeam-utils v0.7.0
    Removing h2 v0.1.26
    Removing http v0.1.21
    Removing http-body v0.1.0
    Removing hyper v0.12.35
    Removing hyper-tls v0.3.2
    Removing publicsuffix v1.5.4
    Removing reqwest v0.9.24
    Removing serde_urlencoded v0.5.5
    Removing string v0.2.1
    Removing tokio v0.1.22
    Removing tokio-buf v0.1.1
    Removing tokio-current-thread v0.1.6
    Removing tokio-executor v0.1.9
    Removing tokio-io v0.1.12
    Removing tokio-reactor v0.1.11
    Removing tokio-sync v0.1.7
    Removing tokio-tcp v0.1.3
    Removing tokio-threadpool v0.1.17
    Removing tokio-timer v0.2.12
    Removing try_from v0.3.2
    Removing want v0.2.0
      Adding webfinger v0.5.0 (https://github.com/Plume-org/webfinger?rev=update-deps#cdaab95e)
    Removing webfinger v0.5.0
meena@76ix ~/s/a/plume (go/async)>
```
2020-05-06 22:30:33 +02:00
Igor Galić 2c285b9aca start async-ifying routes
template utils and error routes
2020-05-06 22:29:36 +02:00
Igor Galić e4bb73d22e cargo clippy 2020-05-06 22:29:36 +02:00
Igor Galić e9c7259ffb cargo fmt 2020-05-06 22:29:35 +02:00
Igor Galić be8c67ee9a move reqwest client out of thread spawning
this way, we only spawn one, and reuse that.
2020-05-06 22:29:34 +02:00
Igor Galić 65b2c38c29 .await? result from read_to_string() 2020-05-06 22:29:33 +02:00
Jeb Rosen 8aa99cea35 move signature outside the spawning
this allows us to actually move stuff into the async block
and we can drop the 'static life-time.
2020-05-06 22:29:32 +02:00
Igor Galić a010025074 asyncify reqwest calls (again?) 2020-05-06 22:29:32 +02:00
Igor Galić 82088596a8 asyncify from_activity calls (i.e.: block_on()) 2020-05-06 22:29:31 +02:00
Igor Galić 87ce3a7b51 asyncify plume-models: media upload is now async
including the use of tokio!
2020-05-06 22:29:27 +02:00
Igor Galić 3472a58299 move ClientBuilder into thread, since we cannot Copy it 2020-05-06 22:26:37 +02:00
Igor Galić a3f165f9f4 Use blocking reqwest API in defer
defer, or, trait functions such as it in general(?) cannot be async (yet)
2020-05-06 22:26:32 +02:00
Igor Galić 25c5da1a7c add tokio (0.2) as dependency to further async-ify our FromData code
i'm using this opportunity to also update reqwest (0.10), but it's
turning out to be a little trickier, as it requires more modern async
setup, and that appears to need a lot of thinking…
2020-05-06 22:23:35 +02:00
Igor Galić 022e037eea when using macros!() we need to import the things that they use 2020-05-06 22:20:49 +02:00
Igor Galić 45c335e17b "manually" create ETag and Cache-Control headers 2020-05-06 22:20:48 +02:00
Igor Galić b51551973a start fixing tests in plume-models 2020-05-06 22:20:47 +02:00
Igor Galić 59e5c49aa8 convert plume-models to all async
where sensible! note that State has no asynchronous work to do, so
wrapping it up in async makes no sense.
2020-05-06 22:20:47 +02:00
Igor Galić ce119ffe50 start making PlumeRocket async 2020-05-06 22:20:46 +02:00
Igor Galić 944f8c42fa plume-models: convert api-tokens. use DbConn::from_request() directly
there doesn't seem to be a request.guard_async (yet?)
2020-05-06 22:17:25 +02:00
Igor Galić 909f677bdd plume-models: convert admin & api-tokens to async
n.b.: I do *not* like the error handling in api_tokens 😒
2020-05-06 22:17:24 +02:00
Igor Galić fd9764ff17 plume-common: also make requests async 2020-05-06 22:17:24 +02:00
Igor Galić 75722abc9e rocket does not need decl_macro anymore 2020-05-06 22:17:23 +02:00
Igor Galić ec9b699c6e convert plume-common to rocket async
it only took 3 hours of @jebrosen's patient help.
2020-05-06 22:17:22 +02:00
Igor Galić bb5c2b69a7 update rocket* everywhere!
and run cargo update
2020-05-06 22:17:17 +02:00
Igor Galić e52944e477 update rocket*; which gets us stuck in dependency conflicts 2020-05-06 21:01:25 +02:00
Igor Galić 928470610e remove csrf for now, so we can update the rest 2020-05-06 21:01:18 +02:00
KITAITI Makoto 3be842c653 Make database connections configurable by environment variables (#768)
* Make env DB_MAX_SIZE and DB_MIN_IDLE recognizable

* Make database max size and minimum idle configurable

* Restore file permission

* Fail fast
2020-05-06 19:27:59 +02:00
KITAITI Makoto dabe904642 Escape expressions in @Html (#767) 2020-05-05 23:48:29 +02:00
KITAITI Makoto 180e34b07c Fix Atom feed datetime format (#766) 2020-05-04 23:46:59 +02:00
KITAITI Makoto 847d6f7fac Fix Atom feed (#764)
* Percent-encode URI segments in ap_url

* Fix invalid Atoms

* Remove redundant clone according to cargo clippy

* Revert "Percent-encode URI segments in ap_url"

This reverts commit 8253aa79bd.
ActivityPub(JSON-LD) accepts URI.
See https://github.com/Plume-org/Plume/pull/764#issuecomment-623105734

* Use absolute IRI for IDs in Atom

* Reuse formatted string

* Use parent element's creation date for Atom updated if there's no post

* Remove uncecessary UTC conversion

* Extract routes::build_atom_feed function
2020-05-04 15:28:52 +02:00
KITAITI Makoto 6a3f210dfc Keep atmarks and hashes in link (#765)
* [REFACTORING]Use DocumentContext during parsing Markdown

* Add test case for hash in link

* Make DocumentContext derive Debug

* Add in_link field in DocumentContext

* Don't make hash words tags in link

* Add test for atmark in link

* Don't make atmark words in link mentions
2020-05-03 14:50:32 +02:00
KITAITI Makoto 73aa301d4a Fix user subscription URI so that plume::routes:interact accept it (#762) 2020-05-02 12:07:45 +02:00
KITAITI Makoto b3d367b174 Use plural form for 0 in French (#760)
See https://github.com/Plume-org/Plume/issues/745
2020-04-30 15:35:12 +02:00
KITAITI Makoto edaccd1a31 Fixes #757 Allow Unicode hashtags (#758)
* Add test for Persian language hashtags

See https://github.com/Plume-org/Plume/issues/757

* Add regex-syntax with unicode-perl feature to dependencies

* Install regex-syntax

* Allow hashtag to use Unicode word characters

* Run cargo fmt
2020-04-29 15:13:31 +02:00
Floréal Toumikian e1bd2eab75 Updated: Cargo.lock (#753) 2020-04-19 09:34:05 +02:00
KITAITI Makoto ac7a05b09a Make blocklist deletion possible (#750) 2020-04-18 11:46:10 +02:00
KITAITI Makoto 71e0a35e06 Use LenientForm instead Form for CSRF protected pages (#751) 2020-04-18 11:45:28 +02:00
KITAITI Makoto c217e5e9b3 Move stylesheets for header from _global.sccss to _header.scss (#749) 2020-04-14 23:32:27 +02:00
KITAITI Makoto 8ba0c17db5 Build app and po files before upload pos to Crowdin (#748) 2020-04-14 20:51:53 +02:00
Floréal Toumikian 4e43c676b4 Fixed: #713: Disply likes and boosts on post cards (#744)
This is a basic and simple way to display them. No interaction possible.

Alos, this patch is not optimised. as everytime a partial post_card is
called, `Post::count_likes()` and `Post::count_reshares()` are called
which means quite a few more quesies are sent to database unless diesel
uses some cache mechanisem.

A way to enhance this this would be to keep a count of likes and reshares
are kept in Post model / table.
2020-04-12 21:29:48 +02:00
KITAITI Makoto b834d1c282 Fix #701 Preferable default theme (#746)
* Make it possible to update users.preferred_theme to NULL

* Make preferred them null when 'Default theme' is selected

* Run cargo fmt
2020-04-12 17:36:00 +02:00
Kenneth Steimel 506fe9955d Fixed #734 , passowrds are now hidden on the remote_interact pages (#741)
* Fixed #734 , passowrds are now hidden on the remote_interact pages

* Update templates/remote_interact_base.rs.html

Co-Authored-By: Floréal Toumikian <floreal+github@nimukaito.net>

Co-authored-by: Floréal Toumikian <floreal+github@nimukaito.net>
2020-04-09 20:55:22 +02:00
KemoNine 02c528cae4 Bump llvm -> 9.0.0 (fixes arm builds) (#737) 2020-01-29 21:37:54 +01:00
Christopher James Halse Rogers 2a58835f92 Snapcraft updates (#731)
* snap: Update rust compiler

* snap: Fix the build.

We now need libclang

* snap: Fix the non-x86 builds.

The goddamned environment variable is SNAPCRAFT_ARCH_TRIPLE*T*

* snap: Mark as stable.

The snap works fine; we don't need to warn people away
2020-01-22 14:10:49 +02:00
60 changed files with 2937 additions and 2742 deletions
+1
View File
@@ -226,6 +226,7 @@ jobs:
steps:
- restore_env:
cache: none
- run: cargo build
- run: crowdin upload -b master
workflows:
+1
View File
@@ -18,3 +18,4 @@ tags.*
search_index
.buildconfig
__pycache__
.vscode/
Generated
+1993 -2103
View File
File diff suppressed because it is too large Load Diff
+12 -10
View File
@@ -8,6 +8,7 @@ edition = "2018"
[dependencies]
activitypub = "0.1.3"
askama_escape = "0.1"
async-trait = "*"
atom_syndication = "0.6"
clap = "2.33"
colored = "1.8"
@@ -20,20 +21,19 @@ heck = "0.3.0"
lettre = "0.9.2"
lettre_email = "0.9.2"
num_cpus = "1.10"
rocket = "0.4.2"
rocket_contrib = { version = "0.4.2", features = ["json"] }
rocket_i18n = { git = "https://github.com/Plume-org/rocket_i18n", rev = "e922afa7c366038b3433278c03b1456b346074f2" }
rocket = { git = "https://github.com/SergioBenitez/Rocket", rev = "async" }
rocket_contrib = { git = "https://github.com/SergioBenitez/Rocket", rev = "async" , features = ["json"] }
rpassword = "4.0"
runtime-fmt = "0.4.0"
scheduled-thread-pool = "0.2.2"
serde = "1.0"
serde_json = "1.0"
serde_qs = "0.5"
shrinkwraprs = "0.2.1"
syntect = "3.3"
validator = "0.8"
validator_derive = "0.8"
webfinger = "0.4.1"
tokio = "0.2"
validator = "0.10"
validator_derive = "0.10"
webfinger = { git = "https://github.com/Plume-org/webfinger", rev = "4e8f12810c4a7ba7a07bbcb722cd265fdff512b6", features = ["async"] }
[[bin]]
name = "plume"
@@ -65,9 +65,11 @@ path = "plume-common"
[dependencies.plume-models]
path = "plume-models"
[dependencies.rocket_csrf]
git = "https://github.com/fdb-hiroshima/rocket_csrf"
rev = "29910f2829e7e590a540da3804336577b48c7b31"
[dependencies.rocket_i18n]
git = "https://github.com/Plume-org/rocket_i18n"
branch = "go-async"
default-features = false
features = ["rocket"]
[build-dependencies]
ructe = "0.9.0"
+22 -88
View File
@@ -190,7 +190,28 @@ p.error {
background: $gray;
text-overflow: ellipsis;
text-overflow: ellipsis;
footer.authors {
div {
float: left;
margin-right: 0.25em;
}
.likes { color: $red; }
.reshares { color: $primary; }
span.likes, span.resahres {
font-family: "Route159",serif;
font-size: 1em;
}
svg.feather {
width: 0.85em;
height: 0.85em;
}
}
> * {
margin: 20px;
@@ -469,93 +490,6 @@ figure {
/// Small screens
@media screen and (max-width: 600px) {
@keyframes menuOpening {
from {
transform: scaleX(0);
transform-origin: left;
opacity: 0;
}
to {
transform: scaleX(1);
transform-origin: left;
opacity: 1;
}
}
body > header {
flex-direction: column;
nav#menu {
display: inline-flex;
z-index: 21;
}
#content {
display: none;
appearance: none;
text-align: center;
z-index: 20;
}
}
body > header:focus-within #content, #content.show {
position: fixed;
display: flex;
flex-direction: column;
justify-content: flex-start;
top: 0;
left: 0;
width: 100%;
height: 100%;
box-sizing: border-box;
animation: 0.2s menuOpening;
&::before {
content: "";
position: absolute;
transform: skewX(-10deg);
top: 0;
left: -20%;
width: 100%;
height: 100%;
z-index: -10;
background: $primary;
}
> nav {
flex-direction: column;
align-items: flex-start;
a {
display: flex;
flex-direction: row;
align-items: center;
margin: 0;
padding: 1rem 1.5rem;
color: $background;
font-size: 1.4em;
font-weight: 300;
&.title { font-size: 1.8em; }
> *:first-child { width: 3rem; }
> img:first-child { height: 3rem; }
> *:last-child { margin-left: 1rem; }
> nav hr {
display: block;
margin: 0;
width: 100%;
border: solid $background 0.1rem;
}
.mobile-label { display: initial; }
}
}
}
main .article-meta {
> *, .comments {
margin: 0 5%;
+90
View File
@@ -101,6 +101,96 @@ body > header {
}
}
/// Small screens
@media screen and (max-width: 600px) {
@keyframes menuOpening {
from {
transform: scaleX(0);
transform-origin: left;
opacity: 0;
}
to {
transform: scaleX(1);
transform-origin: left;
opacity: 1;
}
}
body > header {
flex-direction: column;
nav#menu {
display: inline-flex;
z-index: 21;
}
#content {
display: none;
appearance: none;
text-align: center;
z-index: 20;
}
}
body > header:focus-within #content, #content.show {
position: fixed;
display: flex;
flex-direction: column;
justify-content: flex-start;
top: 0;
left: 0;
width: 100%;
height: 100%;
box-sizing: border-box;
animation: 0.2s menuOpening;
&::before {
content: "";
position: absolute;
transform: skewX(-10deg);
top: 0;
left: -20%;
width: 100%;
height: 100%;
z-index: -10;
background: $primary;
}
> nav {
flex-direction: column;
align-items: flex-start;
a {
display: flex;
flex-direction: row;
align-items: center;
margin: 0;
padding: 1rem 1.5rem;
color: $background;
font-size: 1.4em;
font-weight: 300;
&.title { font-size: 1.8em; }
> *:first-child { width: 3rem; }
> img:first-child { height: 3rem; }
> *:last-child { margin-left: 1rem; }
> nav hr {
display: block;
margin: 0;
width: 100%;
border: solid $background 0.1rem;
}
.mobile-label { display: initial; }
}
}
}
}
/* Only enable label animations on large screens */
@media screen and (min-width: 600px) {
header nav a {
-2
View File
@@ -1,5 +1,3 @@
use rsass;
use ructe::Ructe;
use std::process::{Command, Stdio};
use std::{ffi::OsStr, fs::*, io::Write, path::*};
+10 -5
View File
@@ -6,22 +6,23 @@ edition = "2018"
[dependencies]
activitypub = "0.1.1"
activitystreams-derive = "0.1.1"
activitystreams-derive = "0.2"
activitystreams-traits = "0.1.0"
array_tool = "1.0"
base64 = "0.10"
futures-util = "*"
heck = "0.3.0"
hex = "0.3"
hyper = "0.12.33"
hyper = "0.13"
openssl = "0.10.22"
rocket = "0.4.0"
reqwest = "0.9"
rocket = { git = "https://github.com/SergioBenitez/Rocket", rev = "async" }
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
shrinkwraprs = "0.2.1"
syntect = "3.3"
tokio = "0.1.22"
tokio = "0.2"
regex-syntax = { version = "0.6.17", default-features = false, features = ["unicode-perl"] }
[dependencies.chrono]
features = ["serde"]
@@ -30,3 +31,7 @@ version = "0.4"
[dependencies.pulldown-cmark]
default-features = false
version = "0.2.0"
[dependencies.reqwest]
features = ["json", "blocking"]
version = "0.10"
+4 -3
View File
@@ -279,8 +279,9 @@ pub trait FromId<C>: Sized {
/// Dereferences an ID
fn deref(id: &str) -> Result<Self::Object, (Option<serde_json::Value>, Self::Error)> {
reqwest::ClientBuilder::new()
.connect_timeout(Some(std::time::Duration::from_secs(5)))
// Use blocking reqwest API here, since defer cannot be async (yet)
reqwest::blocking::Client::builder()
.connect_timeout(std::time::Duration::from_secs(5))
.build()
.map_err(|_| (None, InboxError::DerefError.into()))?
.get(id)
@@ -296,7 +297,7 @@ pub trait FromId<C>: Sized {
)
.send()
.map_err(|_| (None, InboxError::DerefError))
.and_then(|mut r| {
.and_then(|r| {
let json: serde_json::Value = r
.json()
.map_err(|_| (None, InboxError::InvalidObject(None)))?;
+42 -37
View File
@@ -1,14 +1,12 @@
use activitypub::{Activity, Link, Object};
use array_tool::vec::Uniq;
use reqwest::r#async::ClientBuilder;
use reqwest::ClientBuilder;
use rocket::{
http::Status,
request::{FromRequest, Request},
response::{Responder, Response},
response::{Responder, Response, Result},
Outcome,
};
use serde_json;
use tokio::prelude::*;
use self::sign::Signable;
@@ -62,39 +60,45 @@ impl<T> ActivityStream<T> {
ActivityStream(t)
}
}
impl<'r, O: Object> Responder<'r> for ActivityStream<O> {
fn respond_to(self, request: &Request<'_>) -> Result<Response<'r>, Status> {
#[rocket::async_trait]
impl<'r, O: Object + Send + 'r> Responder<'r> for ActivityStream<O> {
async fn respond_to(self, request: &'r Request<'_>) -> Result<'r> {
let mut json = serde_json::to_value(&self.0).map_err(|_| Status::InternalServerError)?;
json["@context"] = context();
serde_json::to_string(&json).respond_to(request).map(|r| {
Response::build_from(r)
let result = serde_json::to_string(&json).map_err(rocket::response::Debug);
match result.respond_to(request).await {
Ok(r) => Response::build_from(r)
.raw_header("Content-Type", "application/activity+json")
.finalize()
})
.ok(),
Err(e) => Err(e),
}
}
}
#[derive(Clone)]
pub struct ApRequest;
#[rocket::async_trait]
impl<'a, 'r> FromRequest<'a, 'r> for ApRequest {
type Error = ();
fn from_request(request: &'a Request<'r>) -> Outcome<Self, (Status, Self::Error), ()> {
async fn from_request(request: &'a Request<'r>) -> Outcome<Self, (Status, Self::Error), ()> {
request
.headers()
.get_one("Accept")
.map(|header| {
header
.split(',')
.map(|ct| match ct.trim() {
// bool for Forward: true if found a valid Content-Type for Plume first (HTML), false otherwise
"application/ld+json; profile=\"https://w3.org/ns/activitystreams\""
| "application/ld+json;profile=\"https://w3.org/ns/activitystreams\""
| "application/activity+json"
| "application/ld+json" => Outcome::Success(ApRequest),
"text/html" => Outcome::Forward(true),
_ => Outcome::Forward(false),
.map(|ct| {
match ct.trim() {
// bool for Forward: true if found a valid Content-Type for Plume first (HTML),
// false otherwise
"application/ld+json; profile=\"https://w3.org/ns/activitystreams\""
| "application/ld+json;profile=\"https://w3.org/ns/activitystreams\""
| "application/activity+json"
| "application/ld+json" => Outcome::Success(ApRequest),
"text/html" => Outcome::Forward(true),
_ => Outcome::Forward(false),
}
})
.fold(Outcome::Forward(false), |out, ct| {
if out.clone().forwarded().unwrap_or_else(|| out.is_success()) {
@@ -130,36 +134,38 @@ where
.sign(sender)
.expect("activity_pub::broadcast: signature error");
let mut rt = tokio::runtime::current_thread::Runtime::new()
.expect("Error while initializing tokio runtime for federation");
let client = ClientBuilder::new()
.connect_timeout(std::time::Duration::from_secs(5))
let rt = tokio::runtime::Builder::new()
.threaded_scheduler()
.build()
.expect("Can't build client");
.expect("Error while initializing tokio runtime for federation");
for inbox in boxes {
let body = signed.to_string();
let mut headers = request::headers();
headers.insert("Digest", request::Digest::digest(&body));
rt.spawn(
let sig = request::signature(sender, &headers)
.expect("activity_pub::broadcast: request signature error");
let client = ClientBuilder::new()
.connect_timeout(std::time::Duration::from_secs(5))
.build()
.expect("Can't build client");
rt.spawn(async move {
client
.post(&inbox)
.headers(headers.clone())
.header(
"Signature",
request::signature(sender, &headers)
.expect("activity_pub::broadcast: request signature error"),
)
.header("Signature", sig)
.body(body)
.send()
.and_then(|r| r.into_body().concat2())
.await
.unwrap()
.text()
.await
.map(move |response| {
println!("Successfully sent activity to inbox ({})", inbox);
println!("Response: \"{:?}\"\n", response)
})
.map_err(|e| println!("Error while sending to inbox ({:?})", e)),
);
.map_err(|e| println!("Error while sending to inbox ({:?})", e))
});
}
rt.run().unwrap();
}
#[derive(Shrinkwrap, Clone, Serialize, Deserialize)]
@@ -203,8 +209,7 @@ pub struct PublicKey {
pub public_key_pem: Option<serde_json::Value>,
}
#[derive(Clone, Debug, Default, UnitString)]
#[activitystreams(Hashtag)]
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct HashtagType;
#[derive(Clone, Debug, Default, Deserialize, Serialize, Properties)]
-1
View File
@@ -1,4 +1,3 @@
use base64;
use chrono::{offset::Utc, DateTime};
use openssl::hash::{Hasher, MessageDigest};
use reqwest::header::{HeaderMap, HeaderValue, ACCEPT, CONTENT_TYPE, DATE, USER_AGENT};
-3
View File
@@ -1,10 +1,7 @@
use super::request;
use base64;
use chrono::{naive::NaiveDateTime, DateTime, Duration, Utc};
use hex;
use openssl::{pkey::PKey, rsa::Rsa, sha::sha256};
use rocket::http::HeaderMap;
use serde_json;
/// Returns (public key, private key)
pub fn gen_keypair() -> (Vec<u8>, Vec<u8>) {
-2
View File
@@ -2,9 +2,7 @@
#[macro_use]
extern crate activitystreams_derive;
use activitystreams_traits;
use serde;
#[macro_use]
extern crate shrinkwraprs;
#[macro_use]
+24 -6
View File
@@ -1,6 +1,7 @@
use heck::CamelCase;
use openssl::rand::rand_bytes;
use pulldown_cmark::{html, Event, Options, Parser, Tag};
use regex_syntax::is_word_character;
use rocket::{
http::uri::Uri,
response::{Flash, Redirect},
@@ -200,6 +201,12 @@ fn process_image<'a, 'b>(
}
}
#[derive(Default, Debug)]
struct DocumentContext {
in_code: bool,
in_link: bool,
}
/// Returns (HTML, mentions, hashtags)
pub fn md_to_html<'a>(
md: &str,
@@ -223,13 +230,21 @@ pub fn md_to_html<'a>(
.map(|evt| process_image(evt, inline, &media_processor))
// Ignore headings, images, and tables if inline = true
.scan((vec![], inline), inline_tags)
.scan(false, |in_code, evt| match evt {
.scan(&mut DocumentContext::default(), |ctx, evt| match evt {
Event::Start(Tag::CodeBlock(_)) | Event::Start(Tag::Code) => {
*in_code = true;
ctx.in_code = true;
Some((vec![evt], vec![], vec![]))
}
Event::End(Tag::CodeBlock(_)) | Event::End(Tag::Code) => {
*in_code = false;
ctx.in_code = false;
Some((vec![evt], vec![], vec![]))
}
Event::Start(Tag::Link(_, _)) => {
ctx.in_link = true;
Some((vec![evt], vec![], vec![]))
}
Event::End(Tag::Link(_, _)) => {
ctx.in_link = false;
Some((vec![evt], vec![], vec![]))
}
Event::Text(txt) => {
@@ -269,7 +284,7 @@ pub fn md_to_html<'a>(
}
}
State::Hashtag => {
let char_matches = c.is_alphanumeric() || "-_".contains(c);
let char_matches = c == '-' || is_word_character(c);
if char_matches && (n < (txt.chars().count() - 1)) {
text_acc.push(c);
(events, State::Hashtag, text_acc, n + 1, mentions, hashtags)
@@ -300,7 +315,7 @@ pub fn md_to_html<'a>(
}
}
State::Ready => {
if !*in_code && c == '@' {
if !ctx.in_code && !ctx.in_link && c == '@' {
events.push(Event::Text(text_acc.into()));
(
events,
@@ -310,7 +325,7 @@ pub fn md_to_html<'a>(
mentions,
hashtags,
)
} else if !*in_code && c == '#' {
} else if !ctx.in_code && !ctx.in_link && c == '#' {
events.push(Event::Text(text_acc.into()));
(
events,
@@ -399,6 +414,7 @@ mod tests {
("not_a@mention", vec![]),
("`@helo`", vec![]),
("```\n@hello\n```", vec![]),
("[@atmark in link](https://example.org/)", vec![]),
];
for (md, mentions) in tests {
@@ -424,6 +440,8 @@ mod tests {
("with some punctuation #test!", vec!["test"]),
(" #spaces ", vec!["spaces"]),
("not_a#hashtag", vec![]),
("#نرم‌افزار_آزاد", vec!["نرم‌افزار_آزاد"]),
("[#hash in link](https://example.org/)", vec![]),
];
for (md, mentions) in tests {
+17 -6
View File
@@ -10,24 +10,24 @@ ammonia = "2.1.1"
askama_escape = "0.1"
bcrypt = "0.5"
guid-create = "0.1"
futures = "0.3"
heck = "0.3.0"
itertools = "0.8.0"
lazy_static = "1.0"
migrations_internals= "1.4.0"
openssl = "0.10.22"
rocket = "0.4.0"
rocket_i18n = { git = "https://github.com/Plume-org/rocket_i18n", rev = "e922afa7c366038b3433278c03b1456b346074f2" }
reqwest = "0.9"
rocket = { git = "https://github.com/SergioBenitez/Rocket", rev = "async" }
scheduled-thread-pool = "0.2.2"
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
tantivy = "0.10.1"
tokio = "0.2"
url = "2.1"
walkdir = "2.2"
webfinger = "0.4.1"
webfinger = { git = "https://github.com/Plume-org/webfinger", rev = "4e8f12810c4a7ba7a07bbcb722cd265fdff512b6", features = ["async"] }
whatlang = "0.7.1"
shrinkwraprs = "0.2.1"
shrinkwraprs = "0.3"
diesel-derive-newtype = "0.1.2"
glob = "0.3.0"
@@ -48,8 +48,19 @@ path = "../plume-common"
[dependencies.plume-macro]
path = "../plume-macro"
[dependencies.reqwest]
features = ["json", "blocking"]
version = "0.10"
[dependencies.rocket_i18n]
git = "https://github.com/Plume-org/rocket_i18n"
branch = "go-async"
default-features = false
features = ["rocket"]
[dev-dependencies]
diesel_migrations = "1.3.0"
diesel_migrations = "1.4.0"
[features]
postgres = ["diesel/postgres", "plume-macro/postgres" ]
+6 -4
View File
@@ -8,11 +8,12 @@ use rocket::{
/// Wrapper around User to use as a request guard on pages reserved to admins.
pub struct Admin(pub User);
#[rocket::async_trait]
impl<'a, 'r> FromRequest<'a, 'r> for Admin {
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<Admin, ()> {
let user = request.guard::<User>()?;
async fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
let user = try_outcome!(User::from_request(request).await);
if user.is_admin() {
Outcome::Success(Admin(user))
} else {
@@ -24,11 +25,12 @@ impl<'a, 'r> FromRequest<'a, 'r> for Admin {
/// Same as `Admin` but for moderators.
pub struct Moderator(pub User);
#[rocket::async_trait]
impl<'a, 'r> FromRequest<'a, 'r> for Moderator {
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<Moderator, ()> {
let user = request.guard::<User>()?;
async fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
let user = try_outcome!(User::from_request(request).await);
if user.is_moderator() {
Outcome::Success(Moderator(user))
} else {
+20 -16
View File
@@ -76,32 +76,36 @@ pub enum TokenError {
DbError,
}
#[rocket::async_trait]
impl<'a, 'r> FromRequest<'a, 'r> for ApiToken {
type Error = TokenError;
fn from_request(request: &'a Request<'r>) -> request::Outcome<ApiToken, TokenError> {
async fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
let headers: Vec<_> = request.headers().get("Authorization").collect();
if headers.len() != 1 {
return Outcome::Failure((Status::BadRequest, TokenError::NoHeader));
}
let mut parsed_header = headers[0].split(' ');
let auth_type = parsed_header.next().map_or_else(
|| Outcome::Failure((Status::BadRequest, TokenError::NoType)),
Outcome::Success,
)?;
let val = parsed_header.next().map_or_else(
|| Outcome::Failure((Status::BadRequest, TokenError::NoValue)),
Outcome::Success,
)?;
if auth_type == "Bearer" {
let conn = request
.guard::<DbConn>()
.map_failure(|_| (Status::InternalServerError, TokenError::DbError))?;
if let Ok(token) = ApiToken::find_by_value(&*conn, val) {
return Outcome::Success(token);
if let Some(auth_type) = parsed_header.next() {
if let Some(val) = parsed_header.next() {
if auth_type == "Bearer" {
if let Outcome::Success(conn) = DbConn::from_request(request).await {
if let Ok(token) = ApiToken::find_by_value(&*conn, val) {
return Outcome::Success(token);
}
} else {
return Outcome::Failure((
Status::InternalServerError,
TokenError::DbError,
));
}
}
} else {
return Outcome::Failure((Status::BadRequest, TokenError::NoValue));
}
} else {
return Outcome::Failure((Status::BadRequest, TokenError::NoType));
}
Outcome::Forward(())
+7 -6
View File
@@ -20,7 +20,6 @@ use plume_common::activity_pub::{
inbox::{AsActor, FromId},
sign, ActivityStream, ApSignature, Id, IntoId, PublicKey, Source,
};
use serde_json;
use url::Url;
use webfinger::*;
@@ -71,7 +70,8 @@ impl Blog {
insert!(blogs, NewBlog, |inserted, conn| {
let instance = inserted.get_instance(conn)?;
if inserted.outbox_url.is_empty() {
inserted.outbox_url = instance.compute_box(BLOG_PREFIX, &inserted.actor_id, "outbox");
inserted.outbox_url =
instance.compute_box(BLOG_PREFIX, &inserted.actor_id, r#"outbox"#);
}
if inserted.inbox_url.is_empty() {
@@ -132,7 +132,7 @@ impl Blog {
.map_err(Error::from)
}
pub fn find_by_fqn(c: &PlumeRocket, fqn: &str) -> Result<Blog> {
pub async fn find_by_fqn(c: &PlumeRocket, fqn: &str) -> Result<Blog> {
let from_db = blogs::table
.filter(blogs::fqn.eq(fqn))
.first(&*c.conn)
@@ -140,12 +140,13 @@ impl Blog {
if let Some(from_db) = from_db {
Ok(from_db)
} else {
Blog::fetch_from_webfinger(c, fqn)
Blog::fetch_from_webfinger(c, fqn).await
}
}
fn fetch_from_webfinger(c: &PlumeRocket, acct: &str) -> Result<Blog> {
resolve_with_prefix(Prefix::Group, acct.to_owned(), true)?
async fn fetch_from_webfinger(c: &PlumeRocket, acct: &str) -> Result<Blog> {
resolve_with_prefix(Prefix::Group, acct.to_owned(), true)
.await?
.links
.into_iter()
.find(|l| l.mime_type == Some(String::from("application/activity+json")))
+8 -8
View File
@@ -17,6 +17,7 @@ use activitypub::{
};
use chrono::{self, NaiveDateTime};
use diesel::{self, ExpressionMethods, QueryDsl, RunQueryDsl, SaveChangesDsl};
use futures::stream::{self, StreamExt};
use plume_common::{
activity_pub::{
inbox::{AsActor, AsObject, FromId},
@@ -24,7 +25,6 @@ use plume_common::{
},
utils,
};
use serde_json;
use std::collections::HashSet;
#[derive(Queryable, Identifiable, Clone, AsChangeset)]
@@ -105,7 +105,7 @@ impl Comment {
.unwrap_or(false)
}
pub fn to_activity(&self, c: &PlumeRocket) -> Result<Note> {
pub async fn to_activity(&self, c: &PlumeRocket) -> Result<Note> {
let author = User::get(&c.conn, self.author_id)?;
let (html, mentions, _hashtags) = utils::md_to_html(
self.content.get().as_ref(),
@@ -132,18 +132,18 @@ impl Comment {
note.object_props.set_attributed_to_link(author.into_id())?;
note.object_props.set_to_link_vec(to)?;
note.object_props.set_tag_link_vec(
mentions
.into_iter()
.filter_map(|m| Mention::build_activity(c, &m).ok())
.collect::<Vec<link::Mention>>(),
stream::iter(mentions)
.filter_map(|m| async move { Mention::build_activity(c, &m).await.ok() })
.collect::<Vec<link::Mention>>()
.await,
)?;
Ok(note)
}
pub fn create_activity(&self, c: &PlumeRocket) -> Result<Create> {
pub async fn create_activity(&self, c: &PlumeRocket) -> Result<Create> {
let author = User::get(&c.conn, self.author_id)?;
let note = self.to_activity(c)?;
let note = self.to_activity(c).await?;
let mut act = Create::default();
act.create_props.set_actor_link(author.into_id())?;
act.create_props.set_object_object(note.clone())?;
+10
View File
@@ -11,6 +11,8 @@ pub struct Config {
pub base_url: String,
pub database_url: String,
pub db_name: &'static str,
pub db_max_size: Option<u32>,
pub db_min_idle: Option<u32>,
pub search_index: String,
pub rocket: Result<RocketConfig, RocketError>,
pub logo: LogoConfig,
@@ -193,6 +195,14 @@ lazy_static! {
var("ROCKET_PORT").unwrap_or_else(|_| "7878".to_owned())
)),
db_name: DB_NAME,
db_max_size: var("DB_MAX_SIZE").map_or(None, |s| Some(
s.parse::<u32>()
.expect("Couldn't parse DB_MAX_SIZE into u32")
)),
db_min_idle: var("DB_MIN_IDLE").map_or(None, |s| Some(
s.parse::<u32>()
.expect("Couldn't parse DB_MIN_IDLE into u32")
)),
#[cfg(feature = "postgres")]
database_url: var("DATABASE_URL")
.unwrap_or_else(|_| format!("postgres://plume:plume@localhost/{}", DB_NAME)),
+6 -6
View File
@@ -7,7 +7,7 @@ use diesel::{dsl::sql_query, ConnectionError, RunQueryDsl};
use rocket::{
http::Status,
request::{self, FromRequest},
Outcome, Request, State,
Outcome, Request,
};
use std::ops::Deref;
@@ -21,14 +21,14 @@ pub struct DbConn(pub PooledConnection<ConnectionManager<Connection>>);
/// Attempts to retrieve a single connection from the managed database pool. If
/// no pool is currently managed, fails with an `InternalServerError` status. If
/// no connections are available, fails with a `ServiceUnavailable` status.
#[rocket::async_trait]
impl<'a, 'r> FromRequest<'a, 'r> for DbConn {
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
let pool = request.guard::<State<'_, DbPool>>()?;
match pool.get() {
Ok(conn) => Outcome::Success(DbConn(conn)),
Err(_) => Outcome::Failure((Status::ServiceUnavailable, ())),
async fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
match DbConn::from_request(request).await {
Outcome::Success(a) => Outcome::Success(a),
_ => Outcome::Failure((Status::ServiceUnavailable, ())),
}
}
}
+2 -1
View File
@@ -6,10 +6,11 @@ use rocket::{
pub struct Headers<'r>(pub HeaderMap<'r>);
#[rocket::async_trait]
impl<'a, 'r> FromRequest<'a, 'r> for Headers<'r> {
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, ()> {
async fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, ()> {
let mut headers = HeaderMap::new();
for header in request.headers().clone().into_iter() {
headers.add(header);
-1
View File
@@ -1,5 +1,4 @@
use activitypub::activity::*;
use serde_json;
use crate::{
comments::Comment,
+7
View File
@@ -4,6 +4,7 @@
#[macro_use]
extern crate diesel;
extern crate futures;
#[macro_use]
extern crate lazy_static;
#[macro_use]
@@ -75,6 +76,12 @@ impl From<std::option::NoneError> for Error {
}
}
impl From<Error> for std::option::NoneError {
fn from(_: Error) -> Self {
std::option::NoneError
}
}
impl From<url::ParseError> for Error {
fn from(_: url::ParseError) -> Self {
Error::Url
+60 -20
View File
@@ -7,8 +7,8 @@ use crate::{
use diesel::{self, ExpressionMethods, QueryDsl, RunQueryDsl};
use std::convert::{TryFrom, TryInto};
/// Represent what a list is supposed to store. Represented in database as an integer
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
/// Represent what a list is supposed to store. Represented in database as an integer
pub enum ListType {
User,
Blog,
@@ -58,7 +58,11 @@ struct NewList<'a> {
}
macro_rules! func {
(@elem User $id:expr, $value:expr) => {
(
$(#[$outer:meta])*
@elem User $id:expr, $value:expr
) => {
$(#[$outer])*
NewListElem {
list_id: $id,
user_id: Some(*$value),
@@ -66,7 +70,11 @@ macro_rules! func {
word: None,
}
};
(@elem Blog $id:expr, $value:expr) => {
(
$(#[$outer:meta])*
@elem Blog $id:expr, $value:expr
) => {
$(#[$outer])*
NewListElem {
list_id: $id,
user_id: None,
@@ -74,7 +82,11 @@ macro_rules! func {
word: None,
}
};
(@elem Word $id:expr, $value:expr) => {
(
$(#[$outer:meta])*
@elem Word $id:expr, $value:expr
) => {
$(#[$outer])*
NewListElem {
list_id: $id,
user_id: None,
@@ -82,7 +94,11 @@ macro_rules! func {
word: Some($value),
}
};
(@elem Prefix $id:expr, $value:expr) => {
(
$(#[$outer:meta])*
@elem Prefix $id:expr, $value:expr
) => {
$(#[$outer])*
NewListElem {
list_id: $id,
user_id: None,
@@ -99,7 +115,11 @@ macro_rules! func {
(@out_type Word) => { String };
(@out_type Prefix) => { String };
(add: $fn:ident, $kind:ident) => {
(
$(#[$outer:meta])*
add: $fn:ident, $kind:ident
) => {
$(#[$outer])*
pub fn $fn(&self, conn: &Connection, vals: &[func!(@in_type $kind)]) -> Result<()> {
if self.kind() != ListType::$kind {
return Err(Error::InvalidValue);
@@ -116,7 +136,11 @@ macro_rules! func {
}
};
(list: $fn:ident, $kind:ident, $table:ident) => {
(
$(#[$outer:meta])*
list: $fn:ident, $kind:ident, $table:ident
) => {
$(#[$outer])*
pub fn $fn(&self, conn: &Connection) -> Result<Vec<func!(@out_type $kind)>> {
if self.kind() != ListType::$kind {
return Err(Error::InvalidValue);
@@ -132,7 +156,11 @@ macro_rules! func {
(set: $fn:ident, $kind:ident, $add:ident) => {
(
$(#[$outer:meta])*
set: $fn:ident, $kind:ident, $add:ident
) => {
$(#[$outer])*
pub fn $fn(&self, conn: &Connection, val: &[func!(@in_type $kind)]) -> Result<()> {
if self.kind() != ListType::$kind {
return Err(Error::InvalidValue);
@@ -246,23 +274,35 @@ impl List {
private::ListElem::prefix_in_list(conn, self, word)
}
/// Insert new users in a list
func! {add: add_users, User}
func! {
/// Insert new users in a list
add: add_users, User
}
/// Insert new blogs in a list
func! {add: add_blogs, Blog}
func! {
/// Insert new blogs in a list
add: add_blogs, Blog
}
/// Insert new words in a list
func! {add: add_words, Word}
func! {
/// Insert new words in a list
add: add_words, Word
}
/// Insert new prefixes in a list
func! {add: add_prefixes, Prefix}
func! {
/// Insert new prefixes in a list
add: add_prefixes, Prefix
}
/// Get all users in the list
func! {list: list_users, User, users}
func! {
/// Get all users in the list
list: list_users, User, users
}
/// Get all blogs in the list
func! {list: list_blogs, Blog, blogs}
func! {
/// Get all blogs in the list
list: list_blogs, Blog, blogs
}
/// Get all words in the list
pub fn list_words(&self, conn: &Connection) -> Result<Vec<String>> {
+5 -7
View File
@@ -10,8 +10,8 @@ use plume_common::{
activity_pub::{inbox::FromId, Id},
utils::MediaProcessor,
};
use reqwest;
use std::{fs, path::Path};
use tokio::prelude::*;
#[derive(Clone, Identifiable, Queryable)]
pub struct Media {
@@ -197,7 +197,7 @@ impl Media {
}
// TODO: merge with save_remote?
pub fn from_activity(c: &PlumeRocket, image: &Image) -> Result<Media> {
pub async fn from_activity(c: &PlumeRocket, image: &Image) -> Result<Media> {
let conn = &*c.conn;
let remote_url = image.object_props.url_string().ok()?;
let ext = remote_url
@@ -211,11 +211,9 @@ impl Media {
ext
));
let mut dest = fs::File::create(path.clone()).ok()?;
reqwest::get(remote_url.as_str())
.ok()?
.copy_to(&mut dest)
.ok()?;
let mut dest = tokio::fs::File::create(path.clone()).await?;
let contents = reqwest::get(remote_url.as_str()).await?.bytes().await?;
dest.write_all(&contents).await?;
Media::insert(
conn,
+2 -2
View File
@@ -52,8 +52,8 @@ impl Mention {
}
}
pub fn build_activity(c: &PlumeRocket, ment: &str) -> Result<link::Mention> {
let user = User::find_by_fqn(c, ment)?;
pub async fn build_activity(c: &PlumeRocket, ment: &str) -> Result<link::Mention> {
let user = User::find_by_fqn(c, ment).await?;
let mut mention = link::Mention::default();
mention.link_props.set_href_string(user.ap_url)?;
mention.link_props.set_name_string(format!("@{}", ment))?;
+30 -14
View File
@@ -20,20 +20,35 @@ mod module {
pub flash_msg: Option<(String, String)>,
}
#[rocket::async_trait]
impl<'a, 'r> FromRequest<'a, 'r> for PlumeRocket {
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<PlumeRocket, ()> {
let conn = request.guard::<DbConn>()?;
let intl = request.guard::<rocket_i18n::I18n>()?;
let user = request.guard::<users::User>().succeeded();
let worker = request.guard::<'_, State<'_, Arc<ScheduledThreadPool>>>()?;
let searcher = request.guard::<'_, State<'_, Arc<search::Searcher>>>()?;
let flash_msg = request.guard::<FlashMessage<'_, '_>>().succeeded();
async fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
let conn = DbConn::from_request(request).await.succeeded().unwrap();
let intl = rocket_i18n::I18n::from_request(request)
.await
.succeeded()
.unwrap();
let user = users::User::from_request(request)
.await
.succeeded()
.unwrap();
let worker = request
.guard::<State<'_, Arc<ScheduledThreadPool>>>()
.await
.succeeded()
.unwrap();
let searcher = request
.guard::<State<'_, Arc<search::Searcher>>>()
.await
.succeeded()
.unwrap();
let flash_msg = request.guard::<FlashMessage<'_, '_>>().await.succeeded();
Outcome::Success(PlumeRocket {
conn,
intl,
user,
user: Some(user),
flash_msg: flash_msg.map(|f| (f.name().into(), f.msg().into())),
worker: worker.clone(),
searcher: searcher.clone(),
@@ -60,17 +75,18 @@ mod module {
pub worker: Arc<ScheduledThreadPool>,
}
#[rocket::async_trait]
impl<'a, 'r> FromRequest<'a, 'r> for PlumeRocket {
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<PlumeRocket, ()> {
let conn = request.guard::<DbConn>()?;
let user = request.guard::<users::User>().succeeded();
let worker = request.guard::<'_, State<'_, Arc<ScheduledThreadPool>>>()?;
let searcher = request.guard::<'_, State<'_, Arc<search::Searcher>>>()?;
async fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
let conn = try_outcome!(DbConn::from_request(request).await);
let user = try_outcome!(users::User::from_request(request).await);
let worker = try_outcome!(request.guard::<'_, State<'_, Arc<ScheduledThreadPool>>>());
let searcher = try_outcome!(request.guard::<'_, State<'_, Arc<search::Searcher>>>());
Outcome::Success(PlumeRocket {
conn,
user,
user: Some(user),
worker: worker.clone(),
searcher: searcher.clone(),
})
+17 -12
View File
@@ -19,8 +19,8 @@ use plume_common::{
},
utils::md_to_html,
};
use serde_json;
use std::collections::HashSet;
use tokio::runtime::Runtime;
pub type LicensedArticle = CustomObject<Licensed, Article>;
@@ -579,11 +579,11 @@ impl FromId<PlumeRocket> for Post {
}
});
let cover = article
.object_props
.icon_object::<Image>()
.ok()
.and_then(|img| Media::from_activity(&c, &img).ok().map(|m| m.id));
let image = article.object_props.icon_object::<Image>().ok().unwrap();
let mut r = Runtime::new().unwrap();
let cover =
Some(r.block_on(async { Media::from_activity(&c, &image).await.ok().unwrap().id }));
let title = article.object_props.name_string()?;
let post = Post::insert(
@@ -699,17 +699,22 @@ impl FromId<PlumeRocket> for PostUpdate {
}
fn from_activity(c: &PlumeRocket, updated: LicensedArticle) -> Result<Self> {
let image = updated
.object
.object_props
.icon_object::<Image>()
.ok()
.unwrap();
let mut r = Runtime::new().unwrap();
let cover =
Some(r.block_on(async { Media::from_activity(&c, &image).await.ok().unwrap().id }));
Ok(PostUpdate {
ap_url: updated.object.object_props.id_string()?,
title: updated.object.object_props.name_string().ok(),
subtitle: updated.object.object_props.summary_string().ok(),
content: updated.object.object_props.content_string().ok(),
cover: updated
.object
.object_props
.icon_object::<Image>()
.ok()
.and_then(|img| Media::from_activity(&c, &img).ok().map(|m| m.id)),
cover,
source: updated
.object
.ap_object_props
+28 -8
View File
@@ -7,7 +7,9 @@ use crate::{
users::User,
PlumeRocket, Result,
};
use futures::stream::{self, StreamExt};
use plume_common::activity_pub::inbox::AsActor;
use tokio::runtime::Runtime;
use whatlang::{self, Lang};
#[derive(Debug, Clone, PartialEq)]
@@ -295,15 +297,33 @@ impl WithList {
}
}
List::Array(list) => match self {
WithList::Blog => Ok(list
.iter()
.filter_map(|b| Blog::find_by_fqn(rocket, b).ok())
.any(|b| b.id == post.blog_id)),
WithList::Blog => {
let mut rt = Runtime::new().unwrap();
rt.block_on(async move {
Ok(stream::iter(list)
.filter_map(|b| async move {
Some(Blog::find_by_fqn(rocket, b).await.ok().unwrap())
})
.collect::<Vec<_>>()
.await
.into_iter()
.any(|b| b.id == post.blog_id))
})
}
WithList::Author { boosts, likes } => match kind {
Kind::Original => Ok(list
.iter()
.filter_map(|a| User::find_by_fqn(rocket, a).ok())
.any(|a| post.is_author(&rocket.conn, a.id).unwrap_or(false))),
Kind::Original => {
let mut rt = Runtime::new().unwrap();
rt.block_on(async move {
Ok(stream::iter(list)
.filter_map(|a| async move {
Some(User::find_by_fqn(rocket, a).await.ok().unwrap())
})
.collect::<Vec<_>>()
.await
.into_iter()
.any(|a| post.is_author(&rocket.conn, a.id).unwrap_or(false)))
})
}
Kind::Reshare(u) => {
if *boosts {
Ok(list.iter().any(|user| &u.fqn == user))
+78 -71
View File
@@ -11,7 +11,6 @@ use activitypub::{
object::{Image, Tombstone},
Activity, CustomObject, Endpoint,
};
use bcrypt;
use chrono::{NaiveDateTime, Utc};
use diesel::{self, BelongingToDsl, ExpressionMethods, OptionalExtension, QueryDsl, RunQueryDsl};
use openssl::{
@@ -37,7 +36,6 @@ use rocket::{
outcome::IntoOutcome,
request::{self, FromRequest, Request},
};
use serde_json;
use std::{
cmp::PartialEq,
hash::{Hash, Hasher},
@@ -54,6 +52,7 @@ pub enum Role {
}
#[derive(Queryable, Identifiable, Clone, Debug, AsChangeset)]
#[changeset_options(treat_none_as_null = "true")]
pub struct User {
pub id: i32,
pub username: String,
@@ -190,7 +189,7 @@ impl User {
.map_err(Error::from)
}
pub fn find_by_fqn(c: &PlumeRocket, fqn: &str) -> Result<User> {
pub async fn find_by_fqn(c: &PlumeRocket, fqn: &str) -> Result<User> {
let from_db = users::table
.filter(users::fqn.eq(fqn))
.first(&*c.conn)
@@ -198,12 +197,13 @@ impl User {
if let Some(from_db) = from_db {
Ok(from_db)
} else {
User::fetch_from_webfinger(c, fqn)
User::fetch_from_webfinger(c, fqn).await
}
}
fn fetch_from_webfinger(c: &PlumeRocket, acct: &str) -> Result<User> {
let link = resolve(acct.to_owned(), true)?
async fn fetch_from_webfinger(c: &PlumeRocket, acct: &str) -> Result<User> {
let link = resolve(acct.to_owned(), true)
.await?
.links
.into_iter()
.find(|l| l.mime_type == Some(String::from("application/activity+json")))
@@ -211,8 +211,9 @@ impl User {
User::from_id(c, link.href.as_ref()?, None).map_err(|(_, e)| e)
}
pub fn fetch_remote_interact_uri(acct: &str) -> Result<String> {
resolve(acct.to_owned(), true)?
pub async fn fetch_remote_interact_uri(acct: &str) -> Result<String> {
resolve(acct.to_owned(), true)
.await?
.links
.into_iter()
.find(|l| l.rel == "http://ostatus.org/schema/1.0/subscribe")
@@ -220,9 +221,9 @@ impl User {
.ok_or(Error::Webfinger)
}
fn fetch(url: &str) -> Result<CustomPerson> {
let mut res = ClientBuilder::new()
.connect_timeout(Some(std::time::Duration::from_secs(5)))
async fn fetch(url: &str) -> Result<CustomPerson> {
let res = ClientBuilder::new()
.connect_timeout(std::time::Duration::from_secs(5))
.build()?
.get(url)
.header(
@@ -234,8 +235,9 @@ impl User {
.join(", "),
)?,
)
.send()?;
let text = &res.text()?;
.send()
.await?;
let text = &res.text().await?;
// without this workaround, publicKey is not correctly deserialized
let ap_sign = serde_json::from_str::<ApSignature>(text)?;
let mut json = serde_json::from_str::<CustomPerson>(text)?;
@@ -243,48 +245,48 @@ impl User {
Ok(json)
}
pub fn fetch_from_url(c: &PlumeRocket, url: &str) -> Result<User> {
User::fetch(url).and_then(|json| User::from_activity(c, json))
pub async fn fetch_from_url(c: &PlumeRocket, url: &str) -> Result<User> {
let json = User::fetch(url).await?;
User::from_activity(c, json)
}
pub fn refetch(&self, conn: &Connection) -> Result<()> {
User::fetch(&self.ap_url.clone()).and_then(|json| {
let avatar = Media::save_remote(
conn,
json.object
.object_props
.icon_image()?
.object_props
.url_string()?,
&self,
)
.ok();
pub async fn refetch(&self, conn: &Connection) -> Result<()> {
let json = User::fetch(&self.ap_url.clone()).await?;
let avatar = Media::save_remote(
conn,
json.object
.object_props
.icon_image()?
.object_props
.url_string()?,
&self,
)
.ok();
diesel::update(self)
.set((
users::username.eq(json.object.ap_actor_props.preferred_username_string()?),
users::display_name.eq(json.object.object_props.name_string()?),
users::outbox_url.eq(json.object.ap_actor_props.outbox_string()?),
users::inbox_url.eq(json.object.ap_actor_props.inbox_string()?),
users::summary.eq(SafeString::new(
&json
.object
.object_props
.summary_string()
.unwrap_or_default(),
)),
users::followers_endpoint.eq(json.object.ap_actor_props.followers_string()?),
users::avatar_id.eq(avatar.map(|a| a.id)),
users::last_fetched_date.eq(Utc::now().naive_utc()),
users::public_key.eq(json
.custom_props
.public_key_publickey()?
.public_key_pem_string()?),
))
.execute(conn)
.map(|_| ())
.map_err(Error::from)
})
diesel::update(self)
.set((
users::username.eq(json.object.ap_actor_props.preferred_username_string()?),
users::display_name.eq(json.object.object_props.name_string()?),
users::outbox_url.eq(json.object.ap_actor_props.outbox_string()?),
users::inbox_url.eq(json.object.ap_actor_props.inbox_string()?),
users::summary.eq(SafeString::new(
&json
.object
.object_props
.summary_string()
.unwrap_or_default(),
)),
users::followers_endpoint.eq(json.object.ap_actor_props.followers_string()?),
users::avatar_id.eq(avatar.map(|a| a.id)),
users::last_fetched_date.eq(Utc::now().naive_utc()),
users::public_key.eq(json
.custom_props
.public_key_publickey()?
.public_key_pem_string()?),
))
.execute(conn)
.map(|_| ())
.map_err(Error::from)
}
pub fn hash_pass(pass: &str) -> Result<String> {
@@ -355,9 +357,10 @@ impl User {
.set_part_of_link(Id::new(&self.outbox_url))?;
Ok(ActivityStream::new(coll))
}
fn fetch_outbox_page<T: Activity>(&self, url: &str) -> Result<(Vec<T>, Option<String>)> {
let mut res = ClientBuilder::new()
.connect_timeout(Some(std::time::Duration::from_secs(5)))
async fn fetch_outbox_page<T: Activity>(&self, url: &str) -> Result<(Vec<T>, Option<String>)> {
let res = ClientBuilder::new()
.connect_timeout(std::time::Duration::from_secs(5))
.build()?
.get(url)
.header(
@@ -369,8 +372,9 @@ impl User {
.join(", "),
)?,
)
.send()?;
let text = &res.text()?;
.send()
.await?;
let text = &res.text().await?;
let json: serde_json::Value = serde_json::from_str(text)?;
let items = json["items"]
.as_array()
@@ -385,9 +389,9 @@ impl User {
};
Ok((items, next))
}
pub fn fetch_outbox<T: Activity>(&self) -> Result<Vec<T>> {
let mut res = ClientBuilder::new()
.connect_timeout(Some(std::time::Duration::from_secs(5)))
pub async fn fetch_outbox<T: Activity>(&self) -> Result<Vec<T>> {
let res = ClientBuilder::new()
.connect_timeout(std::time::Duration::from_secs(5))
.build()?
.get(&self.outbox_url[..])
.header(
@@ -399,13 +403,14 @@ impl User {
.join(", "),
)?,
)
.send()?;
let text = &res.text()?;
.send()
.await?;
let text = &res.text().await?;
let json: serde_json::Value = serde_json::from_str(text)?;
if let Some(first) = json.get("first") {
let mut items: Vec<T> = Vec::new();
let mut next = first.as_str().unwrap().to_owned();
while let Ok((mut page, nxt)) = self.fetch_outbox_page(&next) {
while let Ok((mut page, nxt)) = self.fetch_outbox_page(&next).await {
if page.is_empty() {
break;
}
@@ -430,9 +435,9 @@ impl User {
}
}
pub fn fetch_followers_ids(&self) -> Result<Vec<String>> {
let mut res = ClientBuilder::new()
.connect_timeout(Some(std::time::Duration::from_secs(5)))
pub async fn fetch_followers_ids(&self) -> Result<Vec<String>> {
let res = ClientBuilder::new()
.connect_timeout(std::time::Duration::from_secs(5))
.build()?
.get(&self.followers_endpoint[..])
.header(
@@ -444,8 +449,9 @@ impl User {
.join(", "),
)?,
)
.send()?;
let text = &res.text()?;
.send()
.await?;
let text = &res.text().await?;
let json: serde_json::Value = serde_json::from_str(text)?;
Ok(json["items"]
.as_array()
@@ -759,7 +765,7 @@ impl User {
mime_type: None,
href: None,
template: Some(format!(
"https://{}/remote_interact?{{uri}}",
"https://{}/remote_interact?target={{uri}}",
self.get_instance(conn)?.public_domain
)),
},
@@ -788,11 +794,12 @@ impl User {
}
}
#[rocket::async_trait]
impl<'a, 'r> FromRequest<'a, 'r> for User {
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<User, ()> {
let conn = request.guard::<DbConn>()?;
async fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
let conn = try_outcome!(DbConn::from_request(request).await);
request
.cookies()
.get_private(AUTH_COOKIE)
+1 -1
View File
@@ -10,7 +10,7 @@ msgstr ""
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Crowdin-Project: plume\n"
"X-Crowdin-Language: fr\n"
"X-Crowdin-File: /master/po/plume-front/plume-front.pot\n"
+2 -1
View File
@@ -10,7 +10,8 @@ msgstr ""
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=6; plural=(n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 && n%100<=99 ? 4 : 5);\n"
"Plural-Forms: nplurals=6; plural=(n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 "
"&& n%100<=10 ? 3 : n%100>=11 && n%100<=99 ? 4 : 5);\n"
"X-Crowdin-Project: plume\n"
"X-Crowdin-Language: ar\n"
"X-Crowdin-File: /master/po/plume/plume.pot\n"
+1 -1
View File
@@ -10,7 +10,7 @@ msgstr ""
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Crowdin-Project: plume\n"
"X-Crowdin-Language: fr\n"
"X-Crowdin-File: /master/po/plume/plume.pot\n"
+1 -1
View File
@@ -1 +1 @@
nightly-2020-01-15
nightly-2020-05-05
+2 -2
View File
@@ -24,9 +24,9 @@ if [ $ARCH == "aarch64" -o $ARCH == "armv71" ] ; then
apt-get install -y --no-install-recommends build-essential subversion ninja-build cmake
mkdir -p /scratch/src
cd /scratch/src
svn co http://llvm.org/svn/llvm-project/llvm/tags/RELEASE_800/final/ llvm
svn co http://llvm.org/svn/llvm-project/llvm/tags/RELEASE_900/final/ llvm
cd /scratch/src/llvm/tools
svn co http://llvm.org/svn/llvm-project/lld/tags/RELEASE_800/final/ lld
svn co http://llvm.org/svn/llvm-project/lld/tags/RELEASE_900/final/ lld
mkdir -p /scratch/build/arm
cd /scratch/build/arm
if [ "$ARCH" == "aarch64" ] ; then
+4 -3
View File
@@ -8,7 +8,7 @@ description: |
* Media management: you can upload pictures to illustrate your articles, but also audio files if you host a podcast, and manage them all from Plume.
* Federation: Plume is part of a network of interconnected websites called the Fediverse. Each of these websites (often called instances) have their own rules and thematics, but they can all communicate with each other.
* Collaborative writing: invite other people to your blogs, and write articles together.
grade: devel # must be 'stable' to release into candidate/stable channels
grade: stable
confinement: strict
apps:
@@ -25,12 +25,13 @@ parts:
plume:
plugin: rust
source: .
rust-revision: nightly-2019-03-23
rust-revision: nightly-2020-01-15
build-packages:
- libssl-dev
- pkg-config
- libsqlite3-dev
- gettext
- libclang-8-dev
- on arm64,armhf,ppc64el,s390x:
- lld-8
override-build: |
@@ -42,7 +43,7 @@ parts:
# Only Tier 1 Rust platforms get rust-lld
# On the others (arm64, armhf, powerpc64, s390x) fall back to using
# the system LLD we've installed earlier.
case ${SNAPCRAFT_ARCH_TRIPLE} in \
case ${SNAPCRAFT_ARCH_TRIPLET} in \
aarch64-linux-gnu|arm-linux-gnueabihf|powerpc64-linux-gnu|s390x-linux-gnu) \
RUSTFLAGS="-C linker=lld-8" cargo web deploy -p plume-front --release \
;; \
+3 -1
View File
@@ -35,6 +35,7 @@ impl Scope for plume_models::posts::Post {
pub struct Authorization<A, S>(pub ApiToken, PhantomData<(A, S)>);
#[rocket::async_trait]
impl<'a, 'r, A, S> FromRequest<'a, 'r> for Authorization<A, S>
where
A: Action,
@@ -42,9 +43,10 @@ where
{
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<Authorization<A, S>, ()> {
async fn from_request(request: &'a Request<'r>) -> request::Outcome<Authorization<A, S>, ()> {
request
.guard::<ApiToken>()
.await
.map_failure(|_| (Status::Unauthorized, ()))
.and_then(|token| {
if token.can(A::to_str(), S::to_str()) {
+25 -16
View File
@@ -4,7 +4,6 @@ use rocket::{
response::{self, Responder},
};
use rocket_contrib::json::Json;
use serde_json;
use plume_common::utils::random_hex;
use plume_models::{api_tokens::*, apps::App, users::User, Error, PlumeRocket};
@@ -26,21 +25,31 @@ impl From<std::option::NoneError> for ApiError {
}
}
#[rocket::async_trait]
impl<'r> Responder<'r> for ApiError {
fn respond_to(self, req: &Request<'_>) -> response::Result<'r> {
async fn respond_to(self, req: &'r Request<'_>) -> response::Result<'r> {
match self.0 {
Error::NotFound => Json(json!({
"error": "Not found"
}))
.respond_to(req),
Error::Unauthorized => Json(json!({
"error": "You are not authorized to access this resource"
}))
.respond_to(req),
_ => Json(json!({
"error": "Server error"
}))
.respond_to(req),
Error::NotFound => {
Json(json!({
"error": "Not found"
}))
.respond_to(req)
.await
}
Error::Unauthorized => {
Json(json!({
"error": "You are not authorized to access this resource"
}))
.respond_to(req)
.await
}
_ => {
Json(json!({
"error": "Server error"
}))
.respond_to(req)
.await
}
}
}
}
@@ -55,14 +64,14 @@ pub struct OAuthRequest {
}
#[get("/oauth2?<query..>")]
pub fn oauth(
pub async fn oauth(
query: Form<OAuthRequest>,
rockets: PlumeRocket,
) -> Result<Json<serde_json::Value>, ApiError> {
let conn = &*rockets.conn;
let app = App::find_by_client_id(conn, &query.client_id)?;
if app.client_secret == query.client_secret {
if let Ok(user) = User::find_by_fqn(&rockets, &query.username) {
if let Ok(user) = User::find_by_fqn(&rockets, &query.username).await {
if user.auth(&query.password) {
let token = ApiToken::insert(
conn,
+2 -2
View File
@@ -98,7 +98,7 @@ pub fn list(
}
#[post("/posts", data = "<payload>")]
pub fn create(
pub async fn create(
auth: Authorization<Write, Post>,
payload: Json<NewPostData>,
rockets: PlumeRocket,
@@ -192,7 +192,7 @@ pub fn create(
for m in mentions.into_iter() {
Mention::from_activity(
&*conn,
&Mention::build_activity(&rockets, &m)?,
&Mention::build_activity(&rockets, &m).await?,
post.id,
true,
true,
+22 -22
View File
@@ -9,9 +9,9 @@ use plume_models::{
use rocket::{data::*, http::Status, response::status, Outcome::*, Request};
use rocket_contrib::json::*;
use serde::Deserialize;
use std::io::Read;
use tokio::io::AsyncReadExt;
pub fn handle_incoming(
pub async fn handle_incoming(
rockets: PlumeRocket,
data: SignedJson<serde_json::Value>,
headers: Headers<'_>,
@@ -32,6 +32,7 @@ pub fn handle_incoming(
// maybe we just know an old key?
actor
.refetch(conn)
.await
.and_then(|_| User::get(conn, actor.id))
.and_then(|u| {
if verify_http_headers(&u, &headers.0, &sig).is_secure() || act.clone().verify(&u) {
@@ -73,32 +74,31 @@ impl<'a, T: Deserialize<'a>> FromData<'a> for SignedJson<T> {
type Owned = String;
type Borrowed = str;
fn transform(
r: &Request<'_>,
d: Data,
) -> Transform<rocket::data::Outcome<Self::Owned, Self::Error>> {
let size_limit = r.limits().get("json").unwrap_or(JSON_LIMIT);
let mut s = String::with_capacity(512);
match d.open().take(size_limit).read_to_string(&mut s) {
Ok(_) => Transform::Borrowed(Success(s)),
Err(e) => Transform::Borrowed(Failure((Status::BadRequest, JsonError::Io(e)))),
}
fn transform<'r>(r: &'r Request, d: Data) -> TransformFuture<'r, Self::Owned, Self::Error> {
Box::pin(async move {
let size_limit = r.limits().get("json").unwrap_or(JSON_LIMIT);
let mut s = String::with_capacity(512);
let outcome = match d.open().take(size_limit).read_to_string(&mut s).await {
Ok(_) => Success(s),
Err(e) => Failure((Status::BadRequest, JsonError::Io(e))),
};
Transform::Borrowed(outcome)
})
}
fn from_data(
_: &Request<'_>,
o: Transformed<'a, Self>,
) -> rocket::data::Outcome<Self, Self::Error> {
let string = o.borrowed()?;
match serde_json::from_str(&string) {
Ok(v) => Success(SignedJson(Digest::from_body(&string), Json(v))),
Err(e) => {
if e.is_data() {
Failure((Status::UnprocessableEntity, JsonError::Parse(string, e)))
} else {
Failure((Status::BadRequest, JsonError::Parse(string, e)))
) -> FromDataFuture<'a, Self, Self::Error> {
Box::pin(async move {
let string = try_outcome!(o.borrowed());
match serde_json::from_str(&string) {
Ok(v) => Success(SignedJson(Digest::from_body(&string), Json(v))),
Err(e) if e.is_data() => {
return Failure((Status::UnprocessableEntity, JsonError::Parse(string, e)))
}
Err(e) => Failure((Status::BadRequest, JsonError::Parse(string, e))),
}
}
})
}
}
+9 -26
View File
@@ -1,16 +1,15 @@
#![allow(clippy::too_many_arguments)]
#![feature(decl_macro, proc_macro_hygiene, try_trait)]
#![feature(proc_macro_hygiene, try_trait)]
#[macro_use]
extern crate gettext_macros;
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate runtime_fmt;
#[macro_use]
extern crate serde_json;
#[macro_use]
extern crate validator_derive;
extern crate validator;
use clap::App;
use diesel::r2d2::ConnectionManager;
@@ -21,7 +20,6 @@ use plume_models::{
search::{Searcher as UnmanagedSearcher, SearcherError},
Connection, Error, CONFIG,
};
use rocket_csrf::CsrfFairingBuilder;
use scheduled_thread_pool::ScheduledThreadPool;
use std::process::exit;
use std::sync::{Arc, Mutex};
@@ -55,10 +53,13 @@ fn init_pool() -> Option<DbPool> {
}
let manager = ConnectionManager::<Connection>::new(CONFIG.database_url.as_str());
let pool = DbPool::builder()
let mut builder = DbPool::builder()
.connection_customizer(Box::new(PragmaForeignKey))
.build(manager)
.ok()?;
.min_idle(CONFIG.db_min_idle);
if let Some(max_size) = CONFIG.db_max_size {
builder = builder.max_size(max_size);
};
let pool = builder.build(manager).ok()?;
Instance::cache_local(&pool.get().unwrap());
Some(pool)
}
@@ -272,25 +273,7 @@ Then try to restart Plume
.manage(dbpool)
.manage(Arc::new(workpool))
.manage(searcher)
.manage(include_i18n!())
.attach(
CsrfFairingBuilder::new()
.set_default_target(
"/csrf-violation?target=<uri>".to_owned(),
rocket::http::Method::Post,
)
.add_exceptions(vec![
("/inbox".to_owned(), "/inbox".to_owned(), None),
(
"/@/<name>/inbox".to_owned(),
"/@/<name>/inbox".to_owned(),
None,
),
("/api/<path..>".to_owned(), "/api/<path..>".to_owned(), None),
])
.finalize()
.expect("main: csrf fairing creation error"),
);
.manage(include_i18n!());
#[cfg(feature = "test")]
let rocket = rocket.mount("/test", routes![test_routes::health,]);
+38 -33
View File
@@ -1,5 +1,4 @@
use activitypub::collection::{OrderedCollection, OrderedCollectionPage};
use atom_syndication::{Entry, FeedBuilder};
use diesel::SaveChangesDsl;
use rocket::{
http::ContentType,
@@ -20,10 +19,14 @@ use plume_models::{
};
#[get("/~/<name>?<page>", rank = 2)]
pub fn details(name: String, page: Option<Page>, rockets: PlumeRocket) -> Result<Ructe, ErrorPage> {
pub async fn details(
name: String,
page: Option<Page>,
rockets: PlumeRocket,
) -> Result<Ructe, ErrorPage> {
let page = page.unwrap_or_default();
let conn = &*rockets.conn;
let blog = Blog::find_by_fqn(&rockets, &name)?;
let blog = Blog::find_by_fqn(&rockets, &name).await?;
let posts = Post::blog_page(conn, &blog, page.limits())?;
let articles_count = Post::count_for_blog(conn, &blog)?;
let authors = &blog.list_authors(conn)?;
@@ -39,12 +42,12 @@ pub fn details(name: String, page: Option<Page>, rockets: PlumeRocket) -> Result
}
#[get("/~/<name>", rank = 1)]
pub fn activity_details(
pub async fn activity_details(
name: String,
rockets: PlumeRocket,
_ap: ApRequest,
) -> Option<ActivityStream<CustomGroup>> {
let blog = Blog::find_by_fqn(&rockets, &name).ok()?;
let blog = Blog::find_by_fqn(&rockets, &name).await?;
Some(ActivityStream::new(blog.to_activity(&*rockets.conn).ok()?))
}
@@ -84,7 +87,7 @@ fn valid_slug(title: &str) -> Result<(), ValidationError> {
}
#[post("/blogs/new", data = "<form>")]
pub fn create(form: LenientForm<NewBlogForm>, rockets: PlumeRocket) -> RespondOrRedirect {
pub async fn create(form: LenientForm<NewBlogForm>, rockets: PlumeRocket) -> RespondOrRedirect {
let slug = utils::make_actor_id(&form.title);
let conn = &*rockets.conn;
let intl = &rockets.intl.catalog;
@@ -94,7 +97,7 @@ pub fn create(form: LenientForm<NewBlogForm>, rockets: PlumeRocket) -> RespondOr
Ok(_) => ValidationErrors::new(),
Err(e) => e,
};
if Blog::find_by_fqn(&rockets, &slug).is_ok() {
if Blog::find_by_fqn(&rockets, &slug).await.is_ok() {
errors.add(
"title",
ValidationError {
@@ -144,9 +147,11 @@ pub fn create(form: LenientForm<NewBlogForm>, rockets: PlumeRocket) -> RespondOr
}
#[post("/~/<name>/delete")]
pub fn delete(name: String, rockets: PlumeRocket) -> RespondOrRedirect {
pub async fn delete(name: String, rockets: PlumeRocket) -> RespondOrRedirect {
let conn = &*rockets.conn;
let blog = Blog::find_by_fqn(&rockets, &name).expect("blog::delete: blog not found");
let blog = Blog::find_by_fqn(&rockets, &name)
.await
.expect("blog::delete: blog not found");
if rockets
.user
@@ -185,9 +190,9 @@ pub struct EditForm {
}
#[get("/~/<name>/edit")]
pub fn edit(name: String, rockets: PlumeRocket) -> Result<Ructe, ErrorPage> {
pub async fn edit(name: String, rockets: PlumeRocket) -> Result<Ructe, ErrorPage> {
let conn = &*rockets.conn;
let blog = Blog::find_by_fqn(&rockets, &name)?;
let blog = Blog::find_by_fqn(&rockets, &name).await?;
if rockets
.user
.clone()
@@ -234,14 +239,16 @@ fn check_media(conn: &Connection, id: i32, user: &User) -> bool {
}
#[put("/~/<name>/edit", data = "<form>")]
pub fn update(
pub async fn update(
name: String,
form: LenientForm<EditForm>,
rockets: PlumeRocket,
) -> RespondOrRedirect {
let conn = &*rockets.conn;
let intl = &rockets.intl.catalog;
let mut blog = Blog::find_by_fqn(&rockets, &name).expect("blog::update: blog not found");
let mut blog = Blog::find_by_fqn(&rockets, &name)
.await
.expect("blog::update: blog not found");
if !rockets
.user
.clone()
@@ -343,38 +350,36 @@ pub fn update(
}
#[get("/~/<name>/outbox")]
pub fn outbox(name: String, rockets: PlumeRocket) -> Option<ActivityStream<OrderedCollection>> {
let blog = Blog::find_by_fqn(&rockets, &name).ok()?;
pub async fn outbox(
name: String,
rockets: PlumeRocket,
) -> Option<ActivityStream<OrderedCollection>> {
let blog = Blog::find_by_fqn(&rockets, &name).await?;
Some(blog.outbox(&*rockets.conn).ok()?)
}
#[allow(unused_variables)]
#[get("/~/<name>/outbox?<page>")]
pub fn outbox_page(
pub async fn outbox_page(
name: String,
page: Page,
rockets: PlumeRocket,
) -> Option<ActivityStream<OrderedCollectionPage>> {
let blog = Blog::find_by_fqn(&rockets, &name).ok()?;
let blog = Blog::find_by_fqn(&rockets, &name).await?;
Some(blog.outbox_page(&*rockets.conn, page.limits()).ok()?)
}
#[get("/~/<name>/atom.xml")]
pub fn atom_feed(name: String, rockets: PlumeRocket) -> Option<Content<String>> {
let blog = Blog::find_by_fqn(&rockets, &name).ok()?;
pub async fn atom_feed(name: String, rockets: PlumeRocket) -> Option<Content<String>> {
let blog = Blog::find_by_fqn(&rockets, &name).await?;
let conn = &*rockets.conn;
let feed = FeedBuilder::default()
.title(blog.title.clone())
.id(Instance::get_local()
.ok()?
.compute_box("~", &name, "atom.xml"))
.entries(
Post::get_recents_for_blog(&*conn, &blog, 15)
.ok()?
.into_iter()
.map(|p| super::post_to_atom(p, &*conn))
.collect::<Vec<Entry>>(),
)
.build()
.ok()?;
let entries = Post::get_recents_for_blog(&*conn, &blog, 15).ok()?;
let uri = Instance::get_local()
.ok()?
.compute_box("~", &name, "atom.xml");
let title = &blog.title;
let default_updated = &blog.creation_date;
let feed = super::build_atom_feed(entries, &uri, title, default_updated, conn);
Some(Content(
ContentType::new("application", "atom+xml"),
feed.to_string(),
+23 -17
View File
@@ -22,13 +22,13 @@ use plume_models::{
#[derive(Default, FromForm, Debug, Validate)]
pub struct NewCommentForm {
pub responding_to: Option<i32>,
#[validate(length(min = "1", message = "Your comment can't be empty"))]
#[validate(length(min = 1, message = "Your comment can't be empty"))]
pub content: String,
pub warning: String,
}
#[post("/~/<blog_name>/<slug>/comment", data = "<form>")]
pub fn create(
pub async fn create(
blog_name: String,
slug: String,
form: LenientForm<NewCommentForm>,
@@ -36,10 +36,12 @@ pub fn create(
rockets: PlumeRocket,
) -> Result<Flash<Redirect>, Ructe> {
let conn = &*rockets.conn;
let blog = Blog::find_by_fqn(&rockets, &blog_name).expect("comments::create: blog error");
let blog = Blog::find_by_fqn(&rockets, &blog_name)
.await
.expect("comments::create: blog error");
let post = Post::find_by_slug(&*conn, &slug, blog.id).expect("comments::create: post error");
form.validate()
.map(|_| {
match form.validate() {
Ok(_ok) => {
let (html, mentions, _hashtags) = utils::md_to_html(
form.content.as_ref(),
Some(
@@ -66,6 +68,7 @@ pub fn create(
.expect("comments::create: insert error");
let new_comment = comm
.create_activity(&rockets)
.await
.expect("comments::create: activity error");
// save mentions
@@ -73,6 +76,7 @@ pub fn create(
Mention::from_activity(
&*conn,
&Mention::build_activity(&rockets, &ment)
.await
.expect("comments::create: build mention error"),
comm.id,
false,
@@ -90,14 +94,14 @@ pub fn create(
.worker
.execute(move || broadcast(&user_clone, new_comment, dest));
Flash::success(
Ok(Flash::success(
Redirect::to(
uri!(super::posts::details: blog = blog_name, slug = slug, responding_to = _),
),
i18n!(&rockets.intl.catalog, "Your comment has been posted."),
)
})
.map_err(|errors| {
))
}
Err(errors) => {
// TODO: de-duplicate this code
let comments = CommentTree::from_post(&*conn, &post, Some(&user))
.expect("comments::create: comments error");
@@ -106,7 +110,7 @@ pub fn create(
.responding_to
.and_then(|r| Comment::get(&*conn, r).ok());
render!(posts::details(
Err(render!(posts::details(
&rockets.to_context(),
post.clone(),
blog,
@@ -133,8 +137,9 @@ pub fn create(
post.get_authors(&*conn)
.expect("comments::create: authors error")[0]
.clone()
))
})
)))
}
}
}
#[post("/~/<blog>/<slug>/comment/<id>/delete")]
@@ -174,15 +179,16 @@ pub fn delete(
}
#[get("/~/<_blog>/<_slug>/comment/<id>")]
pub fn activity_pub(
pub async fn activity_pub(
_blog: String,
_slug: String,
id: i32,
_ap: ApRequest,
rockets: PlumeRocket,
) -> Option<ActivityStream<Note>> {
Comment::get(&*rockets.conn, id)
.and_then(|c| c.to_activity(&rockets))
.ok()
.map(ActivityStream::new)
let c = match Comment::get(&*rockets.conn, id) {
Ok(c) => c.to_activity(&rockets).await.ok(),
Err(_) => None,
};
c.map(ActivityStream::new)
}
+24 -12
View File
@@ -1,6 +1,7 @@
use crate::template_utils::{IntoContext, Ructe};
use plume_models::{Error, PlumeRocket};
use rocket::{
request::FromRequest,
response::{self, Responder},
Request,
};
@@ -14,35 +15,46 @@ impl From<Error> for ErrorPage {
}
}
#[rocket::async_trait]
impl<'r> Responder<'r> for ErrorPage {
fn respond_to(self, req: &Request<'_>) -> response::Result<'r> {
let rockets = req.guard::<PlumeRocket>().unwrap();
async fn respond_to(self, req: &'r Request<'_>) -> response::Result<'r> {
let rockets = PlumeRocket::from_request(req).await.unwrap();
match self.0 {
Error::NotFound => render!(errors::not_found(&rockets.to_context())).respond_to(req),
Error::Unauthorized => {
render!(errors::not_found(&rockets.to_context())).respond_to(req)
Error::NotFound => {
render!(errors::not_found(&rockets.to_context()))
.respond_to(req)
.await
}
Error::Unauthorized => {
render!(errors::not_found(&rockets.to_context()))
.respond_to(req)
.await
}
_ => {
render!(errors::not_found(&rockets.to_context()))
.respond_to(req)
.await
}
_ => render!(errors::not_found(&rockets.to_context())).respond_to(req),
}
}
}
#[catch(404)]
pub fn not_found(req: &Request<'_>) -> Ructe {
let rockets = req.guard::<PlumeRocket>().unwrap();
pub async fn not_found(req: &Request<'_>) -> Ructe {
let rockets = req.guard::<PlumeRocket>().await.unwrap();
render!(errors::not_found(&rockets.to_context()))
}
#[catch(422)]
pub fn unprocessable_entity(req: &Request<'_>) -> Ructe {
let rockets = req.guard::<PlumeRocket>().unwrap();
pub async fn unprocessable_entity(req: &Request<'_>) -> Ructe {
let rockets = req.guard::<PlumeRocket>().await.unwrap();
render!(errors::unprocessable_entity(&rockets.to_context()))
}
#[catch(500)]
pub fn server_error(req: &Request<'_>) -> Ructe {
let rockets = req.guard::<PlumeRocket>().unwrap();
pub async fn server_error(req: &Request<'_>) -> Ructe {
let rockets = req.guard::<PlumeRocket>().await.unwrap();
render!(errors::server_error(&rockets.to_context()))
}
+11 -7
View File
@@ -5,7 +5,7 @@ use rocket::{
use rocket_contrib::json::Json;
use rocket_i18n::I18n;
use scheduled_thread_pool::ScheduledThreadPool;
use serde_json;
use std::path::PathBuf;
use std::str::FromStr;
use validator::{Validate, ValidationErrors};
@@ -76,12 +76,12 @@ pub fn admin_mod(_mod: Moderator, rockets: PlumeRocket) -> Ructe {
#[derive(Clone, FromForm, Validate)]
pub struct InstanceSettingsForm {
#[validate(length(min = "1"))]
#[validate(length(min = 1))]
pub name: String,
pub open_registrations: bool,
pub short_description: SafeString,
pub long_description: SafeString,
#[validate(length(min = "1"))]
#[validate(length(min = 1))]
pub default_license: String,
}
@@ -386,17 +386,21 @@ fn ban(
}
#[post("/inbox", data = "<data>")]
pub fn shared_inbox(
pub async fn shared_inbox(
rockets: PlumeRocket,
data: inbox::SignedJson<serde_json::Value>,
headers: Headers<'_>,
) -> Result<String, status::BadRequest<&'static str>> {
inbox::handle_incoming(rockets, data, headers)
inbox::handle_incoming(rockets, data, headers).await
}
#[get("/remote_interact?<target>")]
pub fn interact(rockets: PlumeRocket, user: Option<User>, target: String) -> Option<Redirect> {
if User::find_by_fqn(&rockets, &target).is_ok() {
pub async fn interact(
rockets: PlumeRocket,
user: Option<User>,
target: String,
) -> Option<Redirect> {
if User::find_by_fqn(&rockets, &target).await.is_ok() {
return Some(Redirect::to(uri!(super::user::details: name = target)));
}
Regular → Executable
+53 -15
View File
@@ -1,12 +1,14 @@
#![warn(clippy::too_many_arguments)]
use crate::template_utils::Ructe;
use atom_syndication::{ContentBuilder, Entry, EntryBuilder, LinkBuilder, Person, PersonBuilder};
use atom_syndication::{
ContentBuilder, Entry, EntryBuilder, Feed, FeedBuilder, LinkBuilder, Person, PersonBuilder,
};
use chrono::naive::NaiveDateTime;
use plume_models::{posts::Post, Connection, CONFIG, ITEMS_PER_PAGE};
use rocket::{
http::{
hyper::header::{CacheControl, CacheDirective, ETag, EntityTag},
uri::{FromUriParam, Query},
RawStr, Status,
Header, RawStr, Status,
},
request::{self, FromFormValue, FromRequest, Request},
response::{self, Flash, NamedFile, Redirect, Responder, Response},
@@ -92,10 +94,11 @@ impl Page {
#[derive(Shrinkwrap)]
pub struct ContentLen(pub u64);
#[rocket::async_trait]
impl<'a, 'r> FromRequest<'a, 'r> for ContentLen {
type Error = ();
fn from_request(r: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
async fn from_request(r: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
match r.limits().get("forms") {
Some(l) => Outcome::Success(ContentLen(l)),
None => Outcome::Failure((Status::InternalServerError, ())),
@@ -115,13 +118,46 @@ pub struct RemoteForm {
pub remote: String,
}
pub fn post_to_atom(post: Post, conn: &Connection) -> Entry {
pub fn build_atom_feed(
entries: Vec<Post>,
uri: &str,
title: &str,
default_updated: &NaiveDateTime,
conn: &Connection,
) -> Feed {
let updated = if entries.is_empty() {
default_updated
} else {
&entries[0].creation_date
};
FeedBuilder::default()
.title(title)
.id(uri)
.updated(updated.format("%Y-%m-%dT%H:%M:%SZ").to_string())
.entries(
entries
.into_iter()
.map(|p| post_to_atom(p, conn))
.collect::<Vec<Entry>>(),
)
.links(vec![LinkBuilder::default()
.href(uri)
.rel("self")
.mime_type("application/atom+xml".to_string())
.build()
.expect("Atom feed: link error")])
.build()
.expect("user::atom_feed: Error building Atom feed")
}
fn post_to_atom(post: Post, conn: &Connection) -> Entry {
let formatted_creation_date = post.creation_date.format("%Y-%m-%dT%H:%M:%SZ").to_string();
EntryBuilder::default()
.title(format!("<![CDATA[{}]]>", post.title))
.content(
ContentBuilder::default()
.value(format!("<![CDATA[{}]]>", *post.content.get()))
.src(post.ap_url.clone())
.content_type("html".to_string())
.build()
.expect("Atom feed: content error"),
@@ -141,8 +177,9 @@ pub fn post_to_atom(post: Post, conn: &Connection) -> Entry {
)
// Using RFC 4287 format, see https://tools.ietf.org/html/rfc4287#section-3.3 for dates
// eg: 2003-12-13T18:30:02Z (Z is here because there is no timezone support with the NaiveDateTime crate)
.published(post.creation_date.format("%Y-%m-%dT%H:%M:%SZ").to_string())
.id(post.id.to_string())
.published(formatted_creation_date.clone())
.updated(formatted_creation_date)
.id(post.ap_url.clone())
.links(vec![LinkBuilder::default()
.href(post.ap_url)
.build()
@@ -171,14 +208,15 @@ pub mod well_known;
#[response()]
pub struct CachedFile {
inner: NamedFile,
cache_control: CacheControl,
cache_control: Header<'static>,
}
#[derive(Debug)]
pub struct ThemeFile(NamedFile);
#[rocket::async_trait]
impl<'r> Responder<'r> for ThemeFile {
fn respond_to(self, r: &Request<'_>) -> response::Result<'r> {
async fn respond_to(self, r: &'r Request<'_>) -> response::Result<'r> {
let contents = std::fs::read(self.0.path()).map_err(|_| Status::InternalServerError)?;
let mut hasher = DefaultHasher::new();
@@ -191,12 +229,12 @@ impl<'r> Responder<'r> for ThemeFile {
{
Response::build()
.status(Status::NotModified)
.header(ETag(EntityTag::strong(etag)))
.header(Header::new("ETag", etag))
.ok()
} else {
Response::build()
.merge(self.0.respond_to(r)?)
.header(ETag(EntityTag::strong(etag)))
.merge(self.0.respond_to(r).await.ok().unwrap())
.header(Header::new("ETag", etag))
.ok()
}
}
@@ -219,7 +257,7 @@ pub fn plume_media_files(file: PathBuf) -> Option<CachedFile> {
.ok()
.map(|f| CachedFile {
inner: f,
cache_control: CacheControl(vec![CacheDirective::MaxAge(60 * 60 * 24 * 30)]),
cache_control: Header::new("Cache-Control", format!("max-age={}", 60 * 60 * 24 * 30)),
})
}
#[get("/static/<file..>", rank = 3)]
@@ -228,6 +266,6 @@ pub fn static_files(file: PathBuf) -> Option<CachedFile> {
.ok()
.map(|f| CachedFile {
inner: f,
cache_control: CacheControl(vec![CacheDirective::MaxAge(60 * 60 * 24 * 30)]),
cache_control: Header::new("Cache-Control", format!("max-age={}", 60 * 60 * 24 * 30)),
})
}
+40 -28
View File
@@ -1,3 +1,4 @@
use activitypub::link;
use chrono::Utc;
use heck::{CamelCase, KebabCase};
use rocket::request::LenientForm;
@@ -11,7 +12,7 @@ use std::{
use validator::{Validate, ValidationError, ValidationErrors};
use crate::routes::{
comments::NewCommentForm, errors::ErrorPage, ContentLen, RemoteForm, RespondOrRedirect,
comments::NewCommentForm, errors::ErrorPage, ContentLen, Page, RemoteForm, RespondOrRedirect,
};
use crate::template_utils::{IntoContext, Ructe};
use plume_common::activity_pub::{broadcast, ActivityStream, ApRequest};
@@ -33,7 +34,7 @@ use plume_models::{
};
#[get("/~/<blog>/<slug>?<responding_to>", rank = 4)]
pub fn details(
pub async fn details(
blog: String,
slug: String,
responding_to: Option<i32>,
@@ -41,7 +42,7 @@ pub fn details(
) -> Result<Ructe, ErrorPage> {
let conn = &*rockets.conn;
let user = rockets.user.clone();
let blog = Blog::find_by_fqn(&rockets, &blog)?;
let blog = Blog::find_by_fqn(&rockets, &blog).await?;
let post = Post::find_by_slug(&*conn, &slug, blog.id)?;
if !(post.published
|| post
@@ -99,14 +100,14 @@ pub fn details(
}
#[get("/~/<blog>/<slug>", rank = 3)]
pub fn activity_details(
pub async fn activity_details(
blog: String,
slug: String,
_ap: ApRequest,
rockets: PlumeRocket,
) -> Result<ActivityStream<LicensedArticle>, Option<String>> {
let conn = &*rockets.conn;
let blog = Blog::find_by_fqn(&rockets, &blog).map_err(|_| None)?;
let blog = Blog::find_by_fqn(&rockets, &blog).await.map_err(|_| None)?;
let post = Post::find_by_slug(&*conn, &slug, blog.id).map_err(|_| None)?;
if post.published {
Ok(ActivityStream::new(
@@ -130,9 +131,9 @@ pub fn new_auth(blog: String, i18n: I18n) -> Flash<Redirect> {
}
#[get("/~/<blog>/new", rank = 1)]
pub fn new(blog: String, cl: ContentLen, rockets: PlumeRocket) -> Result<Ructe, ErrorPage> {
pub async fn new(blog: String, cl: ContentLen, rockets: PlumeRocket) -> Result<Ructe, ErrorPage> {
let conn = &*rockets.conn;
let b = Blog::find_by_fqn(&rockets, &blog)?;
let b = Blog::find_by_fqn(&rockets, &blog).await?;
let user = rockets.user.clone().unwrap();
if !user.is_author_in(&*conn, &b)? {
@@ -162,7 +163,7 @@ pub fn new(blog: String, cl: ContentLen, rockets: PlumeRocket) -> Result<Ructe,
}
#[get("/~/<blog>/<slug>/edit")]
pub fn edit(
pub async fn edit(
blog: String,
slug: String,
cl: ContentLen,
@@ -170,7 +171,7 @@ pub fn edit(
) -> Result<Ructe, ErrorPage> {
let conn = &*rockets.conn;
let intl = &rockets.intl.catalog;
let b = Blog::find_by_fqn(&rockets, &blog)?;
let b = Blog::find_by_fqn(&rockets, &blog).await?;
let post = Post::find_by_slug(&*conn, &slug, b.id)?;
let user = rockets.user.clone().unwrap();
@@ -216,7 +217,7 @@ pub fn edit(
}
#[post("/~/<blog>/<slug>/edit", data = "<form>")]
pub fn update(
pub async fn update(
blog: String,
slug: String,
cl: ContentLen,
@@ -224,7 +225,9 @@ pub fn update(
rockets: PlumeRocket,
) -> RespondOrRedirect {
let conn = &*rockets.conn;
let b = Blog::find_by_fqn(&rockets, &blog).expect("post::update: blog error");
let b = Blog::find_by_fqn(&rockets, &blog)
.await
.expect("post::update: blog error");
let mut post =
Post::find_by_slug(&*conn, &slug, b.id).expect("post::update: find by slug error");
let user = rockets.user.clone().unwrap();
@@ -301,14 +304,16 @@ pub fn update(
.expect("post::update: update error");
if post.published {
post.update_mentions(
&conn,
mentions
.into_iter()
.filter_map(|m| Mention::build_activity(&rockets, &m).ok())
.collect(),
)
.expect("post::update: mentions error");
// NOTE: here we unroll a filter_map(), so we can use .await painlessly
let mut filtered_mentions: Vec<link::Mention> = vec![];
for m in mentions.into_iter() {
match Mention::build_activity(&rockets, &m).await {
Ok(m) => filtered_mentions.push(m),
Err(_) => {}
}
}
post.update_mentions(&conn, filtered_mentions)
.expect("post::update: mentions error");
}
let tags = form
@@ -321,7 +326,7 @@ pub fn update(
.filter_map(|t| Tag::build_activity(t).ok())
.collect::<Vec<_>>();
post.update_tags(&conn, tags)
.expect("post::update: tags error");
.expect(r#"post::update: tags error"#);
let hashtags = hashtags
.into_iter()
@@ -399,14 +404,16 @@ pub fn valid_slug(title: &str) -> Result<(), ValidationError> {
}
#[post("/~/<blog_name>/new", data = "<form>")]
pub fn create(
pub async fn create(
blog_name: String,
form: LenientForm<NewPostForm>,
cl: ContentLen,
rockets: PlumeRocket,
) -> Result<RespondOrRedirect, ErrorPage> {
let conn = &*rockets.conn;
let blog = Blog::find_by_fqn(&rockets, &blog_name).expect("post::create: blog error");
let blog = Blog::find_by_fqn(&rockets, &blog_name)
.await
.expect("post::create: blog error");
let slug = form.title.to_string().to_kebab_case();
let user = rockets.user.clone().unwrap();
@@ -520,6 +527,7 @@ pub fn create(
Mention::from_activity(
&*conn,
&Mention::build_activity(&rockets, &m)
.await
.expect("post::create: mention build error"),
post.id,
true,
@@ -562,7 +570,7 @@ pub fn create(
}
#[post("/~/<blog_name>/<slug>/delete")]
pub fn delete(
pub async fn delete(
blog_name: String,
slug: String,
rockets: PlumeRocket,
@@ -570,6 +578,7 @@ pub fn delete(
) -> Result<Flash<Redirect>, ErrorPage> {
let user = rockets.user.clone().unwrap();
let post = Blog::find_by_fqn(&rockets, &blog_name)
.await
.and_then(|blog| Post::find_by_slug(&*rockets.conn, &slug, blog.id));
if let Ok(post) = post {
@@ -615,12 +624,13 @@ pub fn delete(
}
#[get("/~/<blog_name>/<slug>/remote_interact")]
pub fn remote_interact(
pub async fn remote_interact(
rockets: PlumeRocket,
blog_name: String,
slug: String,
) -> Result<Ructe, ErrorPage> {
let target = Blog::find_by_fqn(&rockets, &blog_name)
.await
.and_then(|blog| Post::find_by_slug(&rockets.conn, &slug, blog.id))?;
Ok(render!(posts::remote_interact(
&rockets.to_context(),
@@ -633,17 +643,19 @@ pub fn remote_interact(
}
#[post("/~/<blog_name>/<slug>/remote_interact", data = "<remote>")]
pub fn remote_interact_post(
pub async fn remote_interact_post(
rockets: PlumeRocket,
blog_name: String,
slug: String,
remote: LenientForm<RemoteForm>,
) -> Result<RespondOrRedirect, ErrorPage> {
let target = Blog::find_by_fqn(&rockets, &blog_name)
.await
.and_then(|blog| Post::find_by_slug(&rockets.conn, &slug, blog.id))?;
if let Some(uri) = User::fetch_remote_interact_uri(&remote.remote)
.ok()
.and_then(|uri| rt_format!(uri, uri = target.ap_url).ok())
if let uri = User::fetch_remote_interact_uri(&remote.remote)
.await
.map(|uri| uri.replace("{uri}", &format!("{}", target.ap_url)))
.unwrap()
{
Ok(Redirect::to(uri).into())
} else {
+2 -2
View File
@@ -10,14 +10,14 @@ use plume_models::{
};
#[post("/~/<blog>/<slug>/reshare")]
pub fn create(
pub async fn create(
blog: String,
slug: String,
user: User,
rockets: PlumeRocket,
) -> Result<Redirect, ErrorPage> {
let conn = &*rockets.conn;
let b = Blog::find_by_fqn(&rockets, &blog)?;
let b = Blog::find_by_fqn(&rockets, &blog).await?;
let post = Post::find_by_slug(&*conn, &slug, b.id)?;
if !user.has_reshared(&*conn, &post)? {
+11 -9
View File
@@ -3,7 +3,7 @@ use lettre::Transport;
use rocket::http::ext::IntoOwned;
use rocket::{
http::{uri::Uri, Cookie, Cookies, SameSite},
request::{Form, LenientForm},
request::LenientForm,
response::{Flash, Redirect},
State,
};
@@ -35,21 +35,23 @@ pub fn new(m: Option<String>, rockets: PlumeRocket) -> Ructe {
#[derive(Default, FromForm, Validate)]
pub struct LoginForm {
#[validate(length(min = "1", message = "We need an email, or a username to identify you"))]
#[validate(length(min = 1, message = "We need an email, or a username to identify you"))]
pub email_or_name: String,
#[validate(length(min = "1", message = "Your password can't be empty"))]
#[validate(length(min = 1, message = "Your password can't be empty"))]
pub password: String,
}
#[post("/login", data = "<form>")]
pub fn create(
pub async fn create(
form: LenientForm<LoginForm>,
mut cookies: Cookies<'_>,
rockets: PlumeRocket,
) -> RespondOrRedirect {
let conn = &*rockets.conn;
let user = User::find_by_email(&*conn, &form.email_or_name)
.or_else(|_| User::find_by_fqn(&rockets, &form.email_or_name));
let user = match User::find_by_email(&*conn, &form.email_or_name) {
Ok(user) => Ok(user),
Err(_) => User::find_by_fqn(&rockets, &form.email_or_name).await,
};
let mut errors = match form.validate() {
Ok(_) => ValidationErrors::new(),
Err(e) => e,
@@ -159,7 +161,7 @@ pub struct ResetForm {
#[post("/password-reset", data = "<form>")]
pub fn password_reset_request(
mail: State<'_, Arc<Mutex<Mailer>>>,
form: Form<ResetForm>,
form: LenientForm<ResetForm>,
rockets: PlumeRocket,
) -> Ructe {
if User::find_by_email(&*rockets.conn, &form.email).is_ok() {
@@ -197,7 +199,7 @@ pub fn password_reset_form(token: String, rockets: PlumeRocket) -> Result<Ructe,
#[derive(FromForm, Default, Validate)]
#[validate(schema(
function = "passwords_match",
skip_on_field_errors = "false",
skip_on_field_errors = false,
message = "Passwords are not matching"
))]
pub struct NewPasswordForm {
@@ -216,7 +218,7 @@ fn passwords_match(form: &NewPasswordForm) -> Result<(), ValidationError> {
#[post("/password-reset/<token>", data = "<form>")]
pub fn password_reset(
token: String,
form: Form<NewPasswordForm>,
form: LenientForm<NewPasswordForm>,
rockets: PlumeRocket,
) -> Result<Flash<Redirect>, Ructe> {
form.validate()
+79 -73
View File
@@ -2,7 +2,6 @@ use activitypub::{
activity::Create,
collection::{OrderedCollection, OrderedCollectionPage},
};
use atom_syndication::{Entry, FeedBuilder};
use diesel::SaveChangesDsl;
use rocket::{
http::{ContentType, Cookies},
@@ -10,7 +9,6 @@ use rocket::{
response::{status, Content, Flash, Redirect},
};
use rocket_i18n::I18n;
use serde_json;
use std::{borrow::Cow, collections::HashMap};
use validator::{Validate, ValidationError, ValidationErrors};
@@ -43,7 +41,7 @@ pub fn me(user: Option<User>) -> RespondOrRedirect {
}
#[get("/@/<name>", rank = 2)]
pub fn details(
pub async fn details(
name: String,
rockets: PlumeRocket,
fetch_rockets: PlumeRocket,
@@ -51,7 +49,7 @@ pub fn details(
update_conn: DbConn,
) -> Result<Ructe, ErrorPage> {
let conn = &*rockets.conn;
let user = User::find_by_fqn(&rockets, &name)?;
let user = User::find_by_fqn(&rockets, &name).await?;
let recents = Post::get_recents_for_author(&*conn, &user, 6)?;
let reshares = Reshare::get_recents_for_author(&*conn, &user, 6)?;
let worker = &rockets.worker;
@@ -62,6 +60,7 @@ pub fn details(
worker.execute(move || {
for create_act in user_clone
.fetch_outbox::<Create>()
.await
.expect("Remote user: outbox couldn't be fetched")
{
match create_act.create_props.object_object::<LicensedArticle>() {
@@ -80,6 +79,7 @@ pub fn details(
worker.execute(move || {
for user_id in user_clone
.fetch_followers_ids()
.await
.expect("Remote user: fetching followers error")
{
let follower = User::from_id(&fetch_followers_rockets, &user_id, None)
@@ -102,6 +102,7 @@ pub fn details(
worker.execute(move || {
user_clone
.refetch(&*update_conn)
.await
.expect("Couldn't update user info");
});
}
@@ -147,13 +148,13 @@ pub fn dashboard_auth(i18n: I18n) -> Flash<Redirect> {
}
#[post("/@/<name>/follow")]
pub fn follow(
pub async fn follow(
name: String,
user: User,
rockets: PlumeRocket,
) -> Result<Flash<Redirect>, ErrorPage> {
let conn = &*rockets.conn;
let target = User::find_by_fqn(&rockets, &name)?;
let target = User::find_by_fqn(&rockets, &name).await?;
let message = if let Ok(follow) = follows::Follow::find(&*conn, user.id, target.id) {
let delete_act = follow.build_undo(&*conn)?;
local_inbox(
@@ -191,26 +192,26 @@ pub fn follow(
}
#[post("/@/<name>/follow", data = "<remote_form>", rank = 2)]
pub fn follow_not_connected(
pub async fn follow_not_connected(
rockets: PlumeRocket,
name: String,
remote_form: Option<LenientForm<RemoteForm>>,
i18n: I18n,
) -> Result<RespondOrRedirect, ErrorPage> {
let target = User::find_by_fqn(&rockets, &name)?;
let target = User::find_by_fqn(&rockets, &name).await?;
if let Some(remote_form) = remote_form {
if let Some(uri) = User::fetch_remote_interact_uri(&remote_form)
.await
.ok()
.and_then(|uri| {
rt_format!(
uri,
uri = format!(
Some(uri.replace(
"{uri}",
&format!(
"{}@{}",
target.fqn,
target.get_instance(&rockets.conn).ok()?.public_domain
)
)
.ok()
),
))
})
{
Ok(Redirect::to(uri).into())
@@ -267,15 +268,18 @@ pub fn follow_auth(name: String, i18n: I18n) -> Flash<Redirect> {
}
#[get("/@/<name>/followers?<page>", rank = 2)]
pub fn followers(
pub async fn followers(
name: String,
page: Option<Page>,
rockets: PlumeRocket,
) -> Result<Ructe, ErrorPage> {
let conn = &*rockets.conn;
let page = page.unwrap_or_default();
let user = User::find_by_fqn(&rockets, &name)?;
let followers_count = user.count_followers(&*conn)?;
let user: User = User::find_by_fqn(&rockets, &name).await?;
let followers_count = match user.count_followers(&conn) {
Ok(num) => num,
Err(_) => 0,
};
Ok(render!(users::followers(
&rockets.to_context(),
@@ -294,14 +298,14 @@ pub fn followers(
}
#[get("/@/<name>/followed?<page>", rank = 2)]
pub fn followed(
pub async fn followed(
name: String,
page: Option<Page>,
rockets: PlumeRocket,
) -> Result<Ructe, ErrorPage> {
let conn = &*rockets.conn;
let page = page.unwrap_or_default();
let user = User::find_by_fqn(&rockets, &name)?;
let user = User::find_by_fqn(&rockets, &name).await?;
let followed_count = user.count_followed(conn)?;
Ok(render!(users::followed(
@@ -321,12 +325,12 @@ pub fn followed(
}
#[get("/@/<name>", rank = 1)]
pub fn activity_details(
pub async fn activity_details(
name: String,
rockets: PlumeRocket,
_ap: ApRequest,
) -> Option<ActivityStream<CustomPerson>> {
let user = User::find_by_fqn(&rockets, &name).ok()?;
let user: User = User::find_by_fqn(&rockets, &name).await?;
Some(ActivityStream::new(user.to_activity(&*rockets.conn).ok()?))
}
@@ -399,7 +403,10 @@ pub fn update(
)
.0,
);
user.preferred_theme = form.theme.clone();
user.preferred_theme = form
.theme
.clone()
.and_then(|t| if &t == "" { None } else { Some(t) });
user.hide_custom_css = form.hide_custom_css;
let _: User = user.save_changes(&*conn).map_err(Error::from)?;
@@ -410,50 +417,49 @@ pub fn update(
}
#[post("/@/<name>/delete")]
pub fn delete(
pub async fn delete(
name: String,
user: User,
mut cookies: Cookies<'_>,
rockets: PlumeRocket,
) -> Result<Flash<Redirect>, ErrorPage> {
let account = User::find_by_fqn(&rockets, &name)?;
if user.id == account.id {
account.delete(&*rockets.conn, &rockets.searcher)?;
let target = User::one_by_instance(&*rockets.conn)?;
let delete_act = account.delete_activity(&*rockets.conn)?;
rockets
.worker
.execute(move || broadcast(&account, delete_act, target));
if let Some(cookie) = cookies.get_private(AUTH_COOKIE) {
cookies.remove_private(cookie);
}
Ok(Flash::success(
Redirect::to(uri!(super::instance::index)),
i18n!(rockets.intl.catalog, "Your account has been deleted."),
))
} else {
Ok(Flash::error(
let account = User::find_by_fqn(&rockets, &name).await?;
if user.id != account.id {
return Ok(Flash::error(
Redirect::to(uri!(edit: name = name)),
i18n!(
rockets.intl.catalog,
"You can't delete someone else's account."
),
))
));
}
account.delete(&*rockets.conn, &rockets.searcher)?;
let target = User::one_by_instance(&*rockets.conn)?;
let delete_act = account.delete_activity(&*rockets.conn)?;
rockets
.worker
.execute(move || broadcast(&account, delete_act, target));
if let Some(cookie) = cookies.get_private(AUTH_COOKIE) {
cookies.remove_private(cookie);
}
Ok(Flash::success(
Redirect::to(uri!(super::instance::index)),
i18n!(rockets.intl.catalog, "Your account has been deleted."),
))
}
#[derive(Default, FromForm, Validate)]
#[validate(schema(
function = "passwords_match",
skip_on_field_errors = "false",
skip_on_field_errors = false,
message = "Passwords are not matching"
))]
pub struct NewUserForm {
#[validate(
length(min = "1", message = "Username can't be empty"),
length(min = 1, message = "Username can't be empty"),
custom(
function = "validate_username",
message = "User name is not allowed to contain any of < > & @ ' or \""
@@ -462,9 +468,9 @@ pub struct NewUserForm {
pub username: String,
#[validate(email(message = "Invalid email"))]
pub email: String,
#[validate(length(min = "8", message = "Password should be at least 8 characters long"))]
#[validate(length(min = 8, message = "Password should be at least 8 characters long"))]
pub password: String,
#[validate(length(min = "8", message = "Password should be at least 8 characters long"))]
#[validate(length(min = 8, message = "Password should be at least 8 characters long"))]
pub password_confirmation: String,
}
@@ -563,37 +569,44 @@ pub fn create(
}
#[get("/@/<name>/outbox")]
pub fn outbox(name: String, rockets: PlumeRocket) -> Option<ActivityStream<OrderedCollection>> {
let user = User::find_by_fqn(&rockets, &name).ok()?;
pub async fn outbox(
name: String,
rockets: PlumeRocket,
) -> Option<ActivityStream<OrderedCollection>> {
let user = User::find_by_fqn(&rockets, &name).await.ok()?;
user.outbox(&*rockets.conn).ok()
}
#[get("/@/<name>/outbox?<page>")]
pub fn outbox_page(
pub async fn outbox_page(
name: String,
page: Page,
rockets: PlumeRocket,
) -> Option<ActivityStream<OrderedCollectionPage>> {
let user = User::find_by_fqn(&rockets, &name).ok()?;
let user = User::find_by_fqn(&rockets, &name).await.ok()?;
user.outbox_page(&*rockets.conn, page.limits()).ok()
}
#[post("/@/<name>/inbox", data = "<data>")]
pub fn inbox(
pub async fn inbox(
name: String,
data: inbox::SignedJson<serde_json::Value>,
headers: Headers<'_>,
rockets: PlumeRocket,
) -> Result<String, status::BadRequest<&'static str>> {
User::find_by_fqn(&rockets, &name).map_err(|_| status::BadRequest(Some("User not found")))?;
inbox::handle_incoming(rockets, data, headers)
User::find_by_fqn(&rockets, &name)
.await
.map_err(|_| status::BadRequest(Some("User not found")))?;
inbox::handle_incoming(rockets, data, headers).await
}
#[get("/@/<name>/followers", rank = 1)]
pub fn ap_followers(
pub async fn ap_followers(
name: String,
rockets: PlumeRocket,
_ap: ApRequest,
) -> Option<ActivityStream<OrderedCollection>> {
let user = User::find_by_fqn(&rockets, &name).ok()?;
let user = User::find_by_fqn(&rockets, &name).await?;
let followers = user
.get_followers(&*rockets.conn)
.ok()?
@@ -613,23 +626,16 @@ pub fn ap_followers(
}
#[get("/@/<name>/atom.xml")]
pub fn atom_feed(name: String, rockets: PlumeRocket) -> Option<Content<String>> {
pub async fn atom_feed(name: String, rockets: PlumeRocket) -> Option<Content<String>> {
let conn = &*rockets.conn;
let author = User::find_by_fqn(&rockets, &name).ok()?;
let feed = FeedBuilder::default()
.title(author.display_name.clone())
.id(Instance::get_local()
.unwrap()
.compute_box("@", &name, "atom.xml"))
.entries(
Post::get_recents_for_author(conn, &author, 15)
.ok()?
.into_iter()
.map(|p| super::post_to_atom(p, conn))
.collect::<Vec<Entry>>(),
)
.build()
.expect("user::atom_feed: Error building Atom feed");
let author = User::find_by_fqn(&rockets, &name).await?;
let entries = Post::get_recents_for_author(conn, &author, 15).ok()?;
let uri = Instance::get_local()
.ok()?
.compute_box("@", &name, "atom.xml");
let title = &author.display_name;
let default_updated = &author.creation_date;
let feed = super::build_atom_feed(entries, &uri, title, default_updated, conn);
Some(Content(
ContentType::new("application", "atom+xml"),
feed.to_string(),
+36 -6
View File
@@ -1,6 +1,5 @@
use rocket::http::ContentType;
use rocket::response::Content;
use serde_json;
use webfinger::*;
use plume_models::{ap_url, blogs::Blog, users::User, PlumeRocket, CONFIG};
@@ -43,27 +42,58 @@ pub fn host_meta() -> String {
struct WebfingerResolver;
impl Resolver<PlumeRocket> for WebfingerResolver {
fn instance_domain<'a>() -> &'a str {
#[async_trait::async_trait]
impl AsyncResolver for WebfingerResolver {
type Repo = PlumeRocket;
async fn instance_domain<'a>(&self) -> &'a str {
CONFIG.base_url.as_str()
}
fn find(prefix: Prefix, acct: String, ctx: PlumeRocket) -> Result<Webfinger, ResolverError> {
async fn find(
&self,
prefix: Prefix,
acct: String,
ctx: PlumeRocket,
) -> Result<Webfinger, ResolverError> {
match prefix {
Prefix::Acct => User::find_by_fqn(&ctx, &acct)
.await
.and_then(|usr| usr.webfinger(&*ctx.conn))
.or(Err(ResolverError::NotFound)),
Prefix::Group => Blog::find_by_fqn(&ctx, &acct)
.await
.and_then(|blog| blog.webfinger(&*ctx.conn))
.or(Err(ResolverError::NotFound)),
Prefix::Custom(_) => Err(ResolverError::NotFound),
}
}
async fn endpoint<R: Into<String> + Send>(
&self,
resource: R,
resource_repo: PlumeRocket,
) -> Result<Webfinger, ResolverError> {
let resource = resource.into();
let mut parsed_query = resource.splitn(2, ':');
let res_prefix = Prefix::from(parsed_query.next().ok_or(ResolverError::InvalidResource)?);
let res = parsed_query.next().ok_or(ResolverError::InvalidResource)?;
let mut parsed_res = res.splitn(2, '@');
let user = parsed_res.next().ok_or(ResolverError::InvalidResource)?;
let domain = parsed_res.next().ok_or(ResolverError::InvalidResource)?;
if domain == self.instance_domain().await {
self.find(res_prefix, user.to_string(), resource_repo).await
} else {
Err(ResolverError::WrongDomain)
}
}
}
#[get("/.well-known/webfinger?<resource>")]
pub fn webfinger(resource: String, rockets: PlumeRocket) -> Content<String> {
match WebfingerResolver::endpoint(resource, rockets)
pub async fn webfinger(resource: String, rockets: PlumeRocket) -> Content<String> {
let wf_resolver = WebfingerResolver;
match wf_resolver
.endpoint(resource, rockets)
.await
.and_then(|wf| serde_json::to_string(&wf).map_err(|_| ResolverError::NotFound))
{
Ok(wf) => Content(ContentType::new("application", "jrd+json"), wf),
+7 -7
View File
@@ -1,8 +1,7 @@
use plume_models::{notifications::*, users::User, Connection, PlumeRocket};
use crate::templates::Html;
use rocket::http::hyper::header::{ETag, EntityTag};
use rocket::http::{Method, Status};
use rocket::http::{Header, Method, Status};
use rocket::request::Request;
use rocket::response::{self, content::Html as HtmlCt, Responder, Response};
use rocket_i18n::Catalog;
@@ -52,11 +51,12 @@ impl IntoContext for PlumeRocket {
#[derive(Debug)]
pub struct Ructe(pub Vec<u8>);
#[rocket::async_trait]
impl<'r> Responder<'r> for Ructe {
fn respond_to(self, r: &Request<'_>) -> response::Result<'r> {
async fn respond_to(self, r: &'r Request<'_>) -> response::Result<'r> {
//if method is not Get or page contain a form, no caching
if r.method() != Method::Get || self.0.windows(6).any(|w| w == b"<form ") {
return HtmlCt(self.0).respond_to(r);
return HtmlCt(self.0).respond_to(r).await;
}
let mut hasher = DefaultHasher::new();
hasher.write(&self.0);
@@ -67,12 +67,12 @@ impl<'r> Responder<'r> for Ructe {
{
Response::build()
.status(Status::NotModified)
.header(ETag(EntityTag::strong(etag)))
.header(Header::new("ETag", etag))
.ok()
} else {
Response::build()
.merge(HtmlCt(self.0).respond_to(r)?)
.header(ETag(EntityTag::strong(etag)))
.merge(HtmlCt(self.0).respond_to(r).await.ok().unwrap())
.header(Header::new("ETag", etag))
.ok()
}
}
+4
View File
@@ -1,8 +1,12 @@
@use plume_models::CONFIG;
@use plume_models::instance::Instance;
@use rocket::http::RawStr;
@use rocket::request::Form;
@use std::path::Path;
@use std::path::PathBuf;
@use crate::template_utils::*;
@use crate::routes::*;
@use crate::routes::search::SearchQuery;
@(ctx: BaseContext, title: String, head: Content, header: Content, content: Content)
+2
View File
@@ -2,7 +2,9 @@
@use plume_models::instance::Instance;
@use plume_models::posts::Post;
@use plume_models::users::User;
@use rocket::http::RawStr;
@use std::path::Path;
@use std::path::PathBuf;
@use crate::templates::{base, partials::post_card};
@use crate::template_utils::*;
@use crate::routes::*;
+2
View File
@@ -5,10 +5,12 @@
@use crate::template_utils::*;
@use crate::templates::base;
@use crate::templates::partials::image_select;
@use crate::routes::Page;
@use crate::routes::blogs;
@use crate::routes::blogs::EditForm;
@use crate::routes::medias;
@(ctx: BaseContext, blog: &Blog, medias: Vec<Media>, form: &EditForm, errors: ValidationErrors)
@:base(ctx, i18n!(ctx.1, "Edit \"{}\""; &blog.title), {}, {
+2 -2
View File
@@ -32,9 +32,9 @@
<form method="post" action="@uri!(instance::delete_email_blocklist)">
<header>
@if emails.is_empty() {
<input type="submit" class="destructive" value='@i18n!(ctx.1, "Delete selected emails")'>
} else {
<p class="center" >@i18n!(ctx.1, "There are no blocked emails on your instance")</p>
} else {
<input type="submit" class="destructive" value='@i18n!(ctx.1, "Delete selected emails")'>
}
</header>
<div class="list">
+23 -10
View File
@@ -17,17 +17,30 @@
<p class="p-summary" dir="auto">@article.subtitle</p>
</main>
<footer class="authors">
@Html(i18n!(ctx.1, "By {0}"; format!(
"<a class=\"p-author h-card\" href=\"{}\">{}</a>",
uri!(user::details: name = &article.get_authors(ctx.0).unwrap_or_default()[0].fqn),
escape(&article.get_authors(ctx.0).unwrap_or_default()[0].name())
)))
@if article.published {
<span class="dt-published" datetime="@article.creation_date.format("%F %T")">@article.creation_date.format("%B %e, %Y")</span>
}
<a href="@uri!(blogs::details: name = &article.get_blog(ctx.0).unwrap().fqn, page = _)">@article.get_blog(ctx.0).unwrap().title</a>
<div>
@Html(i18n!(ctx.1, "By {0}"; format!(
"<a class=\"p-author h-card\" href=\"{}\">{}</a>",
uri!(user::details: name = &article.get_authors(ctx.0).unwrap_or_default()[0].fqn),
escape(&article.get_authors(ctx.0).unwrap_or_default()[0].name())
)))
@if article.published {
<span class="dt-published" datetime="@article.creation_date.format("%F %T")">@article.creation_date.format("%B %e, %Y")</span>
}
<a href="@uri!(blogs::details: name = &article.get_blog(ctx.0).unwrap().fqn, page = _)">@article.get_blog(ctx.0).unwrap().title</a>
</div>
@if !article.published {
⋅ @i18n!(ctx.1, "Draft")
<div>⋅ @i18n!(ctx.1, "Draft")</div>
} else {
<div>
<span class="likes" aria-label="@i18n!(ctx.1, "One like", "{0} likes"; article.count_likes(ctx.0).unwrap_or_default())" title="@i18n!(ctx.1, "One like", "{0} likes"; article.count_likes(ctx.0).unwrap_or_default())">
@icon!("heart") @article.count_likes(ctx.0).unwrap_or_default()
</span>
<span class="reshares" aria-label="@i18n!(ctx.1, "One like", "{0} boost"; article.count_reshares(ctx.0).unwrap_or_default())" title="@i18n!(ctx.1, "One boost", "{0} boosts"; article.count_reshares(ctx.0).unwrap_or_default())">
@icon!("repeat") @article.count_reshares(ctx.0).unwrap_or_default()
</span>
</div>
}
</footer>
</div>
+5 -3
View File
@@ -3,7 +3,9 @@
@use plume_models::posts::Post;
@use plume_models::tags::Tag;
@use plume_models::users::User;
@use rocket::http::RawStr;
@use std::path::Path;
@use std::path::PathBuf;
@use validator::ValidationErrors;
@use crate::templates::{base, partials::comment};
@use crate::template_utils::*;
@@ -40,7 +42,7 @@
<div class="article-info" dir="auto">
<span class="author">
@Html(i18n!(ctx.1, "Written by {0}"; format!("<a href=\"{}\">{}</a>",
uri!(user::details: name = &author.fqn),
escape(&uri!(user::details: name = &author.fqn).to_string()),
escape(&author.name()))))
</span>
&mdash;
@@ -103,8 +105,8 @@
</section>
} else {
<p class="center">@Html(i18n!(ctx.1, "{0}Log in{1}, or {2}use your Fediverse account{3} to interact with this article";
format!("<a href='{}'>", uri!(session::new: m = _)), "</a>",
format!("<a href='{}'>", uri!(posts::remote_interact: blog_name = &blog.fqn, slug = &article.slug)), "</a>"
format!("<a href='{}'>", escape(&uri!(session::new: m = _).to_string())), "</a>",
format!("<a href='{}'>", escape(&uri!(posts::remote_interact: blog_name = &blog.fqn, slug = &article.slug).to_string())), "</a>"
))
</p>
<section class="actions">
+1
View File
@@ -25,6 +25,7 @@
.default(login_form.password)
.error(&login_errs)
.set_prop("minlength", 1)
.input_type("password")
.html(ctx.1))
<input type="submit" value="@i18n!(ctx.1, "Log in")" />
</form>