Federated blogging application, thanks to ActivityPub https://joinplu.me
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

910 lines
30 KiB

  1. use crate::{
  2. ap_url, blogs::Blog, instance::Instance, medias::Media, mentions::Mention, post_authors::*,
  3. safe_string::SafeString, schema::posts, search::Searcher, search::UpdateDocument, tags::*,
  4. timeline::*, users::User, Connection, Error, PlumeRocket, Result, CONFIG,
  5. };
  6. use activitypub::{
  7. activity::{Create, Delete, Update},
  8. link,
  9. object::{Article, Image, Tombstone},
  10. CustomObject,
  11. };
  12. use chrono::{NaiveDateTime, TimeZone, Utc};
  13. use diesel::{self, BelongingToDsl, ExpressionMethods, QueryDsl, RunQueryDsl, SaveChangesDsl};
  14. use heck::{CamelCase, KebabCase};
  15. use plume_common::{
  16. activity_pub::{
  17. inbox::{AsObject, FromId},
  18. Hashtag, Id, IntoId, Licensed, Source, PUBLIC_VISIBILITY,
  19. },
  20. utils::md_to_html,
  21. };
  22. use riker::actors::*;
  23. use serde_json;
  24. use std::collections::HashSet;
  25. pub type LicensedArticle = CustomObject<Licensed, Article>;
  26. #[derive(Debug, Queryable, Identifiable, Clone, AsChangeset)]
  27. #[changeset_options(treat_none_as_null = "true")]
  28. pub struct Post {
  29. pub id: i32,
  30. pub blog_id: i32,
  31. pub slug: String,
  32. pub title: String,
  33. pub content: SafeString,
  34. pub published: bool,
  35. pub license: String,
  36. pub creation_date: NaiveDateTime,
  37. pub ap_url: String,
  38. pub subtitle: String,
  39. pub source: String,
  40. pub cover_id: Option<i32>,
  41. }
  42. #[derive(Insertable)]
  43. #[table_name = "posts"]
  44. pub struct NewPost {
  45. pub blog_id: i32,
  46. pub slug: String,
  47. pub title: String,
  48. pub content: SafeString,
  49. pub published: bool,
  50. pub license: String,
  51. pub creation_date: Option<NaiveDateTime>,
  52. pub ap_url: String,
  53. pub subtitle: String,
  54. pub source: String,
  55. pub cover_id: Option<i32>,
  56. }
  57. impl Post {
  58. get!(posts);
  59. find_by!(posts, find_by_slug, slug as &str, blog_id as i32);
  60. find_by!(posts, find_by_ap_url, ap_url as &str);
  61. last!(posts);
  62. pub fn insert(conn: &Connection, new: NewPost, searcher: &Searcher) -> Result<Self> {
  63. diesel::insert_into(posts::table)
  64. .values(new)
  65. .execute(conn)?;
  66. let mut post = Self::last(conn)?;
  67. if post.ap_url.is_empty() {
  68. post.ap_url = ap_url(&format!(
  69. "{}/~/{}/{}/",
  70. CONFIG.base_url,
  71. post.get_blog(conn)?.fqn,
  72. post.slug
  73. ));
  74. let _: Post = post.save_changes(conn)?;
  75. }
  76. searcher.add_document(&post)?;
  77. Ok(post)
  78. }
  79. pub fn update(&self, conn: &Connection) -> Result<Self> {
  80. diesel::update(self).set(self).execute(conn)?;
  81. let post = Self::get(conn, self.id)?;
  82. Ok(post)
  83. }
  84. pub fn delete(&self, conn: &Connection, searcher: &Searcher) -> Result<()> {
  85. for m in Mention::list_for_post(&conn, self.id)? {
  86. m.delete(conn)?;
  87. }
  88. diesel::delete(self).execute(conn)?;
  89. searcher.delete_document(self);
  90. Ok(())
  91. }
  92. pub fn list_by_tag(
  93. conn: &Connection,
  94. tag: String,
  95. (min, max): (i32, i32),
  96. ) -> Result<Vec<Post>> {
  97. use crate::schema::tags;
  98. let ids = tags::table.filter(tags::tag.eq(tag)).select(tags::post_id);
  99. posts::table
  100. .filter(posts::id.eq_any(ids))
  101. .filter(posts::published.eq(true))
  102. .order(posts::creation_date.desc())
  103. .offset(min.into())
  104. .limit((max - min).into())
  105. .load(conn)
  106. .map_err(Error::from)
  107. }
  108. pub fn count_for_tag(conn: &Connection, tag: String) -> Result<i64> {
  109. use crate::schema::tags;
  110. let ids = tags::table.filter(tags::tag.eq(tag)).select(tags::post_id);
  111. posts::table
  112. .filter(posts::id.eq_any(ids))
  113. .filter(posts::published.eq(true))
  114. .count()
  115. .load(conn)?
  116. .iter()
  117. .next()
  118. .cloned()
  119. .ok_or(Error::NotFound)
  120. }
  121. pub fn count_local(conn: &Connection) -> Result<i64> {
  122. use crate::schema::post_authors;
  123. use crate::schema::users;
  124. let local_authors = users::table
  125. .filter(users::instance_id.eq(Instance::get_local()?.id))
  126. .select(users::id);
  127. let local_posts_id = post_authors::table
  128. .filter(post_authors::author_id.eq_any(local_authors))
  129. .select(post_authors::post_id);
  130. posts::table
  131. .filter(posts::id.eq_any(local_posts_id))
  132. .filter(posts::published.eq(true))
  133. .count()
  134. .get_result(conn)
  135. .map_err(Error::from)
  136. }
  137. pub fn count(conn: &Connection) -> Result<i64> {
  138. posts::table
  139. .filter(posts::published.eq(true))
  140. .count()
  141. .get_result(conn)
  142. .map_err(Error::from)
  143. }
  144. pub fn list_filtered(
  145. conn: &Connection,
  146. title: Option<String>,
  147. subtitle: Option<String>,
  148. content: Option<String>,
  149. ) -> Result<Vec<Post>> {
  150. let mut query = posts::table.into_boxed();
  151. if let Some(title) = title {
  152. query = query.filter(posts::title.eq(title));
  153. }
  154. if let Some(subtitle) = subtitle {
  155. query = query.filter(posts::subtitle.eq(subtitle));
  156. }
  157. if let Some(content) = content {
  158. query = query.filter(posts::content.eq(content));
  159. }
  160. query.get_results::<Post>(conn).map_err(Error::from)
  161. }
  162. pub fn get_recents_for_author(
  163. conn: &Connection,
  164. author: &User,
  165. limit: i64,
  166. ) -> Result<Vec<Post>> {
  167. use crate::schema::post_authors;
  168. let posts = PostAuthor::belonging_to(author).select(post_authors::post_id);
  169. posts::table
  170. .filter(posts::id.eq_any(posts))
  171. .filter(posts::published.eq(true))
  172. .order(posts::creation_date.desc())
  173. .limit(limit)
  174. .load::<Post>(conn)
  175. .map_err(Error::from)
  176. }
  177. pub fn get_recents_for_blog(conn: &Connection, blog: &Blog, limit: i64) -> Result<Vec<Post>> {
  178. posts::table
  179. .filter(posts::blog_id.eq(blog.id))
  180. .filter(posts::published.eq(true))
  181. .order(posts::creation_date.desc())
  182. .limit(limit)
  183. .load::<Post>(conn)
  184. .map_err(Error::from)
  185. }
  186. pub fn get_for_blog(conn: &Connection, blog: &Blog) -> Result<Vec<Post>> {
  187. posts::table
  188. .filter(posts::blog_id.eq(blog.id))
  189. .filter(posts::published.eq(true))
  190. .load::<Post>(conn)
  191. .map_err(Error::from)
  192. }
  193. pub fn count_for_blog(conn: &Connection, blog: &Blog) -> Result<i64> {
  194. posts::table
  195. .filter(posts::blog_id.eq(blog.id))
  196. .filter(posts::published.eq(true))
  197. .count()
  198. .get_result(conn)
  199. .map_err(Error::from)
  200. }
  201. pub fn blog_page(conn: &Connection, blog: &Blog, (min, max): (i32, i32)) -> Result<Vec<Post>> {
  202. posts::table
  203. .filter(posts::blog_id.eq(blog.id))
  204. .filter(posts::published.eq(true))
  205. .order(posts::creation_date.desc())
  206. .offset(min.into())
  207. .limit((max - min).into())
  208. .load::<Post>(conn)
  209. .map_err(Error::from)
  210. }
  211. pub fn drafts_by_author(conn: &Connection, author: &User) -> Result<Vec<Post>> {
  212. use crate::schema::post_authors;
  213. let posts = PostAuthor::belonging_to(author).select(post_authors::post_id);
  214. posts::table
  215. .order(posts::creation_date.desc())
  216. .filter(posts::published.eq(false))
  217. .filter(posts::id.eq_any(posts))
  218. .load::<Post>(conn)
  219. .map_err(Error::from)
  220. }
  221. pub fn get_authors(&self, conn: &Connection) -> Result<Vec<User>> {
  222. use crate::schema::post_authors;
  223. use crate::schema::users;
  224. let author_list = PostAuthor::belonging_to(self).select(post_authors::author_id);
  225. users::table
  226. .filter(users::id.eq_any(author_list))
  227. .load::<User>(conn)
  228. .map_err(Error::from)
  229. }
  230. pub fn is_author(&self, conn: &Connection, author_id: i32) -> Result<bool> {
  231. use crate::schema::post_authors;
  232. Ok(PostAuthor::belonging_to(self)
  233. .filter(post_authors::author_id.eq(author_id))
  234. .count()
  235. .get_result::<i64>(conn)?
  236. > 0)
  237. }
  238. pub fn get_blog(&self, conn: &Connection) -> Result<Blog> {
  239. use crate::schema::blogs;
  240. blogs::table
  241. .filter(blogs::id.eq(self.blog_id))
  242. .first(conn)
  243. .map_err(Error::from)
  244. }
  245. pub fn count_likes(&self, conn: &Connection) -> Result<i64> {
  246. use crate::schema::likes;
  247. likes::table
  248. .filter(likes::post_id.eq(self.id))
  249. .count()
  250. .get_result(conn)
  251. .map_err(Error::from)
  252. }
  253. pub fn count_reshares(&self, conn: &Connection) -> Result<i64> {
  254. use crate::schema::reshares;
  255. reshares::table
  256. .filter(reshares::post_id.eq(self.id))
  257. .count()
  258. .get_result(conn)
  259. .map_err(Error::from)
  260. }
  261. pub fn get_receivers_urls(&self, conn: &Connection) -> Result<Vec<String>> {
  262. let followers = self
  263. .get_authors(conn)?
  264. .into_iter()
  265. .filter_map(|a| a.get_followers(conn).ok())
  266. .collect::<Vec<Vec<User>>>();
  267. Ok(followers.into_iter().fold(vec![], |mut acc, f| {
  268. for x in f {
  269. acc.push(x.ap_url);
  270. }
  271. acc
  272. }))
  273. }
  274. pub fn to_activity(&self, conn: &Connection) -> Result<LicensedArticle> {
  275. let cc = self.get_receivers_urls(conn)?;
  276. let to = vec![PUBLIC_VISIBILITY.to_string()];
  277. let mut mentions_json = Mention::list_for_post(conn, self.id)?
  278. .into_iter()
  279. .map(|m| json!(m.to_activity(conn).ok()))
  280. .collect::<Vec<serde_json::Value>>();
  281. let mut tags_json = Tag::for_post(conn, self.id)?
  282. .into_iter()
  283. .map(|t| json!(t.to_activity().ok()))
  284. .collect::<Vec<serde_json::Value>>();
  285. mentions_json.append(&mut tags_json);
  286. let mut article = Article::default();
  287. article.object_props.set_name_string(self.title.clone())?;
  288. article.object_props.set_id_string(self.ap_url.clone())?;
  289. let mut authors = self
  290. .get_authors(conn)?
  291. .into_iter()
  292. .map(|x| Id::new(x.ap_url))
  293. .collect::<Vec<Id>>();
  294. authors.push(self.get_blog(conn)?.into_id()); // add the blog URL here too
  295. article
  296. .object_props
  297. .set_attributed_to_link_vec::<Id>(authors)?;
  298. article
  299. .object_props
  300. .set_content_string(self.content.get().clone())?;
  301. article.ap_object_props.set_source_object(Source {
  302. content: self.source.clone(),
  303. media_type: String::from("text/markdown"),
  304. })?;
  305. article
  306. .object_props
  307. .set_published_utctime(Utc.from_utc_datetime(&self.creation_date))?;
  308. article
  309. .object_props
  310. .set_summary_string(self.subtitle.clone())?;
  311. article.object_props.tag = Some(json!(mentions_json));
  312. if let Some(media_id) = self.cover_id {
  313. let media = Media::get(conn, media_id)?;
  314. let mut cover = Image::default();
  315. cover.object_props.set_url_string(media.url()?)?;
  316. if media.sensitive {
  317. cover
  318. .object_props
  319. .set_summary_string(media.content_warning.unwrap_or_default())?;
  320. }
  321. cover.object_props.set_content_string(media.alt_text)?;
  322. cover
  323. .object_props
  324. .set_attributed_to_link_vec(vec![User::get(conn, media.owner_id)?.into_id()])?;
  325. article.object_props.set_icon_object(cover)?;
  326. }
  327. article.object_props.set_url_string(self.ap_url.clone())?;
  328. article
  329. .object_props
  330. .set_to_link_vec::<Id>(to.into_iter().map(Id::new).collect())?;
  331. article
  332. .object_props
  333. .set_cc_link_vec::<Id>(cc.into_iter().map(Id::new).collect())?;
  334. let mut license = Licensed::default();
  335. license.set_license_string(self.license.clone())?;
  336. Ok(LicensedArticle::new(article, license))
  337. }
  338. pub fn create_activity(&self, conn: &Connection) -> Result<Create> {
  339. let article = self.to_activity(conn)?;
  340. let mut act = Create::default();
  341. act.object_props
  342. .set_id_string(format!("{}activity", self.ap_url))?;
  343. act.object_props
  344. .set_to_link_vec::<Id>(article.object.object_props.to_link_vec()?)?;
  345. act.object_props
  346. .set_cc_link_vec::<Id>(article.object.object_props.cc_link_vec()?)?;
  347. act.create_props
  348. .set_actor_link(Id::new(self.get_authors(conn)?[0].clone().ap_url))?;
  349. act.create_props.set_object_object(article)?;
  350. Ok(act)
  351. }
  352. pub fn update_activity(&self, conn: &Connection) -> Result<Update> {
  353. let article = self.to_activity(conn)?;
  354. let mut act = Update::default();
  355. act.object_props.set_id_string(format!(
  356. "{}/update-{}",
  357. self.ap_url,
  358. Utc::now().timestamp()
  359. ))?;
  360. act.object_props
  361. .set_to_link_vec::<Id>(article.object.object_props.to_link_vec()?)?;
  362. act.object_props
  363. .set_cc_link_vec::<Id>(article.object.object_props.cc_link_vec()?)?;
  364. act.update_props
  365. .set_actor_link(Id::new(self.get_authors(conn)?[0].clone().ap_url))?;
  366. act.update_props.set_object_object(article)?;
  367. Ok(act)
  368. }
  369. pub fn update_mentions(&self, conn: &Connection, mentions: Vec<link::Mention>) -> Result<()> {
  370. let mentions = mentions
  371. .into_iter()
  372. .map(|m| {
  373. (
  374. m.link_props
  375. .href_string()
  376. .ok()
  377. .and_then(|ap_url| User::find_by_ap_url(conn, &ap_url).ok())
  378. .map(|u| u.id),
  379. m,
  380. )
  381. })
  382. .filter_map(|(id, m)| {
  383. if let Some(id) = id {
  384. Some((m, id))
  385. } else {
  386. None
  387. }
  388. })
  389. .collect::<Vec<_>>();
  390. let old_mentions = Mention::list_for_post(&conn, self.id)?;
  391. let old_user_mentioned = old_mentions
  392. .iter()
  393. .map(|m| m.mentioned_id)
  394. .collect::<HashSet<_>>();
  395. for (m, id) in &mentions {
  396. if !old_user_mentioned.contains(&id) {
  397. Mention::from_activity(&*conn, &m, self.id, true, true)?;
  398. }
  399. }
  400. let new_mentions = mentions
  401. .into_iter()
  402. .map(|(_m, id)| id)
  403. .collect::<HashSet<_>>();
  404. for m in old_mentions
  405. .iter()
  406. .filter(|m| !new_mentions.contains(&m.mentioned_id))
  407. {
  408. m.delete(&conn)?;
  409. }
  410. Ok(())
  411. }
  412. pub fn update_tags(&self, conn: &Connection, tags: Vec<Hashtag>) -> Result<()> {
  413. let tags_name = tags
  414. .iter()
  415. .filter_map(|t| t.name_string().ok())
  416. .collect::<HashSet<_>>();
  417. let old_tags = Tag::for_post(&*conn, self.id)?;
  418. let old_tags_name = old_tags
  419. .iter()
  420. .filter_map(|tag| {
  421. if !tag.is_hashtag {
  422. Some(tag.tag.clone())
  423. } else {
  424. None
  425. }
  426. })
  427. .collect::<HashSet<_>>();
  428. for t in tags {
  429. if !t
  430. .name_string()
  431. .map(|n| old_tags_name.contains(&n))
  432. .unwrap_or(true)
  433. {
  434. Tag::from_activity(conn, &t, self.id, false)?;
  435. }
  436. }
  437. for ot in old_tags.iter().filter(|t| !t.is_hashtag) {
  438. if !tags_name.contains(&ot.tag) {
  439. ot.delete(conn)?;
  440. }
  441. }
  442. Ok(())
  443. }
  444. pub fn update_hashtags(&self, conn: &Connection, tags: Vec<Hashtag>) -> Result<()> {
  445. let tags_name = tags
  446. .iter()
  447. .filter_map(|t| t.name_string().ok())
  448. .collect::<HashSet<_>>();
  449. let old_tags = Tag::for_post(&*conn, self.id)?;
  450. let old_tags_name = old_tags
  451. .iter()
  452. .filter_map(|tag| {
  453. if tag.is_hashtag {
  454. Some(tag.tag.clone())
  455. } else {
  456. None
  457. }
  458. })
  459. .collect::<HashSet<_>>();
  460. for t in tags {
  461. if !t
  462. .name_string()
  463. .map(|n| old_tags_name.contains(&n))
  464. .unwrap_or(true)
  465. {
  466. Tag::from_activity(conn, &t, self.id, true)?;
  467. }
  468. }
  469. for ot in old_tags.into_iter().filter(|t| t.is_hashtag) {
  470. if !tags_name.contains(&ot.tag) {
  471. ot.delete(conn)?;
  472. }
  473. }
  474. Ok(())
  475. }
  476. pub fn url(&self, conn: &Connection) -> Result<String> {
  477. let blog = self.get_blog(conn)?;
  478. Ok(format!("/~/{}/{}", blog.fqn, self.slug))
  479. }
  480. pub fn cover_url(&self, conn: &Connection) -> Option<String> {
  481. self.cover_id
  482. .and_then(|i| Media::get(conn, i).ok())
  483. .and_then(|c| c.url().ok())
  484. }
  485. pub fn build_delete(&self, conn: &Connection) -> Result<Delete> {
  486. let mut act = Delete::default();
  487. act.delete_props
  488. .set_actor_link(self.get_authors(conn)?[0].clone().into_id())?;
  489. let mut tombstone = Tombstone::default();
  490. tombstone.object_props.set_id_string(self.ap_url.clone())?;
  491. act.delete_props.set_object_object(tombstone)?;
  492. act.object_props
  493. .set_id_string(format!("{}#delete", self.ap_url))?;
  494. act.object_props
  495. .set_to_link_vec(vec![Id::new(PUBLIC_VISIBILITY)])?;
  496. Ok(act)
  497. }
  498. }
  499. impl FromId<PlumeRocket> for Post {
  500. type Error = Error;
  501. type Object = LicensedArticle;
  502. fn from_db(c: &PlumeRocket, id: &str) -> Result<Self> {
  503. Self::find_by_ap_url(&c.conn, id)
  504. }
  505. fn from_activity(c: &PlumeRocket, article: LicensedArticle) -> Result<Self> {
  506. let conn = &*c.conn;
  507. let searcher = &c.searcher;
  508. let license = article.custom_props.license_string().unwrap_or_default();
  509. let article = article.object;
  510. let (blog, authors) = article
  511. .object_props
  512. .attributed_to_link_vec::<Id>()?
  513. .into_iter()
  514. .fold((None, vec![]), |(blog, mut authors), link| {
  515. let url = link;
  516. match User::from_id(&c, &url, None) {
  517. Ok(u) => {
  518. authors.push(u);
  519. (blog, authors)
  520. }
  521. Err(_) => (blog.or_else(|| Blog::from_id(&c, &url, None).ok()), authors),
  522. }
  523. });
  524. let cover = article
  525. .object_props
  526. .icon_object::<Image>()
  527. .ok()
  528. .and_then(|img| Media::from_activity(&c, &img).ok().map(|m| m.id));
  529. let title = article.object_props.name_string()?;
  530. let post = Post::insert(
  531. conn,
  532. NewPost {
  533. blog_id: blog?.id,
  534. slug: title.to_kebab_case(),
  535. title,
  536. content: SafeString::new(&article.object_props.content_string()?),
  537. published: true,
  538. license,
  539. // FIXME: This is wrong: with this logic, we may use the display URL as the AP ID. We need two different fields
  540. ap_url: article
  541. .object_props
  542. .url_string()
  543. .or_else(|_| article.object_props.id_string())?,
  544. creation_date: Some(article.object_props.published_utctime()?.naive_utc()),
  545. subtitle: article.object_props.summary_string()?,
  546. source: article.ap_object_props.source_object::<Source>()?.content,
  547. cover_id: cover,
  548. },
  549. searcher,
  550. )?;
  551. for author in authors {
  552. PostAuthor::insert(
  553. conn,
  554. NewPostAuthor {
  555. post_id: post.id,
  556. author_id: author.id,
  557. },
  558. )?;
  559. }
  560. // save mentions and tags
  561. let mut hashtags = md_to_html(&post.source, None, false, None)
  562. .2
  563. .into_iter()
  564. .map(|s| s.to_camel_case())
  565. .collect::<HashSet<_>>();
  566. if let Some(serde_json::Value::Array(tags)) = article.object_props.tag {
  567. for tag in tags {
  568. serde_json::from_value::<link::Mention>(tag.clone())
  569. .map(|m| Mention::from_activity(conn, &m, post.id, true, true))
  570. .ok();
  571. serde_json::from_value::<Hashtag>(tag.clone())
  572. .map_err(Error::from)
  573. .and_then(|t| {
  574. let tag_name = t.name_string()?;
  575. Ok(Tag::from_activity(
  576. conn,
  577. &t,
  578. post.id,
  579. hashtags.remove(&tag_name),
  580. ))
  581. })
  582. .ok();
  583. }
  584. }
  585. Timeline::add_to_all_timelines(c, &post, Kind::Original)?;
  586. Ok(post)
  587. }
  588. }
  589. impl AsObject<User, Create, &PlumeRocket> for Post {
  590. type Error = Error;
  591. type Output = Post;
  592. fn activity(self, _c: &PlumeRocket, _actor: User, _id: &str) -> Result<Post> {
  593. // TODO: check that _actor is actually one of the author?
  594. Ok(self)
  595. }
  596. }
  597. impl AsObject<User, Delete, &PlumeRocket> for Post {
  598. type Error = Error;
  599. type Output = ();
  600. fn activity(self, c: &PlumeRocket, actor: User, _id: &str) -> Result<()> {
  601. let can_delete = self
  602. .get_authors(&c.conn)?
  603. .into_iter()
  604. .any(|a| actor.id == a.id);
  605. if can_delete {
  606. self.delete(&c.conn, &c.searcher).map(|_| ())
  607. } else {
  608. Err(Error::Unauthorized)
  609. }
  610. }
  611. }
  612. pub struct PostUpdate {
  613. pub ap_url: String,
  614. pub title: Option<String>,
  615. pub subtitle: Option<String>,
  616. pub content: Option<String>,
  617. pub cover: Option<i32>,
  618. pub source: Option<String>,
  619. pub license: Option<String>,
  620. pub tags: Option<serde_json::Value>,
  621. }
  622. impl FromId<PlumeRocket> for PostUpdate {
  623. type Error = Error;
  624. type Object = LicensedArticle;
  625. fn from_db(_: &PlumeRocket, _: &str) -> Result<Self> {
  626. // Always fail because we always want to deserialize the AP object
  627. Err(Error::NotFound)
  628. }
  629. fn from_activity(c: &PlumeRocket, updated: LicensedArticle) -> Result<Self> {
  630. Ok(PostUpdate {
  631. ap_url: updated.object.object_props.id_string()?,
  632. title: updated.object.object_props.name_string().ok(),
  633. subtitle: updated.object.object_props.summary_string().ok(),
  634. content: updated.object.object_props.content_string().ok(),
  635. cover: updated
  636. .object
  637. .object_props
  638. .icon_object::<Image>()
  639. .ok()
  640. .and_then(|img| Media::from_activity(&c, &img).ok().map(|m| m.id)),
  641. source: updated
  642. .object
  643. .ap_object_props
  644. .source_object::<Source>()
  645. .ok()
  646. .map(|x| x.content),
  647. license: updated.custom_props.license_string().ok(),
  648. tags: updated.object.object_props.tag,
  649. })
  650. }
  651. }
  652. impl AsObject<User, Update, &PlumeRocket> for PostUpdate {
  653. type Error = Error;
  654. type Output = ();
  655. fn activity(self, c: &PlumeRocket, actor: User, _id: &str) -> Result<()> {
  656. let conn = &*c.conn;
  657. let searcher_actor = &c.actors.select("searcher-actor").unwrap();
  658. let mut post = Post::from_id(c, &self.ap_url, None).map_err(|(_, e)| e)?;
  659. if !post.is_author(conn, actor.id)? {
  660. // TODO: maybe the author was added in the meantime
  661. return Err(Error::Unauthorized);
  662. }
  663. if let Some(title) = self.title {
  664. post.slug = title.to_kebab_case();
  665. post.title = title;
  666. }
  667. if let Some(content) = self.content {
  668. post.content = SafeString::new(&content);
  669. }
  670. if let Some(subtitle) = self.subtitle {
  671. post.subtitle = subtitle;
  672. }
  673. post.cover_id = self.cover;
  674. if let Some(source) = self.source {
  675. post.source = source;
  676. }
  677. if let Some(license) = self.license {
  678. post.license = license;
  679. }
  680. let mut txt_hashtags = md_to_html(&post.source, None, false, None)
  681. .2
  682. .into_iter()
  683. .map(|s| s.to_camel_case())
  684. .collect::<HashSet<_>>();
  685. if let Some(serde_json::Value::Array(mention_tags)) = self.tags {
  686. let mut mentions = vec![];
  687. let mut tags = vec![];
  688. let mut hashtags = vec![];
  689. for tag in mention_tags {
  690. serde_json::from_value::<link::Mention>(tag.clone())
  691. .map(|m| mentions.push(m))
  692. .ok();
  693. serde_json::from_value::<Hashtag>(tag.clone())
  694. .map_err(Error::from)
  695. .and_then(|t| {
  696. let tag_name = t.name_string()?;
  697. if txt_hashtags.remove(&tag_name) {
  698. hashtags.push(t);
  699. } else {
  700. tags.push(t);
  701. }
  702. Ok(())
  703. })
  704. .ok();
  705. }
  706. post.update_mentions(conn, mentions)?;
  707. post.update_tags(conn, tags)?;
  708. post.update_hashtags(conn, hashtags)?;
  709. }
  710. post.update(conn)?;
  711. searcher_actor.try_tell(UpdateDocument(post.clone()), None);
  712. Ok(())
  713. }
  714. }
  715. impl IntoId for Post {
  716. fn into_id(self) -> Id {
  717. Id::new(self.ap_url)
  718. }
  719. }
  720. #[cfg(test)]
  721. mod tests {
  722. use super::*;
  723. use crate::inbox::{inbox, tests::fill_database, InboxResult};
  724. use crate::safe_string::SafeString;
  725. use crate::tests::rockets;
  726. use diesel::Connection;
  727. // creates a post, get it's Create activity, delete the post,
  728. // "send" the Create to the inbox, and check it works
  729. #[test]
  730. fn self_federation() {
  731. let r = rockets();
  732. let conn = &*r.conn;
  733. conn.test_transaction::<_, (), _>(|| {
  734. let (_, users, blogs) = fill_database(&r);
  735. let post = Post::insert(
  736. conn,
  737. NewPost {
  738. blog_id: blogs[0].id,
  739. slug: "yo".into(),
  740. title: "Yo".into(),
  741. content: SafeString::new("Hello"),
  742. published: true,
  743. license: "WTFPL".to_string(),
  744. creation_date: None,
  745. ap_url: String::new(), // automatically updated when inserting
  746. subtitle: "Testing".into(),
  747. source: "Hello".into(),
  748. cover_id: None,
  749. },
  750. &r.searcher,
  751. )
  752. .unwrap();
  753. PostAuthor::insert(
  754. conn,
  755. NewPostAuthor {
  756. post_id: post.id,
  757. author_id: users[0].id,
  758. },
  759. )
  760. .unwrap();
  761. let create = post.create_activity(conn).unwrap();
  762. post.delete(conn, &r.searcher).unwrap();
  763. match inbox(&r, serde_json::to_value(create).unwrap()).unwrap() {
  764. InboxResult::Post(p) => {
  765. assert!(p.is_author(conn, users[0].id).unwrap());
  766. assert_eq!(p.source, "Hello".to_owned());
  767. assert_eq!(p.blog_id, blogs[0].id);
  768. assert_eq!(p.content, SafeString::new("Hello"));
  769. assert_eq!(p.subtitle, "Testing".to_owned());
  770. assert_eq!(p.title, "Yo".to_owned());
  771. }
  772. _ => panic!("Unexpected result"),
  773. };
  774. Ok(())
  775. });
  776. }
  777. #[test]
  778. fn licensed_article_serde() {
  779. let mut article = Article::default();
  780. article.object_props.set_id_string("Yo".into()).unwrap();
  781. let mut license = Licensed::default();
  782. license.set_license_string("WTFPL".into()).unwrap();
  783. let full_article = LicensedArticle::new(article, license);
  784. let json = serde_json::to_value(full_article).unwrap();
  785. let article_from_json: LicensedArticle = serde_json::from_value(json).unwrap();
  786. assert_eq!(
  787. "Yo",
  788. &article_from_json.object.object_props.id_string().unwrap()
  789. );
  790. assert_eq!(
  791. "WTFPL",
  792. &article_from_json.custom_props.license_string().unwrap()
  793. );
  794. }
  795. #[test]
  796. fn licensed_article_deserialization() {
  797. let json = json!({
  798. "type": "Article",
  799. "id": "https://plu.me/~/Blog/my-article",
  800. "attributedTo": ["https://plu.me/@/Admin", "https://plu.me/~/Blog"],
  801. "content": "Hello.",
  802. "name": "My Article",
  803. "summary": "Bye.",
  804. "source": {
  805. "content": "Hello.",
  806. "mediaType": "text/markdown"
  807. },
  808. "published": "2014-12-12T12:12:12Z",
  809. "to": [plume_common::activity_pub::PUBLIC_VISIBILITY]
  810. });
  811. let article: LicensedArticle = serde_json::from_value(json).unwrap();
  812. assert_eq!(
  813. "https://plu.me/~/Blog/my-article",
  814. &article.object.object_props.id_string().unwrap()
  815. );
  816. }
  817. }