-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathghurlbot.pl
executable file
·2318 lines (1905 loc) · 82.2 KB
/
ghurlbot.pl
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env perl
#
# This IRC 'bot expands short references to issues, pull requests,
# persons and teams on GitHub to full URLs. See the perldoc at the end
# for how to run it and manual.html for the interaction on IRC.
#
#
# TODO: The map-file should contain the IRC network, not just the
# channel names.
#
# TODO: Allow "action-9" as an alternative for "#9"?
#
# TODO: Add a permission system to limit who can create, close, reopen
# or comment on issues? (Maybe people on IRC can somehow prove to ghurlbot
# that they have a GitHub account and maybe ghurlbot can find out if
# that account has the right to close an issue?)
#
# TODO: A way for a user to ask for the github login of a given nick?
# Or to ask for all known aliases?
#
# TODO: Should all responses from the bot other than expanded
# references be emoted ("/me")?
#
# TODO: Get plain text instead of markdown from GitHub? (Requires
# setting the Accept header to "application/vnd.github.text+json" and
# using the "body_text" field instead of "body" from the returned
# JSON.)
#
# TODO: Add and remove labels from issues?
#
# TODO: Add a way to use other servers than github.com.
#
# TODO: Set the default to not expanding names ("set names = off")?
#
# TODO: Try to track nick changes and update matching aliases?
#
# TODO: Add comments (with the "note" or "comment" commands) to the
# most recently created issue without having to say its number? Refer
# to it as "this" or "that"?
#
# TODO: Edit an issue? The bot can edit issues it created itself, with
# PATCH
# https://api.github.com/repos/{owner}/{repo}/issues/{issue_number}.
# It is possible to change the title, the body, the assignees and the
# labels: "edit #7: A new title", "edit text #7: Text for the body",
# "edit due #7: in two weeks", etc.
#
# TODO: handle_process_output() should use emote() instead of say()
# when the output is in response to a /me (emoted) command.
#
# Created: 2022-01-11
# Author: Bert Bos <[email protected]>
#
# Copyright © 2022-2023 World Wide Web Consortium, (Massachusetts Institute
# of Technology, European Research Consortium for Informatics and
# Mathematics, Keio University, Beihang). All Rights Reserved. This
# work is distributed under the W3C® Software License
# (http://www.w3.org/Consortium/Legal/2015/copyright-software-and-document)
# in the hope that it will be useful, but WITHOUT ANY WARRANTY;
# without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.
package GHURLBot;
use FindBin;
use lib "$FindBin::Bin"; # Look for modules in agendabot's directory
use parent 'Bot::BasicBot::ExtendedBot';
use strict;
use warnings;
use utf8;
use v5.16; # Enable fc
use Getopt::Std;
use Scalar::Util 'blessed';
use Term::ReadKey; # To read a password without echoing
use open qw(:encoding(UTF-8)); # Undeclared streams in UTF-8
use File::Temp qw(tempfile tempdir);
use File::Copy;
use Fcntl ':flock';
use LWP;
use LWP::ConnCache;
use JSON;
use Date::Manip::Date;
use Date::Manip::Delta;
use POSIX qw(strftime);
use Net::Netrc;
use Encode qw(encode decode);
use POE; # For OBJECT, ARG0 and ARG1
use constant MANUAL => 'https://w3c.github.io/GHURLBot/manual.html';
use constant HOME => 'https://w3c.github.io/GHURLBot';
use constant VERSION => '0.5';
use constant DEFAULT_DELAY => 15;
use constant DEFAULT_MAXLINES => 10; # Nr. of issues to list in full. ( <= 100)
my $githubissue =
qr{https://github\.com/[a-z0-9._-]+/[a-z0-9._-]+/issues/[0-9]+}i;
# GitHub limits requests to 5000 per hour per authenticated user (and
# will return 403 if the limit is exceeded). We impose an extra limit
# of 100 changes to a given repository in 10 minutes.
use constant MAXRATE => 100;
use constant RATEPERIOD => 10;
# init -- initialize some parameters
sub init($)
{
my $self = shift;
my $errmsg;
$self->{delays} = {}; # Maps from a channel to a delay (# of lines)
$self->{linenumber} = {}; # Maps from a channel to a # of lines seen
$self->{joined_channels} = {}; # Set of all channels currently joined
$self->{history} = {}; # Maps a channel to a map of when each ref was expanded
$self->{suspend_issues} = {}; # Set of channels currently not expanding issues
$self->{suspend_names} = {}; # Set of channels currently not expanding names
$self->{repos} = {}; # Maps from a channel to a list of repository URLs
# Create a user agent to retrieve data from GitHub.
if ($self->{github_api_token}) {
$self->{ua} = LWP::UserAgent->new(agent => blessed($self) . '/' . VERSION,
timeout => 10, keep_alive => 1, env_proxy => 1);
$self->{ua}->default_header('X-GitHub-Api-Version', '2022-11-28');
$self->{ua}->default_header('Accept', 'application/json');
$self->{ua}->default_header(
'Authorization' => 'token ' . $self->{github_api_token});
}
$errmsg = $self->read_rejoin_list() and die "$errmsg\n";
$errmsg = $self->read_mapfile() and die "$errmsg\n";
$self->log("Connecting...");
return 1;
}
# read_rejoin_list -- read or create the rejoin file, if any
sub read_rejoin_list($)
{
my $self = shift;
my $mode;
return if ! $self->{rejoinfile};
# If the rejoinfile exists, open it for reading, but also for
# writing, because writing mode is needed to set a lock on it. If
# the file doesn't exist, create it.
$mode = -e $self->{rejoinfile} ? "+<" : ">";
open $self->{rejoinfile_handle}, $mode, $self->{rejoinfile} or
return "$self->{rejoinfile}: $!";
flock $self->{rejoinfile_handle}, LOCK_EX | LOCK_NB or
return "$self->{rejoinfile}: already in use";
return if $mode eq ">"; # File just created, nothing to read
$self->log("Reading $self->{rejoinfile}");
while (readline $self->{rejoinfile_handle}) {
chomp;
$self->{joined_channels}->{$_} = 1;
$self->{linenumber}->{$_} = 0;
$self->{history}->{$_} = {};
}
# The connected() method takes care of rejoining those channels.
# Do not close the file. We want to keep a lock on it.
return; # undef return means there were no errors
}
# rewrite_rejoinfile -- replace the rejoinfile with an updated one
sub rewrite_rejoinfile($)
{
my ($self) = @_;
return if ! $self->{rejoinfile};
eval {
# Write a temporary file in the same directory as rejoinfile. When
# done, rename it to rejoinfile. This way, the rejoinfile will
# always be a complete file, even if the program is interrupted.
# Get a lock on the temporary file before closing the filehandle
# of the old rejoinfile (which release the lock on that file).
my ($fh, $tempname) = tempfile($self->{rejoinfile}."XXXX", UNLINK => 1);
flock $fh, LOCK_EX | LOCK_NB or
$self->log("Cannot lock $tempname, continuing anyway");
foreach (keys %{$self->{joined_channels}}) {
print $fh "$_\n" or die "$tempname: $!";
}
$fh->flush;
move($tempname, $self->{rejoinfile});
close $self->{rejoinfile_handle}; # Releases lock
$self->{rejoinfile_handle} = $fh;
};
$self->log($@) if $@;
}
# read_mapfile -- read or create the file mapping channels to repositories
sub read_mapfile($)
{
my $self = shift;
my ($channel, $fh, $mode);
# If the file exists, open it for reading and writing, because write
# mode is needed to set a lock on it. Otherwise create it.
$mode = -e $self->{mapfile} ? "+<" : ">";
open $self->{mapfile_handle}, $mode, $self->{mapfile} or
return "$self->{mapfile}: $!";
flock $self->{mapfile_handle}, LOCK_EX | LOCK_NB or
return "$self->{mapfile}: already in use";
return if $mode eq ">"; # File just created, nothing to read
$self->log("Reading $self->{mapfile}");
while (readline $self->{mapfile_handle}) {
# Empty lines and line that start with "#" are ignored. Other
# lines must start with a keyword:
#
# alias NAME GITHUB-NAME
# When an action is assigned to NAME, use GITHUB-NAME instead.
# channel CHANNEL
# Lines up to the next "channel" apply to CHANNEL.
# repo REPO
# Add REPO to the list of repositories for the current CHANNEL.
# delay NN
# Set the delay for CHANNEL to NN.
# issues off
# Do not expand issue references on CHANNEL.
# names off
# Do not expand name references on CHANNEL.
# ignore NAME
# Ignore commands that open/close issues when they come from NAME.
# maxlines NN
# When listing issues in full, show up to NN issues at a time.
chomp;
if ($_ =~ /^#/) {
# Comment, ignored.
} elsif ($_ =~ /^\s*$/) {
# Empty line, ignored.
} elsif ($_ =~ /^\s*alias\s+([^\s]+)\s+([^\s]+)\s*$/) {
$self->{github_names}->{fc $1} = $2;
} elsif ($_ =~ /^\s*channel\s+([^\s]+)\s*$/) {
$channel = $1;
} elsif (! defined $channel) {
return "$self->{mapfile}:$.: missing \"channel\" line";
} elsif ($_ =~ /^\s*repo\b\s*([^\s]*)\s*$/) {
push @{$self->{repos}->{$channel}}, $1 if $1;
} elsif ($_ =~ /^\s*delay\s+([0-9]+)\s*$/) {
$self->{delays}->{$channel} = 0 + $1;
} elsif ($_ =~ /^\s*issues\s+off\s*$/) {
$self->{suspend_issues}->{$channel} = 1;
} elsif ($_ =~ /^\s*names\s+off\s*$/) {
$self->{suspend_names}->{$channel} = 1;
} elsif ($_ =~ /^\s*ignore\s+([^\s]+)\s*$/) {
$self->{ignored_nicks}->{$channel}->{fc $1} = $1;
} elsif ($_ =~ /^\s*maxlines\s+([0-9]+)\s*$/) {
$self->{maxlines}->{$channel} = 0 + $1;
} else {
return "$self->{mapfile}:$.: wrong syntax";
}
}
# Do not close the file, because we want to keep a lock on it.
return undef; # No errors
}
# write_mapfile -- write the current status to file
sub write_mapfile($)
{
my $self = shift;
eval {
my ($fh, $tempname) = tempfile($self->{mapfile}."XXXX", UNLINK => 1);
flock $fh, LOCK_EX | LOCK_NB or
$self->log("Cannot lock $tempname. Continuing anyway");
# Sorting (of channel names and aliases) is not
# necessary, but helps make the mapfile more readable.
#
foreach my $channel
(sort(uniq(keys(%{$self->{repos}}), keys(%{$self->{suspend_issues}}),
keys(%{$self->{suspend_names}}), keys(%{$self->{delays}}),
keys(%{$self->{ignored_nicks}})))) {
printf $fh "channel %s\n", $channel or die $!;
printf $fh "repo %s\n", $_ for @{$self->{repos}->{$channel} // []};
printf $fh "delay %d\n", $self->{delays}->{$channel} if
defined $self->{delays}->{$channel} &&
$self->{delays}->{$channel} != DEFAULT_DELAY;
printf $fh "issues off\n" if $self->{suspend_issues}->{$channel};
printf $fh "names off\n" if $self->{suspend_names}->{$channel};
printf $fh "ignore %s\n", $_
for sort values %{$self->{ignored_nicks}->{$channel} // {}};
printf $fh, "maxlines %d\n", $self->{$channel} if
defined $self->{$channel} && $self->{$channel} != DEFAULT_MAXLINES;
printf $fh "\n" or die $!;
}
foreach my $nick (sort keys %{$self->{github_names} // {}}) {
printf $fh "alias %s %s\n",$nick,$self->{github_names}->{$nick} or die $!;
}
$fh->flush;
move($tempname, $self->{mapfile});
close $self->{mapfile_handle}; # Releases lock
$self->{mapfile_handle} = $fh;
};
$self->log($@) if $@;
}
# part_channel -- leave a channel, the channel name is given as argument
sub part_channel($$)
{
my ($self, $channel) = @_;
# Use inherited method to leave the channel.
$self->SUPER::part_channel($channel);
# Remove channel from list of joined channels.
if (delete $self->{joined_channels}->{$channel}) {
# If we keep a rejoin file, remove the channel from it.
$self->rewrite_rejoinfile();
}
}
# chanjoin -- called when somebody joins a channel
sub chanjoin($$)
{
my ($self, $mess) = @_;
my $who = $mess->{who};
my $channel = $mess->{channel};
if ($who eq $self->nick()) { # It's us
$self->log("Joined $channel");
# Initialize data structures with information about this channel.
if (!defined $self->{joined_channels}->{$channel}) {
$self->{joined_channels}->{$channel} = 1;
$self->{linenumber}->{$channel} = 0;
$self->{history}->{$channel} = {};
# If we keep a rejoin file, add the channel to it.
$self->rewrite_rejoinfile();
}
}
return;
}
# repository_to_url -- expand a repository name to a full URL, or return error
sub repository_to_url($$$)
{
my ($self, $channel, $repo) = @_;
my ($base, $owner, $name) = $repo =~
/^([a-z]+:\/\/(?:[^\/?\#]*\/)*?)?([^\/?\#]+\/)?([^\/?\#]+)\/?$/i;
return ($repo, undef)
if $base; # It's already a full URL
return (defined $self->{repos}->{$channel}->[0] ?
$self->{repos}->{$channel}->[0] =~ s/[^\/]+\/[^\/]+$/$owner$name/r :
"https://github.com/$owner$name", undef)
if $owner;
return (undef, "sorry, that doesn't look like a valid repository: $repo")
if ! $name;
return ("https://github.com/w3c/$name", undef)
# or: (undef,"sorry, I don't know the owner. Please, use 'OWNER/$name'")
if ! defined $self->{repos}->{$channel};
return ($self->{repos}->{$channel}->[0] =~ s/[^\/]+$/$name/r, undef);
}
# add_repositories -- remember the repositories $2 for channel $1
sub add_repositories($$$)
{
my ($self, $channel, $repos) = @_;
my $err = '';
my @h;
foreach (split /[ ,]+/, $repos) {
my ($repository, $msg) = $self->repository_to_url($channel, $_);
if ($msg) {
$err .= "$msg\n";
} else {
# Add $repository at the head of the list of repositories for this
# channel, or move it to the head, if it was already in the list.
if (defined $self->{repos}->{$channel}) {
@h = grep $_ ne $repository, @{$self->{repos}->{$channel}};
}
unshift @h, $repository;
$self->{repos}->{$channel} = \@h;
}
}
$self->write_mapfile();
$self->{history}->{$channel} = {}; # Forget recently expanded issues
return $err if $err;
return "OK. But note that I am not currently expanding issues. " .
"You can change that with: ".$self->nick()." issues on"
if defined $self->{suspend_issues}->{$channel};
return 'OK.';
}
# remove_repositories -- remove one or more repositories from this channel
sub remove_repositories($$$)
{
my ($self, $channel, $repos) = @_;
my $err = '';
my $found = 0;
return "sorry, this channel has no repositories."
if scalar @{$self->{repos}->{$channel}} == 0;
foreach my $repo (split /[ ,]+/, $repos) {
my @x = grep /(?:^|\/)\Q$repo\E$/, @{$self->{repos}->{$channel}};
if (scalar @x) {
my @h = grep $_ ne $x[0], @{$self->{repos}->{$channel}};
$self->{repos}->{$channel} = \@h;
$found = 1;
} else {
$err .= "$repo was already removed.\n";
}
}
$self->write_mapfile() if $found; # Write the new list to disk.
$self->{history}->{$channel} = {}; # Forget recently expanded issues
return $err ? $err : 'OK.';
}
# clear_repositories -- forget all repositories for a channel
sub clear_repositories($$)
{
my ($self, $channel) = @_;
delete $self->{repos}->{$channel};
return 'OK.';
}
# find_matching_repository -- return the repository that matches $prefix
sub find_matching_repository($$$)
{
my ($self, $channel, $prefix) = @_;
my ($repos, @matchingrepos);
$repos = $self->{repos}->{$channel} // [];
# First find all repos in our list with the exact name $prefix
# (with or without an owner part). If there are none, find all
# repos whose name start with $prefix. E.g., if prefix is "i",
# it will match repos that have an "i" at the start of the repo
# name, such as "https://github.com/w3c/i18n" and
# "https://github.com/foo/ima"; if prefix is "w3c/i" it will
# match a repo that has "w3c" as owner and a repo name that
# starts with "i", i.e., it will only match the first of those
# two; and likewise if prefix is "i18". If prefix is empty, all
# repos match. (It is important to start with an exact match,
# otherwise if there two repos "rdf-star" and
# "rdf-star-wg-charter", you can never get to the former,
# because it is a prefix of the latter.)
@matchingrepos = grep $_ =~ /\/\Q$prefix\E$/i, @$repos or
@matchingrepos = grep $_ =~ /\/\Q$prefix\E[^\/]*$/i, @$repos;
# Found one or more repos whose name starts with $prefix:
return $matchingrepos[0] if @matchingrepos;
# Did not find a match, but $prefix has a "/", maybe it is a repo name:
return "https://github.com/$prefix" if $prefix =~ /\//;
# Use the owner part of the most recent repo:
return $repos->[0] =~ s/[^\/]*$/$prefix/r if $prefix && scalar @$repos;
# No recent repo, so we can't guess the owner:
return undef;
}
# find_repository_for_issue -- expand issue reference to full URL, or undef
sub find_repository_for_issue($$$)
{
my ($self, $channel, $ref) = @_;
# $ref may be an abbreviated issue reference (#nn, repo#nn, or
# owner/repo#nn), or a full URL
# (https://github.com/owner/repo/issues/nn).
if ($ref =~
m{^(https://github\.com/[a-z0-9._-]+/[a-z0-9._-]+)/issues/([0-9]+)$}i) {
return ($1, $2);
} elsif ($ref =~ m{^([a-z0-9/._-]*)#([0-9]+)$}i) {
my $issue = $2;
return ($self->find_matching_repository($channel, $1), $issue);
} else {
$self->log("Bug! wrong argument to find_repository_for_issue()");
return (undef, undef);
}
}
# name_to_login -- return the github name for a name, otherwise return the name
sub name_to_login($$)
{
my ($self, $nick) = @_;
# A name prefixed with "@" is assumed to be a GitHub login.
# If we have an alias for the nick, use that.
# Otherwise just return the nick itself.
return $1 if $nick =~ /^@(.*)/;
return $self->{github_names}->{fc $nick} // $nick;
}
# check_and_update_rate -- false if the rate is already too high, or update it
sub check_and_update_rate($$)
{
my ($self, $repository) = @_;
my $now = time;
if (($self->{ratestart}->{$repository} // 0) < $now - 60 * RATEPERIOD) {
# No rate period for this repository started, or it started more
# than RATEPERIOD minutes ago. Start a new period, count one
# action, and return OK.
$self->{ratestart}->{$repository} = $now;
$self->{rate}->{$repository} = 1;
return 1;
} elsif (($self->{rate}->{$repository} // 0) < MAXRATE) {
# The current rate period started less than RATEPERIOD minutes
# ago, but we have done less than MAXRATE actions in this period.
# Increase the number of actions by one and return OK.
$self->{rate}->{$repository}++;
return 1;
} else {
# The current rate period started less than RATEPERIOD minutes ago
# and we have already done MAXRATE actions in this period. So
# return FAIL.
$self->log("Rate limit reached for $repository");
return 0;
}
}
# handle_process_output -- handler for text from a forked process, calls say()
sub handle_process_output($$$)
{
my ($self, $body, $wheel_id) = @_[OBJECT, ARG0, ARG1];
# This is not a method, but a POE event handler. It is called when a
# background process prints a line to STDOUT. $body has the contents
# of that line.
# If the text starts with "say", just write it to IRC (minus the
# "say"). No other keywords are currently defined.
$body = decode('UTF-8', $body);
chomp $body; # remove newline necessary to move data;
if (($body =~ s/^say //)) {
# Pick up the default arguments we squirreled away earlier.
my $args = $self->{forks}{$wheel_id}{args};
$args->{body} = $body;
$self->say($args);
} else {
die "Bug: unrecognized output from a background process(): $body\n";
}
return;
}
# get_github_id_and_type -- get GitHub's ID for an issue/PR/discussion
sub get_github_id_and_type($$$$$$)
{
my ($self, $owner, $repo, $issuenumber, $who, $channel) = @_;
my ($q, $ref, $res);
# This function is called from forked processes. It should not
# modify anything in $self and should use print for output rather
# than $self->say().
$q = "query {
repository(owner: \"$owner\", name: \"$repo\") {
discussion(number: $issuenumber) { id }
issue(number: $issuenumber) { id }
pullRequest(number: $issuenumber) { id } } }";
$res = $self->{ua}->post("https://api.github.com/graphql",
'Content' => encode_json({query => $q}));
print STDERR "Channel $channel, get id of $owner/$repo#$issuenumber -> ",
$res->code, "\n";
return (undef, undef) if $res->code != 200;
$ref = decode_json($res->decoded_content)->{data}->{repository};
return ($ref->{issue}->{id}, 'issue') if defined $ref->{issue};
return ($ref->{pullRequest}->{id}, 'pr') if defined $ref->{pullRequest};
return ($ref->{discussion}->{id}, 'discussion') if defined $ref->{discussion};
return (undef, undef);
}
# create_action_process -- process that creates an action item on GitHub
sub create_action_process($$$$$$$$)
{
my ($body, $self, $channel, $owner, $repo, $names, $text, $who) = @_;
my (@names, @labels, $res, $content, $date, $due, $today, $s, $login);
# This is not a method, but a routine that is run as a background
# process by create_action(). Output to STDERR is meant for the log.
# Output to STDOUT goes to IRC, via handle_process_output().
# Creating an action item is like creating an issue, but with
# assignees and a label "action".
binmode(STDOUT, ":utf8");
binmode(STDERR, ":utf8");
@names = map($self->name_to_login($_),
grep(/./, split(/ *,? +and +| *, */, $names)));
# If the action has a due date, remove it and put it in $date. Or use 1 week.
$date = new Date::Manip::Date;
if ($text =~ /^(.*) *- *due +(.*?)[. ]*$/i && $date->parse($2) == 0) {
$text = $1;
} elsif ($text =~ /^(.*) +due +(.*?)[. ]*$/i && $date->parse($2) == 0) {
$text = $1;
} else {
$date->parse("next week"); # Default to 1 week
}
$text =~ s/,$//; # Remove any final comma
# When a due date is in the past, adjust the year and print a warning.
$today = new Date::Manip::Date;
$today->parse("today");
if ($today->cmp($date) > 0) {
my $delta = new Date::Manip::Delta;
$delta->parse("+1 year");
$date = $date->calc($delta) until $date->cmp($today) >= 0;
print "say Assumed the due date is in ", $date->printf("%Y"), "\n";
}
$due = $date->printf("Due: %Y-%m-%d (%A %e %B)");
$login = $self->name_to_login($who);
$login = '@'.$login if $login ne $who;
$s = "Opened by $login via IRC channel $channel on $self->{server}\n\n$due\n";
$res = $self->{ua}->post(
"https://api.github.com/repos/$owner/$repo/issues",
'Content' => encode_json({title => $text, assignees => \@names,
body => "$s", labels => ['action']}));
print STDERR "Channel $channel, new action \"$text\" in $owner/$repo -> ",
$res->code, "\n";
if ($res->code == 403) {
print "say Cannot create action. Forbidden.\n";
} elsif ($res->code == 401) {
print "say Cannot create action. I have insufficient (or expired) authorization.\n";
} elsif ($res->code == 404) {
print "say Cannot create action. Please, check that I have write access to $owner/$repo\n";
} elsif ($res->code == 410) {
print "say Cannot create action. The repository $owner/$repo is gone.\n";
} elsif ($res->code == 422) {
print "say Cannot create action. Validation failed. Maybe ",
scalar @names > 1 ? "one of the names" : $names[0],
" is not a valid user for $owner/$repo?\n";
} elsif ($res->code == 503) {
print "say Cannot create action. Service unavailable.\n";
} elsif ($res->code != 201) {
print "say Cannot create action. Error ", $res->code, "\n";
} else {
# Issues created. Check that label and assignees were also added.
$content = decode_json($res->decoded_content);
my %n; $n{fc $_->{login}} = 1 foreach @{$content->{assignees}};
@names = grep !exists $n{fc $_}, @names; # Remove names that were assigned
if (! @{$content->{labels}}) {
print "say I created -> issue #$content->{number} $content->{html_url}\n",
"say but I could not add the \"action\" label.\n",
"say That probably means I don't have push permission on $owner/$repo.\n";
} elsif (@names) { # Some names were not assigned
print "say I created -> action #$content->{number} $content->{html_url}\n",
"say but I could not assign it to ", join(", ", @names), "\n",
"say They probably aren't collaborators on $owner/$repo.\n";
} else {
print "say Created -> action #$content->{number} $content->{html_url}\n";
}
}
}
# create_action -- create a new action item
sub create_action($$$$)
{
my ($self, $channel, $names, $text, $who) = @_;
my ($repository, $owner, $repo);
return "Sorry, I cannot create actions, because I am running without " .
"an access token for GitHub." if !defined $self->{github_api_token};
# Check that this channel has a repository and that it is on GitHub.
$repository = $self->{repos}->{$channel}->[0] or
return "Sorry, I don't know what repository to use.";
($owner, $repo) =
$repository =~ /^https:\/\/github\.com\/([^\/]+)\/([^\/]+)$/i or
return "Cannot create actions on $repository as it is not on github.com.";
# Check the rate limit.
$self->check_and_update_rate("$owner/$repo") or
return "Sorry, for security reasons, I won't touch a repository more ".
"than ".MAXRATE." times in ".RATEPERIOD." minutes. ".
"Please, try again later.";
$self->forkit(run => \&create_action_process,
handler => "handle_process_output", channel => $channel,
arguments => [$self, $channel, $owner, $repo, $names, $text, $who]);
return undef; # The forked process will print a result
}
# create_issue_process -- process that creates an issue on GitHub
sub create_issue_process($$$$$$)
{
my ($body, $self, $channel, $owner, $repo, $text, $who) = @_;
my ($res, $content, $login, $s);
# This is not a method, but a routine that is run as a background
# process by create_issue(). Output to STDERR is meant for the log.
# Output to STDOUT goes to IRC, via handle_process_output().
binmode(STDOUT, ":utf8");
binmode(STDERR, ":utf8");
$login = $self->name_to_login($who);
$login = '@'.$login if $login ne $who;
$s = "Opened by $login via IRC channel $channel on $self->{server}";
$res = $self->{ua}->post(
"https://api.github.com/repos/$owner/$repo/issues",
'Content' => encode_json({title => $text, body => $s}));
print STDERR "Channel $channel, new issue \"$text\" in $owner/$repo -> ",
$res->code, "\n";
if ($res->code == 403) {
print "say Cannot create issue. Forbidden.\n";
} elsif ($res->code == 401) {
print "say Cannot create issue. I have insufficient (or expired) authorization.\n";
} elsif ($res->code == 404) {
print "say Cannot create issue. Please, check that I have write access to $owner/$repo.\n";
} elsif ($res->code == 410) {
print "say Cannot create issue. The repository $owner/$repo is gone.\n";
} elsif ($res->code == 422) {
print "say Cannot create issue. Validation failed.\n";
} elsif ($res->code == 503) {
print "say Cannot create issue. Service unavailable.\n";
} elsif ($res->code != 201) {
print "say Cannot create issue. Error ", $res->code, "\n";
} else {
$content = decode_json($res->decoded_content);
print "say Created -> issue #$content->{number} $content->{html_url}",
" $content->{title}\n";
}
}
# create_issue -- create a new issue
sub create_issue($$$$)
{
my ($self, $channel, $text, $who) = @_;
my ($repository, $owner, $repo);
return "Sorry, I cannot create issues, because I am running without " .
"an access token for GitHub." if !defined $self->{github_api_token};
# Check that this channel has a repository and that it is on GitHub.
$repository = $self->{repos}->{$channel}->[0] or
return "Sorry, I don't know what repository to use.";
($owner, $repo) =
$repository =~ /^https:\/\/github\.com\/([^\/]+)\/([^\/]+)$/i or
return "Cannot create issues on $repository as it is not on github.com.";
# Check the rate limit.
$self->check_and_update_rate("$owner/$repo") or
return "Sorry, for security reasons, I won't touch a repository more " .
"than ".MAXRATE." times in ".RATEPERIOD." minutes. " .
"Please, try again later.";
$self->forkit(run => \&create_issue_process,
handler => "handle_process_output", channel => $channel,
arguments => [$self, $channel, $owner, $repo, $text, $who]);
return undef; # The forked process will print a result
}
# close_issue_process -- process that closes an issue on GitHub
sub close_issue_process($$$$$$$)
{
my ($body, $self, $channel, $owner, $repo, $issuenr, $who) = @_;
my ($res, $login, $comment, $q, $ref, $data, $url, $err, $id, $type);
# This is not a method, but a routine that is run as a background
# process by create_issue(). Output to STDERR is meant for the log.
# Output to STDOUT goes to IRC, via handle_process_output().
binmode(STDOUT, ":utf8");
binmode(STDERR, ":utf8");
# First get the object ID of the issue/pull-request/discussion with
# the given number and find out if it is an issue, a pull request or
# a dicussion.
($id, $type) =
$self->get_github_id_and_type($owner, $repo, $issuenr, $who, $channel);
if (! defined $id) {
print STDERR "Channel $channel, failed to close $owner/$repo#$issuenr\n";
print "say Issue #$issuenr not found\n";
return;
}
# Add a comment saying who closed the issue.
$login = $self->name_to_login($who);
$login = '@'.$login if $login ne $who;
$comment = "Closed by $login via IRC channel $channel on $self->{server}";
# Different types need different GraphQL queries. The result has the
# same structure, however, thanks to the aliases ("close:",
# "item:").
$q = "mutation {
addComment(input: { subjectId: \"$id\", body: \"$comment\" }) {
commentEdge { node { url } } }
close: closeIssue(input: { issueId: \"$id\" }) {
item: issue { url } } }" if $type eq 'issue';
$q = "mutation {
addComment(input: { subjectId: \"$id\", body: \"$comment\" }) {
commentEdge { node { url } } }
close: closePullRequest(input: { pullRequestId: \"$id\" }) {
item: pullRequest { url } } }" if $type eq 'pr';
$q = "mutation {
addDiscussionComment(input: {discussionId: \"$id\", body: \"$comment\" }){
comment { resourcePath } }
close: closeDiscussion(input: { discussionId: \"$id\" }) {
item: discussion { url } } }" if $type eq 'discussion';
$res = $self->{ua}->post("https://api.github.com/graphql",
'Content' => encode_json({query => $q}));
if ($res->code != 200) {
print STDERR "Channel $channel, cannot close $owner/$repo#$issuenr -> ",
$res->code, "\n";
print "say Cannot close $type #$issuenr. Error ", $res->code, "\n";
return;
}
$ref = decode_json($res->decoded_content);
$err = $ref->{errors};
$data = $ref->{data};
if (! defined $data->{close}) {
print STDERR "Channel $channel, cannot close $owner/$repo#$issuenr",
" -> $err->[0]->{message}\n";
print "say Cannot close $type #$issuenr -> $err->[0]->{message}\n";
return;
}
$url = $data->{close}->{item}->{url};
print STDERR "Channel $channel, closed $type $owner/$repo#$issuenr\n";
print "say Closed -> $type #$issuenr $url\n";
}
# close_issue -- close an issue
sub close_issue($$$$)
{
my ($self, $channel, $text, $who) = @_;
my ($repository, $issue, $owner, $repo);
return "Sorry, I cannot close issues, because I am running without " .
"an access token for GitHub." if !defined $self->{github_api_token};
# Parse the reference and infer the full repository URL.
($repository, $issue) = $self->find_repository_for_issue($channel, $text);
return "Sorry, I don't know what repository to use for $text"
if ! defined $issue;
# Check that it is under "https://github.com/" and then remove that part.
($owner, $repo) =
$repository =~ /^https:\/\/github\.com\/([^\/]+)\/([^\/]+)$/i or
return "Cannot close issues on $repository as it is not on github.com.";
# Check the rate limit.
$self->check_and_update_rate("$owner/$repo") or
return "Sorry, for security reasons, I won't touch a repository more " .
"than ".MAXRATE." times in ".RATEPERIOD." minutes. " .
"Please, try again later.";
$self->forkit(run => \&close_issue_process,
handler => "handle_process_output", channel => $channel,
arguments => [$self, $channel, $owner, $repo, $issue, $who]);
return undef; # The forked process will print a result
}
# look_for_due_date -- find a due date, if any, in the given text
sub look_for_due_date($$)
{
my ($self, $body) = @_;
# A due date, if any, must be on a line of its own and look like
# "Due: yyyy-mm-dd" with optionally something in parentheses after
# it and optionally a full stop. For backward compatibility with
# very early versions, "due dd mmmm yyyy" at the start of the body
# is also supported.
return " due $1" if $body =~
/^[ \t]*Due:[ \t]+([0-9]{4}-[0-9]{2}-[0-9]{2})[ \t]*(?:\(.*\))?[. \t\r]*$/mi;
return " due $1" if $body =~ /^due ([1-3 ]?[0-9] [a-z]{3} [0-9]{4}\b)/si;
return '';
}
# reopen_issue_process -- process that reopens an issue on GitHub
sub reopen_issue_process($$$$$$)
{
my ($body, $self, $channel, $owner, $repo, $issuenr, $who) = @_;
my ($res, $comment, $login, $q, $ref, $err, $data, $url, $title, $id, $type);
# This is not a method, but a routine that is run as a background
# process by create_issue(). Output to STDERR is meant for the log.
# Output to STDOUT goes to IRC, via handle_process_output().
binmode(STDOUT, ":utf8");
binmode(STDERR, ":utf8");
# First get the object ID of the issue/pull-request/discussion with
# the given number and find out if it is an issue, a pull request or
# a dicussion.
($id, $type) =
$self->get_github_id_and_type($owner, $repo, $issuenr, $who, $channel);
if (! defined $id) {
print STDERR "Channel $channel, failed to reopen $owner/$repo#$issuenr\n";
print "say Issue #$issuenr not found\n";
return;
}
# Add a comment saying who reopened the issue.
$login = $self->name_to_login($who);
$login = '@'.$login if $login ne $who;
$comment = "Reopened by $login via IRC channel $channel on $self->{server}";
# Different types need different GraphQL queries. The three queries
# return the same structure, because the objects are given aliases
# ("reopen:" and "item:").
$q = "mutation {
addComment(input: { subjectId: \"$id\", body: \"$comment\" }) {
__typename }
reopen: reopenIssue(input: { issueId: \"$id\" }) {
item: issue { url title } } }" if $type eq 'issue';
$q = "mutation {
addComment(input: { subjectId: \"$id\", body: \"$comment\" }) {
__typename }
reopen: reopenPullRequest(input: { pullRequestId: \"$id\" }) {
item: pullRequest { url title } } }" if $type eq 'pr';
$q = "mutation {
addDiscussionComment(input: {discussionId: \"$id\", body: \"$comment\" }){
__typename }
reopen: reopenDiscussion(input: { discussionId: \"$id\" }) {
item: discussion { url title } } }" if $type eq 'discussion';
$res = $self->{ua}->post("https://api.github.com/graphql",
'Content' => encode_json({query => $q}));
if ($res->code != 200) {
print STDERR "Channel $channel, cannot reopen $owner/$repo#$issuenr -> ",
$res->code, "\n";
print "say Cannot reopen $type #$issuenr. Error ", $res->code, "\n";
return;
}
$ref = decode_json($res->decoded_content);
$err = $ref->{errors};
$data = $ref->{data};
if (! defined $data->{reopen}) {
print STDERR "Channel $channel, cannot reopen $owner/$repo#$issuenr",
" -> $err->[0]->{message}\n";
print "say Cannot reopen $type #$issuenr -> $err->[0]->{message}\n";
return;
}
$url = $data->{reopen}->{item}->{url};
$title = $data->{reopen}->{item}->{title};
print STDERR "Channel $channel, reopened $type $owner/$repo#$issuenr\n";
print "say Reopened -> $type #$issuenr $url $title\n";
}
# reopen_issue -- reopen an issue
sub reopen_issue($$$$)
{
my ($self, $channel, $text, $who) = @_;
my ($repository, $issue, $owner, $repo);
return "Sorry, I cannot open issues, because I am running without " .
"an access token for GitHub." if !defined $self->{github_api_token};
# Parse the reference and infer the full repository URL.
($repository, $issue) = $self->find_repository_for_issue($channel, $text);
return "Sorry, I don't know what repository to use for $text"