This commit is contained in:
Didier Link
2018-06-21 12:38:00 +02:00
29 changed files with 319 additions and 215 deletions
+2 -2
View File
@@ -40,8 +40,8 @@ pub trait FromActivity<T: Object>: Sized {
}
}
pub trait Notify<T: Object> {
fn notify(conn: &PgConnection, act: T, actor: Id);
pub trait Notify {
fn notify(&self, conn: &PgConnection);
}
pub trait Deletable {
+4 -2
View File
@@ -1,10 +1,12 @@
use diesel::{
pg::PgConnection,
r2d2::{ConnectionManager, Pool, PooledConnection}
r2d2::{ConnectionManager, PooledConnection}
};
use rocket::{Request, State, Outcome, http::Status, request::{self, FromRequest}};
use std::ops::Deref;
use setup::PgPool;
// From rocket documentation
// Connection request guard type: a wrapper around an r2d2 pooled connection.
@@ -17,7 +19,7 @@ impl<'a, 'r> FromRequest<'a, 'r> for DbConn {
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
let pool = request.guard::<State<Pool<ConnectionManager<PgConnection>>>>()?;
let pool = request.guard::<State<PgPool>>()?;
match pool.get() {
Ok(conn) => Outcome::Success(DbConn(conn)),
Err(_) => Outcome::Failure((Status::ServiceUnavailable, ()))
+2 -2
View File
@@ -1,4 +1,4 @@
#![feature(plugin, custom_derive, decl_macro, iterator_find_map)]
#![feature(plugin, custom_derive, decl_macro, iterator_find_map, iterator_flatten)]
#![plugin(rocket_codegen)]
extern crate activitypub;
@@ -8,7 +8,6 @@ extern crate base64;
extern crate bcrypt;
extern crate chrono;
extern crate colored;
extern crate comrak;
extern crate failure;
#[macro_use]
extern crate failure_derive;
@@ -23,6 +22,7 @@ extern crate dotenv;
#[macro_use]
extern crate lazy_static;
extern crate openssl;
extern crate pulldown_cmark;
extern crate reqwest;
extern crate rocket;
extern crate rocket_contrib;
+24 -18
View File
@@ -1,5 +1,6 @@
use activitypub::{
activity::Create,
link,
object::{Note, properties::ObjectProperties}
};
use chrono;
@@ -13,6 +14,7 @@ use activity_pub::{
};
use models::{
instance::Instance,
mentions::Mention,
notifications::*,
posts::Post,
users::User
@@ -114,6 +116,16 @@ impl FromActivity<Note> for Comment {
fn from_activity(conn: &PgConnection, note: Note, actor: Id) -> Comment {
let previous_url = note.object_props.in_reply_to.clone().unwrap().as_str().unwrap().to_string();
let previous_comment = Comment::find_by_ap_url(conn, previous_url.clone());
// save mentions
if let Some(serde_json::Value::Array(tags)) = note.object_props.tag.clone() {
for tag in tags.into_iter() {
serde_json::from_value::<link::Mention>(tag)
.map(|m| Mention::from_activity(conn, m, Id::new(note.clone().object_props.clone().url_string().unwrap_or(String::from("")))))
.ok();
}
}
let comm = Comment::insert(conn, NewComment {
content: SafeString::new(&note.object_props.content_string().unwrap()),
spoiler_text: note.object_props.summary_string().unwrap_or(String::from("")),
@@ -125,27 +137,21 @@ impl FromActivity<Note> for Comment {
author_id: User::from_url(conn, actor.clone().into()).unwrap().id,
sensitive: false // "sensitive" is not a standard property, we need to think about how to support it with the activitypub crate
});
Comment::notify(conn, note, actor);
comm.notify(conn);
comm
}
}
impl Notify<Note> for Comment {
fn notify(conn: &PgConnection, note: Note, _actor: Id) {
match Comment::find_by_ap_url(conn, note.object_props.id_string().unwrap()) {
Some(comment) => {
for author in comment.clone().get_post(conn).get_authors(conn) {
let comment = comment.clone();
Notification::insert(conn, NewNotification {
title: "{{ data }} commented your article".to_string(),
data: Some(comment.get_author(conn).display_name.clone()),
content: Some(comment.get_post(conn).title),
link: comment.ap_url,
user_id: author.id
});
}
},
None => println!("Couldn't find comment by AP id, to create a new notification")
};
impl Notify for Comment {
fn notify(&self, conn: &PgConnection) {
for author in self.get_post(conn).get_authors(conn) {
Notification::insert(conn, NewNotification {
title: "{{ data }} commented your article".to_string(),
data: Some(self.get_author(conn).display_name.clone()),
content: Some(self.get_post(conn).title),
link: self.ap_url.clone(),
user_id: author.id
});
}
}
}
+4 -4
View File
@@ -62,15 +62,15 @@ impl FromActivity<FollowAct> for Follow {
}
}
impl Notify<FollowAct> for Follow {
fn notify(conn: &PgConnection, follow: FollowAct, actor: Id) {
let follower = User::from_url(conn, actor.into()).unwrap();
impl Notify for Follow {
fn notify(&self, conn: &PgConnection) {
let follower = User::get(conn, self.follower_id).unwrap();
Notification::insert(conn, NewNotification {
title: "{{ data }} started following you".to_string(),
data: Some(follower.display_name.clone()),
content: None,
link: Some(follower.ap_url),
user_id: User::from_url(conn, follow.follow_props.object_link::<Id>().unwrap().into()).unwrap().id
user_id: self.following_id
});
}
}
+6 -6
View File
@@ -77,7 +77,7 @@ impl Like {
}
impl FromActivity<activity::Like> for Like {
fn from_activity(conn: &PgConnection, like: activity::Like, actor: Id) -> Like {
fn from_activity(conn: &PgConnection, like: activity::Like, _actor: Id) -> Like {
let liker = User::from_url(conn, like.like_props.actor.as_str().unwrap().to_string());
let post = Post::find_by_ap_url(conn, like.like_props.object.as_str().unwrap().to_string());
let res = Like::insert(conn, NewLike {
@@ -85,15 +85,15 @@ impl FromActivity<activity::Like> for Like {
user_id: liker.unwrap().id,
ap_url: like.object_props.id_string().unwrap_or(String::from(""))
});
Like::notify(conn, like, actor);
res.notify(conn);
res
}
}
impl Notify<activity::Like> for Like {
fn notify(conn: &PgConnection, like: activity::Like, actor: Id) {
let liker = User::from_url(conn, actor.into()).unwrap();
let post = Post::find_by_ap_url(conn, like.like_props.object_link::<Id>().unwrap().into()).unwrap();
impl Notify for Like {
fn notify(&self, conn: &PgConnection) {
let liker = User::get(conn, self.user_id).unwrap();
let post = Post::get(conn, self.post_id).unwrap();
for author in post.get_authors(conn) {
let post = post.clone();
Notification::insert(conn, NewNotification {
+113
View File
@@ -0,0 +1,113 @@
use activitypub::link;
use diesel::{self, PgConnection, QueryDsl, RunQueryDsl, ExpressionMethods};
use activity_pub::{Id, inbox::Notify};
use models::{
comments::Comment,
notifications::*,
posts::Post,
users::User
};
use schema::mentions;
#[derive(Queryable, Identifiable)]
pub struct Mention {
pub id: i32,
pub mentioned_id: i32,
pub post_id: Option<i32>,
pub comment_id: Option<i32>,
pub ap_url: String
}
#[derive(Insertable)]
#[table_name = "mentions"]
pub struct NewMention {
pub mentioned_id: i32,
pub post_id: Option<i32>,
pub comment_id: Option<i32>,
pub ap_url: String
}
impl Mention {
insert!(mentions, NewMention);
get!(mentions);
find_by!(mentions, find_by_ap_url, ap_url as String);
list_by!(mentions, list_for_user, mentioned_id as i32);
list_by!(mentions, list_for_post, post_id as i32);
pub fn get_mentioned(&self, conn: &PgConnection) -> Option<User> {
User::get(conn, self.mentioned_id)
}
pub fn get_post(&self, conn: &PgConnection) -> Option<Post> {
self.post_id.and_then(|id| Post::get(conn, id))
}
pub fn get_comment(&self, conn: &PgConnection) -> Option<Comment> {
self.post_id.and_then(|id| Comment::get(conn, id))
}
pub fn build_activity(conn: &PgConnection, ment: String) -> link::Mention {
let user = User::find_by_fqn(conn, ment.clone());
println!("building act : {} -> {:?}", ment, user);
let mut mention = link::Mention::default();
mention.link_props.set_href_string(user.clone().map(|u| u.ap_url).unwrap_or(String::new())).expect("Error setting mention's href");
mention.link_props.set_name_string(format!("@{}", ment)).expect("Error setting mention's name");
mention
}
pub fn to_activity(&self, conn: &PgConnection) -> link::Mention {
let user = self.get_mentioned(conn);
let mut mention = link::Mention::default();
mention.link_props.set_href_string(user.clone().map(|u| u.ap_url).unwrap_or(String::new())).expect("Error setting mention's href");
mention.link_props.set_name_string(user.map(|u| format!("@{}", u.get_fqn(conn))).unwrap_or(String::new())).expect("Error setting mention's name");
mention
}
pub fn from_activity(conn: &PgConnection, ment: link::Mention, inside: Id) -> Option<Self> {
let ap_url = ment.link_props.href_string().unwrap();
let mentioned = User::find_by_ap_url(conn, ap_url).unwrap();
if let Some(post) = Post::find_by_ap_url(conn, inside.clone().into()) {
let res = Mention::insert(conn, NewMention {
mentioned_id: mentioned.id,
post_id: Some(post.id),
comment_id: None,
ap_url: ment.link_props.href_string().unwrap_or(String::new())
});
res.notify(conn);
Some(res)
} else {
if let Some(comment) = Comment::find_by_ap_url(conn, inside.into()) {
let res = Mention::insert(conn, NewMention {
mentioned_id: mentioned.id,
post_id: None,
comment_id: Some(comment.id),
ap_url: ment.link_props.href_string().unwrap_or(String::new())
});
res.notify(conn);
Some(res)
} else {
None
}
}
}
}
impl Notify for Mention {
fn notify(&self, conn: &PgConnection) {
let author = self.get_comment(conn)
.map(|c| c.get_author(conn).display_name.clone())
.unwrap_or(self.get_post(conn).unwrap().get_authors(conn)[0].display_name.clone());
self.get_mentioned(conn).map(|m| {
Notification::insert(conn, NewNotification {
title: "{{ data }} mentioned you.".to_string(),
data: Some(author),
content: None,
link: Some(self.get_post(conn).map(|p| p.ap_url).unwrap_or_else(|| self.get_comment(conn).unwrap().ap_url.unwrap_or(String::new()))),
user_id: m.id
});
});
}
}
+13
View File
@@ -12,6 +12,18 @@ macro_rules! find_by {
};
}
macro_rules! list_by {
($table:ident, $fn:ident, $($col:ident as $type:ident),+) => {
/// Try to find a $table with a given $col
pub fn $fn(conn: &PgConnection, $($col: $type),+) -> Vec<Self> {
$table::table
$(.filter($table::$col.eq($col)))+
.load::<Self>(conn)
.expect("Error loading $table by $col")
}
};
}
macro_rules! get {
($table:ident) => {
pub fn get(conn: &PgConnection, id: i32) -> Option<Self> {
@@ -41,6 +53,7 @@ pub mod comments;
pub mod follows;
pub mod instance;
pub mod likes;
pub mod mentions;
pub mod notifications;
pub mod post_authors;
pub mod posts;
+15 -3
View File
@@ -1,5 +1,6 @@
use activitypub::{
activity::Create,
link,
object::{Article, properties::ObjectProperties}
};
use chrono::NaiveDateTime;
@@ -9,13 +10,13 @@ use serde_json;
use BASE_URL;
use activity_pub::{
PUBLIC_VISIBILTY, ap_url, Id, IntoId,
actor::Actor,
inbox::FromActivity
};
use models::{
blogs::Blog,
instance::Instance,
likes::Like,
mentions::Mention,
post_authors::PostAuthor,
reshares::Reshare,
users::User
@@ -144,6 +145,8 @@ impl Post {
let mut to = self.get_receivers_urls(conn);
to.push(PUBLIC_VISIBILTY.to_string());
let mentions = Mention::list_for_post(conn, self.id).into_iter().map(|m| m.to_activity(conn)).collect::<Vec<link::Mention>>();
let mut article = Article::default();
article.object_props = ObjectProperties {
name: Some(serde_json::to_value(self.title.clone()).unwrap()),
@@ -151,11 +154,11 @@ impl Post {
attributed_to: Some(serde_json::to_value(self.get_authors(conn).into_iter().map(|x| x.ap_url).collect::<Vec<String>>()).unwrap()),
content: Some(serde_json::to_value(self.content.clone()).unwrap()),
published: Some(serde_json::to_value(self.creation_date).unwrap()),
tag: Some(serde_json::to_value(Vec::<serde_json::Value>::new()).unwrap()),
tag: Some(serde_json::to_value(mentions).unwrap()),
url: Some(serde_json::to_value(self.compute_id(conn)).unwrap()),
to: Some(serde_json::to_value(to).unwrap()),
cc: Some(serde_json::to_value(Vec::<serde_json::Value>::new()).unwrap()),
..ObjectProperties::default()
..ObjectProperties::default()
};
article
}
@@ -184,6 +187,15 @@ impl Post {
impl FromActivity<Article> for Post {
fn from_activity(conn: &PgConnection, article: Article, _actor: Id) -> Post {
// save mentions
if let Some(serde_json::Value::Array(tags)) = article.object_props.tag.clone() {
for tag in tags.into_iter() {
serde_json::from_value::<link::Mention>(tag)
.map(|m| Mention::from_activity(conn, m, Id::new(article.clone().object_props.clone().url_string().unwrap_or(String::from("")))))
.ok();
}
}
Post::insert(conn, NewPost {
blog_id: 0, // TODO
slug: String::from(""), // TODO
+6 -6
View File
@@ -73,7 +73,7 @@ impl Reshare {
}
impl FromActivity<Announce> for Reshare {
fn from_activity(conn: &PgConnection, announce: Announce, actor: Id) -> Reshare {
fn from_activity(conn: &PgConnection, announce: Announce, _actor: Id) -> Reshare {
let user = User::from_url(conn, announce.announce_props.actor.as_str().unwrap().to_string());
let post = Post::find_by_ap_url(conn, announce.announce_props.object.as_str().unwrap().to_string());
let reshare = Reshare::insert(conn, NewReshare {
@@ -81,15 +81,15 @@ impl FromActivity<Announce> for Reshare {
user_id: user.unwrap().id,
ap_url: announce.object_props.id_string().unwrap_or(String::from(""))
});
Reshare::notify(conn, announce, actor);
reshare.notify(conn);
reshare
}
}
impl Notify<Announce> for Reshare {
fn notify(conn: &PgConnection, announce: Announce, actor: Id) {
let actor = User::from_url(conn, actor.into()).unwrap();
let post = Post::find_by_ap_url(conn, announce.announce_props.object_link::<Id>().unwrap().into()).unwrap();
impl Notify for Reshare {
fn notify(&self, conn: &PgConnection) {
let actor = User::get(conn, self.user_id).unwrap();
let post = self.get_post(conn).unwrap();
for author in post.get_authors(conn) {
let post = post.clone();
Notification::insert(conn, NewNotification {
+10 -18
View File
@@ -47,7 +47,7 @@ use safe_string::SafeString;
pub const AUTH_COOKIE: &'static str = "user_id";
#[derive(Queryable, Identifiable, Serialize, Deserialize, Clone)]
#[derive(Queryable, Identifiable, Serialize, Deserialize, Clone, Debug)]
pub struct User {
pub id: i32,
pub username: String,
@@ -89,7 +89,7 @@ impl User {
get!(users);
find_by!(users, find_by_email, email as String);
find_by!(users, find_by_name, username as String, instance_id as i32);
find_by!(users, find_by_ap_url, ap_url as String);
pub fn grant_admin_rights(&self, conn: &PgConnection) {
diesel::update(self)
@@ -419,23 +419,15 @@ impl APActor for User {
}
fn from_url(conn: &PgConnection, url: String) -> Option<User> {
let in_db = users::table.filter(users::ap_url.eq(url.clone()))
.limit(1)
.load::<User>(conn)
.expect("Error loading user by AP url")
.into_iter().nth(0);
match in_db {
Some(u) => Some(u),
None => {
// The requested user was not in the DB
// We try to fetch it if it is remote
if Url::parse(url.as_ref()).unwrap().host_str().unwrap() != BASE_URL.as_str() {
Some(User::fetch_from_url(conn, url).unwrap())
} else {
None
}
User::find_by_ap_url(conn, url.clone()).or_else(|| {
// The requested user was not in the DB
// We try to fetch it if it is remote
if Url::parse(url.as_ref()).unwrap().host_str().unwrap() != BASE_URL.as_str() {
Some(User::fetch_from_url(conn, url).unwrap())
} else {
None
}
}
})
}
}
+3 -3
View File
@@ -4,7 +4,7 @@ use rocket::{
};
use rocket_contrib::Template;
use activity_pub::{broadcast, IntoId, inbox::Notify};
use activity_pub::{broadcast, inbox::Notify};
use db_conn::DbConn;
use models::{
blogs::Blog,
@@ -53,12 +53,12 @@ fn create(blog_name: String, slug: String, query: CommentQuery, data: Form<NewCo
in_response_to_id: query.responding_to,
post_id: post.id,
author_id: user.id,
ap_url: None,
ap_url: None, // TODO: set it
sensitive: false,
spoiler_text: "".to_string()
});
comment.notify(&*conn);
Comment::notify(&*conn, comment.into_activity(&*conn), user.clone().into_id());
broadcast(&*conn, &user, comment.create_activity(&*conn), user.get_followers(&*conn));
Redirect::to(format!("/~/{}/{}/#comment-{}", blog_name, slug, comment.id))
+2 -2
View File
@@ -1,6 +1,6 @@
use rocket::response::{Redirect, Flash};
use activity_pub::{broadcast, IntoId, inbox::Notify};
use activity_pub::{broadcast, inbox::Notify};
use db_conn::DbConn;
use models::{
blogs::Blog,
@@ -23,8 +23,8 @@ fn create(blog: String, slug: String, user: User, conn: DbConn) -> Redirect {
ap_url: "".to_string()
});
like.update_ap_url(&*conn);
like.notify(&*conn);
likes::Like::notify(&*conn, like.into_activity(&*conn), user.clone().into_id());
broadcast(&*conn, &user, like.into_activity(&*conn), user.get_followers(&*conn));
} else {
let like = likes::Like::find_by_user_on_post(&*conn, user.id, post.id).unwrap();
+8 -16
View File
@@ -1,21 +1,21 @@
use comrak::{markdown_to_html, ComrakOptions};
use heck::KebabCase;
use rocket::request::Form;
use rocket::response::{Redirect, Flash};
use rocket_contrib::Template;
use serde_json;
use activity_pub::{broadcast, context, activity_pub, ActivityPub};
use activity_pub::{broadcast, context, activity_pub, ActivityPub, Id};
use db_conn::DbConn;
use models::{
blogs::*,
comments::Comment,
mentions::Mention,
post_authors::*,
posts::*,
users::User
};
use utils;
use safe_string::SafeString;
use utils;
#[get("/~/<blog>/<slug>", rank = 4)]
fn details(blog: String, slug: String, conn: DbConn, user: Option<User>) -> Template {
@@ -88,19 +88,7 @@ fn create(blog_name: String, data: Form<NewPostForm>, user: User, conn: DbConn)
if slug == "new" || Post::find_by_slug(&*conn, slug.clone(), blog.id).is_some() {
Redirect::to(uri!(new: blog = blog_name))
} else {
let content = markdown_to_html(form.content.to_string().as_ref(), &ComrakOptions{
smart: true,
safe: true,
ext_strikethrough: true,
ext_tagfilter: true,
ext_table: true,
ext_autolink: true,
ext_tasklist: true,
ext_superscript: true,
ext_header_ids: Some("title".to_string()),
ext_footnotes: true,
..ComrakOptions::default()
});
let (content, mentions) = utils::md_to_html(form.content.to_string().as_ref());
let post = Post::insert(&*conn, NewPost {
blog_id: blog.id,
@@ -117,6 +105,10 @@ fn create(blog_name: String, data: Form<NewPostForm>, user: User, conn: DbConn)
author_id: user.id
});
for m in mentions.into_iter() {
Mention::from_activity(&*conn, Mention::build_activity(&*conn, m), Id::new(post.compute_id(&*conn)));
}
let act = post.create_activity(&*conn);
broadcast(&*conn, &user, act, user.get_followers(&*conn));
+2 -2
View File
@@ -1,6 +1,6 @@
use rocket::response::{Redirect, Flash};
use activity_pub::{broadcast, IntoId, inbox::Notify};
use activity_pub::{broadcast, inbox::Notify};
use db_conn::DbConn;
use models::{
blogs::Blog,
@@ -23,8 +23,8 @@ fn create(blog: String, slug: String, user: User, conn: DbConn) -> Redirect {
ap_url: "".to_string()
});
reshare.update_ap_url(&*conn);
reshare.notify(&*conn);
Reshare::notify(&*conn, reshare.into_activity(&*conn), user.clone().into_id());
broadcast(&*conn, &user, reshare.into_activity(&*conn), user.get_followers(&*conn));
} else {
let reshare = Reshare::find_by_user_on_post(&*conn, user.id, post.id).unwrap();
+3 -2
View File
@@ -71,16 +71,17 @@ fn dashboard_auth() -> Flash<Redirect> {
#[get("/@/<name>/follow")]
fn follow(name: String, conn: DbConn, user: User) -> Redirect {
let target = User::find_by_fqn(&*conn, name.clone()).unwrap();
follows::Follow::insert(&*conn, follows::NewFollow {
let f = follows::Follow::insert(&*conn, follows::NewFollow {
follower_id: user.id,
following_id: target.id
});
f.notify(&*conn);
let mut act = Follow::default();
act.follow_props.set_actor_link::<Id>(user.clone().into_id()).unwrap();
act.follow_props.set_object_object(user.into_activity(&*conn)).unwrap();
act.object_props.set_id_string(format!("{}/follow/{}", user.ap_url, target.ap_url)).unwrap();
follows::Follow::notify(&*conn, act.clone(), user.clone().into_id());
broadcast(&*conn, &user, act, vec![target]);
Redirect::to(uri!(details: name = name))
}
+14
View File
@@ -66,6 +66,16 @@ table! {
}
}
table! {
mentions (id) {
id -> Int4,
mentioned_id -> Int4,
post_id -> Nullable<Int4>,
comment_id -> Nullable<Int4>,
ap_url -> Varchar,
}
}
table! {
notifications (id) {
id -> Int4,
@@ -137,6 +147,9 @@ joinable!(comments -> posts (post_id));
joinable!(comments -> users (author_id));
joinable!(likes -> posts (post_id));
joinable!(likes -> users (user_id));
joinable!(mentions -> comments (comment_id));
joinable!(mentions -> posts (post_id));
joinable!(mentions -> users (mentioned_id));
joinable!(notifications -> users (user_id));
joinable!(post_authors -> posts (post_id));
joinable!(post_authors -> users (author_id));
@@ -152,6 +165,7 @@ allow_tables_to_appear_in_same_query!(
follows,
instances,
likes,
mentions,
notifications,
post_authors,
posts,
+1 -1
View File
@@ -12,7 +12,7 @@ use db_conn::DbConn;
use models::instance::*;
use models::users::*;
type PgPool = Pool<ConnectionManager<PgConnection>>;
pub type PgPool = Pool<ConnectionManager<PgConnection>>;
/// Initializes a database pool.
fn init_pool() -> Option<PgPool> {
+50
View File
@@ -1,5 +1,6 @@
use gettextrs::gettext;
use heck::CamelCase;
use pulldown_cmark::{Event, Parser, Options, Tag, html};
use rocket::{
http::uri::Uri,
response::{Redirect, Flash}
@@ -18,3 +19,52 @@ pub fn make_actor_id(name: String) -> String {
pub fn requires_login(message: &str, url: Uri) -> Flash<Redirect> {
Flash::new(Redirect::to(Uri::new(format!("/login?m={}", gettext(message.to_string())))), "callback", url.as_str())
}
/// Returns (HTML, mentions)
pub fn md_to_html(md: &str) -> (String, Vec<String>) {
let parser = Parser::new_ext(md, Options::all());
let (parser, mentions): (Vec<Vec<Event>>, Vec<Vec<String>>) = parser.map(|evt| match evt {
Event::Text(txt) => {
let (evts, _, _, _, new_mentions) = txt.chars().fold((vec![], false, String::new(), 0, vec![]), |(mut events, in_mention, text_acc, n, mut mentions), c| {
if in_mention {
if (c.is_alphanumeric() || c == '@' || c == '.' || c == '-' || c == '_') && (n < (txt.chars().count() - 1)) {
(events, in_mention, text_acc + c.to_string().as_ref(), n + 1, mentions)
} else {
let mention = text_acc + c.to_string().as_ref();
let short_mention = mention.clone();
let short_mention = short_mention.splitn(1, '@').nth(0).unwrap_or("");
let link = Tag::Link(format!("/@/{}/", mention).into(), short_mention.to_string().into());
mentions.push(mention);
events.push(Event::Start(link.clone()));
events.push(Event::Text(format!("@{}", short_mention).into()));
events.push(Event::End(link));
(events, false, c.to_string(), n + 1, mentions)
}
} else {
if c == '@' {
events.push(Event::Text(text_acc.into()));
(events, true, String::new(), n + 1, mentions)
} else {
if n >= (txt.chars().count() - 1) { // Add the text after at the end, even if it is not followed by a mention.
events.push(Event::Text((text_acc.clone() + c.to_string().as_ref()).into()))
}
(events, in_mention, text_acc + c.to_string().as_ref(), n + 1, mentions)
}
}
});
(evts, new_mentions)
},
_ => (vec![evt], vec![])
}).unzip();
let parser = parser.into_iter().flatten();
let mentions = mentions.into_iter().flatten().map(|m| String::from(m.trim()));
// TODO: fetch mentionned profiles in background, if needed
let mut buf = String::new();
html::push_html(&mut buf, parser);
(buf, mentions.collect())
}