1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
|
use std::{collections::HashSet, path::Path};
use chrono::Utc;
use jid::JID;
use sqlx::{SqlitePool, migrate};
use uuid::Uuid;
use crate::{
chat::{Chat, Message},
error::{DatabaseError as Error, DatabaseOpenError},
presence::Online,
roster::Contact,
user::User,
};
#[derive(Clone)]
pub struct Db {
db: SqlitePool,
}
// TODO: turn into trait
impl Db {
pub async fn create_connect_and_migrate(
path: impl AsRef<Path>,
) -> Result<Self, DatabaseOpenError> {
if let Some(dir) = path.as_ref().parent() {
if dir.is_dir() {
} else {
tokio::fs::create_dir_all(dir).await?;
}
let _file = tokio::fs::OpenOptions::new()
.append(true)
.create(true)
.open(path.as_ref())
.await?;
}
let url = format!(
"sqlite://{}",
path.as_ref()
.to_str()
.ok_or(DatabaseOpenError::InvalidPath)?
);
let db = SqlitePool::connect(&url).await?;
migrate!().run(&db).await?;
Ok(Self { db })
}
pub(crate) fn new(db: SqlitePool) -> Self {
Self { db }
}
pub(crate) async fn create_user(&self, user: User) -> Result<(), Error> {
sqlx::query!(
"insert into users ( jid, nick, cached_status_message ) values ( ?, ?, ? )",
user.jid,
user.nick,
user.cached_status_message
)
.execute(&self.db)
.await?;
Ok(())
}
pub(crate) async fn read_user(&self, user: JID) -> Result<User, Error> {
sqlx::query!(
"insert into users ( jid ) values ( ? ) on conflict do nothing",
user
)
.execute(&self.db)
.await?;
let user: User = sqlx::query_as("select * from users where jid = ?")
.bind(user)
.fetch_one(&self.db)
.await?;
Ok(user)
}
/// returns whether or not the nickname was updated
pub(crate) async fn delete_user_nick(&self, jid: JID) -> Result<bool, Error> {
if sqlx::query!(
"insert into users (jid, nick) values (?, ?) on conflict do update set nick = ? where nick is not ?",
jid,
None::<String>,
None::<String>,
None::<String>,
)
.execute(&self.db)
.await?
.rows_affected()
> 0
{
Ok(true)
} else {
Ok(false)
}
}
/// returns whether or not the nickname was updated
pub(crate) async fn upsert_user_nick(&self, jid: JID, nick: String) -> Result<bool, Error> {
let rows_affected = sqlx::query!(
"insert into users (jid, nick) values (?, ?) on conflict do update set nick = ? where nick is not ?",
jid,
nick,
nick,
nick
)
.execute(&self.db)
.await?
.rows_affected();
tracing::debug!("rows affected: {}", rows_affected);
if rows_affected > 0 {
Ok(true)
} else {
Ok(false)
}
}
/// returns whether or not the avatar was updated, and the file to delete if there existed an old avatar
pub(crate) async fn delete_user_avatar(
&self,
jid: JID,
) -> Result<(bool, Option<String>), Error> {
#[derive(sqlx::FromRow)]
struct AvatarRow {
avatar: Option<String>,
}
let old_avatar: Option<String> = sqlx::query_as("select avatar from users where jid = ?")
.bind(jid.clone())
.fetch_optional(&self.db)
.await?
.map(|row: AvatarRow| row.avatar)
.unwrap_or(None);
if sqlx::query!(
"insert into users (jid, avatar) values (?, ?) on conflict do update set avatar = ? where avatar is not ?",
jid,
None::<String>,
None::<String>,
None::<String>,
)
.execute(&self.db)
.await?
.rows_affected()
> 0
{
Ok((true, old_avatar))
} else {
Ok((false, old_avatar))
}
}
/// returns whether or not the avatar was updated, and the file to delete if there existed an old avatar
pub(crate) async fn upsert_user_avatar(
&self,
jid: JID,
avatar: String,
) -> Result<(bool, Option<String>), Error> {
#[derive(sqlx::FromRow)]
struct AvatarRow {
avatar: Option<String>,
}
let old_avatar: Option<String> = sqlx::query_as("select avatar from users where jid = ?")
.bind(jid.clone())
.fetch_optional(&self.db)
.await?
.map(|row: AvatarRow| row.avatar)
.unwrap_or(None);
if sqlx::query!(
"insert into users (jid, avatar) values (?, ?) on conflict do update set avatar = ? where avatar is not ?",
jid,
avatar,
avatar,
avatar,
)
.execute(&self.db)
.await?
.rows_affected()
> 0
{
Ok((true, old_avatar))
} else {
Ok((false, old_avatar))
}
}
pub(crate) async fn update_user(&self, user: User) -> Result<(), Error> {
sqlx::query!(
"update users set cached_status_message = ?, nick = ? where jid = ?",
user.cached_status_message,
user.nick,
user.jid
)
.execute(&self.db)
.await?;
Ok(())
}
// TODO: should this be allowed? messages need to reference users. should probably only allow delete if every other thing referencing it has been deleted, or if you make clear to the user deleting a user will delete all messages associated with them.
// pub(crate) async fn delete_user(&self, user: JID) -> Result<(), Error> {}
/// does not create the underlying user, if underlying user does not exist, create_user() must be called separately
pub(crate) async fn create_contact(&self, contact: Contact) -> Result<(), Error> {
sqlx::query!(
"insert into roster ( user_jid, name, subscription ) values ( ?, ?, ? )",
contact.user_jid,
contact.name,
contact.subscription
)
.execute(&self.db)
.await?;
// TODO: abstract this out in to add_to_group() function ?
for group in contact.groups {
sqlx::query!(
"insert into groups (group_name) values (?) on conflict do nothing",
group
)
.execute(&self.db)
.await?;
sqlx::query!(
"insert into groups_roster (group_name, contact_jid) values (?, ?)",
group,
contact.user_jid
)
.execute(&self.db)
.await?;
}
Ok(())
}
pub(crate) async fn read_contact(&self, contact: JID) -> Result<Contact, Error> {
let mut contact: Contact = sqlx::query_as("select * from roster where user_jid = ?")
.bind(contact)
.fetch_one(&self.db)
.await?;
#[derive(sqlx::FromRow)]
struct Row {
group_name: String,
}
let groups: Vec<Row> =
sqlx::query_as("select group_name from groups_roster where contact_jid = ?")
.bind(&contact.user_jid)
.fetch_all(&self.db)
.await?;
contact.groups = HashSet::from_iter(groups.into_iter().map(|row| row.group_name));
Ok(contact)
}
pub(crate) async fn read_contact_opt(&self, contact: &JID) -> Result<Option<Contact>, Error> {
let contact: Option<Contact> =
sqlx::query_as("select * from roster join users on jid = user_jid where jid = ?")
.bind(contact)
.fetch_optional(&self.db)
.await?;
if let Some(mut contact) = contact {
#[derive(sqlx::FromRow)]
struct Row {
group_name: String,
}
let groups: Vec<Row> =
sqlx::query_as("select group_name from groups_roster where contact_jid = ?")
.bind(&contact.user_jid)
.fetch_all(&self.db)
.await?;
contact.groups = HashSet::from_iter(groups.into_iter().map(|row| row.group_name));
Ok(Some(contact))
} else {
Ok(None)
}
}
/// does not update the underlying user, to update user, update_user() must be called separately
pub(crate) async fn update_contact(&self, contact: Contact) -> Result<(), Error> {
sqlx::query!(
"update roster set name = ?, subscription = ? where user_jid = ?",
contact.name,
contact.subscription,
contact.user_jid
)
.execute(&self.db)
.await?;
sqlx::query!(
"delete from groups_roster where contact_jid = ?",
contact.user_jid
)
.execute(&self.db)
.await?;
// TODO: delete orphaned groups from groups table
for group in contact.groups {
sqlx::query!(
"insert into groups (group_name) values (?) on conflict do nothing",
group
)
.execute(&self.db)
.await?;
sqlx::query!(
"insert into groups_roster (group_name, contact_jid) values (?, ?)",
group,
contact.user_jid
)
.execute(&self.db)
.await?;
}
Ok(())
}
pub(crate) async fn upsert_contact(&self, contact: Contact) -> Result<(), Error> {
sqlx::query!(
"insert into users ( jid ) values ( ? ) on conflict do nothing",
contact.user_jid,
)
.execute(&self.db)
.await?;
sqlx::query!(
"insert into roster ( user_jid, name, subscription ) values ( ?, ?, ? ) on conflict do update set name = ?, subscription = ?",
contact.user_jid,
contact.name,
contact.subscription,
contact.name,
contact.subscription
)
.execute(&self.db)
.await?;
sqlx::query!(
"delete from groups_roster where contact_jid = ?",
contact.user_jid
)
.execute(&self.db)
.await?;
// TODO: delete orphaned groups from groups table
for group in contact.groups {
sqlx::query!(
"insert into groups (group_name) values (?) on conflict do nothing",
group
)
.execute(&self.db)
.await?;
sqlx::query!(
"insert into groups_roster (group_name, contact_jid) values (?, ?)",
group,
contact.user_jid
)
.execute(&self.db)
.await?;
}
Ok(())
}
pub(crate) async fn delete_contact(&self, contact: JID) -> Result<(), Error> {
sqlx::query!("delete from roster where user_jid = ?", contact)
.execute(&self.db)
.await?;
// TODO: delete orphaned groups from groups table
Ok(())
}
pub(crate) async fn replace_cached_roster(&self, roster: Vec<Contact>) -> Result<(), Error> {
sqlx::query!("delete from roster").execute(&self.db).await?;
for contact in roster {
self.upsert_contact(contact).await?;
}
Ok(())
}
pub(crate) async fn read_cached_roster(&self) -> Result<Vec<Contact>, Error> {
let mut roster: Vec<Contact> =
sqlx::query_as("select * from roster join users on jid = user_jid")
.fetch_all(&self.db)
.await?;
for contact in &mut roster {
#[derive(sqlx::FromRow)]
struct Row {
group_name: String,
}
let groups: Vec<Row> =
sqlx::query_as("select group_name from groups_roster where contact_jid = ?")
.bind(&contact.user_jid)
.fetch_all(&self.db)
.await?;
contact.groups = HashSet::from_iter(groups.into_iter().map(|row| row.group_name));
}
Ok(roster)
}
pub(crate) async fn create_chat(&self, chat: Chat) -> Result<(), Error> {
let id = Uuid::new_v4();
let jid = chat.correspondent();
sqlx::query!(
"insert into chats (id, correspondent, have_chatted) values (?, ?, ?)",
id,
jid,
chat.have_chatted,
)
.execute(&self.db)
.await?;
Ok(())
}
// TODO: what happens if a correspondent changes from a user to a contact? maybe just have correspondent be a user, then have the client make the user show up as a contact in ui if they are in the loaded roster.
pub(crate) async fn read_chat(&self, chat: JID) -> Result<Chat, Error> {
// check if the chat correponding with the jid exists
let chat: Chat = sqlx::query_as("select correspondent from chats where correspondent = ?")
.bind(chat)
.fetch_one(&self.db)
.await?;
Ok(chat)
}
pub(crate) async fn mark_chat_as_chatted(&self, chat: JID) -> Result<(), Error> {
let jid = chat.as_bare();
sqlx::query!(
"update chats set have_chatted = true where correspondent = ?",
jid
)
.execute(&self.db)
.await?;
Ok(())
}
pub(crate) async fn update_chat_correspondent(
&self,
old_chat: Chat,
new_correspondent: JID,
) -> Result<Chat, Error> {
// TODO: update other chat data if it differs (for now there is only correspondent so doesn't matter)
let new_jid = &new_correspondent;
let old_jid = old_chat.correspondent();
sqlx::query!(
"update chats set correspondent = ? where correspondent = ?",
new_jid,
old_jid,
)
.execute(&self.db)
.await?;
let chat = self.read_chat(new_correspondent).await?;
Ok(chat)
}
// pub(crate) async fn update_chat
pub(crate) async fn delete_chat(&self, chat: JID) -> Result<(), Error> {
sqlx::query!("delete from chats where correspondent = ?", chat)
.execute(&self.db)
.await?;
Ok(())
}
/// TODO: sorting and filtering (for now there is no sorting)
pub(crate) async fn read_chats(&self) -> Result<Vec<Chat>, Error> {
let chats: Vec<Chat> = sqlx::query_as("select * from chats")
.fetch_all(&self.db)
.await?;
Ok(chats)
}
/// chats ordered by date of last message
// greatest-n-per-group
pub(crate) async fn read_chats_ordered(&self) -> Result<Vec<Chat>, Error> {
let chats = sqlx::query_as("select c.*, m.* from chats c join (select chat_id, max(timestamp) max_timestamp from messages group by chat_id) max_timestamps on c.id = max_timestamps.chat_id join messages m on max_timestamps.chat_id = m.chat_id and max_timestamps.max_timestamp = m.timestamp order by m.timestamp desc")
.fetch_all(&self.db)
.await?;
Ok(chats)
}
/// chats ordered by date of last message
// greatest-n-per-group
pub(crate) async fn read_chats_ordered_with_latest_messages(
&self,
) -> Result<Vec<(Chat, Message)>, Error> {
#[derive(sqlx::FromRow)]
pub struct ChatWithMessage {
#[sqlx(flatten)]
pub chat: Chat,
#[sqlx(flatten)]
pub message: Message,
}
// TODO: sometimes chats have no messages.
// TODO: i don't know if this will assign the right uuid to the latest message or the chat's id. should probably check but i don't think it matters as nothing ever gets called with the id of the latest message in the chats list
// TODO: it does matter in fact, as message updates and delivery receipts need to go to the right latest_message
let chats: Vec<ChatWithMessage> = sqlx::query_as("select c.*, m.* from chats c join (select chat_id, max(timestamp) max_timestamp from messages group by chat_id) max_timestamps on c.id = max_timestamps.chat_id join messages m on max_timestamps.chat_id = m.chat_id and max_timestamps.max_timestamp = m.timestamp order by m.timestamp desc")
.fetch_all(&self.db)
.await?;
let chats = chats
.into_iter()
.map(|chat_with_message| (chat_with_message.chat, chat_with_message.message))
.collect();
Ok(chats)
}
async fn read_chat_id(&self, chat: JID) -> Result<Uuid, Error> {
#[derive(sqlx::FromRow)]
struct Row {
id: Uuid,
}
let chat = chat.as_bare();
let chat_id: Row = sqlx::query_as("select id from chats where correspondent = ?")
.bind(chat)
.fetch_one(&self.db)
.await?;
let chat_id = chat_id.id;
Ok(chat_id)
}
async fn read_chat_id_opt(&self, chat: JID) -> Result<Option<Uuid>, Error> {
#[derive(sqlx::FromRow)]
struct Row {
id: Uuid,
}
let chat_id: Option<Row> = sqlx::query_as("select id from chats where correspondent = ?")
.bind(chat)
.fetch_optional(&self.db)
.await?;
let chat_id = chat_id.map(|row| row.id);
Ok(chat_id)
}
/// if the chat doesn't already exist, it must be created by calling create_chat() before running this function.
pub(crate) async fn create_message(
&self,
message: Message,
chat: JID,
from: JID,
) -> Result<(), Error> {
// TODO: one query
let from_jid = from.as_bare();
let chat_id = self.read_chat_id(chat).await?;
sqlx::query!("insert into messages (id, body, chat_id, from_jid, from_resource, timestamp) values (?, ?, ?, ?, ?, ?)", message.id, message.body.body, chat_id, from_jid, from.resourcepart, message.timestamp).execute(&self.db).await?;
Ok(())
}
pub(crate) async fn upsert_chat_and_user(&self, chat: &JID) -> Result<bool, Error> {
let bare_chat = chat.as_bare();
sqlx::query!(
"insert into users (jid) values (?) on conflict do nothing",
bare_chat,
)
.execute(&self.db)
.await?;
let id = Uuid::new_v4();
let chat: Chat = sqlx::query_as("insert into chats (id, correspondent, have_chatted) values (?, ?, ?) on conflict do nothing; select * from chats where correspondent = ?")
.bind(id)
.bind(bare_chat.clone())
.bind(false)
.bind(bare_chat)
.fetch_one(&self.db)
.await?;
tracing::debug!("CHECKING chat: {:?}", chat);
Ok(chat.have_chatted)
}
/// MUST upsert chat beforehand
pub(crate) async fn create_message_with_self_resource(
&self,
message: Message,
chat: JID,
// full jid
from: JID,
) -> Result<(), Error> {
let from_jid = from.as_bare();
if let Some(resource) = &from.resourcepart {
sqlx::query!(
"insert into resources (bare_jid, resource) values (?, ?) on conflict do nothing",
from_jid,
resource
)
.execute(&self.db)
.await?;
}
self.create_message(message, chat, from).await?;
Ok(())
}
/// create direct message from incoming. MUST upsert chat and user
pub(crate) async fn create_message_with_user_resource(
&self,
message: Message,
chat: JID,
// full jid
from: JID,
) -> Result<(), Error> {
let bare_chat = chat.as_bare();
let resource = &chat.resourcepart;
// sqlx::query!(
// "insert into users (jid) values (?) on conflict do nothing",
// bare_chat
// )
// .execute(&self.db)
// .await?;
// let id = Uuid::new_v4();
// sqlx::query!(
// "insert into chats (id, correspondent) values (?, ?) on conflict do nothing",
// id,
// bare_chat
// )
// .execute(&self.db)
// .await?;
if let Some(resource) = resource {
sqlx::query!(
"insert into resources (bare_jid, resource) values (?, ?) on conflict do nothing",
bare_chat,
resource
)
.execute(&self.db)
.await?;
}
self.create_message(message, chat, from).await?;
Ok(())
}
pub(crate) async fn read_message(&self, message: Uuid) -> Result<Message, Error> {
let message: Message = sqlx::query_as("select * from messages where id = ?")
.bind(message)
.fetch_one(&self.db)
.await?;
Ok(message)
}
// TODO: message updates/edits pub(crate) async fn update_message(&self, message: Message) -> Result<(), Error> {}
pub(crate) async fn delete_message(&self, message: Uuid) -> Result<(), Error> {
sqlx::query!("delete from messages where id = ?", message)
.execute(&self.db)
.await?;
Ok(())
}
// TODO: paging
pub(crate) async fn read_message_history(&self, chat: JID) -> Result<Vec<Message>, Error> {
let chat_id = self.read_chat_id(chat).await?;
let messages: Vec<Message> =
sqlx::query_as("select * from messages where chat_id = ? order by timestamp asc")
.bind(chat_id)
.fetch_all(&self.db)
.await?;
Ok(messages)
}
pub(crate) async fn read_cached_status(&self) -> Result<Online, Error> {
let online: Online = sqlx::query_as("select * from cached_status where id = 0")
.fetch_one(&self.db)
.await?;
Ok(online)
}
pub(crate) async fn upsert_cached_status(&self, status: Online) -> Result<(), Error> {
sqlx::query!(
"insert into cached_status (id, show, message) values (0, ?, ?) on conflict do update set show = ?, message = ?",
status.show,
status.status,
status.show,
status.status
).execute(&self.db).await?;
Ok(())
}
pub(crate) async fn delete_cached_status(&self) -> Result<(), Error> {
sqlx::query!("update cached_status set show = null, message = null where id = 0")
.execute(&self.db)
.await?;
Ok(())
}
pub(crate) async fn read_capabilities(&self, node: &str) -> Result<String, Error> {
#[derive(sqlx::FromRow)]
struct Row {
capabilities: String,
}
let row: Row =
sqlx::query_as("select capabilities from capability_hash_nodes where node = ?")
.bind(node)
.fetch_one(&self.db)
.await?;
Ok(row.capabilities)
}
pub(crate) async fn upsert_capabilities(
&self,
node: &str,
capabilities: &str,
) -> Result<(), Error> {
let now = Utc::now();
sqlx::query!(
"insert into capability_hash_nodes (node, timestamp, capabilities) values (?, ?, ?) on conflict do update set timestamp = ?, capabilities = ?", node, now, capabilities, now, capabilities
).execute(&self.db).await?;
Ok(())
}
}
|