summaryrefslogtreecommitdiffstats
path: root/lib/Bot/Flowdock/IRC.pm
blob: 7b199e1872ceee85e89c706d85d609fe0862f293 (plain) (blame)
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
package Bot::Flowdock::IRC;
use Moose;
use MooseX::NonMoose;

use JSON;
use List::MoreUtils 'any';
use Net::Flowdock 0.03;
use Net::Flowdock::Stream;
use String::Truncate 'elide';
use WWW::Shorten 'GitHub';

extends 'Bot::BasicBot';

sub FOREIGNBUILDARGS {
    my $class = shift;
    my (%args) = @_;
    delete $args{$_} for qw(email token key organization flow);
    return %args;
}

# XXX require this for now so that we can tell which account is the bot
# (to allow us to filter those out so we don't get echos)
# ideally, there would be a better way to detect this
has email => (
    is       => 'ro',
    isa      => 'Str',
    required => 1,
);

has token => (
    is  => 'ro',
    isa => 'Str',
    required => 1,
);

has key => (
    is  => 'ro',
    isa => 'Str',
);

has organization => (
    is       => 'ro',
    isa      => 'Str',
    required => 1,
);

has flow => (
    is       => 'ro',
    isa      => 'Str',
    required => 1,
);

has flowdock_api => (
    is      => 'ro',
    isa     => 'Net::Flowdock',
    lazy    => 1,
    default => sub {
        my $self = shift;
        Net::Flowdock->new(
            token => $self->token,
            ($self->key ? (key => $self->key) : ()),
        );
    }
);

has flowdock_stream => (
    is      => 'ro',
    isa     => 'Net::Flowdock::Stream',
    lazy    => 1,
    default => sub {
        my $self = shift;
        Net::Flowdock::Stream->new(
            token => $self->token,
            flows => [join('/', $self->organization, $self->flow)],
        );
    },
);

has _id_map => (
    traits  => ['Hash'],
    isa     => 'HashRef[Str]',
    default => sub { {} },
    handles => {
        _set_name_for_id => 'set',
        name_from_id     => 'get',
        flowdock_names   => 'values',
    },
);

has _my_id => (
    is  => 'rw',
    isa => 'Int',
);

sub connected {
    my $self = shift;

    my $flow = $self->flowdock_api->get_flow({
        organization => $self->organization,
        flow         => $self->flow,
    });

    for my $user (@{ $flow->body->{users} }) {
        $self->_set_name_for_id($user->{id}, $user->{nick});
        if ($user->{email} eq $self->email) {
            $self->_my_id($user->{id});
        }
    }
}

sub tick {
    my $self = shift;

    for (1..20) {
        my $event = $self->flowdock_stream->get_next_event;

        last unless $event;

        next if $event->{user} == $self->_my_id;

        my $app = $event->{app} || '';
        my $type = $event->{event};

        if ($app eq 'chat') {
            if ($type eq 'message' || $type eq 'line') {
                $self->flowdock_message($event);
            }
            elsif ($type eq 'status') {
                $self->flowdock_status($event);
            }
            elsif ($type eq 'user-edit') {
                $self->flowdock_user_edit($event);
            }
            else {
                warn "Unknown chat event type $type: " . encode_json($event);
            }
        }
        elsif ($app eq 'influx') { # i think this is timeline stuff
            if ($type eq 'vcs' && any { /^github/ } @{ $event->{tags} }) {
                $self->flowdock_github_event($event);
            }
            else {
                $self->flowdock_unknown_inbox_event($event);
            }
        }
        else {
            # we don't care activity events
            if ($type ne 'activity.user') {
                warn "Unknown event type $type for unknown app $app: " . encode_json($event);
            }
        }
    }

    return 1;
}

sub flowdock_message {
    my $self = shift;
    my ($event) = @_;

    # skip if this is a message that we just sent
    return if exists $event->{external_user_name};

    my $name = $self->name_from_id($event->{user});
    $self->_say_to_channel(
        $event->{content}, $name,
        emoted => ($event->{event} eq 'line' || $event->{event} eq 'status')
    );
}

sub flowdock_status {
    my $self = shift;
    my ($event) = @_;

    $self->flowdock_message($event);
}

sub flowdock_user_edit {
    my $self = shift;
    my ($event) = @_;

    my $id = $event->{user};
    my $nick = $event->{content}{user}{nick};
    my $oldnick = $self->name_from_id($id);

    $self->_say_to_channel("$oldnick is now known as $nick");

    $self->_set_name_for_id($id, $nick);
}

sub flowdock_github_event {
    my $self = shift;
    my ($event) = @_;

    my $content = $event->{content};

    my $pusher = $content->{pusher}{name};
    $pusher = $content->{commits}[0]{author}{username} . '(?)'
        if $pusher eq 'none'; # XXX ?
    my $commits = @{ $content->{commits} };
    my $repo = $content->{repository}{name};
    (my $branch = $content->{ref}) =~ s{^refs/heads/}{};
    my $compare = makeashorterlink($content->{compare});
    my $commit_messages = join(' / ', map { $_->{message} }
                                          @{ $content->{commits} });

    my $msg = "[github] $pusher pushed $commits commit"
            . ($commits == 1 ? '' : 's')
            . " to $repo/$branch (compare $compare): $commit_messages";

    $self->_say_to_channel($msg);
}

sub flowdock_unknown_inbox_event {
    my $self = shift;
    my ($event) = @_;

    warn "unknown timeline event type $event->{event}: " . encode_json($event);
    $self->_say_to_channel("[$event->{event}] unknown");
}

sub said {
    my $self = shift;
    my ($args) = @_;

    my $address = $args->{address} || '';

    return if $address eq 'msg';

    # XXX: Bot::BasicBot does a lot of "helpful" munging of messages that we
    # receive. this is annoying for this use case. look into switching to raw
    # poco::irc at some point.
    my $msg = ($address ? "$address: " : '') . $args->{body};

    # XXX when they allow external users to post status update events, fix this
    $msg = '*' . $msg . '*'
        if $args->{emoted};

    $self->_say_to_flowdock($msg, $args->{who});

    return;
}

around emoted => sub {
    my $orig = shift;
    my $self = shift;
    my ($args) = @_;
    $args->{emoted} = 1;
    return $self->$orig($args);
};

sub nick_change {
    my $self = shift;
    my ($old, $new) = @_;

    $self->_say_to_flowdock("$old is now known as $new");
}

sub _say_to_channel {
    my $self = shift;
    my ($body, $from, %params) = @_;

    if (defined($from)) {
        $body = $params{emoted} ? "* $from $body" : "<$from> $body";
    }
    else {
        $body = "-!- $body";
    }

    $body =~ s/\n/ /g;
    $body = elide($body, 275, { at_space => 1 });

    $self->say(
        channel => ($self->channels)[0],
        body    => $body,
    );
}

sub _say_to_flowdock {
    my $self = shift;
    my ($body, $from) = @_;

    if (defined($from)) {
        $self->flowdock_api->push_chat({
            external_user_name => $from,
            content            => $body,
        });
    }
    else {
        $self->flowdock_api->send_message({
            organization => $self->organization,
            flow         => $self->flow,
            event        => 'status',
            content      => $body,
        });
    }
}

__PACKAGE__->meta->make_immutable;
no Moose;

1;