OSDN Git Service

tiny cleanup
[mubot4fb/mubot4fb.git] / mubot4fb.pl
1 #!/usr/bin/perl
2 #
3 # Copyright (c) 2012 ISHIKAWA Mutsumi <ishikawa@hanzubon.jp>
4 # This program is covered by the GNU General Public License 2
5 #
6 package Mubot4FB::FB;
7 use strict;
8 use utf8;
9
10 use Facebook::Graph;
11 use LWP::UserAgent;
12 use HTTP::Request::Common;
13
14 use Data::Dumper;
15
16 sub new {
17         my $proto = shift;
18         my $class = ref $proto || $proto;
19         my $self = {cfg => shift};
20         bless $self, $class;
21
22         $self->init();
23         return $self;
24 }
25
26 sub init {
27         my ($me) = @_;
28         my $fb = Facebook::Graph->new(app_id   => $me->{cfg}->{fb_app_id},
29                                       secret   => $me->{cfg}->{fb_app_secret},
30                                       postback => $me->{cfg}->{fb_postback_url});
31
32         my $res_token = $fb->request_access_token($me->{cfg}->{fb_access_code});
33         die 'token get error' if (!defined $res_token || !$res_token->response->is_success);
34
35         my $acts = $fb->fetch('me/accounts');
36         die 'can not get account list' if(!defined $acts || !$acts);
37
38         my $page_access_token = '';
39         foreach my $d (@{$acts->{data}}) {
40                 if ($d->{id} eq $me->{cfg}->{fb_page_id}) {
41                         $page_access_token = $d->{'access_token'};
42                 }
43         }
44         die 'can not get access tokenfor page_id=' . $me->{cfg}->{fb_page_id} if ($page_access_token eq '');
45
46         return $me->{fbo} = Facebook::Graph->new(access_token => $page_access_token);
47 }
48
49 sub publish {
50         my ($me, $text, $uri) = @_;
51
52         return $me->{fbo}->add_post($me->{cfg}->{fb_page_id})
53             ->set_message($text)
54             ->set_link_uri($uri)
55             ->publish()
56             ->as_hashref();
57 }
58
59 sub post_uri {
60         my ($me, $post_id) = @_;
61
62         return $me->{cfg}->{fb_page_url} . 'posts/' . $post_id;
63 }
64
65 sub remove {
66         my ($me, $post_id) = @_;
67
68         my $uri = $me->{fbo}->query->find($post_id)->uri_as_string;
69         my $req = HTTP::Request::Common::DELETE($uri);
70         warn Dumper($req) if ($me->{cfg}->{debug});
71         my $resp;
72         $resp = LWP::UserAgent->new->request($req);
73         warn Dumper($resp) if ($me->{cfg}->{debug});
74         if ($resp->is_success && $resp->code == 200 && $resp->content eq 'true') {
75                 return 1;
76         } else {
77                 warn 'DELETE ERROR: http code: ' . $resp->code() . ' , http content: ' . $resp->content;
78                 return 0;
79         }
80 }
81
82 1;
83 package Mubot4FB;
84
85 use strict;
86 use utf8;
87
88 use base 'Bot::BasicBot';
89 use DBI qw/:sql_types/;
90 use POSIX 'strftime';
91
92 use Data::Dumper;
93
94 my $mu_re = qr/^([^\s]+)\s+((?:https?|ftps?):\/\/[^\s]+)\s+(.+)$/i;
95 my $irc_type = 1;
96
97 sub db_init {
98         my ($me) = @_;
99         $me->{dbh} = DBI->connect('DBI:mysql:'.$me->{cfg}->{database}, $me->{cfg}->{db_user}, $me->{cfg}->{db_pass},{mysql_enable_utf8 => 1}) || die $DBI::errstr;
100 }
101
102 sub misc_init {
103         my ($me) = @_;
104
105         $me->{last_search} = {};
106 }
107
108 sub init {
109         my ($me) = @_;
110         $me->{fb} = Mubot4FB::FB->new($me->{cfg});
111         $me->db_init();
112 }
113
114 sub _db_check_dup {
115         my ($me, $db_args) = @_;
116         my $sth = $me->{dbh}->prepare('select * from posts where uri = ? order by post_time desc limit 1');
117         my $rv = $sth->execute($db_args->{uri});
118         my $ret = $sth->fetchrow_hashref;
119
120         $sth->finish;
121         return $ret;
122 }
123
124 sub _db_insert {
125         my ($me, $db_args) = @_;
126
127         my ($scheme, $path) = split(/:\/\//, $db_args->{uri});
128         my $sth = $me->{dbh}->prepare("insert into posts (submitter, fb_post_id, uri, prefix, comment, scheme, path, post_time) values (?, ?, ?, ?, ?, ?, ?, ?)");
129         $sth->bind_param(1, $db_args->{submitter}, SQL_VARCHAR);
130         $sth->bind_param(2, $db_args->{fb_post_id}, SQL_BIGINT);
131         $sth->bind_param(3, $db_args->{uri}, SQL_VARCHAR);
132         $sth->bind_param(4, $db_args->{prefix}, SQL_VARCHAR);
133         $sth->bind_param(5, $db_args->{comment}, SQL_VARCHAR);
134         $sth->bind_param(6, $scheme, SQL_VARCHAR);
135         $sth->bind_param(7, $path, SQL_VARCHAR);
136         $sth->bind_param(8, time, SQL_BIGINT);
137         my $rv = $sth->execute();
138         $sth->finish;
139
140         return $rv;
141 }
142
143 sub _db_delete {
144         my ($me, $db_args) = @_;
145         $db_args->{submitter_type} ||= 1;
146
147         my $sth = $me->{dbh}->prepare("delete from posts where fb_post_id = ? and submitter = ? and submitter_type = ?");
148
149         $sth->bind_param(1, $db_args->{fb_post_id}, SQL_BIGINT);
150         $sth->bind_param(2, $db_args->{submitter}, SQL_VARCHAR);
151         $sth->bind_param(3, $db_args->{submitter_type}, SQL_INTEGER);
152         my $rv = $sth->execute();
153         my $ret = $rv ? $sth->rows : 0;
154
155         $sth->finish;
156
157         return $ret;
158 }
159
160 sub _db_search {
161         my ($me, $db_args) = @_;
162
163         my $column = $db_args->{word} =~ /:\/\// ? 'uri' : 'path';
164         my $w = '%' . $db_args->{word} . '%';
165         my $sth = $me->{dbh}->prepare('select * from posts where prefix like ? or '.$column.' like ? or comment like ? order by post_time desc limit 1000');
166         $sth->bind_param(1, $w, SQL_VARCHAR);
167         $sth->bind_param(2, $w, SQL_VARCHAR);
168         $sth->bind_param(3, $w, SQL_VARCHAR);
169         $sth->execute();
170
171         my $ret = $sth->fetchall_arrayref({});
172         $sth->finish;
173
174         return $ret;
175 }
176
177 sub _db_search_lastpost {
178         my ($me, $db_args) = @_;
179
180         my $sth = $me->{dbh}->prepare('select * from posts where submitter = ? order by post_time desc limit 1');
181         $sth->bind_param(1, $db_args->{who}, SQL_VARCHAR);
182         $sth->execute();
183
184         my $ret = $sth->fetchrow_hashref();
185         $sth->finish;
186
187         return $ret;
188 }
189
190 sub _format_submit {
191         my ($me, $e) = @_;
192
193         return $e->{submitter}.'が『'.$e->{prefix}.' '.$e->{uri}.' '.$e->{comment}.'』と'.strftime('%Y-%m-%d %H:%M:%S', localtime($e->{post_time}));
194 }
195
196 sub _response {
197         my ($me, $args, $msg) = @_;
198
199         $me->say(channel => $args->{channel},
200                  body => $msg);
201 }
202
203 sub _add {
204         my ($me, $args)  =@_;
205         my ($resp, $resp_msg);
206
207         if ($args->{body} =~ /$mu_re/) {
208                 my $prefix = $1;
209                 my $uri = $2;
210                 my $comment = $3;
211                 my $text = $args->{who} . '曰く、'.$prefix.' '.$comment;
212
213                 if (my $res = $me->_db_check_dup({uri =>$uri})) {
214                         if ($res->{post_time} < time() - 7 * 24 * 60 * 60) {
215                                 $resp_msg = 'だいぶ前 '.$me->_format_submit($res).'にいってたにゃー '.$me->{fb}->post_uri($res->{fb_post_id});
216                         } else {
217                                 $resp_msg = '既に '.$me->_format_submit($res).'に言ってますよ? '.$me->{fb}->post_uri($res->{fb_post_id});
218                         }
219                 } else {
220                         my $post_ok = 1;
221                         eval{$resp = $me->{fb}->publish($text, $uri)};
222                         if ($@) {
223                                 $me->fb_init();
224                                 eval{$resp = $me->{fb}->publish($text, $uri)};
225                                 $post_ok = 0 if ($@);
226                         }
227
228                         if ($post_ok) {
229                                 my (undef, $post_id) = split(/_/, $resp->{id});
230                                 $me->_db_insert({submitter => $args->{who},
231                                                  fb_post_id => $post_id,
232                                                  uri => $uri,
233                                                  prefix => $prefix,
234                                                  comment => $comment});
235                                 $resp_msg = $args->{who} . ': うい  '.$me->{fb}->post_uri($post_id).' で登録';
236                         } else {
237                                 $resp_msg = 'can not post to facebook';
238                         }
239                 }
240                 return $resp_msg;
241         }
242         return 0;
243 }
244
245 sub _delete_prev {
246         my ($me, $args) = @_;
247
248         my $last_post = $me->_db_search_lastpost({who => $args->{who}});
249
250         if (!defined $last_post) {
251                 return $args->{who}.': いまのっていつの? というか ないし';
252         } elsif ($last_post->{post_time} < time() - 3600) {
253                 return $args->{who}.': いまのっていつの? 最後のはこれだけど古いんだにゃ ' . $me->{fb}->post_uri($last_post->{fb_post_id});
254         } else {
255                 return $me->_delete($args, $last_post->{'fb_post_id'});
256         }
257 }
258
259 sub _delete {
260         my ($me, $args, $post_id)  =@_;
261         my ($resp_msg, $resp);
262
263         $me->{dbh}->begin_work;
264         if ($resp = $me->_db_delete({fb_post_id => $post_id, submitter => $args->{who}})) {
265                 # fb 側のエントリを削除しないといけない
266                 if ($me->{fb}->remove($post_id)) {
267                         $me->{dbh}->commit;
268                         $resp_msg = $args->{who} . ': 削除しました ' . $me->{fb}->post_uri($post_id);
269                 } else {
270                         $resp_msg = $args->{who} . ': 削除に失敗しましたよ? ' . $me->{fb}->post_uri($post_id);
271                         $me->{dbh}->rollback;
272                 }
273         } else {
274                 $resp_msg = $args->{who} . ': そんな投稿ないよ? ' . $me->{fb}->post_uri($post_id);
275                 $me->{dbh}->rollback;
276         }
277         return $resp_msg;
278 }
279
280 sub _search_start {
281         my ($me, $args)  = @_;
282
283         if ($args->{body} =~ /^ふみくん\s+(.+)\?\s*$/) {
284                 $me->{last_search}->{$args->{who}} = undef;
285                 $me->{last_search}->{$args->{who}} = $me->_db_search({word => $1});
286                 return $me->_search_next($args);
287         }
288 }
289
290 sub _search_next {
291         my ($me, $args)  = @_;
292
293         my $resp_msg = 'ないっす';
294         if (defined $me->{last_search}->{$args->{who}}) {
295                 my $ent = pop($me->{last_search}->{$args->{who}});
296                 if ($ent) {
297                         my $count = @{$me->{last_search}->{$args->{who}}};
298                         if ($count) {
299                         }
300                         $resp_msg = $args->{who} . ': ' . $me->_format_submit($ent).'に言ってた '.($count ? '[ほか'.$count.'件] ' : '[ほかにはもうないよ] ').$me->{fb}->post_uri($ent->{fb_post_id});
301                 }
302         }
303         return $resp_msg;
304 }
305
306 sub _not_yet {
307         return 'まだ実装してないです';
308 }
309
310 sub said {
311         my ($me, $args) = @_;
312         my $resp_msg;
313
314         if ($args->{body} =~ /$mu_re/) {
315                 $resp_msg = $me->_add($args) unless ($1 eq 'deb');
316         } elsif ($args->{body} =~ /^ふみくん\s+(.+)\s*$/) {
317                 my $cmd = $1;
318                 if ($cmd eq 'いまのなし') {
319                         $resp_msg = $me->_delete_prev($args);
320                 } elsif ($cmd =~ /削除\s+(?:$me->{cfg}->{fb_page_url}posts\/)?([0-9]+)$/) {
321                         $resp_msg = $me->_delete($args, $1);
322                 } elsif ($cmd =~ /\?$/) {
323                         $resp_msg = $me->_search_start($args);
324                 } elsif ($cmd =~ /つぎ/) {
325                         $resp_msg = $me->_search_next($args);
326                 }
327         }
328
329         $me->_response($args, $resp_msg) if ($resp_msg);
330 }
331
332 package main;
333 use strict;
334 use utf8;
335
336 use Config::Any;
337 use Hash::Merge::Simple;
338 use Data::Recursive::Encode;
339
340 use Data::Dumper;
341
342 my $config_name = $ARGV[0] || 'not_found';
343
344 my $cfg = {};
345 my $config_path = ['/etc/mubot4fb/'.$config_name,
346                    $ENV{HOME} . '/.mubot4fb/'. $config_name,
347                    $ENV{PWD} . '/mubot4fb_' . $config_name];
348
349 my $c = Config::Any->load_stems({stems => $config_path,  use_ext => 1, flatten_to_hash => 1});
350 foreach my $i (keys %$c) {
351         $cfg = Hash::Merge::Simple->merge($cfg, $c->{$i});
352 }
353 die 'missing config file' unless (keys %$cfg);
354
355 die 'missing some config parameters should be defined (irc_server, fb_app_id, fb_app_secret, fb_access_code, fb_page_id fb_postback_url)'
356   if (!defined $cfg->{'irc_server'}
357       || !defined $cfg->{'fb_app_id'}
358       || !defined $cfg->{'fb_app_secret'}
359       || !defined $cfg->{'fb_access_code'}
360       || !defined $cfg->{'fb_page_id'}
361       || !defined $cfg->{'fb_postback_url'}
362       || !defined $cfg->{'db_user'}
363       || !defined $cfg->{'db_pass'}
364     );
365 $cfg = Data::Recursive::Encode->decode('utf8', $cfg);
366
367 $cfg->{irc_port} ||= 6667;
368 $cfg->{irc_channels} ||= ['#mubot4fb'];
369 $cfg->{irc_nick} ||= 'mubot4fb';
370 $cfg->{irc_name}||= $cfg->{irc_nick};
371 $cfg->{irc_charset} ||= 'utf8';
372 $cfg->{database} ||= 'mubot4fb';
373 $cfg->{debug} ||= 0;
374
375 my $bot = Mubot4FB->new(server => $cfg->{'irc_server'},
376                         port => $cfg->{'irc_port'},
377                         channels => $cfg->{'irc_channels'},
378                         nick => $cfg->{'irc_nick'},
379                         username => $cfg->{'irc_name'},
380                         name => $cfg->{'irc_name'},
381                         charset => $cfg->{'irc_charset'},
382                         cfg => $cfg)->run();
383
384 1;