Guest User

Untitled

a guest
Dec 13th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.70 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. package Pending;
  4.  
  5. use Mojo::Base -base;
  6. use Mojo::Exception;
  7.  
  8. use Mojo::IOLoop;
  9. use Linux::Inotify2;
  10.  
  11. __PACKAGE__->attr(ioloop    => sub {Mojo::IOLoop->singleton});
  12.  
  13. has [qw/dir on_new on_delete/];
  14.  
  15. sub new {
  16.     my $class = shift;
  17.     my $self = $class->SUPER::new(@_);
  18.  
  19.     Mojo::Exception->throw("dir not provided") unless $self->dir;
  20.  
  21.     $self->{notify} = new Linux::Inotify2;
  22.     $self->{notify}->watch($self->dir, IN_CREATE | IN_MOVED_TO | IN_MOVED_FROM | IN_DELETE, sub {$self->_notify(@_)});
  23.  
  24.     #open my $fh, "+<&", $self->{notify}->fileno or die $!;
  25.     #open my $fh, "+<=&", $self->{notify}->fileno or die $!;
  26.     open $self->{watching}, "<&=", $self->{notify}->fileno or die $!;
  27.  
  28.     $self->ioloop->reactor->io($self->{watching} => sub {$self->{notify}->poll});
  29.     $self->ioloop->reactor->watch($self->{watching}, 1, 0);
  30.  
  31.     return $self;
  32. }
  33.  
  34. sub _notify {
  35.     my ($self, $event) = @_;
  36.     print "Evented\n";
  37.     if (($event->IN_MOVED_FROM || $event->IN_DELETE) && ref $self->on_delete()) {
  38.         print "File deleted\n";
  39.         &{$self->on_delete()}($self, $event);
  40.     }
  41.     elsif (($event->IN_CREATE || $event->IN_MOVE_TO) && ref $self->on_new()) {
  42.         print "File added\n";
  43.         &{$self->on_new()}($self, $event);
  44.     }
  45. }
  46.  
  47. sub _dir {
  48.     my ($self, @path) = @_;
  49.     return File::Spec->catdir($self->dir, @path);
  50. }
  51.  
  52. sub _file {
  53.     my ($self, @path) = @_;
  54.     return File::Spec->catfile($self->dir, @path);
  55. }
  56.  
  57. package main;
  58.  
  59. use Mojo::IOLoop;
  60.  
  61. mkdir './pending' unless -e './pending';
  62. my $loop = Mojo::IOLoop->singleton();
  63. my $pending = new Pending(
  64.     dir       => './pending',
  65.     on_delete => sub {
  66.         print "Deleted!\n"
  67.     },
  68.     on_new => sub {
  69.         print "NEW!\n"
  70.     }
  71. );
  72.  
  73. $loop->start();
  74.  
  75. print "$!\n";
  76. print $^F . "\n";
Add Comment
Please, Sign In to add comment