aboutsummaryrefslogtreecommitdiff
path: root/lib/Matrix/Client/Room.pm6
blob: e0b14a20f7b0afd65c80a7a132a9ad2259592a21 (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use JSON::Tiny;
use Matrix::Client::Common;
use Matrix::Client::Requester;
use Matrix::Response;

unit class Matrix::Client::Room does Matrix::Client::Requester;

has $!name;
has $.id;

submethod TWEAK {
    $!url-prefix = "/rooms/$!id";
}

method !get-name() {
    CATCH {
        when X::Matrix::Response {
            .code ~~ /M_NOT_FOUND/
            ?? ($!name = '')
            !! fail
        }
        default { fail }
    }
    my $data = $.state('m.room.name');
    $!name = $data<name>;
}

method joined-members {
    my %data = from-json($.get("/joined_members").content);
    %data<joined>
}

method name {
    self!get-name;

    $!name
}

method fallback-name(--> Str) {
    my @members = $.joined-members.kv.map(
        -> $k, %v {
            %v<display_name> // $k
        }
    );

    $!name = do given @members.elems {
        when 1 { @members.first }
        when 2 { @members[0] ~ " and " ~ @members[1] }
        when * > 2 { @members.first ~ " and {@members.elems - 1} others" }
        default { "Empty room" }
    };
}

method messages() {
    my $res = $.get("/messages");
    my $data = from-json($res.content);

    return $data<chunk>.clone;
}

method send(Str $body!, Str :$type? = "m.text") {
    $Matrix::Client::Common::TXN-ID++;
    my $res = $.put(
        "/send/m.room.message/{$Matrix::Client::Common::TXN-ID}",
        msgtype => $type, body => $body
    );

    from-json($res.content)<event_id>
}

multi method state(--> Seq) {
    my $data = from-json($.get('/state').content);

    gather for $data.List -> $event {
        take Matrix::Response::StateEvent.new(:room-id($.id), |$event)
    }
}

multi method state(Str $event-type) {
    from-json($.get("/state/$event-type").content)
}

method send-state(Str:D $event-type, :$state-key = "", *%args --> Str) {
    my $res = $.put(
        "/state/$event-type/$state-key",
        |%args
    );
    from-json($res.content)<event_id>
}

method leave() {
    $.post('/leave')
}

method Str(--> Str) {
    "Room<id: {self.id}>"
}