| 1 | package Plagger::Plugin::Search::Spotlight; | ||
| 2 | use strict; | ||
| 3 | use base qw( Plagger::Plugin ); | ||
| 4 | |||
| 5 | use Encode; | ||
| 6 | use File::Spec; | ||
| 7 | |||
| 8 | sub init { | ||
| 9 | my $self = shift; | ||
| 10 | $self->SUPER::init(@_); | ||
| 11 | |||
| 12 | if ($self->conf->{add_comment}) { | ||
| 13 | $self->{has_macglue} = eval { require Mac::Glue; 1 }; | ||
| 14 | } | ||
| 15 | } | ||
| 16 | |||
| 17 | sub register { | ||
| 18 | my($self, $context) = @_; | ||
| 19 | $context->register_hook( | ||
| 20 | $self, | ||
| 21 | 'publish.entry' => \&entry, | ||
| 22 | ); | ||
| 23 | } | ||
| 24 | |||
| 25 | sub entry { | ||
| 26 | my($self, $context, $args) = @_; | ||
| 27 | |||
| 28 | my $dir = $self->conf->{dir}; | ||
| 29 | unless (-e $dir && -d _) { | ||
| 30 | mkdir $dir, 0755 or $context->error("mkdir $dir: $!"); | ||
| 31 | } | ||
| 32 | |||
| 33 | my $entry = $args->{entry}; | ||
| 34 | my $file = $entry->id_safe . '.webbookmark'; | ||
| 35 | my $path = File::Spec->catfile($dir, $file); | ||
| 36 | $context->log(info => "writing output to $path"); | ||
| 37 | |||
| 38 | my $body = $self->templatize('spotlight.tt', { entry => $entry }); | ||
| 39 | |||
| 40 | open my $out, ">:utf8", $path or $context->error("$path: $!"); | ||
| 41 | print $out $body; | ||
| 42 | close $out; | ||
| 43 | |||
| 44 | # Add $entry->body as spotlight comment using AppleScript (OSX only) | ||
| 45 | if ($self->conf->{add_comment}) { | ||
| 46 | my $comment = $entry->body_text; | ||
| 47 | utf8::decode($comment) unless utf8::is_utf8($comment); | ||
| 48 | $comment = encode("shift_jis", $comment); # xxx UTF-16? | ||
| 49 | $self->add_comment($path, $comment); | ||
| 50 | } | ||
| 51 | } | ||
| 52 | |||
| 53 | sub add_comment { | ||
| 54 | my($self, $path, $comment) = @_; | ||
| 55 | |||
| 56 | if ($self->{has_macglue}) { | ||
| 57 | my $finder = Mac::Glue->new("Finder"); | ||
| 58 | my $file = $finder->obj(file => $path); | ||
| 59 | $file->prop('comment')->set(to => $comment); | ||
| 60 | } else { | ||
| 61 | system( | ||
| 62 | 'osascript', | ||
| 63 | 'bin/spotlight_comment.scpt', | ||
| 64 | $path, | ||
| 65 | $comment, | ||
| 66 | ) == 0 or Plagger->context->error("$path: $!"); | ||
| 67 | } | ||
| 68 | } | ||
| 69 | |||
| 70 | 1; | ||
| 71 | |||
| 72 | __END__ |