headless_talk/channel/
open.rs

1use diesel::{ExpressionMethods, RunQueryDsl};
2use talk_loco_client::talk::session::TalkSession;
3
4use crate::{
5    conn::Conn, database::schema::channel_list, updater::channel::ChannelUpdater, ClientResult,
6};
7
8#[derive(Debug, Clone)]
9pub struct OpenChannel {}
10
11#[derive(Debug, Clone, Copy)]
12pub struct OpenChannelOp<'a> {
13    id: i64,
14    link_id: i64,
15    conn: &'a Conn,
16}
17
18impl<'a> OpenChannelOp<'a> {
19    pub const fn new(id: i64, link_id: i64, conn: &'a Conn) -> Self {
20        Self { id, link_id, conn }
21    }
22
23    pub const fn id(self) -> i64 {
24        self.id
25    }
26
27    pub const fn link_id(self) -> i64 {
28        self.link_id
29    }
30
31    pub async fn read_chat(self, watermark: i64) -> ClientResult<()> {
32        let id = self.id;
33
34        TalkSession(&self.conn.session)
35            .open_channel(id, self.link_id)
36            .noti_read(watermark)
37            .await?;
38
39        self.conn
40            .pool
41            .spawn(move |conn| {
42                diesel::update(channel_list::table)
43                    .filter(channel_list::id.eq(id))
44                    .set(channel_list::last_seen_log_id.eq(watermark))
45                    .execute(conn)?;
46
47                Ok(())
48            })
49            .await?;
50
51        Ok(())
52    }
53
54    pub async fn leave(self, block: bool) -> ClientResult<()> {
55        let id = self.id;
56
57        TalkSession(&self.conn.session)
58            .open_channel(id, self.link_id)
59            .leave(block)
60            .await?;
61
62        self.conn
63            .pool
64            .spawn_transaction(move |conn| ChannelUpdater::new(id).remove(conn))
65            .await?;
66
67        Ok(())
68    }
69}