aboutsummaryrefslogtreecommitdiff
path: root/lib/firebase/database.dart
blob: 46970ce83b24a744091199f7c8e1b6db4f61c230 (plain)
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
import 'dart:async';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:linkchat/models/group.dart';
import 'package:linkchat/models/message.dart';
import 'package:simple_link_preview/simple_link_preview.dart';

import '../models/user.dart';

class Database {
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;

  Future<FsUser?> getUserById(String uid) async {
    var snap = await _firestore.collection('users').doc(uid).get();
    return snap.data() != null ? FsUser.fromMap(snap.data()!) : null;
  }

  Stream<List<FsUser>> getAllUsers() {
    return _firestore.collection('users').snapshots().map<List<FsUser>>((e) {
      return e.docs.map((e) {
        return FsUser.fromMap(e.data());
      }).toList();
    });
  }

  Future<void> saveUser(FsUser user) async {
    await _firestore.collection('users').doc(user.uid).set({
      "uid": user.uid,
      "displayName": user.displayName,
      "photoUrl": user.photoUrl,
      "email": user.email,
    });
  }

  Stream<List<Group>> getGroupsByUserID(String uid) {
    return _firestore
        .collection('groups')
        .where('members', arrayContains: uid)
        .snapshots()
        .map<List<Group>>((e) {
      return e.docs.map((e) {
        return Group.fromMap(e.data(), e.id);
      }).toList();
    });
  }

  Stream<List<Message>> getMessagesByGroupId(String id) {
    return _firestore
        .collection('messages')
        .doc(id)
        .collection('messages')
        .orderBy('sentAt')
        .snapshots()
        .map<List<Message>>((e) {
      return e.docs.map((e) {
        return Message.fromMap(e.data());
      }).toList();
    });
  }

  Future<void> saveMessage(Message msg, String groupId) async {
    LinkPreview? preview = await SimpleLinkPreview.getPreview(msg.messageText);
    await _firestore
        .collection('messages')
        .doc(groupId)
        .collection('messages')
        .add(msg.toMap(preview: preview));
    await _firestore.collection('groups').doc(groupId).update({
      "recentMessage": msg.toMap(preview: preview),
    });
  }

  Future<void> saveGroup(Group group) async {
    await _firestore.collection('groups').add(group.toMap());
  }
}