encode destination name in download directory name
[cloudstore.git] / gearman / transmission.pl
index 220da18..dc30efe 100755 (executable)
@@ -6,11 +6,12 @@ use Transmission::Client;
 use JSON::XS;
 use Data::Dump qw(dump);
 use autodie;
+use File::Path qw(make_path remove_tree);
 
-sub home_dir {
+sub user_info {
        my $login = shift;
        my ( undef, undef, $uid, $gid, undef, undef, $email, $dir, $shell ) = getpwnam $login;
-       return $dir;
+       return ( $uid, $gid, $dir );
 }
 
 use Gearman::Worker;
@@ -54,19 +55,56 @@ $worker->register_function( $name . '_torrent_download' => sub {
 
        my $dir = (getpwnam($user))[7] || die "no user $user";
 
-       my $to_dir = "$torrent_dir/download/$user";
-       if ( ! -e $to_dir ) {
-               mkdir $to_dir;
-               # fix perm
-               my ($uid,$gid) = (stat($torrent_dir))[4,5];
-               chown $uid, $gid, $to_dir;
-       }
+       my $torrent_file = "$dir/$path";
+
+       $path =~ s/\.torrent$//;
+       my $to_dir = "$torrent_dir/download/$user/$path";
+       my ($uid,$gid) = (stat($torrent_dir))[4,5];
+       make_path $to_dir, { uid => $uid, gid => $gid };
 
-       $tc->add( filename => "$dir/$path", 'download-dir' => $to_dir );
+       my $t = $tc->add( filename => $torrent_file, 'download-dir' => $to_dir );
+       warn "# added $to_dir = ",dump($t);
 
        return $to_dir;
 } );
 
+$worker->register_function( $name . '_torrent_download_done' => sub {
+       my $work = $_[0]->arg;
+       chomp $work;
+       warn "# torrent_download_done [$work]\n";
+
+       my ( $id, $dir, $name, $hash ) = split(/\s+#\s+/,$work);
+
+       my $t = $tc->remove( $id );
+       warn "# remove $id = ",dump($t);
+
+       if ( $dir =~ m{/download/(\w+)/(.+)$} ) {
+               my $user = $1;
+               my $path = $2;
+
+               warn "# check $name md5sum";
+               my $md5sum = `md5sum "$dir/$name"`;
+               $md5sum =~ s/\s+.*$//s;
+               if ( $name ne $md5sum ) {
+                       warn "ERROR: invalid md5sum filename ",dump( $name, $md5sum );
+               }
+
+               warn "# move $name to $user $path\n";
+               my ( $uid, $gid, $home_dir ) = user_info $user;
+               link "$dir/$name", "$home_dir/$path";
+               chown $uid, $gid,  "$home_dir/$path";
+               warn "FIXME: add to md5 pool?";
+
+       } else {
+               warn "ERROR: can't find user in $dir for $name\n";
+       }
+
+       warn "# $id removed $dir $name $hash\n";
+
+       remove_tree $dir;
+
+} );
+
 $worker->register_function( $name . '_torrent_share' => sub {
        my $work = $_[0]->arg;
        chomp $work;