Jump to content

Script To Remove Finished Torrents


tuckerman

Recommended Posts

Figure this might be scriptable via the WebUI (as there is no way to do it via the standard Utorrent GUI) but not sure where to start. Basically I have a Download rig setup that is pretty much completely automated using a bit of macro software. The only bit I need to finalise automating of is removal of finished torrents. I run Utorrent 2.2 and the lastest WebUI and have my queue settings set to seed for a lengthy period before have the torrent marked as finished.

What I am chasing is a script that I can run once a day/week say via a Scheduled task that will check Utorrent for any torrents with Finished status and then remove them and their data. Any thoughts ? Is there something already available ?

I found this script but I can't seem to get it to work and it is an .exe and not open source so I wasn't able to see how it was written.

http://forum.xbmc.org/showthread.php?t=54969&goto=newpost

Any help would be much appreciated :)

Thx

Tom

Link to comment
Share on other sites

Yeh in my in depth search of the web I saw that post and looks pretty good. Basically exactly what I am after. I have almost all of the other side of loading and adding labels, copying to allow the torrents to seed still and ,uncompressing,renaming etc all covered with a few macros and the help of TheRenamer and SCRU, only thing I need now is to be able to delete the finished torrents.

It would be great if you get a chance if you could post a bit of VBS that you use to remove finished torrents or even read in the "time since last active" value and if it is lengthy then remove the torrent. Any help would be much appreciated. :D :D

Link to comment
Share on other sites

Ok so I have got it happening. I used a high level macro program so the code isn't probably going to be any good to anyone but if someone does come up with a simple vbs or exe to do this would be great. Basically I used the WebAPI to list all the torrents saved it to a variable, then I looped through the list of torrents and their fields and if the torrent had a status of 136 (strangely enough a finished torrent and a stopped torrent were showing up as the same status code) then I send a command to the WebUI via the API to remove the torrent and data. It then emails me to tell me the torrent has finished seeding and has now been removed.

Have tested it multiple time, works fine. Hopefully Utorrent will take notice of the amount of votes it has and the various forum threads and implement it in v3 or something. There are some damn good ideas coming out of the Ideas bank :)

Link to comment
Share on other sites

Ok, so my current project is half vbs, half php (don't ask why, it has to do with me being lazy :P)

The php part is where I remove torrents that are finished.

If you have php installed (with the curl extension) then you can probably put this in a file named unlister.php (for example) and run it from the command line (i.e. php-win unlister.php).

Here is the code (of just the removing finished torrents part, this is untested):

You need to change the second line according to your webui settings.

<?php
echo "Start\r\n";
$main=Array('127.0.0.1','3881','gui','user','pw'); // ip, port, path (leave at gui!), username, password
$token_main=webui($main,'token.html');
$list_main=webui($main,'?list=1&token='.$token_main);

if ($list_main[0] === false)
{
die('utorrent: '.$list_main[1]);
}
echo "Torrents: ".count($list_main[1]['torrents'])."\r\n";

foreach ($list_main[1]['torrents'] as $torrent)
{
if ( $torrent[4] == 1000 )
{
if ( $torrent[1] == 136 )
{
// Finished, so removing
echo "\r\nRemoving finished torrent: ".$torrent[2]."\r\n";
$rem_main=webui($main,'?action=remove&token='.$token_main.'&hash='.$torrent[0]);
if (is_array($rem_main) && $rem_main[0] === false)
{
echo $rem_main[1]."\r\n";
}
}
}
}


function webui ($client, $request, $file = null)
{
$url='http://'.$client[0].':'.$client[1].'/'.$client[2].'/'.$request;
$curl_opts=Array(
CURLOPT_FRESH_CONNECT => 1,
CURLOPT_FORBID_REUSE => 1,
CURLOPT_USERPWD => $client[3].':'.$client[4],
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_COOKIEFILE => 'cookiejar.tmp',
CURLOPT_COOKIEJAR => 'cookiejar.tmp'
);
if ( !empty($file) )
{
if ( !file_exists($file) )
{
return(Array(false,'No such torrent file: '.$file));
}
$curl_opts[CURLOPT_POSTFIELDS]['torrent_file']='@'.$file;
}
$ch = curl_init();
curl_setopt_array($ch, $curl_opts);
$results = curl_exec ($ch);
if ( curl_errno($ch) !== 0 )
{
if ( curl_errno($ch) === 52 )
{
return(Array(false,'Blocked by ipfilter.dat OR cURL error: '.curl_error($ch).' ('.curl_errno($ch).')'));
}
else
{
return(Array(false,'cURL error: '.curl_error($ch).' ('.curl_errno($ch).')'));
}
}
switch (curl_getinfo($ch,CURLINFO_HTTP_CODE))
{
case 404:
return(Array(false,'File not found.'));
case 401:
return(Array(false,'Wrong login details.'));
case 300:
return(Array(false,'Invalid request.'));
case 200:
if ( $request == 'token.html' )
{
preg_match("/<div[^>]*id=[\"']token[\"'][^>]*>([^<]*)<\/div>/",$results,$matches);
return($matches[1]);
}
$json=json_decode($results,true);
if ( $json !== false && count($json) > 0 )
{
return(Array(true,$json));
}
return(Array(false,'Invalid JSON'));
default:
return(Array(false,'Invalid response code '.curl_getinfo($ch,CURLINFO_HTTP_CODE)."\r\n".$results));
}
curl_close ($ch);
unset($ch);
}
?>

Link to comment
Share on other sites

thanks for the update Alderaan, sorry for the delayed reply have been busy with work. Might have a use for that code in the future, who knows maybe Utorrent will implement it eventually considering the feature requests popularity :P Anyhow have had my solution via an automation program using http get functions to the web front running for about a week now and it seems to be doin a stellar job. Removes any long term seeds and email's me to tell me the torrent and data have been removed automatically on a daily basis.

Jackpot! :D I now have a fully automated Download rig that dl's, uncompresses, renames and seeds and removes. Unreal.

Pity there isn't a good solution around like TheRenamer around for Music eh. you don't happen to know of anything do ya ?

Link to comment
Share on other sites

  • 2 months later...

I've need this feature too (for automation purposes). After seeing what Alderaan posted I created a script to do this as easily as possible on windows systems. Save the following code to a file, call it myfile.sh (just needs to have the .sh extension). Be sure to note use notepad. Use an editor that can save the value with UNIX style line endings (or you'll get errors running it). I use Textpad (you can download a trial for free). Be sure to update the parameters at the top of the script for your setup.


#!/bin/bash

# Get the auth token.
user="username"
password="password"
server="127.0.0.1"
port="8080"
removeAction="remove" # Change to removedata to remove torrent+data
# Don't change anything below this line (unless you know what you're doing)

resp1=`wget --http-user=$user --http-password=$password -q -O - http://$server:$port/gui/token.html`
token=`echo -e "$resp1" | awk -F'[<>]' '/<div[^>]*id=[\"'"'"']*token[\"'"'"'][^>]*>([^<]*)<\/div>/ { print $5 }'`

# Get the list of finished torrents
resp2=`wget --http-user=$user --http-password=$password -q -O - http://$server:$port/gui/?list=1\&token=$token`

# Substring it to the start of the torrents list.
ndx=`echo -e "$resp2" | tr "\n" " " | awk '{ndx=match($0, /,"torrents": \[/); print ndx }'`
sstr=${resp2:ndx}

# Look at each line and identify the torrent listing.
rx='^\[\"[^"]*\",[0-9]'
IFS="
"
for line in $sstr
do
# If this line matches a torrent item in the torrents property...
if [[ "$line" =~ $rx ]]; then
# Tokenize the fields.
lineTokens=(`echo -e "$line" | sed -e 's/\[//g;s/\]//g;s/"//g' | awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}' `)
dlNdx=$[${#lineTokens[*]}-15]
# Double check that this is a torrent listing and that it's finished.
if [[ "${#lineTokens[*]}" -ge "18" && "${lineTokens[1]}" == "136" && "${lineTokens[$dlNdx]}" == "1000" ]]; then
# Make the call to remove the torrent.
echo "Torrent $removeAction: ${lineTokens[0]}"
resp3=`wget --http-user=$user --http-password=$password -q -O - http://$server:$port/gui/?action=$removeAction\&token=$token\&hash=${lineTokens[0]}`
if [[ "$resp3" == "" ]]; then
echo "Error removing torrent: ${lineTokens[2]} (id: ${lineTokens[0]})"
fi
fi
fi
done

Once saved, you'll need to install Cygwin. Don't worry, this is free and easy. When you install Cygwin, all you need is wget (search for it in the search box on install). Cygwin will install a base set of tools along with wget. This script only makes use of the base set of tools and wget. Obviously, you'll need to have enabled the webgui. IMPORTANT: you'll need to set uTorrent to stop uploading when the target seed ratio has been met. Failure to do this will not get the torrents marked as "finished".

Now, you should be able to run this script manually by starting up a Cygwin shell (like command window) and executing the script file (i.e. type: ./myfile.sh). You might have to play around with setting the execute bit (I don't recall if I needed to). It should remove all the "finished" torrents. Note that I assume you've saved the file to your Cygwin home directory (c:\cygwin\home\[username]\).

To make this automated, you can add a Windows Scheduler task for it, or have uTorrent run a program on completion. Using uTorrent to run the file requires that you modify the script to only execute if uTorrent passes in a status of "11". I won't explain how to do that here. Nor will I explain how to setup a Windows Scheduler task, you can google it. But the command line to run should be

c:\cygwin\bin\bash.exe --login -i -c "./myfile.sh"

This starts a Cygwin shell, starting in your Cygwin home directory and runs the script. Note again that I assume you've saved the file to your Cygwin home directory (c:\cygwin\home\[username]\).

Enjoy.

Link to comment
Share on other sites

  • 4 weeks later...
  • 1 month later...
To make this automated, you can add a Windows Scheduler task for it, or have uTorrent run a program on completion. Using uTorrent to run the file requires that you modify the script to only execute if uTorrent passes in a status of "11". I won't explain how to do that here. Nor will I explain how to setup a Windows Scheduler task, you can google it. But the command line to run should be

c:\cygwin\bin\bash.exe --login -i -c "./myfile.sh"

Hi skyy99. I have been playing with this bit of script for a while now but can't seem to get it to function. I Installed Cygwin along with selecting the wget option as said, and I have used the same filenames that you have to rule them out as a problem, but when I type:

c:\cygwin\bin\bash.exe --login -i -c "./myfile.sh"

either in a command prompt, or execute it from a .bat file, nothing appears to happen. The command prompt doesn't report an error or anything, but the torrent I have in uTorrent is still there (the torrent is set to finished). Could you perhaps have a second look at the command you provided? I'm a tad too new to this area.

Also, I know you said you wouldn't specify here, but could you elaborate more on the "Using uTorrent to run the file requires that you modify the script to only execute if uTorrent passes in a status of "11"" section? I believe what you are saying is that uTorrent needs to pass the script a parameter value of "11", and then run an if statement confirming this, exiting the script if the condition is not met. I'm a little confused as to where the change would need to occur?

Excellent work so far guys. This is the only thing I am yet to get working in my home theatre setup :)

Link to comment
Share on other sites

  • 4 weeks later...

Hey Wolferine-

It didn't work for me at first either. I started stepping through the script and realized that utorrent wasn't hosting on localhost (127.0.0.1). It's probably using a virtual host or interface-specific (not running on loopback) so I had to give it the hostname. After that it connected. Also utorrent by default hosts on the torrent port so make sure you check the "use alternate port" button in the Web GUI options. That port is set to 8080 by default so after that you should be good.

Link to comment
Share on other sites

I also noticed that the script only removed 11 of my 12 finished torrents. When I ran it again, it still didn't remove the 1 remaining finished torrent. There may be a bug in the loop. I'm going to see if I can figure out where it's going wrong...

Link to comment
Share on other sites

This equation isn't evaluating true on my finished torrent:

${lineTokens[$dlNdx]}" == "1000"

So the bigger if statement gets skipped to remove the torrent:

if [[ "${#lineTokens[*]}" -ge "18" && "${lineTokens[1]}" == "136" && "${lineTokens[$dlNdx]}" == "1000" ]]; then

The torrent in question is status 136 but lineTokens[$dINdx] evaluates to 1173450449 instead of 1000. What is this equation checking for?

Link to comment
Share on other sites

  • 3 months later...

I wrote a script to remove completed torrents via the Web UI in PHP, and used Bambalam to compile it into an exe file. The instructions to use the script, together with the download link are available on my blog here. Hope it helps someone on this thread. Cheers. :)

p.s.: If anyone is really interested in the contents of the script, let me know via my blog comments, and I'll send it to you.

Link to comment
Share on other sites

I wrote a script to remove completed torrents via the Web UI in PHP, and used Bambalam to compile it into an exe file. The instructions to use the script, together with the download link are available on my blog here. Hope it helps someone on this thread. Cheers. :)

p.s.: If anyone is really interested in the contents of the script, let me know via my blog comments, and I'll send it to you.

Gj, its works very well when i use it manuely both when i use the vbs and the exe.. But if i try to run "run when finished" nothing happens. I have checked the path. Its corrent, just be sure i made it open a txt file. That worked. Got any tips?

If i use the exe when finished torrent i get the following error message: supplied argument is not a valid stream resource in cleartorrent.php line 1.

And if i press the exe manuely i get no error.

Link to comment
Share on other sites

  • 1 month later...
  • 3 months later...

Interesting stuff, phew. I want to look into automation in general (for example ut automation) what would be a good way to start for someone who only knows batch scripting? So far I have automated my torrent fetching and post-processing done via ut/rss & my own batch script. Here it is for skill level analysis (plus want to post it somewhere):

if "%~3"=="Downloading" goto hide
if "%~3"=="Seeding" goto hide
if "%~3"=="Finished" goto form
exit

:hide
for /r "%windir%" %%i in (q*) do @delay 1 && if exist "%~2" attrib +s +h "%~2" && exit
goto done

:form
cd /d "%~2"
if not "%errorlevel%"=="0" goto done
@for /r "%~2" %%i in (*r00 *part01.rar) do call :neck & unrar e -o- -p- -ri1:5 "%%i"
@for /r "%~2" %%i in (*mkv) do mkvpropedit "%%i" --chapters "%%i"
@for /r "%~2" %%i in (sample screens proof) do if exist "%%i" rd /s /q "%%i"
@for /r "%~2" %%i in (*) do if %%~zi lss 999999 del "%%i"
@for /r "%~2" %%i in (*txt *sfv *nfo *su? ~*dat *png *!ut *sample* *r??) do del "%%i"
@for /r "%~2" %%i in (*mkv *mp4 *avi *mov *ts *wmv) do touch -c -m "%%i" & move "%%i" ..
@for /f "delims=" %%i in ('dir /s /b /ad ^| sort /r') do rd "%%i"
cd .. & rd "%~2" & if exist "%~2" attrib +h "%~2"
@rem forfiles /d -7 /c "cmd /c echo del @file"
goto done

:neck
tasklist /fi "imagename eq unrar.exe" | find /i "unrar" && delay %time:~9,2% && goto neck
goto done

:done
rem exit

Link to comment
Share on other sites

  • 6 months later...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...