📜 ⬆️ ⬇️

wTorrent'a modding

Hello, gentlemen.
Preamble:
A week ago, I bought myself a cheap PC to organize a local file server, router, rocking chair and other convenient services that I was tired of keeping on the desktop machine. The whole thing revolves under gentoo.

Ambula:
Today I spent the evening and a little undertmodted wTorrent :
Now it looks like this:

From the innovations:
1. Now it shows the total amount of traffic, in / out.
2. Presented in the center of the page graph of incoming / outgoing traffic.
')
Consider the first point. Its implementation is simple:
Add rules to the rtorrent scheduler. This is done via ctrl + x in the client or by adding a line to the config and restarting.
schedule = export_traffic, 0.15, "execute = / var / www / localhost / htdocs / wtorrent / schedule / passthrough, $ get_up_total =, $ get_down_total =, / var / www / localhost / htdocs / wtorrent / schedule / traffic.rtorrent "
this rule is every 15 seconds in the traffic.rtorrent file through a small passthrough script
#!/bin/sh
echo $1 $2 > $3

will write 2 numbers: outgoing and incoming traffic. This is done because a signed integer is given through xmlrpc, which, with a traffic volume of> 2GB, is expected to go into the negative range :-) I could not find how to teach him to give large numbers - so I had to make such a crutch.

Now in rtorrent.cls.php add the following three methods:
private function getTrafficInfo()
{
static $data;

if (!$data){
if (is_file('./schedule/traffic.rtorrent')) {
$data = file('./schedule/traffic.rtorrent');
$data = explode(' ', $data[0]);
} else {
$data = array(0, 0);
}
}

return $data;
}

public function getDownTotal()
{
if ($data = $this->getTrafficInfo()) {
return $this->getCorrectUnits($data[1]);
}

return $this->getCorrectUnits($this->get_info_rtorrent('get_down_total', false, false));
}

public function getUpTotal()
{
if ($data = $this->getTrafficInfo()) {
return $this->getCorrectUnits($data[0]);
}

return $this->getCorrectUnits($this->get_info_rtorrent('get_up_total', false, false));
}

which simply extract the numbers exported by the torrent client from the file. Now in the menu.tpl.php template we just show these two numbers:
{$str.dw_rate} {$web->getDownload()} ({$web->getDownTotal()})
{$str.up_rate} {$web->getUpload()} ({$web->getUpTotal()})

adding them to the brackets after the blocks at the current speed.

The task of drawing graphics is a little more complicated.
To implement it, we add another rule to the scheduler:
schedule = import_traffic, 0.60, "execute = / usr / bin / php, -f, / var / www / localhost / htdocs / wtorrent / schedule / bandwidth.php"
this rule runs a php script every minute:
<?php

chdir(dirname(__FILE__));

$datafile = './traffic.rtorrent';

if (is_file($datafile)) {
$data = file($datafile);
list($out, $in) = explode(' ', $data[0]);

$out = (double)$out;
$in = (double)$in;

require_once '../conf/user.conf.php';

$db = new PDO(DB_STAT_DSN, DB_STAT_LOGIN, DB_STAT_PWD);

$qry = 'SELECT `in`, `out`, `time` FROM `bandwidth` ORDER BY `id` DESC LIMIT 1';
$stmt = $db->query($qry);

$delta_in = 0;
$delta_out = 0;

if ($row = $stmt->fetch()) {
if ($in >= $row['in'] && $out >= $row['out']) {
$delta_in = $in - $row['in'];
$delta_out = $out - $row['out'];
}
}

$db->query('INSERT INTO `bandwidth` (`in`, `delta_in`, `out`, `delta_out`, `period`) VALUES (' . $in . ', ' . $delta_in . ', ' . $out . ', ' . $delta_out . ", TIME_TO_SEC(TIMEDIFF(NOW(), '" . $row['time'] . "')))");
}

?>


This primitive script compares the current traffic values ​​in the traffic.torrent file and, based on this data, writes the current values ​​and the difference to the previous ones in the database.

Here is the database schema and the table in which the script writes the data:
CREATE DATABASE `rtorrent`
CHARACTER SET 'utf8'
COLLATE 'utf8_general_ci';

CREATE TABLE `bandwidth` (
`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`in` BIGINT(20) DEFAULT NULL,
`delta_in` BIGINT(20) DEFAULT NULL,
`out` BIGINT(20) DEFAULT NULL,
`delta_out` BIGINT(20) DEFAULT NULL,
`time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`period` INTEGER(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `time` (`time`)
)ENGINE=MyISAM
AUTO_INCREMENT=1 ROW_FORMAT=FIXED CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';


There are very few :-) The drawing graph will use jpgraph . Here is the content of the script itself:

<?php

include "../../lib/jpgraph/jpgraph.php";
include "../../lib/jpgraph/jpgraph_line.php";
include "../../lib/jpgraph/jpgraph_scatter.php";
include "../../lib/jpgraph/jpgraph_regstat.php";

include "../../conf/user.conf.php";

$db = new PDO(DB_STAT_DSN, DB_STAT_LOGIN, DB_STAT_PWD);

$stmt = $db->query('SELECT SUM(`delta_in`) / 1024 / SUM(`period`) AS `in`,
SUM(`delta_out`) / 1024 / SUM(`period`) AS `out`,
MAX(`time`) AS `time`
FROM `bandwidth`
WHERE `time` > DATE_SUB(NOW(), INTERVAL 12 HOUR)
GROUP BY CONCAT(DATE(`time`), HOUR(`time`), FLOOR(MINUTE(`time`) / 5))
ORDER BY `time`');
$x = $in = $out = array();
while ($row = $stmt->fetch()) {
$ts = strtotime($row['time']);
$x[] = $ts;
$in[] = $row['in'];
$out[] = $row['out'];
}

// Setup the basic graph
$graph = new Graph(800, 400);
$graph->SetMargin(30, 10, 0, 30);
$graph->title->Set('Bandwidth, KB/s');
$graph->SetAlphaBlending();

// Setup a manual x-scale (We leave the sentinels for the
// Y-axis at 0 which will then autoscale the Y-axis.)
// We could also use autoscaling for the x-axis but then it
// probably will start a little bit earlier than the first value
// to make the first value an even number as it sees the timestamp
// as an normal integer value.
$graph->SetScale("intlin", 0, max(max($out), max($in)) * 1.1, reset($x), end($x));
$graph->xgrid->Show();
$graph->yaxis->HideZeroLabel();
$graph->SetFrame(false);

function TimeCallback($aVal) {
return Date('H:i',$aVal);
}
// Setup the x-axis with a format callback to convert the timestamp
// to a user readable time
$graph->xaxis->SetLabelFormatCallback('TimeCallback');
//$graph->xaxis->SetLabelAngle(90);

// Create the line
$p1 = new LinePlot($out, $x);
$p1->SetColor("red");

$p2 = new LinePlot($in, $x);
$p2->SetColor("blue");

// Add lineplot to the graph
$graph->Add($p1);
$graph->Add($p2);

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d MYH:i:s") . " GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Cache-Control: post-check=0,pre-check=0");
header("Cache-Control: max-age=0");
header("Pragma: no-cache");

// Output line
$graph->Stroke();

?>


First we connect the necessary libraries. Then - by a simple request we select data from the database. Moreover, we aggregate them in intervals of 5 minutes, so that the graph turns out to be more averaged and smooth. Then - based on the examples coming with jpgraph, we “collect” the graph of the desired type. The resulting code is placed in the file wt / img / bandwidth.php.

And the last thing is to display the resulting graph on the wtorrent page.

Add a menu item. This is also done in the rtorrent.cls.php file, by adding the 'Graphic' => 'Graphic' element to the associative array with the menu menu_admin.
Then we create a class that will manage the display of the Graphic.cls.php page:

<?php

class Graphic extends rtorrent
{
public function construct()
{
if(!$this->setClient())
{
return false;
}
}
}
?>


Finally, we create a template with a single line that will show the graphic, graphic.tpl.php:


Everything, after these simple manipulations, you should have got a result similar to what I showed above. :-)

PS: all the sources listed above can be downloaded here .

Source: https://habr.com/ru/post/51295/


All Articles