]> Untitled Git - lemmy.git/blob - crates/db_schema/src/impls/post.rs
07c652e3148265b32d117500803f3c29cf60351b
[lemmy.git] / crates / db_schema / src / impls / post.rs
1 use crate::{
2   newtypes::{CommunityId, DbUrl, PersonId, PostId},
3   source::post::{
4     Post,
5     PostForm,
6     PostLike,
7     PostLikeForm,
8     PostRead,
9     PostReadForm,
10     PostSaved,
11     PostSavedForm,
12   },
13   traits::{Crud, DeleteableOrRemoveable, Likeable, Readable, Saveable},
14   utils::{naive_now, FETCH_LIMIT_MAX},
15 };
16 use diesel::{dsl::*, result::Error, ExpressionMethods, PgConnection, QueryDsl, RunQueryDsl, *};
17 use url::Url;
18
19 impl Crud for Post {
20   type Form = PostForm;
21   type IdType = PostId;
22   fn read(conn: &PgConnection, post_id: PostId) -> Result<Self, Error> {
23     use crate::schema::post::dsl::*;
24     post.find(post_id).first::<Self>(conn)
25   }
26
27   fn delete(conn: &PgConnection, post_id: PostId) -> Result<usize, Error> {
28     use crate::schema::post::dsl::*;
29     diesel::delete(post.find(post_id)).execute(conn)
30   }
31
32   fn create(conn: &PgConnection, new_post: &PostForm) -> Result<Self, Error> {
33     use crate::schema::post::dsl::*;
34     insert_into(post).values(new_post).get_result::<Self>(conn)
35   }
36
37   fn update(conn: &PgConnection, post_id: PostId, new_post: &PostForm) -> Result<Self, Error> {
38     use crate::schema::post::dsl::*;
39     diesel::update(post.find(post_id))
40       .set(new_post)
41       .get_result::<Self>(conn)
42   }
43 }
44
45 impl Post {
46   pub fn list_for_community(
47     conn: &PgConnection,
48     the_community_id: CommunityId,
49   ) -> Result<Vec<Self>, Error> {
50     use crate::schema::post::dsl::*;
51     post
52       .filter(community_id.eq(the_community_id))
53       .filter(deleted.eq(false))
54       .filter(removed.eq(false))
55       .then_order_by(published.desc())
56       .then_order_by(stickied.desc())
57       .limit(FETCH_LIMIT_MAX)
58       .load::<Self>(conn)
59   }
60
61   pub fn update_ap_id(conn: &PgConnection, post_id: PostId, apub_id: DbUrl) -> Result<Self, Error> {
62     use crate::schema::post::dsl::*;
63
64     diesel::update(post.find(post_id))
65       .set(ap_id.eq(apub_id))
66       .get_result::<Self>(conn)
67   }
68
69   pub fn permadelete_for_creator(
70     conn: &PgConnection,
71     for_creator_id: PersonId,
72   ) -> Result<Vec<Self>, Error> {
73     use crate::schema::post::dsl::*;
74
75     let perma_deleted = "*Permananently Deleted*";
76     let perma_deleted_url = "https://deleted.com";
77
78     diesel::update(post.filter(creator_id.eq(for_creator_id)))
79       .set((
80         name.eq(perma_deleted),
81         url.eq(perma_deleted_url),
82         body.eq(perma_deleted),
83         deleted.eq(true),
84         updated.eq(naive_now()),
85       ))
86       .get_results::<Self>(conn)
87   }
88
89   pub fn update_deleted(
90     conn: &PgConnection,
91     post_id: PostId,
92     new_deleted: bool,
93   ) -> Result<Self, Error> {
94     use crate::schema::post::dsl::*;
95     diesel::update(post.find(post_id))
96       .set((deleted.eq(new_deleted), updated.eq(naive_now())))
97       .get_result::<Self>(conn)
98   }
99
100   pub fn update_removed(
101     conn: &PgConnection,
102     post_id: PostId,
103     new_removed: bool,
104   ) -> Result<Self, Error> {
105     use crate::schema::post::dsl::*;
106     diesel::update(post.find(post_id))
107       .set((removed.eq(new_removed), updated.eq(naive_now())))
108       .get_result::<Self>(conn)
109   }
110
111   pub fn update_removed_for_creator(
112     conn: &PgConnection,
113     for_creator_id: PersonId,
114     for_community_id: Option<CommunityId>,
115     new_removed: bool,
116   ) -> Result<Vec<Self>, Error> {
117     use crate::schema::post::dsl::*;
118
119     let mut update = diesel::update(post).into_boxed();
120     update = update.filter(creator_id.eq(for_creator_id));
121
122     if let Some(for_community_id) = for_community_id {
123       update = update.filter(community_id.eq(for_community_id));
124     }
125
126     update
127       .set((removed.eq(new_removed), updated.eq(naive_now())))
128       .get_results::<Self>(conn)
129   }
130
131   pub fn update_locked(
132     conn: &PgConnection,
133     post_id: PostId,
134     new_locked: bool,
135   ) -> Result<Self, Error> {
136     use crate::schema::post::dsl::*;
137     diesel::update(post.find(post_id))
138       .set(locked.eq(new_locked))
139       .get_result::<Self>(conn)
140   }
141
142   pub fn update_stickied(
143     conn: &PgConnection,
144     post_id: PostId,
145     new_stickied: bool,
146   ) -> Result<Self, Error> {
147     use crate::schema::post::dsl::*;
148     diesel::update(post.find(post_id))
149       .set(stickied.eq(new_stickied))
150       .get_result::<Self>(conn)
151   }
152
153   pub fn is_post_creator(person_id: PersonId, post_creator_id: PersonId) -> bool {
154     person_id == post_creator_id
155   }
156
157   pub fn upsert(conn: &PgConnection, post_form: &PostForm) -> Result<Post, Error> {
158     use crate::schema::post::dsl::*;
159     insert_into(post)
160       .values(post_form)
161       .on_conflict(ap_id)
162       .do_update()
163       .set(post_form)
164       .get_result::<Self>(conn)
165   }
166   pub fn read_from_apub_id(conn: &PgConnection, object_id: Url) -> Result<Option<Self>, Error> {
167     use crate::schema::post::dsl::*;
168     let object_id: DbUrl = object_id.into();
169     Ok(
170       post
171         .filter(ap_id.eq(object_id))
172         .first::<Post>(conn)
173         .ok()
174         .map(Into::into),
175     )
176   }
177
178   pub fn fetch_pictrs_posts_for_creator(
179     conn: &PgConnection,
180     for_creator_id: PersonId,
181   ) -> Result<Vec<Self>, Error> {
182     use crate::schema::post::dsl::*;
183     let pictrs_search = "%pictrs/image%";
184
185     post
186       .filter(creator_id.eq(for_creator_id))
187       .filter(url.like(pictrs_search))
188       .load::<Self>(conn)
189   }
190
191   /// Sets the url and thumbnails fields to None
192   pub fn remove_pictrs_post_images_and_thumbnails_for_creator(
193     conn: &PgConnection,
194     for_creator_id: PersonId,
195   ) -> Result<Vec<Self>, Error> {
196     use crate::schema::post::dsl::*;
197     let pictrs_search = "%pictrs/image%";
198
199     diesel::update(
200       post
201         .filter(creator_id.eq(for_creator_id))
202         .filter(url.like(pictrs_search)),
203     )
204     .set((
205       url.eq::<Option<String>>(None),
206       thumbnail_url.eq::<Option<String>>(None),
207     ))
208     .get_results::<Self>(conn)
209   }
210
211   pub fn fetch_pictrs_posts_for_community(
212     conn: &PgConnection,
213     for_community_id: CommunityId,
214   ) -> Result<Vec<Self>, Error> {
215     use crate::schema::post::dsl::*;
216     let pictrs_search = "%pictrs/image%";
217     post
218       .filter(community_id.eq(for_community_id))
219       .filter(url.like(pictrs_search))
220       .load::<Self>(conn)
221   }
222
223   /// Sets the url and thumbnails fields to None
224   pub fn remove_pictrs_post_images_and_thumbnails_for_community(
225     conn: &PgConnection,
226     for_community_id: CommunityId,
227   ) -> Result<Vec<Self>, Error> {
228     use crate::schema::post::dsl::*;
229     let pictrs_search = "%pictrs/image%";
230
231     diesel::update(
232       post
233         .filter(community_id.eq(for_community_id))
234         .filter(url.like(pictrs_search)),
235     )
236     .set((
237       url.eq::<Option<String>>(None),
238       thumbnail_url.eq::<Option<String>>(None),
239     ))
240     .get_results::<Self>(conn)
241   }
242 }
243
244 impl Likeable for PostLike {
245   type Form = PostLikeForm;
246   type IdType = PostId;
247   fn like(conn: &PgConnection, post_like_form: &PostLikeForm) -> Result<Self, Error> {
248     use crate::schema::post_like::dsl::*;
249     insert_into(post_like)
250       .values(post_like_form)
251       .on_conflict((post_id, person_id))
252       .do_update()
253       .set(post_like_form)
254       .get_result::<Self>(conn)
255   }
256   fn remove(conn: &PgConnection, person_id: PersonId, post_id: PostId) -> Result<usize, Error> {
257     use crate::schema::post_like::dsl;
258     diesel::delete(
259       dsl::post_like
260         .filter(dsl::post_id.eq(post_id))
261         .filter(dsl::person_id.eq(person_id)),
262     )
263     .execute(conn)
264   }
265 }
266
267 impl Saveable for PostSaved {
268   type Form = PostSavedForm;
269   fn save(conn: &PgConnection, post_saved_form: &PostSavedForm) -> Result<Self, Error> {
270     use crate::schema::post_saved::dsl::*;
271     insert_into(post_saved)
272       .values(post_saved_form)
273       .on_conflict((post_id, person_id))
274       .do_update()
275       .set(post_saved_form)
276       .get_result::<Self>(conn)
277   }
278   fn unsave(conn: &PgConnection, post_saved_form: &PostSavedForm) -> Result<usize, Error> {
279     use crate::schema::post_saved::dsl::*;
280     diesel::delete(
281       post_saved
282         .filter(post_id.eq(post_saved_form.post_id))
283         .filter(person_id.eq(post_saved_form.person_id)),
284     )
285     .execute(conn)
286   }
287 }
288
289 impl Readable for PostRead {
290   type Form = PostReadForm;
291   fn mark_as_read(conn: &PgConnection, post_read_form: &PostReadForm) -> Result<Self, Error> {
292     use crate::schema::post_read::dsl::*;
293     insert_into(post_read)
294       .values(post_read_form)
295       .on_conflict((post_id, person_id))
296       .do_update()
297       .set(post_read_form)
298       .get_result::<Self>(conn)
299   }
300
301   fn mark_as_unread(conn: &PgConnection, post_read_form: &PostReadForm) -> Result<usize, Error> {
302     use crate::schema::post_read::dsl::*;
303     diesel::delete(
304       post_read
305         .filter(post_id.eq(post_read_form.post_id))
306         .filter(person_id.eq(post_read_form.person_id)),
307     )
308     .execute(conn)
309   }
310 }
311
312 impl DeleteableOrRemoveable for Post {
313   fn blank_out_deleted_or_removed_info(mut self) -> Self {
314     self.name = "".into();
315     self.url = None;
316     self.body = None;
317     self.embed_title = None;
318     self.embed_description = None;
319     self.embed_video_url = None;
320     self.thumbnail_url = None;
321
322     self
323   }
324 }
325
326 #[cfg(test)]
327 mod tests {
328   use crate::{
329     source::{
330       community::{Community, CommunityForm},
331       person::*,
332       post::*,
333     },
334     traits::{Crud, Likeable, Readable, Saveable},
335     utils::establish_unpooled_connection,
336   };
337   use serial_test::serial;
338
339   #[test]
340   #[serial]
341   fn test_crud() {
342     let conn = establish_unpooled_connection();
343
344     let new_person = PersonForm {
345       name: "jim".into(),
346       public_key: Some("pubkey".to_string()),
347       ..PersonForm::default()
348     };
349
350     let inserted_person = Person::create(&conn, &new_person).unwrap();
351
352     let new_community = CommunityForm {
353       name: "test community_3".to_string(),
354       title: "nada".to_owned(),
355       public_key: Some("pubkey".to_string()),
356       ..CommunityForm::default()
357     };
358
359     let inserted_community = Community::create(&conn, &new_community).unwrap();
360
361     let new_post = PostForm {
362       name: "A test post".into(),
363       creator_id: inserted_person.id,
364       community_id: inserted_community.id,
365       ..PostForm::default()
366     };
367
368     let inserted_post = Post::create(&conn, &new_post).unwrap();
369
370     let expected_post = Post {
371       id: inserted_post.id,
372       name: "A test post".into(),
373       url: None,
374       body: None,
375       creator_id: inserted_person.id,
376       community_id: inserted_community.id,
377       published: inserted_post.published,
378       removed: false,
379       locked: false,
380       stickied: false,
381       nsfw: false,
382       deleted: false,
383       updated: None,
384       embed_title: None,
385       embed_description: None,
386       embed_video_url: None,
387       thumbnail_url: None,
388       ap_id: inserted_post.ap_id.to_owned(),
389       local: true,
390       language_id: Default::default(),
391     };
392
393     // Post Like
394     let post_like_form = PostLikeForm {
395       post_id: inserted_post.id,
396       person_id: inserted_person.id,
397       score: 1,
398     };
399
400     let inserted_post_like = PostLike::like(&conn, &post_like_form).unwrap();
401
402     let expected_post_like = PostLike {
403       id: inserted_post_like.id,
404       post_id: inserted_post.id,
405       person_id: inserted_person.id,
406       published: inserted_post_like.published,
407       score: 1,
408     };
409
410     // Post Save
411     let post_saved_form = PostSavedForm {
412       post_id: inserted_post.id,
413       person_id: inserted_person.id,
414     };
415
416     let inserted_post_saved = PostSaved::save(&conn, &post_saved_form).unwrap();
417
418     let expected_post_saved = PostSaved {
419       id: inserted_post_saved.id,
420       post_id: inserted_post.id,
421       person_id: inserted_person.id,
422       published: inserted_post_saved.published,
423     };
424
425     // Post Read
426     let post_read_form = PostReadForm {
427       post_id: inserted_post.id,
428       person_id: inserted_person.id,
429     };
430
431     let inserted_post_read = PostRead::mark_as_read(&conn, &post_read_form).unwrap();
432
433     let expected_post_read = PostRead {
434       id: inserted_post_read.id,
435       post_id: inserted_post.id,
436       person_id: inserted_person.id,
437       published: inserted_post_read.published,
438     };
439
440     let read_post = Post::read(&conn, inserted_post.id).unwrap();
441     let updated_post = Post::update(&conn, inserted_post.id, &new_post).unwrap();
442     let like_removed = PostLike::remove(&conn, inserted_person.id, inserted_post.id).unwrap();
443     let saved_removed = PostSaved::unsave(&conn, &post_saved_form).unwrap();
444     let read_removed = PostRead::mark_as_unread(&conn, &post_read_form).unwrap();
445     let num_deleted = Post::delete(&conn, inserted_post.id).unwrap();
446     Community::delete(&conn, inserted_community.id).unwrap();
447     Person::delete(&conn, inserted_person.id).unwrap();
448
449     assert_eq!(expected_post, read_post);
450     assert_eq!(expected_post, inserted_post);
451     assert_eq!(expected_post, updated_post);
452     assert_eq!(expected_post_like, inserted_post_like);
453     assert_eq!(expected_post_saved, inserted_post_saved);
454     assert_eq!(expected_post_read, inserted_post_read);
455     assert_eq!(1, like_removed);
456     assert_eq!(1, saved_removed);
457     assert_eq!(1, read_removed);
458     assert_eq!(1, num_deleted);
459   }
460 }