Merge remote-tracking branch 'LemmyNet/master'

pull/959/head
derek 2020-07-08 20:25:13 -04:00
commit e7b9ab1b3a
50 changed files with 941 additions and 438 deletions

2
ansible/VERSION vendored
View File

@ -1 +1 @@
v0.7.12 v0.7.13

View File

@ -1,6 +1,10 @@
#!/bin/bash #!/bin/bash
set -e set -e
# make sure there are no old containers or old data around
sudo docker-compose --file ../federation/docker-compose.yml --project-directory . down
sudo rm -rf volumes
pushd ../../server/ pushd ../../server/
cargo build cargo build
popd popd

View File

@ -110,3 +110,4 @@ services:
image: dogbin/iframely:latest image: dogbin/iframely:latest
volumes: volumes:
- ../iframely.config.local.js:/iframely/config.local.js:ro - ../iframely.config.local.js:/iframely/config.local.js:ro
restart: always

View File

@ -12,7 +12,7 @@ services:
restart: always restart: always
lemmy: lemmy:
image: dessalines/lemmy:v0.7.12 image: dessalines/lemmy:v0.7.13
ports: ports:
- "127.0.0.1:8536:8536" - "127.0.0.1:8536:8536"
restart: always restart: always

145
server/Cargo.lock generated vendored
View File

@ -63,7 +63,7 @@ dependencies = [
"futures-util", "futures-util",
"log", "log",
"once_cell", "once_cell",
"parking_lot", "parking_lot 0.10.2",
"pin-project", "pin-project",
"smallvec", "smallvec",
"tokio", "tokio",
@ -269,7 +269,7 @@ dependencies = [
"lazy_static", "lazy_static",
"log", "log",
"num_cpus", "num_cpus",
"parking_lot", "parking_lot 0.10.2",
"threadpool", "threadpool",
] ]
@ -397,6 +397,12 @@ dependencies = [
"gimli", "gimli",
] ]
[[package]]
name = "adler"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccc9a9dd069569f212bc4330af9f17c4afb5e8ce185e83dbb14f1349dda18b10"
[[package]] [[package]]
name = "adler32" name = "adler32"
version = "1.1.0" version = "1.1.0"
@ -506,7 +512,7 @@ dependencies = [
"addr2line", "addr2line",
"cfg-if", "cfg-if",
"libc", "libc",
"miniz_oxide", "miniz_oxide 0.3.7",
"object", "object",
"rustc-demangle", "rustc-demangle",
] ]
@ -680,9 +686,9 @@ dependencies = [
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.0.55" version = "1.0.57"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1be3409f94d7bdceeb5f5fac551039d9b3f00e25da7a74fc4d33400a0d96368" checksum = "0fde55d2a2bfaa4c9668bbc63f531fbdeee3ffe188f4662511ce2c22b3eedebe"
[[package]] [[package]]
name = "cfg-if" name = "cfg-if"
@ -692,9 +698,9 @@ checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
[[package]] [[package]]
name = "chrono" name = "chrono"
version = "0.4.11" version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80094f509cf8b5ae86a4966a39b3ff66cd7e2a3e594accec3743ff3fabeab5b2" checksum = "f0fee792e164f78f5fe0c296cc2eb3688a2ca2b70cdff33040922d298203f0c4"
dependencies = [ dependencies = [
"num-integer", "num-integer",
"num-traits 0.2.12", "num-traits 0.2.12",
@ -726,6 +732,15 @@ dependencies = [
"bitflags", "bitflags",
] ]
[[package]]
name = "cloudabi"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4344512281c643ae7638bbabc3af17a11307803ec8f0fcad9fae512a8bf36467"
dependencies = [
"bitflags",
]
[[package]] [[package]]
name = "comrak" name = "comrak"
version = "0.7.0" version = "0.7.0"
@ -1120,14 +1135,14 @@ dependencies = [
[[package]] [[package]]
name = "flate2" name = "flate2"
version = "1.0.14" version = "1.0.16"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2cfff41391129e0a856d6d822600b8d71179d46879e310417eb9c762eb178b42" checksum = "68c90b0fc46cf89d227cc78b40e494ff81287a92dd07631e5af0d06fe3cf885e"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"crc32fast", "crc32fast",
"libc", "libc",
"miniz_oxide", "miniz_oxide 0.4.0",
] ]
[[package]] [[package]]
@ -1470,6 +1485,12 @@ dependencies = [
"autocfg 1.0.0", "autocfg 1.0.0",
] ]
[[package]]
name = "instant"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69da7ce1490173c2bf4d26bc8be429aaeeaf4cce6c4b970b7949651fa17655fe"
[[package]] [[package]]
name = "iovec" name = "iovec"
version = "0.1.4" version = "0.1.4"
@ -1508,18 +1529,18 @@ checksum = "dc6f3ad7b9d11a0c00842ff8de1b60ee58661048eb8049ed33c73594f359d7e6"
[[package]] [[package]]
name = "js-sys" name = "js-sys"
version = "0.3.40" version = "0.3.41"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce10c23ad2ea25ceca0093bd3192229da4c5b3c0f2de499c1ecac0d98d452177" checksum = "c4b9172132a62451e56142bff9afc91c8e4a4500aa5b847da36815b63bfda916"
dependencies = [ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]] [[package]]
name = "jsonwebtoken" name = "jsonwebtoken"
version = "7.1.2" version = "7.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1f325ae57ddcf609f02d891486ce740f5bbd0cc3e93f9bffaacdf6594b21404" checksum = "afabcc15e437a6484fc4f12d0fd63068fe457bf93f1c148d3d9649c60b103f32"
dependencies = [ dependencies = [
"base64 0.12.3", "base64 0.12.3",
"pem", "pem",
@ -1676,6 +1697,15 @@ dependencies = [
"scopeguard", "scopeguard",
] ]
[[package]]
name = "lock_api"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de302ce1fe7482db13738fbaf2e21cfb06a986b89c0bf38d88abf16681aada4e"
dependencies = [
"scopeguard",
]
[[package]] [[package]]
name = "log" name = "log"
version = "0.4.8" version = "0.4.8"
@ -1781,6 +1811,15 @@ dependencies = [
"adler32", "adler32",
] ]
[[package]]
name = "miniz_oxide"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be0f75932c1f6cfae3c04000e40114adf955636e19040f9c0a2c380702aa1c7f"
dependencies = [
"adler",
]
[[package]] [[package]]
name = "mio" name = "mio"
version = "0.6.22" version = "0.6.22"
@ -1985,8 +2024,19 @@ version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3a704eb390aafdc107b0e392f56a82b668e3a71366993b5340f5833fd62505e" checksum = "d3a704eb390aafdc107b0e392f56a82b668e3a71366993b5340f5833fd62505e"
dependencies = [ dependencies = [
"lock_api", "lock_api 0.3.4",
"parking_lot_core", "parking_lot_core 0.7.2",
]
[[package]]
name = "parking_lot"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4893845fa2ca272e647da5d0e46660a314ead9c2fdd9a883aabc32e481a8733"
dependencies = [
"instant",
"lock_api 0.4.0",
"parking_lot_core 0.8.0",
] ]
[[package]] [[package]]
@ -1996,7 +2046,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d58c7c768d4ba344e3e8d72518ac13e259d7c7ade24167003b8488e10b6740a3" checksum = "d58c7c768d4ba344e3e8d72518ac13e259d7c7ade24167003b8488e10b6740a3"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"cloudabi", "cloudabi 0.0.3",
"libc",
"redox_syscall",
"smallvec",
"winapi 0.3.9",
]
[[package]]
name = "parking_lot_core"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c361aa727dd08437f2f1447be8b59a33b0edd15e0fcee698f935613d9efbca9b"
dependencies = [
"cfg-if",
"cloudabi 0.1.0",
"instant",
"libc", "libc",
"redox_syscall", "redox_syscall",
"smallvec", "smallvec",
@ -2164,12 +2229,12 @@ dependencies = [
[[package]] [[package]]
name = "r2d2" name = "r2d2"
version = "0.8.8" version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1497e40855348e4a8a40767d8e55174bce1e445a3ac9254ad44ad468ee0485af" checksum = "545c5bc2b880973c9c10e4067418407a0ccaa3091781d1671d46eb35107cb26f"
dependencies = [ dependencies = [
"log", "log",
"parking_lot", "parking_lot 0.11.0",
"scheduled-thread-pool", "scheduled-thread-pool",
] ]
@ -2306,7 +2371,7 @@ version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b75f676a1e053fc562eafbb47838d67c84801e38fc1ba459e8f180deabd5071" checksum = "7b75f676a1e053fc562eafbb47838d67c84801e38fc1ba459e8f180deabd5071"
dependencies = [ dependencies = [
"cloudabi", "cloudabi 0.0.3",
"fuchsia-cprng", "fuchsia-cprng",
"libc", "libc",
"rand_core 0.4.2", "rand_core 0.4.2",
@ -2462,11 +2527,11 @@ dependencies = [
[[package]] [[package]]
name = "scheduled-thread-pool" name = "scheduled-thread-pool"
version = "0.2.4" version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0988d7fdf88d5e5fcf5923a0f1e8ab345f3e98ab4bc6bc45a2d5ff7f7458fbf6" checksum = "dc6f74fd1204073fa02d5d5d68bec8021be4c38690b61264b2fdb48083d0e7d7"
dependencies = [ dependencies = [
"parking_lot", "parking_lot 0.11.0",
] ]
[[package]] [[package]]
@ -2570,9 +2635,9 @@ dependencies = [
[[package]] [[package]]
name = "serde_json" name = "serde_json"
version = "1.0.55" version = "1.0.56"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec2c5d7e739bc07a3e73381a39d61fdb5f671c60c1df26a130690665803d8226" checksum = "3433e879a558dde8b5e8feb2a04899cf34fdde1fafb894687e52105fc1162ac3"
dependencies = [ dependencies = [
"indexmap", "indexmap",
"itoa", "itoa",
@ -3106,9 +3171,9 @@ checksum = "e83e153d1053cbb5a118eeff7fd5be06ed99153f00dbcd8ae310c5fb2b22edc0"
[[package]] [[package]]
name = "unicode-width" name = "unicode-width"
version = "0.1.7" version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caaa9d531767d1ff2150b9332433f32a24622147e5ebb1f26409d5da67afd479" checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3"
[[package]] [[package]]
name = "unicode-xid" name = "unicode-xid"
@ -3222,9 +3287,9 @@ checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519"
[[package]] [[package]]
name = "wasm-bindgen" name = "wasm-bindgen"
version = "0.2.63" version = "0.2.64"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c2dc4aa152834bc334f506c1a06b866416a8b6697d5c9f75b9a689c8486def0" checksum = "6a634620115e4a229108b71bde263bb4220c483b3f07f5ba514ee8d15064c4c2"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"wasm-bindgen-macro", "wasm-bindgen-macro",
@ -3232,9 +3297,9 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-backend" name = "wasm-bindgen-backend"
version = "0.2.63" version = "0.2.64"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ded84f06e0ed21499f6184df0e0cb3494727b0c5da89534e0fcc55c51d812101" checksum = "3e53963b583d18a5aa3aaae4b4c1cb535218246131ba22a71f05b518098571df"
dependencies = [ dependencies = [
"bumpalo", "bumpalo",
"lazy_static", "lazy_static",
@ -3247,9 +3312,9 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-macro" name = "wasm-bindgen-macro"
version = "0.2.63" version = "0.2.64"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "838e423688dac18d73e31edce74ddfac468e37b1506ad163ffaf0a46f703ffe3" checksum = "3fcfd5ef6eec85623b4c6e844293d4516470d8f19cd72d0d12246017eb9060b8"
dependencies = [ dependencies = [
"quote", "quote",
"wasm-bindgen-macro-support", "wasm-bindgen-macro-support",
@ -3257,9 +3322,9 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-macro-support" name = "wasm-bindgen-macro-support"
version = "0.2.63" version = "0.2.64"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3156052d8ec77142051a533cdd686cba889537b213f948cd1d20869926e68e92" checksum = "9adff9ee0e94b926ca81b57f57f86d5545cdcb1d259e21ec9bdd95b901754c75"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -3270,15 +3335,15 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-shared" name = "wasm-bindgen-shared"
version = "0.2.63" version = "0.2.64"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9ba19973a58daf4db6f352eda73dc0e289493cd29fb2632eb172085b6521acd" checksum = "7f7b90ea6c632dd06fd765d44542e234d5e63d9bb917ecd64d79778a13bd79ae"
[[package]] [[package]]
name = "web-sys" name = "web-sys"
version = "0.3.40" version = "0.3.41"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b72fe77fd39e4bd3eaa4412fd299a0be6b3dfe9d2597e2f1c20beb968f41d17" checksum = "863539788676619aac1a23e2df3655e96b32b0e05eb72ca34ba045ad573c625d"
dependencies = [ dependencies = [
"js-sys", "js-sys",
"wasm-bindgen", "wasm-bindgen",

View File

@ -123,7 +123,7 @@ impl FromApub for CommentForm {
/// Parse an ActivityPub note received from another instance into a Lemmy comment /// Parse an ActivityPub note received from another instance into a Lemmy comment
async fn from_apub( async fn from_apub(
note: &Note, note: &mut Note,
client: &Client, client: &Client,
pool: &DbPool, pool: &DbPool,
) -> Result<CommentForm, LemmyError> { ) -> Result<CommentForm, LemmyError> {

View File

@ -4,7 +4,7 @@ use crate::{
create_apub_response, create_apub_response,
create_apub_tombstone_response, create_apub_tombstone_response,
create_tombstone, create_tombstone,
extensions::{group_extensions::GroupExtension, signatures::PublicKey}, extensions::group_extensions::GroupExtension,
fetcher::get_or_fetch_and_upsert_remote_user, fetcher::get_or_fetch_and_upsert_remote_user,
get_shared_inbox, get_shared_inbox,
ActorType, ActorType,
@ -27,21 +27,25 @@ use crate::{
}; };
use activitystreams::{ use activitystreams::{
activity::{Accept, Announce, Delete, Remove, Undo}, activity::{Accept, Announce, Delete, Remove, Undo},
actor::{kind::GroupType, properties::ApActorProperties, Group},
collection::UnorderedCollection,
context,
endpoint::EndpointProperties,
object::properties::ObjectProperties,
Activity, Activity,
Base, Base,
BaseBox, BaseBox,
}; };
use activitystreams_ext::Ext3; use activitystreams_ext::Ext2;
use activitystreams_new::{activity::Follow, object::Tombstone}; use activitystreams_new::{
activity::Follow,
actor::{kind::GroupType, ApActor, Endpoints, Group},
base::BaseExt,
collection::UnorderedCollection,
context,
object::Tombstone,
prelude::*,
primitives::{XsdAnyUri, XsdDateTime},
};
use actix_web::{body::Body, client::Client, web, HttpResponse}; use actix_web::{body::Body, client::Client, web, HttpResponse};
use itertools::Itertools; use itertools::Itertools;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::fmt::Debug; use std::{fmt::Debug, str::FromStr};
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct CommunityQuery { pub struct CommunityQuery {
@ -54,9 +58,6 @@ impl ToApub for Community {
// Turn a Lemmy Community into an ActivityPub group that can be sent out over the network. // Turn a Lemmy Community into an ActivityPub group that can be sent out over the network.
async fn to_apub(&self, pool: &DbPool) -> Result<GroupExt, LemmyError> { async fn to_apub(&self, pool: &DbPool) -> Result<GroupExt, LemmyError> {
let mut group = Group::default();
let oprops: &mut ObjectProperties = group.as_mut();
// The attributed to, is an ordered vector with the creator actor_ids first, // The attributed to, is an ordered vector with the creator actor_ids first,
// then the rest of the moderators // then the rest of the moderators
// TODO Technically the instance admins can mod the community, but lets // TODO Technically the instance admins can mod the community, but lets
@ -66,36 +67,36 @@ impl ToApub for Community {
CommunityModeratorView::for_community(&conn, id) CommunityModeratorView::for_community(&conn, id)
}) })
.await??; .await??;
let moderators = moderators.into_iter().map(|m| m.user_actor_id).collect(); let moderators: Vec<String> = moderators.into_iter().map(|m| m.user_actor_id).collect();
oprops let mut group = Group::new();
.set_context_xsd_any_uri(context())? group
.set_id(self.actor_id.to_owned())? .set_context(context())
.set_name_xsd_string(self.name.to_owned())? .set_id(XsdAnyUri::from_str(&self.actor_id)?)
.set_published(convert_datetime(self.published))? .set_name(self.name.to_owned())
.set_many_attributed_to_xsd_any_uris(moderators)?; .set_published(XsdDateTime::from(convert_datetime(self.published)))
.set_many_attributed_tos(moderators);
if let Some(u) = self.updated.to_owned() { if let Some(u) = self.updated.to_owned() {
oprops.set_updated(convert_datetime(u))?; group.set_updated(XsdDateTime::from(convert_datetime(u)));
} }
if let Some(d) = self.description.to_owned() { if let Some(d) = self.description.to_owned() {
// TODO: this should be html, also add source field with raw markdown // TODO: this should be html, also add source field with raw markdown
// -> same for post.content and others // -> same for post.content and others
oprops.set_content_xsd_string(d)?; group.set_content(d);
} }
let mut endpoint_props = EndpointProperties::default(); let mut ap_actor = ApActor::new(self.get_inbox_url().parse()?, group);
ap_actor
endpoint_props.set_shared_inbox(self.get_shared_inbox_url())?; .set_preferred_username(self.title.to_owned())
.set_outbox(self.get_outbox_url().parse()?)
let mut actor_props = ApActorProperties::default(); .set_followers(self.get_followers_url().parse()?)
.set_following(self.get_following_url().parse()?)
actor_props .set_liked(self.get_liked_url().parse()?)
.set_preferred_username(self.title.to_owned())? .set_endpoints(Endpoints {
.set_inbox(self.get_inbox_url())? shared_inbox: Some(self.get_shared_inbox_url().parse()?),
.set_outbox(self.get_outbox_url())? ..Default::default()
.set_endpoints(endpoint_props)? });
.set_followers(self.get_followers_url())?;
let nsfw = self.nsfw; let nsfw = self.nsfw;
let category_id = self.category_id; let category_id = self.category_id;
@ -104,10 +105,9 @@ impl ToApub for Community {
}) })
.await??; .await??;
Ok(Ext3::new( Ok(Ext2::new(
group, ap_actor,
group_extension, group_extension,
actor_props,
self.get_public_key_ext(), self.get_public_key_ext(),
)) ))
} }
@ -367,38 +367,52 @@ impl FromApub for CommunityForm {
type ApubType = GroupExt; type ApubType = GroupExt;
/// Parse an ActivityPub group received from another instance into a Lemmy community. /// Parse an ActivityPub group received from another instance into a Lemmy community.
async fn from_apub(group: &GroupExt, client: &Client, pool: &DbPool) -> Result<Self, LemmyError> { async fn from_apub(
let group_extensions: &GroupExtension = &group.ext_one; group: &mut GroupExt,
let oprops = &group.inner.object_props; client: &Client,
let aprops = &group.ext_two; pool: &DbPool,
let public_key: &PublicKey = &group.ext_three.public_key; ) -> Result<Self, LemmyError> {
// TODO: this is probably gonna cause problems cause fetcher:292 also calls take_attributed_to()
let mut creator_and_moderator_uris = oprops.get_many_attributed_to_xsd_any_uris().unwrap(); let creator_and_moderator_uris = group.clone().take_attributed_to().unwrap();
let creator_uri = creator_and_moderator_uris.next().unwrap(); let creator_uri = creator_and_moderator_uris
.as_many()
.unwrap()
.iter()
.next()
.unwrap()
.as_xsd_any_uri()
.unwrap();
let creator = get_or_fetch_and_upsert_remote_user(creator_uri.as_str(), client, pool).await?; let creator = get_or_fetch_and_upsert_remote_user(creator_uri.as_str(), client, pool).await?;
Ok(CommunityForm { Ok(CommunityForm {
name: oprops.get_name_xsd_string().unwrap().to_string(), name: group
title: aprops.get_preferred_username().unwrap().to_string(), .take_name()
.unwrap()
.as_single_xsd_string()
.unwrap()
.into(),
title: group.inner.take_preferred_username().unwrap(),
// TODO: should be parsed as html and tags like <script> removed (or use markdown source) // TODO: should be parsed as html and tags like <script> removed (or use markdown source)
// -> same for post.content etc // -> same for post.content etc
description: oprops.get_content_xsd_string().map(|s| s.to_string()), description: group
category_id: group_extensions.category.identifier.parse::<i32>()?, .take_content()
.map(|s| s.as_single_xsd_string().unwrap().into()),
category_id: group.ext_one.category.identifier.parse::<i32>()?,
creator_id: creator.id, creator_id: creator.id,
removed: None, removed: None,
published: oprops published: group
.get_published() .take_published()
.map(|u| u.as_ref().to_owned().naive_local()), .map(|u| u.as_ref().to_owned().naive_local()),
updated: oprops updated: group
.get_updated() .take_updated()
.map(|u| u.as_ref().to_owned().naive_local()), .map(|u| u.as_ref().to_owned().naive_local()),
deleted: None, deleted: None,
nsfw: group_extensions.sensitive, nsfw: group.ext_one.sensitive,
actor_id: oprops.get_id().unwrap().to_string(), actor_id: group.id().unwrap().to_string(),
local: false, local: false,
private_key: None, private_key: None,
public_key: Some(public_key.to_owned().public_key_pem), public_key: Some(group.ext_two.to_owned().public_key.public_key_pem),
last_refreshed_at: Some(naive_now()), last_refreshed_at: Some(naive_now()),
}) })
} }
@ -439,14 +453,12 @@ pub async fn get_apub_community_followers(
}) })
.await??; .await??;
let mut collection = UnorderedCollection::default(); let mut collection = UnorderedCollection::new(vec![]);
let oprops: &mut ObjectProperties = collection.as_mut();
oprops
.set_context_xsd_any_uri(context())?
.set_id(community.actor_id)?;
collection collection
.collection_props .set_context(context())
.set_total_items(community_followers.len() as u64)?; // TODO: this needs its own ID
.set_id(community.actor_id.parse()?)
.set_total_items(community_followers.len() as u64);
Ok(create_apub_response(&collection)) Ok(create_apub_response(&collection))
} }

View File

@ -1,13 +1,14 @@
use activitystreams::object::Note;
use actix_web::client::Client;
use diesel::{result::Error::NotFound, PgConnection};
use log::debug;
use serde::Deserialize;
use std::{fmt::Debug, time::Duration};
use url::Url;
use crate::{ use crate::{
api::site::SearchResponse, api::site::SearchResponse,
apub::{
get_apub_protocol_string,
is_apub_id_valid,
FromApub,
GroupExt,
PageExt,
PersonExt,
APUB_JSON_CONTENT_TYPE,
},
blocking, blocking,
db::{ db::{
comment::{Comment, CommentForm}, comment::{Comment, CommentForm},
@ -17,6 +18,7 @@ use crate::{
post::{Post, PostForm}, post::{Post, PostForm},
post_view::PostView, post_view::PostView,
user::{UserForm, User_}, user::{UserForm, User_},
user_view::UserView,
Crud, Crud,
Joinable, Joinable,
SearchType, SearchType,
@ -27,20 +29,15 @@ use crate::{
DbPool, DbPool,
LemmyError, LemmyError,
}; };
use activitystreams::object::Note;
use crate::{ use activitystreams_new::{base::BaseExt, prelude::*, primitives::XsdAnyUri};
apub::{ use actix_web::client::Client;
get_apub_protocol_string,
is_apub_id_valid,
FromApub,
GroupExt,
PageExt,
PersonExt,
APUB_JSON_CONTENT_TYPE,
},
db::user_view::UserView,
};
use chrono::NaiveDateTime; use chrono::NaiveDateTime;
use diesel::{result::Error::NotFound, PgConnection};
use log::debug;
use serde::Deserialize;
use std::{fmt::Debug, time::Duration};
use url::Url;
static ACTOR_REFETCH_INTERVAL_SECONDS: i64 = 24 * 60 * 60; static ACTOR_REFETCH_INTERVAL_SECONDS: i64 = 24 * 60 * 60;
@ -149,7 +146,7 @@ pub async fn search_by_apub_id(
let response = match fetch_remote_object::<SearchAcceptedObjects>(client, &query_url).await? { let response = match fetch_remote_object::<SearchAcceptedObjects>(client, &query_url).await? {
SearchAcceptedObjects::Person(p) => { SearchAcceptedObjects::Person(p) => {
let user_uri = p.inner.object_props.get_id().unwrap().to_string(); let user_uri = p.inner.id().unwrap().to_string();
let user = get_or_fetch_and_upsert_remote_user(&user_uri, client, pool).await?; let user = get_or_fetch_and_upsert_remote_user(&user_uri, client, pool).await?;
@ -158,7 +155,7 @@ pub async fn search_by_apub_id(
response response
} }
SearchAcceptedObjects::Group(g) => { SearchAcceptedObjects::Group(g) => {
let community_uri = g.inner.object_props.get_id().unwrap().to_string(); let community_uri = g.inner.id().unwrap().to_string();
let community = let community =
get_or_fetch_and_upsert_remote_community(&community_uri, client, pool).await?; get_or_fetch_and_upsert_remote_community(&community_uri, client, pool).await?;
@ -174,15 +171,15 @@ pub async fn search_by_apub_id(
response response
} }
SearchAcceptedObjects::Page(p) => { SearchAcceptedObjects::Page(mut p) => {
let post_form = PostForm::from_apub(&p, client, pool).await?; let post_form = PostForm::from_apub(&mut p, client, pool).await?;
let p = blocking(pool, move |conn| upsert_post(&post_form, conn)).await??; let p = blocking(pool, move |conn| upsert_post(&post_form, conn)).await??;
response.posts = vec![blocking(pool, move |conn| PostView::read(conn, p.id, None)).await??]; response.posts = vec![blocking(pool, move |conn| PostView::read(conn, p.id, None)).await??];
response response
} }
SearchAcceptedObjects::Comment(c) => { SearchAcceptedObjects::Comment(mut c) => {
let post_url = c let post_url = c
.object_props .object_props
.get_many_in_reply_to_xsd_any_uris() .get_many_in_reply_to_xsd_any_uris()
@ -192,9 +189,9 @@ pub async fn search_by_apub_id(
.to_string(); .to_string();
// TODO: also fetch parent comments if any // TODO: also fetch parent comments if any
let post = fetch_remote_object(client, &Url::parse(&post_url)?).await?; let mut post = fetch_remote_object(client, &Url::parse(&post_url)?).await?;
let post_form = PostForm::from_apub(&post, client, pool).await?; let post_form = PostForm::from_apub(&mut post, client, pool).await?;
let comment_form = CommentForm::from_apub(&c, client, pool).await?; let comment_form = CommentForm::from_apub(&mut c, client, pool).await?;
blocking(pool, move |conn| upsert_post(&post_form, conn)).await??; blocking(pool, move |conn| upsert_post(&post_form, conn)).await??;
let c = blocking(pool, move |conn| upsert_comment(&comment_form, conn)).await??; let c = blocking(pool, move |conn| upsert_comment(&comment_form, conn)).await??;
@ -224,9 +221,9 @@ pub async fn get_or_fetch_and_upsert_remote_user(
// If its older than a day, re-fetch it // If its older than a day, re-fetch it
Ok(u) if !u.local && should_refetch_actor(u.last_refreshed_at) => { Ok(u) if !u.local && should_refetch_actor(u.last_refreshed_at) => {
debug!("Fetching and updating from remote user: {}", apub_id); debug!("Fetching and updating from remote user: {}", apub_id);
let person = fetch_remote_object::<PersonExt>(client, &Url::parse(apub_id)?).await?; let mut person = fetch_remote_object::<PersonExt>(client, &Url::parse(apub_id)?).await?;
let mut uf = UserForm::from_apub(&person, client, pool).await?; let mut uf = UserForm::from_apub(&mut person, client, pool).await?;
uf.last_refreshed_at = Some(naive_now()); uf.last_refreshed_at = Some(naive_now());
let user = blocking(pool, move |conn| User_::update(conn, u.id, &uf)).await??; let user = blocking(pool, move |conn| User_::update(conn, u.id, &uf)).await??;
@ -235,9 +232,9 @@ pub async fn get_or_fetch_and_upsert_remote_user(
Ok(u) => Ok(u), Ok(u) => Ok(u),
Err(NotFound {}) => { Err(NotFound {}) => {
debug!("Fetching and creating remote user: {}", apub_id); debug!("Fetching and creating remote user: {}", apub_id);
let person = fetch_remote_object::<PersonExt>(client, &Url::parse(apub_id)?).await?; let mut person = fetch_remote_object::<PersonExt>(client, &Url::parse(apub_id)?).await?;
let uf = UserForm::from_apub(&person, client, pool).await?; let uf = UserForm::from_apub(&mut person, client, pool).await?;
let user = blocking(pool, move |conn| User_::create(conn, &uf)).await??; let user = blocking(pool, move |conn| User_::create(conn, &uf)).await??;
Ok(user) Ok(user)
@ -275,9 +272,9 @@ pub async fn get_or_fetch_and_upsert_remote_community(
match community { match community {
Ok(c) if !c.local && should_refetch_actor(c.last_refreshed_at) => { Ok(c) if !c.local && should_refetch_actor(c.last_refreshed_at) => {
debug!("Fetching and updating from remote community: {}", apub_id); debug!("Fetching and updating from remote community: {}", apub_id);
let group = fetch_remote_object::<GroupExt>(client, &Url::parse(apub_id)?).await?; let mut group = fetch_remote_object::<GroupExt>(client, &Url::parse(apub_id)?).await?;
let mut cf = CommunityForm::from_apub(&group, client, pool).await?; let mut cf = CommunityForm::from_apub(&mut group, client, pool).await?;
cf.last_refreshed_at = Some(naive_now()); cf.last_refreshed_at = Some(naive_now());
let community = blocking(pool, move |conn| Community::update(conn, c.id, &cf)).await??; let community = blocking(pool, move |conn| Community::update(conn, c.id, &cf)).await??;
@ -286,17 +283,19 @@ pub async fn get_or_fetch_and_upsert_remote_community(
Ok(c) => Ok(c), Ok(c) => Ok(c),
Err(NotFound {}) => { Err(NotFound {}) => {
debug!("Fetching and creating remote community: {}", apub_id); debug!("Fetching and creating remote community: {}", apub_id);
let group = fetch_remote_object::<GroupExt>(client, &Url::parse(apub_id)?).await?; let mut group = fetch_remote_object::<GroupExt>(client, &Url::parse(apub_id)?).await?;
let cf = CommunityForm::from_apub(&group, client, pool).await?; let cf = CommunityForm::from_apub(&mut group, client, pool).await?;
let community = blocking(pool, move |conn| Community::create(conn, &cf)).await??; let community = blocking(pool, move |conn| Community::create(conn, &cf)).await??;
// Also add the community moderators too // Also add the community moderators too
let creator_and_moderator_uris = group let attributed_to = group.inner.take_attributed_to().unwrap();
.inner let creator_and_moderator_uris: Vec<&XsdAnyUri> = attributed_to
.object_props .as_many()
.get_many_attributed_to_xsd_any_uris() .unwrap()
.unwrap(); .iter()
.map(|a| a.as_xsd_any_uri().unwrap())
.collect();
let mut creator_and_moderators = Vec::new(); let mut creator_and_moderators = Vec::new();
@ -350,8 +349,8 @@ pub async fn get_or_fetch_and_insert_remote_post(
Ok(p) => Ok(p), Ok(p) => Ok(p),
Err(NotFound {}) => { Err(NotFound {}) => {
debug!("Fetching and creating remote post: {}", post_ap_id); debug!("Fetching and creating remote post: {}", post_ap_id);
let post = fetch_remote_object::<PageExt>(client, &Url::parse(post_ap_id)?).await?; let mut post = fetch_remote_object::<PageExt>(client, &Url::parse(post_ap_id)?).await?;
let post_form = PostForm::from_apub(&post, client, pool).await?; let post_form = PostForm::from_apub(&mut post, client, pool).await?;
let post = blocking(pool, move |conn| Post::create(conn, &post_form)).await??; let post = blocking(pool, move |conn| Post::create(conn, &post_form)).await??;
@ -388,8 +387,8 @@ pub async fn get_or_fetch_and_insert_remote_comment(
"Fetching and creating remote comment and its parents: {}", "Fetching and creating remote comment and its parents: {}",
comment_ap_id comment_ap_id
); );
let comment = fetch_remote_object::<Note>(client, &Url::parse(comment_ap_id)?).await?; let mut comment = fetch_remote_object::<Note>(client, &Url::parse(comment_ap_id)?).await?;
let comment_form = CommentForm::from_apub(&comment, client, pool).await?; let comment_form = CommentForm::from_apub(&mut comment, client, pool).await?;
let comment = blocking(pool, move |conn| Comment::create(conn, &comment_form)).await??; let comment = blocking(pool, move |conn| Comment::create(conn, &comment_form)).await??;

View File

@ -25,20 +25,22 @@ use crate::{
MentionData, MentionData,
Settings, Settings,
}; };
use activitystreams::{ use activitystreams::object::Page;
actor::{properties::ApActorProperties, Group, Person}, use activitystreams_ext::{Ext1, Ext2};
object::Page, use activitystreams_new::{
activity::Follow,
actor::{ApActor, Group, Person},
object::Tombstone,
prelude::*,
}; };
use activitystreams_ext::{Ext1, Ext2, Ext3};
use activitystreams_new::{activity::Follow, object::Tombstone, prelude::*};
use actix_web::{body::Body, client::Client, HttpResponse}; use actix_web::{body::Body, client::Client, HttpResponse};
use chrono::NaiveDateTime; use chrono::NaiveDateTime;
use log::debug; use log::debug;
use serde::Serialize; use serde::Serialize;
use url::Url; use url::Url;
type GroupExt = Ext3<Group, GroupExtension, ApActorProperties, PublicKeyExtension>; type GroupExt = Ext2<ApActor<Group>, GroupExtension, PublicKeyExtension>;
type PersonExt = Ext2<Person, ApActorProperties, PublicKeyExtension>; type PersonExt = Ext1<ApActor<Person>, PublicKeyExtension>;
type PageExt = Ext1<Page, PageExtension>; type PageExt = Ext1<Page, PageExtension>;
pub static APUB_JSON_CONTENT_TYPE: &str = "application/activity+json"; pub static APUB_JSON_CONTENT_TYPE: &str = "application/activity+json";
@ -163,7 +165,7 @@ fn create_tombstone(
pub trait FromApub { pub trait FromApub {
type ApubType; type ApubType;
async fn from_apub( async fn from_apub(
apub: &Self::ApubType, apub: &mut Self::ApubType,
client: &Client, client: &Client,
pool: &DbPool, pool: &DbPool,
) -> Result<Self, LemmyError> ) -> Result<Self, LemmyError>

View File

@ -164,7 +164,7 @@ impl FromApub for PostForm {
/// Parse an ActivityPub page received from another instance into a Lemmy post. /// Parse an ActivityPub page received from another instance into a Lemmy post.
async fn from_apub( async fn from_apub(
page: &PageExt, page: &mut PageExt,
client: &Client, client: &Client,
pool: &DbPool, pool: &DbPool,
) -> Result<PostForm, LemmyError> { ) -> Result<PostForm, LemmyError> {

View File

@ -71,7 +71,7 @@ impl FromApub for PrivateMessageForm {
/// Parse an ActivityPub note received from another instance into a Lemmy Private message /// Parse an ActivityPub note received from another instance into a Lemmy Private message
async fn from_apub( async fn from_apub(
note: &Note, note: &mut Note,
client: &Client, client: &Client,
pool: &DbPool, pool: &DbPool,
) -> Result<PrivateMessageForm, LemmyError> { ) -> Result<PrivateMessageForm, LemmyError> {

View File

@ -335,7 +335,7 @@ async fn receive_create_post(
pool: &DbPool, pool: &DbPool,
chat_server: ChatServerParam, chat_server: ChatServerParam,
) -> Result<HttpResponse, LemmyError> { ) -> Result<HttpResponse, LemmyError> {
let page = create let mut page = create
.create_props .create_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -353,7 +353,7 @@ async fn receive_create_post(
insert_activity(user.id, create, false, pool).await?; insert_activity(user.id, create, false, pool).await?;
let post = PostForm::from_apub(&page, client, pool).await?; let post = PostForm::from_apub(&mut page, client, pool).await?;
let inserted_post = blocking(pool, move |conn| Post::create(conn, &post)).await??; let inserted_post = blocking(pool, move |conn| Post::create(conn, &post)).await??;
@ -381,7 +381,7 @@ async fn receive_create_comment(
pool: &DbPool, pool: &DbPool,
chat_server: ChatServerParam, chat_server: ChatServerParam,
) -> Result<HttpResponse, LemmyError> { ) -> Result<HttpResponse, LemmyError> {
let note = create let mut note = create
.create_props .create_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -399,7 +399,7 @@ async fn receive_create_comment(
insert_activity(user.id, create, false, pool).await?; insert_activity(user.id, create, false, pool).await?;
let comment = CommentForm::from_apub(&note, client, pool).await?; let comment = CommentForm::from_apub(&mut note, client, pool).await?;
let inserted_comment = blocking(pool, move |conn| Comment::create(conn, &comment)).await??; let inserted_comment = blocking(pool, move |conn| Comment::create(conn, &comment)).await??;
@ -440,7 +440,7 @@ async fn receive_update_post(
pool: &DbPool, pool: &DbPool,
chat_server: ChatServerParam, chat_server: ChatServerParam,
) -> Result<HttpResponse, LemmyError> { ) -> Result<HttpResponse, LemmyError> {
let page = update let mut page = update
.update_props .update_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -458,7 +458,7 @@ async fn receive_update_post(
insert_activity(user.id, update, false, pool).await?; insert_activity(user.id, update, false, pool).await?;
let post = PostForm::from_apub(&page, client, pool).await?; let post = PostForm::from_apub(&mut page, client, pool).await?;
let post_id = get_or_fetch_and_insert_remote_post(&post.ap_id, client, pool) let post_id = get_or_fetch_and_insert_remote_post(&post.ap_id, client, pool)
.await? .await?
@ -486,7 +486,7 @@ async fn receive_like_post(
pool: &DbPool, pool: &DbPool,
chat_server: ChatServerParam, chat_server: ChatServerParam,
) -> Result<HttpResponse, LemmyError> { ) -> Result<HttpResponse, LemmyError> {
let page = like let mut page = like
.like_props .like_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -500,7 +500,7 @@ async fn receive_like_post(
insert_activity(user.id, like, false, pool).await?; insert_activity(user.id, like, false, pool).await?;
let post = PostForm::from_apub(&page, client, pool).await?; let post = PostForm::from_apub(&mut page, client, pool).await?;
let post_id = get_or_fetch_and_insert_remote_post(&post.ap_id, client, pool) let post_id = get_or_fetch_and_insert_remote_post(&post.ap_id, client, pool)
.await? .await?
@ -537,7 +537,7 @@ async fn receive_dislike_post(
pool: &DbPool, pool: &DbPool,
chat_server: ChatServerParam, chat_server: ChatServerParam,
) -> Result<HttpResponse, LemmyError> { ) -> Result<HttpResponse, LemmyError> {
let page = dislike let mut page = dislike
.dislike_props .dislike_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -555,7 +555,7 @@ async fn receive_dislike_post(
insert_activity(user.id, dislike, false, pool).await?; insert_activity(user.id, dislike, false, pool).await?;
let post = PostForm::from_apub(&page, client, pool).await?; let post = PostForm::from_apub(&mut page, client, pool).await?;
let post_id = get_or_fetch_and_insert_remote_post(&post.ap_id, client, pool) let post_id = get_or_fetch_and_insert_remote_post(&post.ap_id, client, pool)
.await? .await?
@ -592,7 +592,7 @@ async fn receive_update_comment(
pool: &DbPool, pool: &DbPool,
chat_server: ChatServerParam, chat_server: ChatServerParam,
) -> Result<HttpResponse, LemmyError> { ) -> Result<HttpResponse, LemmyError> {
let note = update let mut note = update
.update_props .update_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -610,7 +610,7 @@ async fn receive_update_comment(
insert_activity(user.id, update, false, pool).await?; insert_activity(user.id, update, false, pool).await?;
let comment = CommentForm::from_apub(&note, client, pool).await?; let comment = CommentForm::from_apub(&mut note, client, pool).await?;
let comment_id = get_or_fetch_and_insert_remote_comment(&comment.ap_id, client, pool) let comment_id = get_or_fetch_and_insert_remote_comment(&comment.ap_id, client, pool)
.await? .await?
@ -651,7 +651,7 @@ async fn receive_like_comment(
pool: &DbPool, pool: &DbPool,
chat_server: ChatServerParam, chat_server: ChatServerParam,
) -> Result<HttpResponse, LemmyError> { ) -> Result<HttpResponse, LemmyError> {
let note = like let mut note = like
.like_props .like_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -665,7 +665,7 @@ async fn receive_like_comment(
insert_activity(user.id, like, false, pool).await?; insert_activity(user.id, like, false, pool).await?;
let comment = CommentForm::from_apub(&note, client, pool).await?; let comment = CommentForm::from_apub(&mut note, client, pool).await?;
let comment_id = get_or_fetch_and_insert_remote_comment(&comment.ap_id, client, pool) let comment_id = get_or_fetch_and_insert_remote_comment(&comment.ap_id, client, pool)
.await? .await?
@ -709,7 +709,7 @@ async fn receive_dislike_comment(
pool: &DbPool, pool: &DbPool,
chat_server: ChatServerParam, chat_server: ChatServerParam,
) -> Result<HttpResponse, LemmyError> { ) -> Result<HttpResponse, LemmyError> {
let note = dislike let mut note = dislike
.dislike_props .dislike_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -727,7 +727,7 @@ async fn receive_dislike_comment(
insert_activity(user.id, dislike, false, pool).await?; insert_activity(user.id, dislike, false, pool).await?;
let comment = CommentForm::from_apub(&note, client, pool).await?; let comment = CommentForm::from_apub(&mut note, client, pool).await?;
let comment_id = get_or_fetch_and_insert_remote_comment(&comment.ap_id, client, pool) let comment_id = get_or_fetch_and_insert_remote_comment(&comment.ap_id, client, pool)
.await? .await?
@ -777,7 +777,7 @@ async fn receive_delete_community(
.unwrap() .unwrap()
.to_string(); .to_string();
let group = delete let mut group = delete
.delete_props .delete_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -789,7 +789,7 @@ async fn receive_delete_community(
insert_activity(user.id, delete, false, pool).await?; insert_activity(user.id, delete, false, pool).await?;
let community_actor_id = CommunityForm::from_apub(&group, client, pool) let community_actor_id = CommunityForm::from_apub(&mut group, client, pool)
.await? .await?
.actor_id; .actor_id;
@ -854,7 +854,7 @@ async fn receive_remove_community(
.unwrap() .unwrap()
.to_string(); .to_string();
let group = remove let mut group = remove
.remove_props .remove_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -866,7 +866,7 @@ async fn receive_remove_community(
insert_activity(mod_.id, remove, false, pool).await?; insert_activity(mod_.id, remove, false, pool).await?;
let community_actor_id = CommunityForm::from_apub(&group, client, pool) let community_actor_id = CommunityForm::from_apub(&mut group, client, pool)
.await? .await?
.actor_id; .actor_id;
@ -931,7 +931,7 @@ async fn receive_delete_post(
.unwrap() .unwrap()
.to_string(); .to_string();
let page = delete let mut page = delete
.delete_props .delete_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -943,7 +943,7 @@ async fn receive_delete_post(
insert_activity(user.id, delete, false, pool).await?; insert_activity(user.id, delete, false, pool).await?;
let post_ap_id = PostForm::from_apub(&page, client, pool).await?.ap_id; let post_ap_id = PostForm::from_apub(&mut page, client, pool).await?.ap_id;
let post = get_or_fetch_and_insert_remote_post(&post_ap_id, client, pool).await?; let post = get_or_fetch_and_insert_remote_post(&post_ap_id, client, pool).await?;
@ -997,7 +997,7 @@ async fn receive_remove_post(
.unwrap() .unwrap()
.to_string(); .to_string();
let page = remove let mut page = remove
.remove_props .remove_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -1009,7 +1009,7 @@ async fn receive_remove_post(
insert_activity(mod_.id, remove, false, pool).await?; insert_activity(mod_.id, remove, false, pool).await?;
let post_ap_id = PostForm::from_apub(&page, client, pool).await?.ap_id; let post_ap_id = PostForm::from_apub(&mut page, client, pool).await?.ap_id;
let post = get_or_fetch_and_insert_remote_post(&post_ap_id, client, pool).await?; let post = get_or_fetch_and_insert_remote_post(&post_ap_id, client, pool).await?;
@ -1063,7 +1063,7 @@ async fn receive_delete_comment(
.unwrap() .unwrap()
.to_string(); .to_string();
let note = delete let mut note = delete
.delete_props .delete_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -1075,7 +1075,7 @@ async fn receive_delete_comment(
insert_activity(user.id, delete, false, pool).await?; insert_activity(user.id, delete, false, pool).await?;
let comment_ap_id = CommentForm::from_apub(&note, client, pool).await?.ap_id; let comment_ap_id = CommentForm::from_apub(&mut note, client, pool).await?.ap_id;
let comment = get_or_fetch_and_insert_remote_comment(&comment_ap_id, client, pool).await?; let comment = get_or_fetch_and_insert_remote_comment(&comment_ap_id, client, pool).await?;
@ -1131,7 +1131,7 @@ async fn receive_remove_comment(
.unwrap() .unwrap()
.to_string(); .to_string();
let note = remove let mut note = remove
.remove_props .remove_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -1143,7 +1143,7 @@ async fn receive_remove_comment(
insert_activity(mod_.id, remove, false, pool).await?; insert_activity(mod_.id, remove, false, pool).await?;
let comment_ap_id = CommentForm::from_apub(&note, client, pool).await?.ap_id; let comment_ap_id = CommentForm::from_apub(&mut note, client, pool).await?.ap_id;
let comment = get_or_fetch_and_insert_remote_comment(&comment_ap_id, client, pool).await?; let comment = get_or_fetch_and_insert_remote_comment(&comment_ap_id, client, pool).await?;
@ -1259,7 +1259,7 @@ async fn receive_undo_delete_comment(
.unwrap() .unwrap()
.to_string(); .to_string();
let note = delete let mut note = delete
.delete_props .delete_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -1271,7 +1271,7 @@ async fn receive_undo_delete_comment(
insert_activity(user.id, delete, false, pool).await?; insert_activity(user.id, delete, false, pool).await?;
let comment_ap_id = CommentForm::from_apub(&note, client, pool).await?.ap_id; let comment_ap_id = CommentForm::from_apub(&mut note, client, pool).await?.ap_id;
let comment = get_or_fetch_and_insert_remote_comment(&comment_ap_id, client, pool).await?; let comment = get_or_fetch_and_insert_remote_comment(&comment_ap_id, client, pool).await?;
@ -1327,7 +1327,7 @@ async fn receive_undo_remove_comment(
.unwrap() .unwrap()
.to_string(); .to_string();
let note = remove let mut note = remove
.remove_props .remove_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -1339,7 +1339,7 @@ async fn receive_undo_remove_comment(
insert_activity(mod_.id, remove, false, pool).await?; insert_activity(mod_.id, remove, false, pool).await?;
let comment_ap_id = CommentForm::from_apub(&note, client, pool).await?.ap_id; let comment_ap_id = CommentForm::from_apub(&mut note, client, pool).await?.ap_id;
let comment = get_or_fetch_and_insert_remote_comment(&comment_ap_id, client, pool).await?; let comment = get_or_fetch_and_insert_remote_comment(&comment_ap_id, client, pool).await?;
@ -1395,7 +1395,7 @@ async fn receive_undo_delete_post(
.unwrap() .unwrap()
.to_string(); .to_string();
let page = delete let mut page = delete
.delete_props .delete_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -1407,7 +1407,7 @@ async fn receive_undo_delete_post(
insert_activity(user.id, delete, false, pool).await?; insert_activity(user.id, delete, false, pool).await?;
let post_ap_id = PostForm::from_apub(&page, client, pool).await?.ap_id; let post_ap_id = PostForm::from_apub(&mut page, client, pool).await?.ap_id;
let post = get_or_fetch_and_insert_remote_post(&post_ap_id, client, pool).await?; let post = get_or_fetch_and_insert_remote_post(&post_ap_id, client, pool).await?;
@ -1461,7 +1461,7 @@ async fn receive_undo_remove_post(
.unwrap() .unwrap()
.to_string(); .to_string();
let page = remove let mut page = remove
.remove_props .remove_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -1473,7 +1473,7 @@ async fn receive_undo_remove_post(
insert_activity(mod_.id, remove, false, pool).await?; insert_activity(mod_.id, remove, false, pool).await?;
let post_ap_id = PostForm::from_apub(&page, client, pool).await?.ap_id; let post_ap_id = PostForm::from_apub(&mut page, client, pool).await?.ap_id;
let post = get_or_fetch_and_insert_remote_post(&post_ap_id, client, pool).await?; let post = get_or_fetch_and_insert_remote_post(&post_ap_id, client, pool).await?;
@ -1527,7 +1527,7 @@ async fn receive_undo_delete_community(
.unwrap() .unwrap()
.to_string(); .to_string();
let group = delete let mut group = delete
.delete_props .delete_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -1539,7 +1539,7 @@ async fn receive_undo_delete_community(
insert_activity(user.id, delete, false, pool).await?; insert_activity(user.id, delete, false, pool).await?;
let community_actor_id = CommunityForm::from_apub(&group, client, pool) let community_actor_id = CommunityForm::from_apub(&mut group, client, pool)
.await? .await?
.actor_id; .actor_id;
@ -1604,7 +1604,7 @@ async fn receive_undo_remove_community(
.unwrap() .unwrap()
.to_string(); .to_string();
let group = remove let mut group = remove
.remove_props .remove_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -1616,7 +1616,7 @@ async fn receive_undo_remove_community(
insert_activity(mod_.id, remove, false, pool).await?; insert_activity(mod_.id, remove, false, pool).await?;
let community_actor_id = CommunityForm::from_apub(&group, client, pool) let community_actor_id = CommunityForm::from_apub(&mut group, client, pool)
.await? .await?
.actor_id; .actor_id;
@ -1704,7 +1704,7 @@ async fn receive_undo_like_comment(
pool: &DbPool, pool: &DbPool,
chat_server: ChatServerParam, chat_server: ChatServerParam,
) -> Result<HttpResponse, LemmyError> { ) -> Result<HttpResponse, LemmyError> {
let note = like let mut note = like
.like_props .like_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -1718,7 +1718,7 @@ async fn receive_undo_like_comment(
insert_activity(user.id, like, false, pool).await?; insert_activity(user.id, like, false, pool).await?;
let comment = CommentForm::from_apub(&note, client, pool).await?; let comment = CommentForm::from_apub(&mut note, client, pool).await?;
let comment_id = get_or_fetch_and_insert_remote_comment(&comment.ap_id, client, pool) let comment_id = get_or_fetch_and_insert_remote_comment(&comment.ap_id, client, pool)
.await? .await?
@ -1758,7 +1758,7 @@ async fn receive_undo_like_post(
pool: &DbPool, pool: &DbPool,
chat_server: ChatServerParam, chat_server: ChatServerParam,
) -> Result<HttpResponse, LemmyError> { ) -> Result<HttpResponse, LemmyError> {
let page = like let mut page = like
.like_props .like_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -1772,7 +1772,7 @@ async fn receive_undo_like_post(
insert_activity(user.id, like, false, pool).await?; insert_activity(user.id, like, false, pool).await?;
let post = PostForm::from_apub(&page, client, pool).await?; let post = PostForm::from_apub(&mut page, client, pool).await?;
let post_id = get_or_fetch_and_insert_remote_post(&post.ap_id, client, pool) let post_id = get_or_fetch_and_insert_remote_post(&post.ap_id, client, pool)
.await? .await?

View File

@ -1,13 +1,5 @@
use crate::{ use crate::{
apub::{ apub::{activities::send_activity, create_apub_response, ActorType, FromApub, PersonExt, ToApub},
activities::send_activity,
create_apub_response,
extensions::signatures::PublicKey,
ActorType,
FromApub,
PersonExt,
ToApub,
},
blocking, blocking,
convert_datetime, convert_datetime,
db::{ db::{
@ -19,20 +11,17 @@ use crate::{
DbPool, DbPool,
LemmyError, LemmyError,
}; };
use activitystreams::{ use activitystreams_ext::Ext1;
actor::{properties::ApActorProperties, Person},
context,
endpoint::EndpointProperties,
object::{properties::ObjectProperties, AnyImage, Image},
primitives::XsdAnyUri,
};
use activitystreams_ext::Ext2;
use activitystreams_new::{ use activitystreams_new::{
activity::{Follow, Undo}, activity::{Follow, Undo},
object::Tombstone, actor::{ApActor, Endpoints, Person},
context,
object::{Image, Tombstone},
prelude::*, prelude::*,
primitives::{XsdAnyUri, XsdDateTime},
}; };
use actix_web::{body::Body, client::Client, web, HttpResponse}; use actix_web::{body::Body, client::Client, web, HttpResponse};
use failure::_core::str::FromStr;
use serde::Deserialize; use serde::Deserialize;
#[derive(Deserialize)] #[derive(Deserialize)]
@ -47,46 +36,39 @@ impl ToApub for User_ {
// Turn a Lemmy Community into an ActivityPub group that can be sent out over the network. // Turn a Lemmy Community into an ActivityPub group that can be sent out over the network.
async fn to_apub(&self, _pool: &DbPool) -> Result<PersonExt, LemmyError> { async fn to_apub(&self, _pool: &DbPool) -> Result<PersonExt, LemmyError> {
// TODO go through all these to_string and to_owned() // TODO go through all these to_string and to_owned()
let mut person = Person::default(); let mut person = Person::new();
let oprops: &mut ObjectProperties = person.as_mut(); person
oprops .set_context(context())
.set_context_xsd_any_uri(context())? .set_id(XsdAnyUri::from_str(&self.actor_id)?)
.set_id(self.actor_id.to_string())? .set_name(self.name.to_owned())
.set_name_xsd_string(self.name.to_owned())? .set_published(XsdDateTime::from(convert_datetime(self.published)));
.set_published(convert_datetime(self.published))?;
if let Some(u) = self.updated { if let Some(u) = self.updated {
oprops.set_updated(convert_datetime(u))?; person.set_updated(XsdDateTime::from(convert_datetime(u)));
}
if let Some(i) = &self.preferred_username {
oprops.set_name_xsd_string(i.to_owned())?;
} }
if let Some(avatar_url) = &self.avatar { if let Some(avatar_url) = &self.avatar {
let mut image = Image::new(); let mut image = Image::new();
image image.set_url(avatar_url.to_owned());
.object_props person.set_icon(image.into_any_base()?);
.set_url_xsd_any_uri(avatar_url.to_owned())?;
let any_image = AnyImage::from_concrete(image)?;
oprops.set_icon_any_image(any_image)?;
} }
let mut endpoint_props = EndpointProperties::default(); let mut ap_actor = ApActor::new(self.get_inbox_url().parse()?, person);
ap_actor
.set_outbox(self.get_outbox_url().parse()?)
.set_followers(self.get_followers_url().parse()?)
.set_following(self.get_following_url().parse()?)
.set_liked(self.get_liked_url().parse()?)
.set_endpoints(Endpoints {
shared_inbox: Some(self.get_shared_inbox_url().parse()?),
..Default::default()
});
endpoint_props.set_shared_inbox(self.get_shared_inbox_url())?; if let Some(i) = &self.preferred_username {
ap_actor.set_preferred_username(i.to_owned());
}
let mut actor_props = ApActorProperties::default(); Ok(Ext1::new(ap_actor, self.get_public_key_ext()))
actor_props
.set_inbox(self.get_inbox_url())?
.set_outbox(self.get_outbox_url())?
.set_endpoints(endpoint_props)?
.set_followers(self.get_followers_url())?
.set_following(self.get_following_url())?
.set_liked(self.get_liked_url())?;
Ok(Ext2::new(person, actor_props, self.get_public_key_ext()))
} }
fn to_tombstone(&self) -> Result<Tombstone, LemmyError> { fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
unimplemented!() unimplemented!()
@ -203,31 +185,33 @@ impl ActorType for User_ {
impl FromApub for UserForm { impl FromApub for UserForm {
type ApubType = PersonExt; type ApubType = PersonExt;
/// Parse an ActivityPub person received from another instance into a Lemmy user. /// Parse an ActivityPub person received from another instance into a Lemmy user.
async fn from_apub(person: &PersonExt, _: &Client, _: &DbPool) -> Result<Self, LemmyError> { async fn from_apub(person: &mut PersonExt, _: &Client, _: &DbPool) -> Result<Self, LemmyError> {
let oprops = &person.inner.object_props; let avatar = match person.take_icon() {
let aprops = &person.ext_one; Some(any_image) => Image::from_any_base(any_image.as_one().unwrap().clone())
let public_key: &PublicKey = &person.ext_two.public_key; .unwrap()
.unwrap()
let avatar = match oprops.get_icon_any_image() { .url
Some(any_image) => any_image .unwrap()
.to_owned() .as_single_xsd_any_uri()
.into_concrete::<Image>()?
.object_props
.get_url_xsd_any_uri()
.map(|u| u.to_string()), .map(|u| u.to_string()),
None => None, None => None,
}; };
Ok(UserForm { Ok(UserForm {
name: oprops.get_name_xsd_string().unwrap().to_string(), name: person
preferred_username: aprops.get_preferred_username().map(|u| u.to_string()), .take_name()
.unwrap()
.as_single_xsd_string()
.unwrap()
.into(),
preferred_username: person.inner.take_preferred_username(),
password_encrypted: "".to_string(), password_encrypted: "".to_string(),
admin: false, admin: false,
banned: false, banned: false,
email: None, email: None,
avatar, avatar,
updated: oprops updated: person
.get_updated() .take_updated()
.map(|u| u.as_ref().to_owned().naive_local()), .map(|u| u.as_ref().to_owned().naive_local()),
show_nsfw: false, show_nsfw: false,
theme: "".to_string(), theme: "".to_string(),
@ -237,11 +221,13 @@ impl FromApub for UserForm {
show_avatars: false, show_avatars: false,
send_notifications_to_email: false, send_notifications_to_email: false,
matrix_user_id: None, matrix_user_id: None,
actor_id: oprops.get_id().unwrap().to_string(), actor_id: person.id().unwrap().to_string(),
bio: oprops.get_summary_xsd_string().map(|s| s.to_string()), bio: person
.take_summary()
.map(|s| s.as_single_xsd_string().unwrap().into()),
local: false, local: false,
private_key: None, private_key: None,
public_key: Some(public_key.to_owned().public_key_pem), public_key: Some(person.ext_one.public_key.to_owned().public_key_pem),
last_refreshed_at: Some(naive_now()), last_refreshed_at: Some(naive_now()),
}) })
} }

View File

@ -116,7 +116,7 @@ async fn receive_create_private_message(
pool: &DbPool, pool: &DbPool,
chat_server: ChatServerParam, chat_server: ChatServerParam,
) -> Result<HttpResponse, LemmyError> { ) -> Result<HttpResponse, LemmyError> {
let note = create let mut note = create
.create_props .create_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -135,7 +135,7 @@ async fn receive_create_private_message(
insert_activity(user.id, create, false, pool).await?; insert_activity(user.id, create, false, pool).await?;
let private_message = PrivateMessageForm::from_apub(&note, client, pool).await?; let private_message = PrivateMessageForm::from_apub(&mut note, client, pool).await?;
let inserted_private_message = blocking(pool, move |conn| { let inserted_private_message = blocking(pool, move |conn| {
PrivateMessage::create(conn, &private_message) PrivateMessage::create(conn, &private_message)
@ -168,7 +168,7 @@ async fn receive_update_private_message(
pool: &DbPool, pool: &DbPool,
chat_server: ChatServerParam, chat_server: ChatServerParam,
) -> Result<HttpResponse, LemmyError> { ) -> Result<HttpResponse, LemmyError> {
let note = update let mut note = update
.update_props .update_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -187,7 +187,7 @@ async fn receive_update_private_message(
insert_activity(user.id, update, false, pool).await?; insert_activity(user.id, update, false, pool).await?;
let private_message_form = PrivateMessageForm::from_apub(&note, client, pool).await?; let private_message_form = PrivateMessageForm::from_apub(&mut note, client, pool).await?;
let private_message_ap_id = private_message_form.ap_id.clone(); let private_message_ap_id = private_message_form.ap_id.clone();
let private_message = blocking(pool, move |conn| { let private_message = blocking(pool, move |conn| {
@ -228,7 +228,7 @@ async fn receive_delete_private_message(
pool: &DbPool, pool: &DbPool,
chat_server: ChatServerParam, chat_server: ChatServerParam,
) -> Result<HttpResponse, LemmyError> { ) -> Result<HttpResponse, LemmyError> {
let note = delete let mut note = delete
.delete_props .delete_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -247,7 +247,7 @@ async fn receive_delete_private_message(
insert_activity(user.id, delete, false, pool).await?; insert_activity(user.id, delete, false, pool).await?;
let private_message_form = PrivateMessageForm::from_apub(&note, client, pool).await?; let private_message_form = PrivateMessageForm::from_apub(&mut note, client, pool).await?;
let private_message_ap_id = private_message_form.ap_id; let private_message_ap_id = private_message_form.ap_id;
let private_message = blocking(pool, move |conn| { let private_message = blocking(pool, move |conn| {
@ -308,7 +308,7 @@ async fn receive_undo_delete_private_message(
.to_owned() .to_owned()
.into_concrete::<Delete>()?; .into_concrete::<Delete>()?;
let note = delete let mut note = delete
.delete_props .delete_props
.get_object_base_box() .get_object_base_box()
.to_owned() .to_owned()
@ -327,7 +327,7 @@ async fn receive_undo_delete_private_message(
insert_activity(user.id, delete, false, pool).await?; insert_activity(user.id, delete, false, pool).await?;
let private_message = PrivateMessageForm::from_apub(&note, client, pool).await?; let private_message = PrivateMessageForm::from_apub(&mut note, client, pool).await?;
let private_message_ap_id = private_message.ap_id.clone(); let private_message_ap_id = private_message.ap_id.clone();
let private_message_id = blocking(pool, move |conn| { let private_message_id = blocking(pool, move |conn| {

View File

@ -325,7 +325,7 @@ pub fn markdown_to_html(text: &str) -> String {
pub fn get_ip(conn_info: &ConnectionInfo) -> String { pub fn get_ip(conn_info: &ConnectionInfo) -> String {
conn_info conn_info
.remote_addr() .realip_remote_addr()
.unwrap_or("127.0.0.1:12345") .unwrap_or("127.0.0.1:12345")
.split(':') .split(':')
.next() .next()

View File

@ -1 +1 @@
pub const VERSION: &str = "v0.7.12"; pub const VERSION: &str = "v0.7.13";

View File

@ -108,8 +108,17 @@ export class CommentForm extends Component<CommentFormProps, CommentFormState> {
}); });
} }
componentDidUpdate() {
if (this.state.commentForm.content) {
window.onbeforeunload = () => true;
} else {
window.onbeforeunload = undefined;
}
}
componentWillUnmount() { componentWillUnmount() {
this.subscription.unsubscribe(); this.subscription.unsubscribe();
window.onbeforeunload = null;
} }
render() { render() {

View File

@ -73,6 +73,7 @@ interface CommentNodeProps {
showCommunity?: boolean; showCommunity?: boolean;
sort?: CommentSortType; sort?: CommentSortType;
sortType?: SortType; sortType?: SortType;
enableDownvotes: boolean;
} }
export class CommentNode extends Component<CommentNodeProps, CommentNodeState> { export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
@ -279,7 +280,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
<span class="ml-1">{this.state.upvotes}</span> <span class="ml-1">{this.state.upvotes}</span>
)} )}
</button> </button>
{WebSocketService.Instance.site.enable_downvotes && ( {this.props.enableDownvotes && (
<button <button
className={`btn btn-link btn-animate ${ className={`btn btn-link btn-animate ${
this.state.my_vote == -1 this.state.my_vote == -1
@ -703,6 +704,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
postCreatorId={this.props.postCreatorId} postCreatorId={this.props.postCreatorId}
sort={this.props.sort} sort={this.props.sort}
sortType={this.props.sortType} sortType={this.props.sortType}
enableDownvotes={this.props.enableDownvotes}
/> />
)} )}
{/* A collapsed clearfix */} {/* A collapsed clearfix */}

View File

@ -24,6 +24,7 @@ interface CommentNodesProps {
showCommunity?: boolean; showCommunity?: boolean;
sort?: CommentSortType; sort?: CommentSortType;
sortType?: SortType; sortType?: SortType;
enableDownvotes: boolean;
} }
export class CommentNodes extends Component< export class CommentNodes extends Component<
@ -52,6 +53,7 @@ export class CommentNodes extends Component<
showCommunity={this.props.showCommunity} showCommunity={this.props.showCommunity}
sort={this.props.sort} sort={this.props.sort}
sortType={this.props.sortType} sortType={this.props.sortType}
enableDownvotes={this.props.enableDownvotes}
/> />
))} ))}
</div> </div>

View File

@ -1,5 +1,4 @@
import { Component, linkEvent } from 'inferno'; import { Component, linkEvent } from 'inferno';
import { Link } from 'inferno-router';
import { Subscription } from 'rxjs'; import { Subscription } from 'rxjs';
import { retryWhen, delay, take } from 'rxjs/operators'; import { retryWhen, delay, take } from 'rxjs/operators';
import { import {
@ -11,6 +10,7 @@ import {
ListCommunitiesForm, ListCommunitiesForm,
SortType, SortType,
WebSocketJsonResponse, WebSocketJsonResponse,
GetSiteResponse,
} from '../interfaces'; } from '../interfaces';
import { WebSocketService } from '../services'; import { WebSocketService } from '../services';
import { wsJsonToRes, toast } from '../utils'; import { wsJsonToRes, toast } from '../utils';
@ -47,6 +47,7 @@ export class Communities extends Component<any, CommunitiesState> {
); );
this.refetch(); this.refetch();
WebSocketService.Instance.getSite();
} }
getPageFromProps(props: any): number { getPageFromProps(props: any): number {
@ -57,12 +58,6 @@ export class Communities extends Component<any, CommunitiesState> {
this.subscription.unsubscribe(); this.subscription.unsubscribe();
} }
componentDidMount() {
document.title = `${i18n.t('communities')} - ${
WebSocketService.Instance.site.name
}`;
}
// Necessary for back button for some reason // Necessary for back button for some reason
componentWillReceiveProps(nextProps: any) { componentWillReceiveProps(nextProps: any) {
if (nextProps.history.action == 'POP') { if (nextProps.history.action == 'POP') {
@ -244,6 +239,9 @@ export class Communities extends Component<any, CommunitiesState> {
found.subscribed = data.community.subscribed; found.subscribed = data.community.subscribed;
found.number_of_subscribers = data.community.number_of_subscribers; found.number_of_subscribers = data.community.number_of_subscribers;
this.setState(this.state); this.setState(this.state);
} else if (res.op == UserOperation.GetSite) {
let data = res.data as GetSiteResponse;
document.title = `${i18n.t('communities')} - ${data.site.name}`;
} }
} }
} }

View File

@ -8,7 +8,6 @@ import {
Category, Category,
ListCategoriesResponse, ListCategoriesResponse,
CommunityResponse, CommunityResponse,
GetSiteResponse,
WebSocketJsonResponse, WebSocketJsonResponse,
} from '../interfaces'; } from '../interfaces';
import { WebSocketService } from '../services'; import { WebSocketService } from '../services';
@ -30,13 +29,13 @@ interface CommunityFormProps {
onCancel?(): any; onCancel?(): any;
onCreate?(community: Community): any; onCreate?(community: Community): any;
onEdit?(community: Community): any; onEdit?(community: Community): any;
enableNsfw: boolean;
} }
interface CommunityFormState { interface CommunityFormState {
communityForm: CommunityFormI; communityForm: CommunityFormI;
categories: Array<Category>; categories: Array<Category>;
loading: boolean; loading: boolean;
enable_nsfw: boolean;
} }
export class CommunityForm extends Component< export class CommunityForm extends Component<
@ -56,7 +55,6 @@ export class CommunityForm extends Component<
}, },
categories: [], categories: [],
loading: false, loading: false,
enable_nsfw: null,
}; };
constructor(props: any, context: any) { constructor(props: any, context: any) {
@ -86,7 +84,6 @@ export class CommunityForm extends Component<
); );
WebSocketService.Instance.listCategories(); WebSocketService.Instance.listCategories();
WebSocketService.Instance.getSite();
} }
componentDidMount() { componentDidMount() {
@ -100,8 +97,22 @@ export class CommunityForm extends Component<
}); });
} }
componentDidUpdate() {
if (
!this.state.loading &&
(this.state.communityForm.name ||
this.state.communityForm.title ||
this.state.communityForm.description)
) {
window.onbeforeunload = () => true;
} else {
window.onbeforeunload = undefined;
}
}
componentWillUnmount() { componentWillUnmount() {
this.subscription.unsubscribe(); this.subscription.unsubscribe();
window.onbeforeunload = null;
} }
render() { render() {
@ -187,7 +198,7 @@ export class CommunityForm extends Component<
</div> </div>
</div> </div>
{this.state.enable_nsfw && ( {this.props.enableNsfw && (
<div class="form-group row"> <div class="form-group row">
<div class="col-12"> <div class="col-12">
<div class="form-check"> <div class="form-check">
@ -303,10 +314,6 @@ export class CommunityForm extends Component<
let data = res.data as CommunityResponse; let data = res.data as CommunityResponse;
this.state.loading = false; this.state.loading = false;
this.props.onEdit(data.community); this.props.onEdit(data.community);
} else if (res.op == UserOperation.GetSite) {
let data = res.data as GetSiteResponse;
this.state.enable_nsfw = data.site.enable_nsfw;
this.setState(this.state);
} }
} }
} }

View File

@ -23,6 +23,8 @@ import {
GetCommentsResponse, GetCommentsResponse,
CommentResponse, CommentResponse,
WebSocketJsonResponse, WebSocketJsonResponse,
GetSiteResponse,
Site,
} from '../interfaces'; } from '../interfaces';
import { WebSocketService } from '../services'; import { WebSocketService } from '../services';
import { PostListings } from './post-listings'; import { PostListings } from './post-listings';
@ -60,6 +62,7 @@ interface State {
dataType: DataType; dataType: DataType;
sort: SortType; sort: SortType;
page: number; page: number;
site: Site;
} }
export class Community extends Component<any, State> { export class Community extends Component<any, State> {
@ -97,6 +100,20 @@ export class Community extends Component<any, State> {
dataType: getDataTypeFromProps(this.props), dataType: getDataTypeFromProps(this.props),
sort: getSortTypeFromProps(this.props), sort: getSortTypeFromProps(this.props),
page: getPageFromProps(this.props), page: getPageFromProps(this.props),
site: {
id: undefined,
name: undefined,
creator_id: undefined,
published: undefined,
creator_name: undefined,
number_of_users: undefined,
number_of_posts: undefined,
number_of_comments: undefined,
number_of_communities: undefined,
enable_downvotes: undefined,
open_registration: undefined,
enable_nsfw: undefined,
},
}; };
constructor(props: any, context: any) { constructor(props: any, context: any) {
@ -119,6 +136,7 @@ export class Community extends Component<any, State> {
name: this.state.communityName ? this.state.communityName : null, name: this.state.communityName ? this.state.communityName : null,
}; };
WebSocketService.Instance.getCommunity(form); WebSocketService.Instance.getCommunity(form);
WebSocketService.Instance.getSite();
} }
componentWillUnmount() { componentWillUnmount() {
@ -174,6 +192,7 @@ export class Community extends Component<any, State> {
moderators={this.state.moderators} moderators={this.state.moderators}
admins={this.state.admins} admins={this.state.admins}
online={this.state.online} online={this.state.online}
enableNsfw={this.state.site.enable_nsfw}
/> />
</div> </div>
</div> </div>
@ -188,6 +207,8 @@ export class Community extends Component<any, State> {
posts={this.state.posts} posts={this.state.posts}
removeDuplicates removeDuplicates
sort={this.state.sort} sort={this.state.sort}
enableDownvotes={this.state.site.enable_downvotes}
enableNsfw={this.state.site.enable_nsfw}
/> />
) : ( ) : (
<CommentNodes <CommentNodes
@ -195,6 +216,7 @@ export class Community extends Component<any, State> {
noIndent noIndent
sortType={this.state.sort} sortType={this.state.sort}
showContext showContext
enableDownvotes={this.state.site.enable_downvotes}
/> />
); );
} }
@ -331,7 +353,7 @@ export class Community extends Component<any, State> {
this.state.moderators = data.moderators; this.state.moderators = data.moderators;
this.state.admins = data.admins; this.state.admins = data.admins;
this.state.online = data.online; this.state.online = data.online;
document.title = `/c/${this.state.community.name} - ${WebSocketService.Instance.site.name}`; document.title = `/c/${this.state.community.name} - ${this.state.site.name}`;
this.setState(this.state); this.setState(this.state);
this.fetchData(); this.fetchData();
} else if (res.op == UserOperation.EditCommunity) { } else if (res.op == UserOperation.EditCommunity) {
@ -399,6 +421,10 @@ export class Community extends Component<any, State> {
let data = res.data as CommentResponse; let data = res.data as CommentResponse;
createCommentLikeRes(data, this.state.comments); createCommentLikeRes(data, this.state.comments);
this.setState(this.state); this.setState(this.state);
} else if (res.op == UserOperation.GetSite) {
let data = res.data as GetSiteResponse;
this.state.site = data.site;
this.setState(this.state);
} }
} }
} }

View File

@ -1,19 +1,44 @@
import { Component } from 'inferno'; import { Component } from 'inferno';
import { Subscription } from 'rxjs';
import { retryWhen, delay, take } from 'rxjs/operators';
import { CommunityForm } from './community-form'; import { CommunityForm } from './community-form';
import { Community } from '../interfaces'; import {
Community,
UserOperation,
WebSocketJsonResponse,
GetSiteResponse,
} from '../interfaces';
import { toast, wsJsonToRes } from '../utils';
import { WebSocketService } from '../services'; import { WebSocketService } from '../services';
import { i18n } from '../i18next'; import { i18n } from '../i18next';
export class CreateCommunity extends Component<any, any> { interface CreateCommunityState {
enableNsfw: boolean;
}
export class CreateCommunity extends Component<any, CreateCommunityState> {
private subscription: Subscription;
private emptyState: CreateCommunityState = {
enableNsfw: null,
};
constructor(props: any, context: any) { constructor(props: any, context: any) {
super(props, context); super(props, context);
this.handleCommunityCreate = this.handleCommunityCreate.bind(this); this.handleCommunityCreate = this.handleCommunityCreate.bind(this);
this.state = this.emptyState;
this.subscription = WebSocketService.Instance.subject
.pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
.subscribe(
msg => this.parseMessage(msg),
err => console.error(err),
() => console.log('complete')
);
WebSocketService.Instance.getSite();
} }
componentDidMount() { componentWillUnmount() {
document.title = `${i18n.t('create_community')} - ${ this.subscription.unsubscribe();
WebSocketService.Instance.site.name
}`;
} }
render() { render() {
@ -22,7 +47,10 @@ export class CreateCommunity extends Component<any, any> {
<div class="row"> <div class="row">
<div class="col-12 col-lg-6 offset-lg-3 mb-4"> <div class="col-12 col-lg-6 offset-lg-3 mb-4">
<h5>{i18n.t('create_community')}</h5> <h5>{i18n.t('create_community')}</h5>
<CommunityForm onCreate={this.handleCommunityCreate} /> <CommunityForm
onCreate={this.handleCommunityCreate}
enableNsfw={this.state.enableNsfw}
/>
</div> </div>
</div> </div>
</div> </div>
@ -32,4 +60,18 @@ export class CreateCommunity extends Component<any, any> {
handleCommunityCreate(community: Community) { handleCommunityCreate(community: Community) {
this.props.history.push(`/c/${community.name}`); this.props.history.push(`/c/${community.name}`);
} }
parseMessage(msg: WebSocketJsonResponse) {
console.log(msg);
let res = wsJsonToRes(msg);
if (msg.error) {
toast(i18n.t(msg.error), 'danger');
return;
} else if (res.op == UserOperation.GetSite) {
let data = res.data as GetSiteResponse;
this.state.enableNsfw = data.site.enable_nsfw;
this.setState(this.state);
document.title = `${i18n.t('create_community')} - ${data.site.name}`;
}
}
} }

View File

@ -1,19 +1,59 @@
import { Component } from 'inferno'; import { Component } from 'inferno';
import { Subscription } from 'rxjs';
import { retryWhen, delay, take } from 'rxjs/operators';
import { PostForm } from './post-form'; import { PostForm } from './post-form';
import { toast, wsJsonToRes } from '../utils';
import { WebSocketService } from '../services'; import { WebSocketService } from '../services';
import { PostFormParams } from '../interfaces'; import {
UserOperation,
PostFormParams,
WebSocketJsonResponse,
GetSiteResponse,
Site,
} from '../interfaces';
import { i18n } from '../i18next'; import { i18n } from '../i18next';
export class CreatePost extends Component<any, any> { interface CreatePostState {
site: Site;
}
export class CreatePost extends Component<any, CreatePostState> {
private subscription: Subscription;
private emptyState: CreatePostState = {
site: {
id: undefined,
name: undefined,
creator_id: undefined,
published: undefined,
creator_name: undefined,
number_of_users: undefined,
number_of_posts: undefined,
number_of_comments: undefined,
number_of_communities: undefined,
enable_downvotes: undefined,
open_registration: undefined,
enable_nsfw: undefined,
},
};
constructor(props: any, context: any) { constructor(props: any, context: any) {
super(props, context); super(props, context);
this.handlePostCreate = this.handlePostCreate.bind(this); this.handlePostCreate = this.handlePostCreate.bind(this);
this.state = this.emptyState;
this.subscription = WebSocketService.Instance.subject
.pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
.subscribe(
msg => this.parseMessage(msg),
err => console.error(err),
() => console.log('complete')
);
WebSocketService.Instance.getSite();
} }
componentDidMount() { componentWillUnmount() {
document.title = `${i18n.t('create_post')} - ${ this.subscription.unsubscribe();
WebSocketService.Instance.site.name
}`;
} }
render() { render() {
@ -22,7 +62,12 @@ export class CreatePost extends Component<any, any> {
<div class="row"> <div class="row">
<div class="col-12 col-lg-6 offset-lg-3 mb-4"> <div class="col-12 col-lg-6 offset-lg-3 mb-4">
<h5>{i18n.t('create_post')}</h5> <h5>{i18n.t('create_post')}</h5>
<PostForm onCreate={this.handlePostCreate} params={this.params} /> <PostForm
onCreate={this.handlePostCreate}
params={this.params}
enableDownvotes={this.state.site.enable_downvotes}
enableNsfw={this.state.site.enable_nsfw}
/>
</div> </div>
</div> </div>
</div> </div>
@ -56,4 +101,18 @@ export class CreatePost extends Component<any, any> {
handlePostCreate(id: number) { handlePostCreate(id: number) {
this.props.history.push(`/post/${id}`); this.props.history.push(`/post/${id}`);
} }
parseMessage(msg: WebSocketJsonResponse) {
console.log(msg);
let res = wsJsonToRes(msg);
if (msg.error) {
toast(i18n.t(msg.error), 'danger');
return;
} else if (res.op == UserOperation.GetSite) {
let data = res.data as GetSiteResponse;
this.state.site = data.site;
this.setState(this.state);
document.title = `${i18n.t('create_post')} - ${data.site.name}`;
}
}
} }

View File

@ -1,22 +1,38 @@
import { Component } from 'inferno'; import { Component } from 'inferno';
import { Subscription } from 'rxjs';
import { retryWhen, delay, take } from 'rxjs/operators';
import { PrivateMessageForm } from './private-message-form'; import { PrivateMessageForm } from './private-message-form';
import { WebSocketService } from '../services'; import { WebSocketService } from '../services';
import { PrivateMessageFormParams } from '../interfaces'; import {
import { toast } from '../utils'; UserOperation,
WebSocketJsonResponse,
GetSiteResponse,
PrivateMessageFormParams,
} from '../interfaces';
import { toast, wsJsonToRes } from '../utils';
import { i18n } from '../i18next'; import { i18n } from '../i18next';
export class CreatePrivateMessage extends Component<any, any> { export class CreatePrivateMessage extends Component<any, any> {
private subscription: Subscription;
constructor(props: any, context: any) { constructor(props: any, context: any) {
super(props, context); super(props, context);
this.handlePrivateMessageCreate = this.handlePrivateMessageCreate.bind( this.handlePrivateMessageCreate = this.handlePrivateMessageCreate.bind(
this this
); );
this.subscription = WebSocketService.Instance.subject
.pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
.subscribe(
msg => this.parseMessage(msg),
err => console.error(err),
() => console.log('complete')
);
WebSocketService.Instance.getSite();
} }
componentDidMount() { componentWillUnmount() {
document.title = `${i18n.t('create_private_message')} - ${ this.subscription.unsubscribe();
WebSocketService.Instance.site.name
}`;
} }
render() { render() {
@ -50,4 +66,18 @@ export class CreatePrivateMessage extends Component<any, any> {
// Navigate to the front // Navigate to the front
this.props.history.push(`/`); this.props.history.push(`/`);
} }
parseMessage(msg: WebSocketJsonResponse) {
console.log(msg);
let res = wsJsonToRes(msg);
if (msg.error) {
toast(i18n.t(msg.error), 'danger');
return;
} else if (res.op == UserOperation.GetSite) {
let data = res.data as GetSiteResponse;
document.title = `${i18n.t('create_private_message')} - ${
data.site.name
}`;
}
}
} }

View File

@ -16,6 +16,7 @@ import {
GetPrivateMessagesForm, GetPrivateMessagesForm,
PrivateMessagesResponse, PrivateMessagesResponse,
PrivateMessageResponse, PrivateMessageResponse,
GetSiteResponse,
} from '../interfaces'; } from '../interfaces';
import { WebSocketService, UserService } from '../services'; import { WebSocketService, UserService } from '../services';
import { import {
@ -56,6 +57,7 @@ interface InboxState {
messages: Array<PrivateMessageI>; messages: Array<PrivateMessageI>;
sort: SortType; sort: SortType;
page: number; page: number;
enableDownvotes: boolean;
} }
export class Inbox extends Component<any, InboxState> { export class Inbox extends Component<any, InboxState> {
@ -68,6 +70,7 @@ export class Inbox extends Component<any, InboxState> {
messages: [], messages: [],
sort: SortType.New, sort: SortType.New,
page: 1, page: 1,
enableDownvotes: undefined,
}; };
constructor(props: any, context: any) { constructor(props: any, context: any) {
@ -85,18 +88,13 @@ export class Inbox extends Component<any, InboxState> {
); );
this.refetch(); this.refetch();
WebSocketService.Instance.getSite();
} }
componentWillUnmount() { componentWillUnmount() {
this.subscription.unsubscribe(); this.subscription.unsubscribe();
} }
componentDidMount() {
document.title = `/u/${UserService.Instance.user.username} ${i18n.t(
'inbox'
)} - ${WebSocketService.Instance.site.name}`;
}
render() { render() {
return ( return (
<div class="container"> <div class="container">
@ -270,6 +268,7 @@ export class Inbox extends Component<any, InboxState> {
noIndent noIndent
markable markable
showContext showContext
enableDownvotes={this.state.enableDownvotes}
/> />
) : ( ) : (
<PrivateMessage privateMessage={i} /> <PrivateMessage privateMessage={i} />
@ -287,6 +286,7 @@ export class Inbox extends Component<any, InboxState> {
noIndent noIndent
markable markable
showContext showContext
enableDownvotes={this.state.enableDownvotes}
/> />
</div> </div>
); );
@ -301,6 +301,7 @@ export class Inbox extends Component<any, InboxState> {
noIndent noIndent
markable markable
showContext showContext
enableDownvotes={this.state.enableDownvotes}
/> />
))} ))}
</div> </div>
@ -522,6 +523,13 @@ export class Inbox extends Component<any, InboxState> {
let data = res.data as CommentResponse; let data = res.data as CommentResponse;
createCommentLikeRes(data, this.state.replies); createCommentLikeRes(data, this.state.replies);
this.setState(this.state); this.setState(this.state);
} else if (res.op == UserOperation.GetSite) {
let data = res.data as GetSiteResponse;
this.state.enableDownvotes = data.site.enable_downvotes;
this.setState(this.state);
document.title = `/u/${UserService.Instance.user.username} ${i18n.t(
'inbox'
)} - ${data.site.name}`;
} }
} }

View File

@ -385,9 +385,7 @@ export class Login extends Component<any, State> {
let data = res.data as GetSiteResponse; let data = res.data as GetSiteResponse;
this.state.enable_nsfw = data.site.enable_nsfw; this.state.enable_nsfw = data.site.enable_nsfw;
this.setState(this.state); this.setState(this.state);
document.title = `${i18n.t('login')} - ${ document.title = `${i18n.t('login')} - ${data.site.name}`;
WebSocketService.Instance.site.name
}`;
} }
} }
} }

View File

@ -418,6 +418,8 @@ export class Main extends Component<any, MainState> {
showCommunity showCommunity
removeDuplicates removeDuplicates
sort={this.state.sort} sort={this.state.sort}
enableDownvotes={this.state.siteRes.site.enable_downvotes}
enableNsfw={this.state.siteRes.site.enable_nsfw}
/> />
) : ( ) : (
<CommentNodes <CommentNodes
@ -426,6 +428,7 @@ export class Main extends Component<any, MainState> {
showCommunity showCommunity
sortType={this.state.sort} sortType={this.state.sort}
showContext showContext
enableDownvotes={this.state.siteRes.site.enable_downvotes}
/> />
); );
} }
@ -617,7 +620,7 @@ export class Main extends Component<any, MainState> {
this.state.siteRes.banned = data.banned; this.state.siteRes.banned = data.banned;
this.state.siteRes.online = data.online; this.state.siteRes.online = data.online;
this.setState(this.state); this.setState(this.state);
document.title = `${WebSocketService.Instance.site.name}`; document.title = `${this.state.siteRes.site.name}`;
} else if (res.op == UserOperation.EditSite) { } else if (res.op == UserOperation.EditSite) {
let data = res.data as SiteResponse; let data = res.data as SiteResponse;
this.state.siteRes.site = data.site; this.state.siteRes.site = data.site;

View File

@ -16,6 +16,7 @@ import {
ModAddCommunity, ModAddCommunity,
ModAdd, ModAdd,
WebSocketJsonResponse, WebSocketJsonResponse,
GetSiteResponse,
} from '../interfaces'; } from '../interfaces';
import { WebSocketService } from '../services'; import { WebSocketService } from '../services';
import { wsJsonToRes, addTypeInfo, fetchLimit, toast } from '../utils'; import { wsJsonToRes, addTypeInfo, fetchLimit, toast } from '../utils';
@ -64,16 +65,13 @@ export class Modlog extends Component<any, ModlogState> {
); );
this.refetch(); this.refetch();
WebSocketService.Instance.getSite();
} }
componentWillUnmount() { componentWillUnmount() {
this.subscription.unsubscribe(); this.subscription.unsubscribe();
} }
componentDidMount() {
document.title = `Modlog - ${WebSocketService.Instance.site.name}`;
}
setCombined(res: GetModlogResponse) { setCombined(res: GetModlogResponse) {
let removed_posts = addTypeInfo(res.removed_posts, 'removed_posts'); let removed_posts = addTypeInfo(res.removed_posts, 'removed_posts');
let locked_posts = addTypeInfo(res.locked_posts, 'locked_posts'); let locked_posts = addTypeInfo(res.locked_posts, 'locked_posts');
@ -434,6 +432,9 @@ export class Modlog extends Component<any, ModlogState> {
this.state.loading = false; this.state.loading = false;
window.scrollTo(0, 0); window.scrollTo(0, 0);
this.setCombined(data); this.setCombined(data);
} else if (res.op == UserOperation.GetSite) {
let data = res.data as GetSiteResponse;
document.title = `Modlog - ${data.site.name}`;
} }
} }
} }

View File

@ -396,9 +396,6 @@ export class Navbar extends Component<any, NavbarState> {
if (data.site && !this.state.siteName) { if (data.site && !this.state.siteName) {
this.state.siteName = data.site.name; this.state.siteName = data.site.name;
this.state.admins = data.admins; this.state.admins = data.admins;
WebSocketService.Instance.site = data.site;
WebSocketService.Instance.admins = data.admins;
this.setState(this.state); this.setState(this.state);
} }
} }

View File

@ -6,6 +6,7 @@ import {
LoginResponse, LoginResponse,
PasswordChangeForm, PasswordChangeForm,
WebSocketJsonResponse, WebSocketJsonResponse,
GetSiteResponse,
} from '../interfaces'; } from '../interfaces';
import { WebSocketService, UserService } from '../services'; import { WebSocketService, UserService } from '../services';
import { wsJsonToRes, capitalizeFirstLetter, toast } from '../utils'; import { wsJsonToRes, capitalizeFirstLetter, toast } from '../utils';
@ -40,18 +41,13 @@ export class PasswordChange extends Component<any, State> {
err => console.error(err), err => console.error(err),
() => console.log('complete') () => console.log('complete')
); );
WebSocketService.Instance.getSite();
} }
componentWillUnmount() { componentWillUnmount() {
this.subscription.unsubscribe(); this.subscription.unsubscribe();
} }
componentDidMount() {
document.title = `${i18n.t('password_change')} - ${
WebSocketService.Instance.site.name
}`;
}
render() { render() {
return ( return (
<div class="container"> <div class="container">
@ -138,14 +134,15 @@ export class PasswordChange extends Component<any, State> {
this.state.loading = false; this.state.loading = false;
this.setState(this.state); this.setState(this.state);
return; return;
} else { } else if (res.op == UserOperation.PasswordChange) {
if (res.op == UserOperation.PasswordChange) {
let data = res.data as LoginResponse; let data = res.data as LoginResponse;
this.state = this.emptyState; this.state = this.emptyState;
this.setState(this.state); this.setState(this.state);
UserService.Instance.login(data); UserService.Instance.login(data);
this.props.history.push('/'); this.props.history.push('/');
} } else if (res.op == UserOperation.GetSite) {
let data = res.data as GetSiteResponse;
document.title = `${i18n.t('password_change')} - ${data.site.name}`;
} }
} }
} }

View File

@ -16,7 +16,6 @@ import {
SearchForm, SearchForm,
SearchType, SearchType,
SearchResponse, SearchResponse,
GetSiteResponse,
WebSocketJsonResponse, WebSocketJsonResponse,
} from '../interfaces'; } from '../interfaces';
import { WebSocketService, UserService } from '../services'; import { WebSocketService, UserService } from '../services';
@ -52,6 +51,8 @@ interface PostFormProps {
onCancel?(): any; onCancel?(): any;
onCreate?(id: number): any; onCreate?(id: number): any;
onEdit?(post: Post): any; onEdit?(post: Post): any;
enableNsfw: boolean;
enableDownvotes: boolean;
} }
interface PostFormState { interface PostFormState {
@ -63,7 +64,6 @@ interface PostFormState {
suggestedTitle: string; suggestedTitle: string;
suggestedPosts: Array<Post>; suggestedPosts: Array<Post>;
crossPosts: Array<Post>; crossPosts: Array<Post>;
enable_nsfw: boolean;
} }
export class PostForm extends Component<PostFormProps, PostFormState> { export class PostForm extends Component<PostFormProps, PostFormState> {
@ -87,7 +87,6 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
suggestedTitle: undefined, suggestedTitle: undefined,
suggestedPosts: [], suggestedPosts: [],
crossPosts: [], crossPosts: [],
enable_nsfw: undefined,
}; };
constructor(props: any, context: any) { constructor(props: any, context: any) {
@ -138,7 +137,6 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
}; };
WebSocketService.Instance.listCommunities(listCommunitiesForm); WebSocketService.Instance.listCommunities(listCommunitiesForm);
WebSocketService.Instance.getSite();
} }
componentDidMount() { componentDidMount() {
@ -153,8 +151,22 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
setupTippy(); setupTippy();
} }
componentDidUpdate() {
if (
!this.state.loading &&
(this.state.postForm.name ||
this.state.postForm.url ||
this.state.postForm.body)
) {
window.onbeforeunload = () => true;
} else {
window.onbeforeunload = undefined;
}
}
componentWillUnmount() { componentWillUnmount() {
this.subscription.unsubscribe(); this.subscription.unsubscribe();
window.onbeforeunload = null;
} }
render() { render() {
@ -240,7 +252,12 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
<div class="my-1 text-muted small font-weight-bold"> <div class="my-1 text-muted small font-weight-bold">
{i18n.t('cross_posts')} {i18n.t('cross_posts')}
</div> </div>
<PostListings showCommunity posts={this.state.crossPosts} /> <PostListings
showCommunity
posts={this.state.crossPosts}
enableDownvotes={this.props.enableDownvotes}
enableNsfw={this.props.enableNsfw}
/>
</> </>
)} )}
</div> </div>
@ -265,7 +282,11 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
<div class="my-1 text-muted small font-weight-bold"> <div class="my-1 text-muted small font-weight-bold">
{i18n.t('related_posts')} {i18n.t('related_posts')}
</div> </div>
<PostListings posts={this.state.suggestedPosts} /> <PostListings
posts={this.state.suggestedPosts}
enableDownvotes={this.props.enableDownvotes}
enableNsfw={this.props.enableNsfw}
/>
</> </>
)} )}
</div> </div>
@ -346,7 +367,7 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
</div> </div>
</div> </div>
)} )}
{this.state.enable_nsfw && ( {this.props.enableNsfw && (
<div class="form-group row"> <div class="form-group row">
<div class="col-sm-10"> <div class="col-sm-10">
<div class="form-check"> <div class="form-check">
@ -631,10 +652,6 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
this.state.crossPosts = data.posts; this.state.crossPosts = data.posts;
} }
this.setState(this.state); this.setState(this.state);
} else if (res.op == UserOperation.GetSite) {
let data = res.data as GetSiteResponse;
this.state.enable_nsfw = data.site.enable_nsfw;
this.setState(this.state);
} }
} }
} }

View File

@ -61,6 +61,8 @@ interface PostListingProps {
showBody?: boolean; showBody?: boolean;
moderators?: Array<CommunityUser>; moderators?: Array<CommunityUser>;
admins?: Array<UserView>; admins?: Array<UserView>;
enableDownvotes: boolean;
enableNsfw: boolean;
} }
export class PostListing extends Component<PostListingProps, PostListingState> { export class PostListing extends Component<PostListingProps, PostListingState> {
@ -115,6 +117,8 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
post={this.props.post} post={this.props.post}
onEdit={this.handleEditPost} onEdit={this.handleEditPost}
onCancel={this.handleEditCancel} onCancel={this.handleEditCancel}
enableNsfw={this.props.enableNsfw}
enableDownvotes={this.props.enableDownvotes}
/> />
</div> </div>
)} )}
@ -273,7 +277,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
> >
{this.state.score} {this.state.score}
</div> </div>
{WebSocketService.Instance.site.enable_downvotes && ( {this.props.enableDownvotes && (
<button <button
className={`btn-animate btn btn-link p-0 ${ className={`btn-animate btn btn-link p-0 ${
this.state.my_vote == -1 ? 'text-danger' : 'text-muted' this.state.my_vote == -1 ? 'text-danger' : 'text-muted'

View File

@ -11,6 +11,8 @@ interface PostListingsProps {
showCommunity?: boolean; showCommunity?: boolean;
removeDuplicates?: boolean; removeDuplicates?: boolean;
sort?: SortType; sort?: SortType;
enableDownvotes: boolean;
enableNsfw: boolean;
} }
export class PostListings extends Component<PostListingsProps, any> { export class PostListings extends Component<PostListingsProps, any> {
@ -27,6 +29,8 @@ export class PostListings extends Component<PostListingsProps, any> {
<PostListing <PostListing
post={post} post={post}
showCommunity={this.props.showCommunity} showCommunity={this.props.showCommunity}
enableDownvotes={this.props.enableDownvotes}
enableNsfw={this.props.enableNsfw}
/> />
<hr class="my-2" /> <hr class="my-2" />
</> </>

View File

@ -18,7 +18,6 @@ import {
BanUserResponse, BanUserResponse,
AddModToCommunityResponse, AddModToCommunityResponse,
AddAdminResponse, AddAdminResponse,
UserView,
SearchType, SearchType,
SortType, SortType,
SearchForm, SearchForm,
@ -52,12 +51,12 @@ interface PostState {
commentSort: CommentSortType; commentSort: CommentSortType;
community: Community; community: Community;
moderators: Array<CommunityUser>; moderators: Array<CommunityUser>;
admins: Array<UserView>;
online: number; online: number;
scrolled?: boolean; scrolled?: boolean;
scrolled_comment_id?: number; scrolled_comment_id?: number;
loading: boolean; loading: boolean;
crossPosts: Array<PostI>; crossPosts: Array<PostI>;
siteRes: GetSiteResponse;
} }
export class Post extends Component<any, PostState> { export class Post extends Component<any, PostState> {
@ -68,11 +67,29 @@ export class Post extends Component<any, PostState> {
commentSort: CommentSortType.Hot, commentSort: CommentSortType.Hot,
community: null, community: null,
moderators: [], moderators: [],
admins: [],
online: null, online: null,
scrolled: false, scrolled: false,
loading: true, loading: true,
crossPosts: [], crossPosts: [],
siteRes: {
admins: [],
banned: [],
site: {
id: undefined,
name: undefined,
creator_id: undefined,
published: undefined,
creator_name: undefined,
number_of_users: undefined,
number_of_posts: undefined,
number_of_comments: undefined,
number_of_communities: undefined,
enable_downvotes: undefined,
open_registration: undefined,
enable_nsfw: undefined,
},
online: null,
},
}; };
constructor(props: any, context: any) { constructor(props: any, context: any) {
@ -97,6 +114,7 @@ export class Post extends Component<any, PostState> {
id: postId, id: postId,
}; };
WebSocketService.Instance.getPost(form); WebSocketService.Instance.getPost(form);
WebSocketService.Instance.getSite();
} }
componentWillUnmount() { componentWillUnmount() {
@ -180,7 +198,9 @@ export class Post extends Component<any, PostState> {
showBody showBody
showCommunity showCommunity
moderators={this.state.moderators} moderators={this.state.moderators}
admins={this.state.admins} admins={this.state.siteRes.admins}
enableDownvotes={this.state.siteRes.site.enable_downvotes}
enableNsfw={this.state.siteRes.site.enable_nsfw}
/> />
<div className="mb-2" /> <div className="mb-2" />
<CommentForm <CommentForm
@ -269,9 +289,10 @@ export class Post extends Component<any, PostState> {
noIndent noIndent
locked={this.state.post.locked} locked={this.state.post.locked}
moderators={this.state.moderators} moderators={this.state.moderators}
admins={this.state.admins} admins={this.state.siteRes.admins}
postCreatorId={this.state.post.creator_id} postCreatorId={this.state.post.creator_id}
showContext showContext
enableDownvotes={this.state.siteRes.site.enable_downvotes}
/> />
</div> </div>
</div> </div>
@ -284,8 +305,9 @@ export class Post extends Component<any, PostState> {
<Sidebar <Sidebar
community={this.state.community} community={this.state.community}
moderators={this.state.moderators} moderators={this.state.moderators}
admins={this.state.admins} admins={this.state.siteRes.admins}
online={this.state.online} online={this.state.online}
enableNsfw={this.state.siteRes.site.enable_nsfw}
/> />
</div> </div>
); );
@ -336,9 +358,10 @@ export class Post extends Component<any, PostState> {
nodes={nodes} nodes={nodes}
locked={this.state.post.locked} locked={this.state.post.locked}
moderators={this.state.moderators} moderators={this.state.moderators}
admins={this.state.admins} admins={this.state.siteRes.admins}
postCreatorId={this.state.post.creator_id} postCreatorId={this.state.post.creator_id}
sort={this.state.commentSort} sort={this.state.commentSort}
enableDownvotes={this.state.siteRes.site.enable_downvotes}
/> />
</div> </div>
); );
@ -360,10 +383,10 @@ export class Post extends Component<any, PostState> {
this.state.comments = data.comments; this.state.comments = data.comments;
this.state.community = data.community; this.state.community = data.community;
this.state.moderators = data.moderators; this.state.moderators = data.moderators;
this.state.admins = data.admins; this.state.siteRes.admins = data.admins;
this.state.online = data.online; this.state.online = data.online;
this.state.loading = false; this.state.loading = false;
document.title = `${this.state.post.name} - ${WebSocketService.Instance.site.name}`; document.title = `${this.state.post.name} - ${this.state.siteRes.site.name}`;
// Get cross-posts // Get cross-posts
if (this.state.post.url) { if (this.state.post.url) {
@ -450,7 +473,7 @@ export class Post extends Component<any, PostState> {
this.setState(this.state); this.setState(this.state);
} else if (res.op == UserOperation.AddAdmin) { } else if (res.op == UserOperation.AddAdmin) {
let data = res.data as AddAdminResponse; let data = res.data as AddAdminResponse;
this.state.admins = data.admins; this.state.siteRes.admins = data.admins;
this.setState(this.state); this.setState(this.state);
} else if (res.op == UserOperation.Search) { } else if (res.op == UserOperation.Search) {
let data = res.data as SearchResponse; let data = res.data as SearchResponse;
@ -461,15 +484,18 @@ export class Post extends Component<any, PostState> {
this.state.post.duplicates = this.state.crossPosts; this.state.post.duplicates = this.state.crossPosts;
} }
this.setState(this.state); this.setState(this.state);
} else if (res.op == UserOperation.TransferSite) { } else if (
res.op == UserOperation.TransferSite ||
res.op == UserOperation.GetSite
) {
let data = res.data as GetSiteResponse; let data = res.data as GetSiteResponse;
this.state.admins = data.admins; this.state.siteRes = data;
this.setState(this.state); this.setState(this.state);
} else if (res.op == UserOperation.TransferCommunity) { } else if (res.op == UserOperation.TransferCommunity) {
let data = res.data as GetCommunityResponse; let data = res.data as GetCommunityResponse;
this.state.community = data.community; this.state.community = data.community;
this.state.moderators = data.moderators; this.state.moderators = data.moderators;
this.state.admins = data.admins; this.state.siteRes.admins = data.admins;
this.setState(this.state); this.setState(this.state);
} }
} }

View File

@ -1,6 +1,5 @@
import { Component, linkEvent } from 'inferno'; import { Component, linkEvent } from 'inferno';
import { Prompt } from 'inferno-router'; import { Prompt } from 'inferno-router';
import { Link } from 'inferno-router';
import { Subscription } from 'rxjs'; import { Subscription } from 'rxjs';
import { retryWhen, delay, take } from 'rxjs/operators'; import { retryWhen, delay, take } from 'rxjs/operators';
import { import {
@ -111,8 +110,17 @@ export class PrivateMessageForm extends Component<
setupTippy(); setupTippy();
} }
componentDidUpdate() {
if (!this.state.loading && this.state.privateMessageForm.content) {
window.onbeforeunload = () => true;
} else {
window.onbeforeunload = undefined;
}
}
componentWillUnmount() { componentWillUnmount() {
this.subscription.unsubscribe(); this.subscription.unsubscribe();
window.onbeforeunload = null;
} }
render() { render() {

View File

@ -15,6 +15,8 @@ import {
PostResponse, PostResponse,
CommentResponse, CommentResponse,
WebSocketJsonResponse, WebSocketJsonResponse,
GetSiteResponse,
Site,
} from '../interfaces'; } from '../interfaces';
import { WebSocketService } from '../services'; import { WebSocketService } from '../services';
import { import {
@ -41,6 +43,7 @@ interface SearchState {
page: number; page: number;
searchResponse: SearchResponse; searchResponse: SearchResponse;
loading: boolean; loading: boolean;
site: Site;
} }
export class Search extends Component<any, SearchState> { export class Search extends Component<any, SearchState> {
@ -58,6 +61,20 @@ export class Search extends Component<any, SearchState> {
users: [], users: [],
}, },
loading: false, loading: false,
site: {
id: undefined,
name: undefined,
creator_id: undefined,
published: undefined,
creator_name: undefined,
number_of_users: undefined,
number_of_posts: undefined,
number_of_comments: undefined,
number_of_communities: undefined,
enable_downvotes: undefined,
open_registration: undefined,
enable_nsfw: undefined,
},
}; };
getSearchQueryFromProps(props: any): string { getSearchQueryFromProps(props: any): string {
@ -94,6 +111,8 @@ export class Search extends Component<any, SearchState> {
() => console.log('complete') () => console.log('complete')
); );
WebSocketService.Instance.getSite();
if (this.state.q) { if (this.state.q) {
this.search(); this.search();
} }
@ -118,12 +137,6 @@ export class Search extends Component<any, SearchState> {
} }
} }
componentDidMount() {
document.title = `${i18n.t('search')} - ${
WebSocketService.Instance.site.name
}`;
}
render() { render() {
return ( return (
<div class="container"> <div class="container">
@ -241,13 +254,19 @@ export class Search extends Component<any, SearchState> {
<div class="row"> <div class="row">
<div class="col-12"> <div class="col-12">
{i.type_ == 'posts' && ( {i.type_ == 'posts' && (
<PostListing post={i.data as Post} showCommunity /> <PostListing
post={i.data as Post}
showCommunity
enableDownvotes={this.state.site.enable_downvotes}
enableNsfw={this.state.site.enable_nsfw}
/>
)} )}
{i.type_ == 'comments' && ( {i.type_ == 'comments' && (
<CommentNodes <CommentNodes
nodes={[{ comment: i.data as Comment }]} nodes={[{ comment: i.data as Comment }]}
locked locked
noIndent noIndent
enableDownvotes={this.state.site.enable_downvotes}
/> />
)} )}
{i.type_ == 'communities' && ( {i.type_ == 'communities' && (
@ -281,6 +300,7 @@ export class Search extends Component<any, SearchState> {
nodes={commentsToFlatNodes(this.state.searchResponse.comments)} nodes={commentsToFlatNodes(this.state.searchResponse.comments)}
locked locked
noIndent noIndent
enableDownvotes={this.state.site.enable_downvotes}
/> />
); );
} }
@ -291,7 +311,12 @@ export class Search extends Component<any, SearchState> {
{this.state.searchResponse.posts.map(post => ( {this.state.searchResponse.posts.map(post => (
<div class="row"> <div class="row">
<div class="col-12"> <div class="col-12">
<PostListing post={post} showCommunity /> <PostListing
post={post}
showCommunity
enableDownvotes={this.state.site.enable_downvotes}
enableNsfw={this.state.site.enable_nsfw}
/>
</div> </div>
</div> </div>
))} ))}
@ -455,7 +480,7 @@ export class Search extends Component<any, SearchState> {
this.state.searchResponse = data; this.state.searchResponse = data;
this.state.loading = false; this.state.loading = false;
document.title = `${i18n.t('search')} - ${this.state.q} - ${ document.title = `${i18n.t('search')} - ${this.state.q} - ${
WebSocketService.Instance.site.name this.state.site.name
}`; }`;
window.scrollTo(0, 0); window.scrollTo(0, 0);
this.setState(this.state); this.setState(this.state);
@ -467,6 +492,11 @@ export class Search extends Component<any, SearchState> {
let data = res.data as PostResponse; let data = res.data as PostResponse;
createPostLikeFindRes(data, this.state.searchResponse.posts); createPostLikeFindRes(data, this.state.searchResponse.posts);
this.setState(this.state); this.setState(this.state);
} else if (res.op == UserOperation.GetSite) {
let data = res.data as GetSiteResponse;
this.state.site = data.site;
this.setState(this.state);
document.title = `${i18n.t('search')} - ${data.site.name}`;
} }
} }
} }

View File

@ -19,6 +19,7 @@ interface SidebarProps {
moderators: Array<CommunityUser>; moderators: Array<CommunityUser>;
admins: Array<UserView>; admins: Array<UserView>;
online: number; online: number;
enableNsfw: boolean;
} }
interface SidebarState { interface SidebarState {
@ -53,6 +54,7 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
community={this.props.community} community={this.props.community}
onEdit={this.handleEditCommunity} onEdit={this.handleEditCommunity}
onCancel={this.handleEditCancel} onCancel={this.handleEditCancel}
enableNsfw={this.props.enableNsfw}
/> />
)} )}
</div> </div>

View File

@ -64,6 +64,22 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
this.setState(this.state); this.setState(this.state);
} }
componentDidUpdate() {
if (
!this.state.loading &&
!this.props.site &&
(this.state.siteForm.name || this.state.siteForm.description)
) {
window.onbeforeunload = () => true;
} else {
window.onbeforeunload = undefined;
}
}
componentWillUnmount() {
window.onbeforeunload = null;
}
render() { render() {
return ( return (
<> <>

View File

@ -1,8 +1,15 @@
import { Component } from 'inferno'; import { Component } from 'inferno';
import { Subscription } from 'rxjs';
import { retryWhen, delay, take } from 'rxjs/operators';
import { WebSocketService } from '../services'; import { WebSocketService } from '../services';
import {
GetSiteResponse,
WebSocketJsonResponse,
UserOperation,
} from '../interfaces';
import { i18n } from '../i18next'; import { i18n } from '../i18next';
import { T } from 'inferno-i18next'; import { T } from 'inferno-i18next';
import { repoUrl } from '../utils'; import { repoUrl, wsJsonToRes, toast } from '../utils';
interface SilverUser { interface SilverUser {
name: string; name: string;
@ -33,17 +40,28 @@ let silver: Array<SilverUser> = [
// let latinum = []; // let latinum = [];
export class Sponsors extends Component<any, any> { export class Sponsors extends Component<any, any> {
private subscription: Subscription;
constructor(props: any, context: any) { constructor(props: any, context: any) {
super(props, context); super(props, context);
this.subscription = WebSocketService.Instance.subject
.pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
.subscribe(
msg => this.parseMessage(msg),
err => console.error(err),
() => console.log('complete')
);
WebSocketService.Instance.getSite();
} }
componentDidMount() { componentDidMount() {
document.title = `${i18n.t('sponsors')} - ${
WebSocketService.Instance.site.name
}`;
window.scrollTo(0, 0); window.scrollTo(0, 0);
} }
componentWillUnmount() {
this.subscription.unsubscribe();
}
render() { render() {
return ( return (
<div class="container text-center"> <div class="container text-center">
@ -153,4 +171,16 @@ export class Sponsors extends Component<any, any> {
</div> </div>
); );
} }
parseMessage(msg: WebSocketJsonResponse) {
console.log(msg);
let res = wsJsonToRes(msg);
if (msg.error) {
toast(i18n.t(msg.error), 'danger');
return;
} else if (res.op == UserOperation.GetSite) {
let data = res.data as GetSiteResponse;
document.title = `${i18n.t('sponsors')} - ${data.site.name}`;
}
}
} }

View File

@ -20,6 +20,8 @@ import {
DeleteAccountForm, DeleteAccountForm,
PostResponse, PostResponse,
WebSocketJsonResponse, WebSocketJsonResponse,
GetSiteResponse,
Site,
} from '../interfaces'; } from '../interfaces';
import { WebSocketService, UserService } from '../services'; import { WebSocketService, UserService } from '../services';
import { import {
@ -74,6 +76,7 @@ interface UserState {
deleteAccountLoading: boolean; deleteAccountLoading: boolean;
deleteAccountShowConfirm: boolean; deleteAccountShowConfirm: boolean;
deleteAccountForm: DeleteAccountForm; deleteAccountForm: DeleteAccountForm;
site: Site;
} }
export class User extends Component<any, UserState> { export class User extends Component<any, UserState> {
@ -122,6 +125,20 @@ export class User extends Component<any, UserState> {
deleteAccountForm: { deleteAccountForm: {
password: null, password: null,
}, },
site: {
id: undefined,
name: undefined,
creator_id: undefined,
published: undefined,
creator_name: undefined,
number_of_users: undefined,
number_of_posts: undefined,
number_of_comments: undefined,
number_of_communities: undefined,
enable_downvotes: undefined,
open_registration: undefined,
enable_nsfw: undefined,
},
}; };
constructor(props: any, context: any) { constructor(props: any, context: any) {
@ -148,6 +165,7 @@ export class User extends Component<any, UserState> {
); );
this.refetch(); this.refetch();
WebSocketService.Instance.getSite();
} }
get isCurrentUser() { get isCurrentUser() {
@ -356,6 +374,8 @@ export class User extends Component<any, UserState> {
post={i.data as Post} post={i.data as Post}
admins={this.state.admins} admins={this.state.admins}
showCommunity showCommunity
enableDownvotes={this.state.site.enable_downvotes}
enableNsfw={this.state.site.enable_nsfw}
/> />
) : ( ) : (
<CommentNodes <CommentNodes
@ -363,6 +383,7 @@ export class User extends Component<any, UserState> {
admins={this.state.admins} admins={this.state.admins}
noIndent noIndent
showContext showContext
enableDownvotes={this.state.site.enable_downvotes}
/> />
)} )}
</div> </div>
@ -379,6 +400,7 @@ export class User extends Component<any, UserState> {
admins={this.state.admins} admins={this.state.admins}
noIndent noIndent
showContext showContext
enableDownvotes={this.state.site.enable_downvotes}
/> />
</div> </div>
); );
@ -388,7 +410,13 @@ export class User extends Component<any, UserState> {
return ( return (
<div> <div>
{this.state.posts.map(post => ( {this.state.posts.map(post => (
<PostListing post={post} admins={this.state.admins} showCommunity /> <PostListing
post={post}
admins={this.state.admins}
showCommunity
enableDownvotes={this.state.site.enable_downvotes}
enableNsfw={this.state.site.enable_nsfw}
/>
))} ))}
</div> </div>
); );
@ -670,7 +698,7 @@ export class User extends Component<any, UserState> {
/> />
</div> </div>
</div> </div>
{WebSocketService.Instance.site.enable_nsfw && ( {this.state.site.enable_nsfw && (
<div class="form-group"> <div class="form-group">
<div class="form-check"> <div class="form-check">
<input <input
@ -1107,7 +1135,7 @@ export class User extends Component<any, UserState> {
UserService.Instance.user.show_avatars; UserService.Instance.user.show_avatars;
this.state.userSettingsForm.matrix_user_id = this.state.user.matrix_user_id; this.state.userSettingsForm.matrix_user_id = this.state.user.matrix_user_id;
} }
document.title = `/u/${this.state.user.name} - ${WebSocketService.Instance.site.name}`; document.title = `/u/${this.state.user.name} - ${this.state.site.name}`;
window.scrollTo(0, 0); window.scrollTo(0, 0);
this.setState(this.state); this.setState(this.state);
setupTippy(); setupTippy();
@ -1159,6 +1187,10 @@ export class User extends Component<any, UserState> {
this.state.deleteAccountShowConfirm = false; this.state.deleteAccountShowConfirm = false;
this.setState(this.state); this.setState(this.state);
this.context.router.history.push('/'); this.context.router.history.push('/');
} else if (res.op == UserOperation.GetSite) {
let data = res.data as GetSiteResponse;
this.state.site = data.site;
this.setState(this.state);
} }
} }
} }

6
ui/src/i18next.ts vendored
View File

@ -25,6 +25,9 @@ import { tr } from './translations/tr';
import { hu } from './translations/hu'; import { hu } from './translations/hu';
import { uk } from './translations/uk'; import { uk } from './translations/uk';
import { sq } from './translations/sq'; import { sq } from './translations/sq';
import { km } from './translations/km';
import { ga } from './translations/ga';
import { sr_Latn } from './translations/sr_Latn';
// https://github.com/nimbusec-oss/inferno-i18next/blob/master/tests/T.test.js#L66 // https://github.com/nimbusec-oss/inferno-i18next/blob/master/tests/T.test.js#L66
const resources = { const resources = {
@ -53,6 +56,9 @@ const resources = {
hu, hu,
uk, uk,
sq, sq,
km,
ga,
sr_Latn,
}; };
function format(value: any, format: any, lng: any): any { function format(value: any, format: any, lng: any): any {

View File

@ -25,7 +25,6 @@ import {
TransferSiteForm, TransferSiteForm,
BanUserForm, BanUserForm,
SiteForm, SiteForm,
Site,
UserView, UserView,
GetRepliesForm, GetRepliesForm,
GetUserMentionsForm, GetUserMentionsForm,
@ -57,7 +56,6 @@ export class WebSocketService {
public ws: ReconnectingWebSocket; public ws: ReconnectingWebSocket;
public subject: Observable<any>; public subject: Observable<any>;
public site: Site;
public admins: Array<UserView>; public admins: Array<UserView>;
public banned: Array<UserView>; public banned: Array<UserView>;

12
ui/src/utils.ts vendored
View File

@ -22,6 +22,9 @@ import 'moment/locale/tr';
import 'moment/locale/hu'; import 'moment/locale/hu';
import 'moment/locale/uk'; import 'moment/locale/uk';
import 'moment/locale/sq'; import 'moment/locale/sq';
import 'moment/locale/km';
import 'moment/locale/ga';
import 'moment/locale/sr';
import { import {
UserOperation, UserOperation,
@ -72,9 +75,11 @@ export const languages = [
{ code: 'eo', name: 'Esperanto' }, { code: 'eo', name: 'Esperanto' },
{ code: 'es', name: 'Español' }, { code: 'es', name: 'Español' },
{ code: 'de', name: 'Deutsch' }, { code: 'de', name: 'Deutsch' },
{ code: 'ga', name: 'Gaeilge' },
{ code: 'gl', name: 'Galego' }, { code: 'gl', name: 'Galego' },
{ code: 'hu', name: 'Magyar Nyelv' }, { code: 'hu', name: 'Magyar Nyelv' },
{ code: 'ka', name: 'ქართული ენა' }, { code: 'ka', name: 'ქართული ენა' },
{ code: 'km', name: 'ភាសាខ្មែរ' },
{ code: 'hi', name: 'मानक हिन्दी' }, { code: 'hi', name: 'मानक हिन्दी' },
{ code: 'fa', name: 'فارسی' }, { code: 'fa', name: 'فارسی' },
{ code: 'ja', name: '日本語' }, { code: 'ja', name: '日本語' },
@ -85,6 +90,7 @@ export const languages = [
{ code: 'fr', name: 'Français' }, { code: 'fr', name: 'Français' },
{ code: 'sv', name: 'Svenska' }, { code: 'sv', name: 'Svenska' },
{ code: 'sq', name: 'Shqip' }, { code: 'sq', name: 'Shqip' },
{ code: 'sr_Latn', name: 'srpski' },
{ code: 'tr', name: 'Türkçe' }, { code: 'tr', name: 'Türkçe' },
{ code: 'uk', name: 'Українська Mова' }, { code: 'uk', name: 'Українська Mова' },
{ code: 'ru', name: 'Русский' }, { code: 'ru', name: 'Русский' },
@ -418,6 +424,12 @@ export function getMomentLanguage(): string {
lang = 'uk'; lang = 'uk';
} else if (lang.startsWith('sq')) { } else if (lang.startsWith('sq')) {
lang = 'sq'; lang = 'sq';
} else if (lang.startsWith('km')) {
lang = 'km';
} else if (lang.startsWith('ga')) {
lang = 'ga';
} else if (lang.startsWith('sr')) {
lang = 'sr';
} else { } else {
lang = 'en'; lang = 'en';
} }

2
ui/src/version.ts vendored
View File

@ -1 +1 @@
export const version: string = 'v0.7.12'; export const version: string = 'v0.7.13';

1
ui/translations/ga.json vendored 100644
View File

@ -0,0 +1 @@
{}

1
ui/translations/km.json vendored 100644
View File

@ -0,0 +1 @@
{}

1
ui/translations/sr_Latn.json vendored 100644
View File

@ -0,0 +1 @@
{}

View File

@ -4,13 +4,15 @@
"no_posts": "Inga inlägg.", "no_posts": "Inga inlägg.",
"create_a_post": "Skriv ett inlägg", "create_a_post": "Skriv ett inlägg",
"create_post": "Skapa inlägg", "create_post": "Skapa inlägg",
"number_of_posts": "{{count}} inlägg", "number_of_posts": "{{count}} Inlägg",
"number_of_posts_plural": "{{count}} Inlägg",
"posts": "Inlägg", "posts": "Inlägg",
"related_posts": "Dessa inlägg kan vara relaterade", "related_posts": "Dessa inlägg kan vara relaterade",
"cross_posts": "Den här länken har även publicerats i:", "cross_posts": "Den här länken har även publicerats i:",
"cross_post": "tvärinlägg", "cross_post": "tvärposta",
"comments": "Kommentarer", "comments": "Kommentarer",
"number_of_comments": "{{count}} kommentarer", "number_of_comments": "{{count}} Kommentar",
"number_of_comments_plural": "{{count}} Kommentarer",
"remove_comment": "Radera kommentar", "remove_comment": "Radera kommentar",
"communities": "Gemenskaper", "communities": "Gemenskaper",
"users": "Användare", "users": "Användare",
@ -20,7 +22,8 @@
"subscribed_to_communities": "Prenumererar på <1>gemenskaper</1>", "subscribed_to_communities": "Prenumererar på <1>gemenskaper</1>",
"trending_communities": "Populära <1>gemenskaper</1>", "trending_communities": "Populära <1>gemenskaper</1>",
"list_of_communities": "Lista över gemenskaper", "list_of_communities": "Lista över gemenskaper",
"number_of_communities": "{{count}} gemenskaper", "number_of_communities": "{{count}} Gemenskap",
"number_of_communities_plural": "{{count}} Gemenskaper",
"community_reqs": "gemener, understreck och inga blanksteg.", "community_reqs": "gemener, understreck och inga blanksteg.",
"edit": "redigera", "edit": "redigera",
"reply": "svara", "reply": "svara",
@ -46,33 +49,36 @@
"remove_as_admin": "tag bort som administratör", "remove_as_admin": "tag bort som administratör",
"appoint_as_admin": "lägg till som administratör", "appoint_as_admin": "lägg till som administratör",
"remove": "ta bort", "remove": "ta bort",
"removed": "borttagen", "removed": "borttagen av moderator",
"locked": "låst", "locked": "låst",
"stickied": "fastnålad", "stickied": "fastnålad",
"reason": "Anledning", "reason": "Anledning",
"mark_as_read": "markera som läst", "mark_as_read": "markera som läst",
"mark_as_unread": "markera som oläst", "mark_as_unread": "markera som oläst",
"delete": "radera", "delete": "radera",
"deleted": "raderad", "deleted": "raderad av skapare",
"delete_account": "Ta bort konto", "delete_account": "Ta bort konto",
"delete_account_confirm": "delete_account_confirm": "Varning: den här åtgärden kommer radera alla dina data permanent. Skriv in ditt lösenord för att bekräfta.",
"Varning: den här åtgärden kommer radera alla dina data permanent. Är du säker?",
"restore": "återställ", "restore": "återställ",
"ban": "blockera", "ban": "blockera",
"ban_from_site": "blockera från webbplats", "ban_from_site": "blockera från webbplats",
"unban": "ta bort blockering", "unban": "ta bort blockering",
"unban_from_site": "ta bort blockering från webbplats", "unban_from_site": "ta bort blockering från webbplats",
"banned": "blocerad", "banned": "blockerad",
"save": "spara", "save": "spara",
"unsave": "förkasta", "unsave": "förkasta",
"create": "skapa", "create": "skapa",
"creator": "skapare", "creator": "skapare",
"username": "Användarnamn", "username": "Användarnamn",
"email_or_username": "E-postadress eller användarnamn", "email_or_username": "E-postadress eller användarnamn",
"number_of_users": "{{count}} användare", "number_of_users": "{{count}} Användare",
"number_of_subscribers": "{{count}} prenumeranter", "number_of_users_plural": "{{count}} Användare",
"number_of_points": "{{count}} poäng", "number_of_subscribers": "{{count}} Prenumerant",
"number_online": "{{count}} användare inloggade", "number_of_subscribers_plural": "{{count}} Prenumeranter",
"number_of_points": "{{count}} Poäng",
"number_of_points_plural": "{{count}} Poäng",
"number_online": "{{count}} Användare inloggad",
"number_online_plural": "{{count}} Användare inloggade",
"name": "Namn", "name": "Namn",
"title": "Titel", "title": "Titel",
"category": "Kategori", "category": "Kategori",
@ -108,8 +114,7 @@
"login_sign_up": "Logga in eller skapa konto", "login_sign_up": "Logga in eller skapa konto",
"login": "Logga in", "login": "Logga in",
"sign_up": "Skapa konto", "sign_up": "Skapa konto",
"notifications_error": "notifications_error": "Din webbläsare har inte stöd för skrivbordsaviseringar. Testa Firefox eller Chrome.",
"Din webbläsare har inte stöd för skrivbordsaviseringar. Testa Firefox eller Chrome.",
"unread_messages": "Olästa meddelanden", "unread_messages": "Olästa meddelanden",
"password": "Lösenord", "password": "Lösenord",
"verify_password": "Bekräfta lösenord", "verify_password": "Bekräfta lösenord",
@ -135,11 +140,9 @@
"theme": "Utseende", "theme": "Utseende",
"sponsors": "Sponsorer", "sponsors": "Sponsorer",
"sponsors_of_lemmy": "Lemmys sponsorer", "sponsors_of_lemmy": "Lemmys sponsorer",
"sponsor_message": "sponsor_message": "Lemmy är fri mjukvara med <1>öppen källkod</1>, vilket innebär att ingen reklam, vinstindrivning eller venturekapital förekommer, någonsin. Dina donationer går direkt till att stöda utvecklingen av projektet. Stort tack till följande personer:",
"Lemmy är fri mjukvara med <1>öppen källkod</1>, vilket innebär att ingen reklam, vinstindrivning eller venturekapital förekommer, någonsin. Dina donationer går direkt till att stöda utvecklingen av projektet. Stort tack till följande personer:",
"support_on_patreon": "Stöd på Patreon", "support_on_patreon": "Stöd på Patreon",
"general_sponsors": "general_sponsors": "Allmänna sponsorer är de som donerat mellan 10 och 39 dollar till Lemmy.",
"Allmänna sponsorer är dem som givit mellan 10 och 39\u00a0dollar till Lemmy.",
"crypto": "Kryptovaluta", "crypto": "Kryptovaluta",
"bitcoin": "Bitcoin", "bitcoin": "Bitcoin",
"ethereum": "Ethereum", "ethereum": "Ethereum",
@ -154,16 +157,15 @@
"yes": "ja", "yes": "ja",
"no": "nej", "no": "nej",
"powered_by": "Drivs av", "powered_by": "Drivs av",
"landing_0": "landing_0": "Lemmy är en <1>länksamlare</1> och alternativ till reddit, ämnad att fungera i <2>Fediversumet</2>.<3></3>Lemmy kan drivas av vem som helst, har kommentarstrådar som updateras i realid och är mycket liten (<4>ca 80 kB</4>). Federering med ActivityPub-nätverket är planerat. <5></5>Detta är en <6>väldigt tidig betaversion</6> och många funktioner saknas därför eller är trasiga.<7></7>Föreslå nya funktioner eller anmäl buggar <8>här</8>.<9></9>Skapad i <10>Rust</10>, <11>Actix</11>, <12>Inferno</12> och <13>Typescript</13>.",
"Lemmy är en <1>länksamlare</1> och alternativ till reddit, ämnad att fungera i <2>Fediversumet</2>.<3></3>Lemmy kan drivas av vem som helst, har kommentarstrådar som updateras i realid och är mycket liten (<4>ca 80\u00a0kB</4>). Federering med ActivityPub-nätverket är planerat. <5></5>Detta är en <6>väldigt tidig betaversion</6> och många funktioner saknas därför eller är trasiga.<7></7>Föreslå nya funktioner eller anmäl buggar <8>här</8>.<9></9>Skapad i <10>Rust</10>, <11>Actix</11>, <12>Inferno</12> och <13>Typescript</13>.",
"not_logged_in": "Inte inloggad.", "not_logged_in": "Inte inloggad.",
"community_ban": "Du har blockerats från den här gemenskapen.", "community_ban": "Du har blockerats från den här gemenskapen.",
"site_ban": "Du har blockerats från webbplatsen.", "site_ban": "Du har blockerats från webbplatsen",
"couldnt_create_comment": "Kunde inte skapa kommentar.", "couldnt_create_comment": "Kunde inte skapa kommentar.",
"couldnt_like_comment": "Kunde inte gilla kommentar.", "couldnt_like_comment": "Kunde inte gilla kommentar.",
"couldnt_update_comment": "Kunde inte uppdatera kommentar.", "couldnt_update_comment": "Kunde inte uppdatera kommentar.",
"couldnt_save_comment": "Kunde inte spara kommentar.", "couldnt_save_comment": "Kunde inte spara kommentar.",
"no_comment_edit_allowed": "Har inte behörighet att redigera komentar.", "no_comment_edit_allowed": "Har inte behörighet att redigera kommentar.",
"no_post_edit_allowed": "Har inte behörighet att redigera inlägg.", "no_post_edit_allowed": "Har inte behörighet att redigera inlägg.",
"no_community_edit_allowed": "Har inte behörighet att redigera gemenskap.", "no_community_edit_allowed": "Har inte behörighet att redigera gemenskap.",
"couldnt_find_community": "Kunde inte hitta gemenskap.", "couldnt_find_community": "Kunde inte hitta gemenskap.",
@ -175,19 +177,84 @@
"couldnt_create_post": "Kunde inte skapa inlägg.", "couldnt_create_post": "Kunde inte skapa inlägg.",
"couldnt_like_post": "Kunde inte gilla inlägg.", "couldnt_like_post": "Kunde inte gilla inlägg.",
"couldnt_find_post": "Kunde inte hitta inlägg.", "couldnt_find_post": "Kunde inte hitta inlägg.",
"couldnt_get_posts": "Kunde inte hämta inlägg.", "couldnt_get_posts": "Kunde inte hämta inlägg",
"couldnt_update_post": "Kunde inte uppdatera inlägg.", "couldnt_update_post": "Kunde inte uppdatera inlägg",
"couldnt_save_post": "Kunde inte spara inlägg.", "couldnt_save_post": "Kunde inte spara inlägg.",
"no_slurs": "Inga förolämpningar.", "no_slurs": "Inga förolämpningar.",
"not_an_admin": "Inte en administratör.", "not_an_admin": "Inte en administratör.",
"site_already_exists": "Webbplatsen finns redan.", "site_already_exists": "Webbplatsen finns redan.",
"couldnt_update_site": "Kunde inte uppdatera webbplats.", "couldnt_update_site": "Kunde inte uppdatera webbplats.",
"couldnt_find_that_username_or_email": "couldnt_find_that_username_or_email": "Kunde inte hitta det användarnamnet eller e-postadressen.",
"Kunde inte hitta det användarnamnet eller e-postadressen.",
"password_incorrect": "Ogiltigt lösenord.", "password_incorrect": "Ogiltigt lösenord.",
"passwords_dont_match": "Lösenorden stämmer inte överens.", "passwords_dont_match": "Lösenorden stämmer inte överens.",
"admin_already_created": "Beklagar, men det finns redan en administratör.", "admin_already_created": "Beklagar, men det finns redan en administratör.",
"user_already_exists": "Användaren finns redan.", "user_already_exists": "Användaren finns redan.",
"couldnt_update_user": "Kunde inte uppdatera användare.", "couldnt_update_user": "Kunde inte uppdatera användare.",
"system_err_login": "Systemfel. Försök att logga ut och sedan in igen." "system_err_login": "Systemfel. Försök att logga ut och sedan in igen.",
"invalid_community_name": "Ogiltigt namn.",
"click_to_delete_picture": "Klicka för att ta bort bild.",
"picture_deleted": "Bild borttagen.",
"upload_avatar": "Ladda upp avatar",
"enable_nsfw": "Aktivera NSFW",
"sorting_help": "sorteringshjälp",
"more": "mer",
"avatar": "Avatar",
"cross_posted_to": "Tvärpostat till: ",
"send_secure_message": "Skicka säkert meddelande",
"send_message": "Skicka meddelande",
"message": "Meddelande",
"create_private_message": "Skapa Privatmeddelande",
"show_avatars": "Visa avatarer",
"archive_link": "Arkivera länk",
"admin_settings": "Administratörsinställningar",
"site_config": "Webbplats konfiguration",
"old": "Gammal",
"banned_users": "Blockerade användare",
"docs": "Dokumentation",
"post_title_too_long": "Inläggstitel är för lång.",
"replies": "Svar",
"mentions": "Nämner",
"message_sent": "Meddelande skickat",
"messages": "Meddelanden",
"old_password": "Gammalt lösenord",
"reset_password_mail_sent": "Skicka e-post för att återställa ditt lösenord.",
"forgot_password": "Glömt lösenord",
"password_change": "Lösenordsbyte",
"new_password": "Nytt lösenord",
"no_email_setup": "Denna server har inte satt upp e-post korrekt.",
"matrix_user_id": "Matrix-användare",
"show_context": "Visa innehåll",
"private_message_disclaimer": "Varning: Privata meddelanden på Lemmy är inte säkra. Vänligen skapa ett konto på <1>Riot.im</1> för att skicka säkra meddelanden.",
"send_notifications_to_email": "Skicka aviseringar till E-post",
"language": "Språk",
"browser_default": "Webbläsarestandard",
"downvotes_disabled": "Nedröstningar inaktiverat",
"enable_downvotes": "Aktivera nedröstningar",
"upvote": "Upprösta",
"number_of_upvotes": "{{count}} Uppröst",
"number_of_upvotes_plural": "{{count}} Uppröstningar",
"downvote": "Nedrösta",
"number_of_downvotes": "{{count}} Nedröst",
"number_of_downvotes_plural": "{{count}} Nedröstningar",
"open_registration": "Öppen registrering",
"registration_closed": "Registrering stängd",
"support_on_liberapay": "Stöd på Liberapay",
"support_on_open_collective": "Stöd på OpenCollective",
"donate_to_lemmy": "Donera till Lemmy",
"donate": "Donera",
"silver_sponsors": "Silversponsor är de som donerat 40 dollar till Lemmy.",
"logged_in": "Inloggad.",
"site_saved": "Webbplats sparad.",
"couldnt_get_comments": "Kunde inte hämta kommentarer.",
"action": "Åtgärd",
"email_already_exists": "E-post finns redan.",
"couldnt_create_private_message": "Kunde inte skapa privat meddelande.",
"no_private_message_edit_allowed": "Inte tillåtet att redigera privata meddelanden.",
"couldnt_update_private_message": "Kunde inte uppdatera privat meddelande.",
"time": "Tid",
"emoji_picker": "Emoji-väljare",
"block_leaving": "Är du säker på att du vill lämna?",
"select_a_community": "Välj en gemenskap",
"from": "från",
"invalid_username": "Ogiltigt användarnamn."
} }

View File

@ -27,9 +27,9 @@
"mod": "社群管理", "mod": "社群管理",
"mods": "社群管理", "mods": "社群管理",
"moderates": "监管", "moderates": "监管",
"remove_as_mod": "删除社群管理", "remove_as_mod": "删除社群管理权限",
"appoint_as_mod": "任命为社群管理", "appoint_as_mod": "任命为社群管理",
"modlog": "审核记录", "modlog": "管理记录",
"admin": "总管理员", "admin": "总管理员",
"admins": "总管理员", "admins": "总管理员",
"remove_as_admin": "移除管理员权限", "remove_as_admin": "移除管理员权限",
@ -55,8 +55,8 @@
"number_of_users": "{{count}} 名用户", "number_of_users": "{{count}} 名用户",
"number_of_subscribers": "{{count}} 名订阅者", "number_of_subscribers": "{{count}} 名订阅者",
"number_of_points": "{{count}} 积分", "number_of_points": "{{count}} 积分",
"name": "名", "name": "名",
"title": "标", "title": "标",
"category": "分类", "category": "分类",
"subscribers": "订阅", "subscribers": "订阅",
"both": "全部", "both": "全部",
@ -66,11 +66,11 @@
"subscribed": "已订阅", "subscribed": "已订阅",
"prev": "上一页", "prev": "上一页",
"next": "下一页", "next": "下一页",
"sidebar": "侧边栏", "sidebar": "介绍",
"sort_type": "排序方式", "sort_type": "排序方式",
"hot": "最热", "hot": "最热",
"new": "最新", "new": "最新",
"top_day": "推荐", "top_day": "日",
"week": "周", "week": "周",
"month": "月", "month": "月",
"year": "年", "year": "年",
@ -82,7 +82,7 @@
"mark_all_as_read": "标记所有已读", "mark_all_as_read": "标记所有已读",
"type": "类型", "type": "类型",
"unread": "未读", "unread": "未读",
"reply_sent": "回复发送", "reply_sent": "回复发送",
"search": "搜索", "search": "搜索",
"overview": "个人中心", "overview": "个人中心",
"view": "查看", "view": "查看",
@ -168,10 +168,10 @@
"yes": "是", "yes": "是",
"no": "否", "no": "否",
"logged_in": "已登录。", "logged_in": "已登录。",
"message": "息", "message": "息",
"create_private_message": "创建私信", "create_private_message": "创建私信",
"send_secure_message": "发送安全息", "send_secure_message": "发送安全息",
"send_message": "发送息", "send_message": "发送息",
"more": "更多", "more": "更多",
"preview": "预览", "preview": "预览",
"upload_image": "上传图片", "upload_image": "上传图片",
@ -184,7 +184,7 @@
"sticky": "固定", "sticky": "固定",
"unsticky": "取消固定", "unsticky": "取消固定",
"archive_link": "链接归档", "archive_link": "链接归档",
"settings": "设", "settings": "设",
"stickied": "已置顶", "stickied": "已置顶",
"delete_account": "删除账号", "delete_account": "删除账号",
"delete_account_confirm": "警告!此操作将永久删除你的数据,请输入密码进行确认。", "delete_account_confirm": "警告!此操作将永久删除你的数据,请输入密码进行确认。",
@ -201,7 +201,7 @@
"replies": "回复", "replies": "回复",
"number_online": "{{count}} 名在线用户", "number_online": "{{count}} 名在线用户",
"mentions": "提到", "mentions": "提到",
"message_sent": "已发送信息", "message_sent": "消息已发送",
"old_password": "当前密码", "old_password": "当前密码",
"forgot_password": "忘记密码", "forgot_password": "忘记密码",
"reset_password_mail_sent": "发送邮件重置密码。", "reset_password_mail_sent": "发送邮件重置密码。",
@ -223,7 +223,7 @@
"open_registration": "开放注册", "open_registration": "开放注册",
"registration_closed": "注册功能已关闭", "registration_closed": "注册功能已关闭",
"recent_comments": "最新评论", "recent_comments": "最新评论",
"by": "", "by": " ",
"transfer_community": "转让社群", "transfer_community": "转让社群",
"transfer_site": "站点转让", "transfer_site": "站点转让",
"post_title_too_long": "帖子标题过长。", "post_title_too_long": "帖子标题过长。",
@ -233,7 +233,7 @@
"no_private_message_edit_allowed": "没有编辑私信的权限。", "no_private_message_edit_allowed": "没有编辑私信的权限。",
"couldnt_update_private_message": "无法更新私信。", "couldnt_update_private_message": "无法更新私信。",
"time": "时间", "time": "时间",
"action": "动", "action": "",
"block_leaving": "确定要离开吗?", "block_leaving": "确定要离开吗?",
"show_context": "显示上下文", "show_context": "显示上下文",
"admin_settings": "管理员设置", "admin_settings": "管理员设置",