はてブのWeb Hookで指定したタグが含まれていたらメールする

のを軽く作ってみた。

#!/usr/bin/env perl

package Email;
use Moose;
use Moose::Util::TypeConstraints;
use utf8;
use Encode;
use Email::MIME;
use Email::MIME::Creator;
use Email::Send;
use Email::Valid::Loose;

subtype 'MailAddr'
  => as 'Str'
  => where { Email::Valid::Loose->address($_) };

has 'from' => (is => 'rw', isa => 'MailAddr', default => 'webhook@hoge.com');
has 'to' => (is => 'rw', isa => 'MailAddr', default => 'to@hoge.com');
has 'subject' => (is => 'rw', isa => 'Str', required => 1);
has 'body' => (is => 'rw', isa => 'Str', required => 1);

sub run {
  my $self = shift;
  my $mail = Email::MIME->create(
      header => [
	  From => $self->from,
	  To => $self->to,
	  Subject => Encode::encode('MIME-Header-ISO_2022_JP', $self->subject),
      ],
      parts => [
	  encode('iso-2022-jp', $self->body),
      ],
  );
  my $sender = Email::Send->new( { mailer => 'Sendmail' } );
  $sender->send($mail);
}

__PACKAGE__->meta->make_immutable;

package main;

use strict;
use warnings;
use utf8;
use CGI;
use Encode;

my $target_tag = 'tag';
my $q = CGI->new;
print $q->header(-type=>'text/plain', -charset=>'utf-8');

if ( $q->param('key') ne 'APIKEY' ) {
  die "Authentication failed";
} elsif ( $q->param('status') ne 'add') {
  die "This program operates only when additional bookmark.";
}

my $url = $q->param('url');
my $title = $q->param('title');
my $comment = $q->param('comment');
my @tags;
while ($comment =~ m!\[([^\:\[\]]+)\]!g) {
  push @tags, $1;
}

#指定したタグを含んでいない場合はメールを送信しない。
die "finished." unless grep /$target_tag/, @tags;

my $body = <<'__MESSAGE__';
$title

$url
$comment
__MESSAGE__

my $subject = "タグ[$target_tag]を含む新規ブックマーク";
my $sender = Email->new(
    to => 'fuba@fuba.com',
    from => 'fuba_recorder@fuba.com',
    subject => $subject,
    body => $body,
);

$sender->run;
print 'OK';