diff --git a/README.md b/README.md index 010ddad..c88f657 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,13 @@ # ocDownloader ocDownloader is an AGPL-licensed application for [Nextcloud](https://nextcloud.com) which allows you to download files from HTTP(S)/FTP(S)/Youtube/Bittorrent using the ARIA2 download manager/Curl and youtube-dl. -***I'm looking for maintainers and translators, every kind of support (especially pull requests) is highly welcome*** - -***If you are interested in translating, visit to [ocDownloader Transifex Project](https://www.transifex.com/projects/p/ocdownloader)*** +***I'm looking for maintainers and translators, every kind of support (especially pull requests) is highly welcome***. ## Companion apps/extensions for Firefox/Chrome/Opera/Vivaldi and Windows -Webextension plugin for both Firefox-based and Chromium-based browsers: https://github.com/e-alfred/ocDownloader_ChromeExtension +Webextension addon for both Firefox-based and Chromium-based browsers: https://github.com/e-alfred/ocDownloader_ChromeExtension + +Jetpack/PMKit addon for Firefox <=56 and Palemoon: https://github.com/e-alfred/ocdownloader_FFAddon UWP Windows 8.1/10 app: https://github.com/e-alfred/ocDownloader_WindowsDesktop @@ -46,7 +46,7 @@ If you have problems with Curl, the log files are saved to the /tmp folder on yo - The download total size - The current downloaded size - The speed -- The PID of the PHP process which downloads your file (this allow to stop the download while it is in progress) +- The PID of the PHP process which downloads your file (this allows to pause/restart the download while it is in progress) ## Translators - Polish : Andrzej Kaczmarczyk @@ -64,6 +64,7 @@ If you have problems with Curl, the log files are saved to the /tmp folder on yo ## Authors e-alfred Nibbels +Loki3000 (formerly) Xavier Beurois ## Releases notes diff --git a/SERVER/fallback.php b/SERVER/fallback.php index ace212f..77b1027 100644 --- a/SERVER/fallback.php +++ b/SERVER/fallback.php @@ -12,108 +12,95 @@ class OCD { - private static $CurlHandler = null; - private static $ProgressFile = null; - private static $CHInfo = null; - private static $PFHandle = null; - - public static function Load ($GID, $URI, $OPTIONS) + private static $CurlHandler = null; + private static $ProgressFile = null; + private static $CHInfo = null; + private static $PFHandle = null; + + public static function load($GID, $URI, $OPTIONS) { - self::$ProgressFile = '/tmp/' . $GID . '.curl'; - self::$PFHandle = fopen (self::$ProgressFile, 'w+'); - - self::$CurlHandler = curl_init (); - - $DestFile = fopen (rtrim ($OPTIONS['dir'], '/') . '/' . $OPTIONS['out'], 'w+'); + self::$ProgressFile = '/tmp/' . $GID . '.curl'; + self::$PFHandle = fopen(self::$ProgressFile, 'w+'); - curl_setopt_array (self::$CurlHandler, Array ( - CURLOPT_FILE => $DestFile, - CURLOPT_URL => $URI - )); - self::CurlSetBasicOptions (); - self::CurlSetAdvancedOptions ($OPTIONS); - - curl_exec (self::$CurlHandler); - curl_close (self::$CurlHandler); - fclose ($DestFile); + self::$CurlHandler = curl_init(); + + $DestFile = fopen(rtrim($OPTIONS['dir'], '/') . '/' . $OPTIONS['out'], 'w+'); + + curl_setopt_array(self::$CurlHandler, array( + CURLOPT_FILE => $DestFile, + CURLOPT_URL => $URI + )); + self::curlSetBasicOptions(); + self::curlSetAdvancedOptions($OPTIONS); + + curl_exec(self::$CurlHandler); + curl_close(self::$CurlHandler); + fclose($DestFile); + } + + private static function writeProgress($DownloadStatus = 0) + { + if (self::$CHInfo['download_content_length'] != -1 && is_resource(self::$PFHandle)) { + $State = $DownloadStatus == 0 ? 'active' :($DownloadStatus == 1 ? 'complete' : 'error'); + $Downloaded = $DownloadStatus == 2 ? 0 : self::$CHInfo['size_download']; + $Size = $DownloadStatus == 2 ? 0 : self::$CHInfo['download_content_length']; + $Speed = $DownloadStatus == 2 ? 0 : self::$CHInfo['speed_download']; + + if (($PID = getmypid()) === false) { + $PID = 0; + } + + fwrite(self::$PFHandle, $State . ';' . $Downloaded . ';' . $Size . ';' . $Speed . ';' . $PID . "\n"); + } } - - private static function WriteProgress ($DownloadStatus = 0) - { - if (self::$CHInfo['download_content_length'] != -1 && is_resource (self::$PFHandle)) - { - $State = $DownloadStatus == 0 ? 'active' : ($DownloadStatus == 1 ? 'complete' : 'error'); - $Downloaded = $DownloadStatus == 2 ? 0 : self::$CHInfo['size_download']; - $Size = $DownloadStatus == 2 ? 0 : self::$CHInfo['download_content_length']; - $Speed = $DownloadStatus == 2 ? 0 : self::$CHInfo['speed_download']; - - if (($PID = getmypid ()) === false) - { - $PID = 0; - } - - fwrite (self::$PFHandle, $State . ';' . $Downloaded . ';' . $Size . ';' . $Speed . ';' . $PID . "\n"); - } - } - - private static function CurlSetBasicOptions () - { - // Basic options - curl_setopt_array (self::$CurlHandler, Array ( + + private static function curlSetBasicOptions() + { + // Basic options + curl_setopt_array(self::$CurlHandler, array( CURLOPT_FOLLOWLOCATION => true, - CURLOPT_MAXREDIRS => 20, - CURLOPT_NOPROGRESS => false, - CURLOPT_PROGRESSFUNCTION => function ($Resource, $TotalDL, $Downloaded, $UpSize, $Uploaded) - { - self::$CHInfo = curl_getinfo (self::$CurlHandler); - - if (self::$CHInfo['size_download'] == self::$CHInfo['download_content_length'] && self::$CHInfo['http_code'] == 200) - { - self::WriteProgress (1); - if (is_resource (self::$PFHandle)) - { - fclose (self::$PFHandle); - } - } - else - { - self::WriteProgress (); - } - }, + CURLOPT_MAXREDIRS => 20, + CURLOPT_NOPROGRESS => false, + CURLOPT_PROGRESSFUNCTION => function ($Resource, $TotalDL, $Downloaded, $UpSize, $Uploaded) { + self::$CHInfo = curl_getinfo(self::$CurlHandler); + + if (self::$CHInfo['size_download'] == self::$CHInfo['download_content_length'] && self::$CHInfo['http_code'] == 200) { + self::writeProgress(1); + if (is_resource(self::$PFHandle)) { + fclose(self::$PFHandle); + } + } else { + self::writeProgress(); + } + }, )); - } - - private static function CurlSetAdvancedOptions ($OPTIONS) - { - if (isset ($OPTIONS['http-user']) && isset ($OPTIONS['http-passwd'])) - { - curl_setopt (self::$CurlHandler, CURLOPT_HTTPAUTH, CURLAUTH_ANY); - curl_setopt (self::$CurlHandler, CURLOPT_USERPWD, $OPTIONS['http-user'] . ':' . $OPTIONS['http-passwd']); - } - if (isset ($OPTIONS['ftp-user']) && isset ($OPTIONS['ftp-passwd'])) - { - curl_setopt (self::$CurlHandler, CURLOPT_HTTPAUTH, CURLAUTH_ANY); - curl_setopt (self::$CurlHandler, CURLOPT_USERPWD, $OPTIONS['ftp-user'] . ':' . $OPTIONS['ftp-passwd']); - } - if (isset ($OPTIONS['ftp-pasv'])) - { - curl_setopt (self::$CurlHandler, CURLOPT_FTP_USE_EPSV, $OPTIONS['ftp-pasv']); - } - if (isset ($OPTIONS['all-proxy'])) - { - curl_setopt (self::$CurlHandler, CURLOPT_PROXY, $OPTIONS['all-proxy']); - if (isset ($OPTIONS['all-proxy-user']) && isset ($OPTIONS['all-proxy-passwd'])) - { - curl_setopt (self::$CurlHandler, CURLOPT_PROXYUSERPWD, $OPTIONS['all-proxy-user'] . ':' . $OPTIONS['all-proxy-passwd']); - } - } - if (isset ($OPTIONS['max-download-limit'])) - { - $OPTIONS['max-download-limit'] = (rtrim ($OPTIONS['max-download-limit'], 'K')) * 1024; - curl_setopt (self::$CurlHandler, CURLOPT_MAX_RECV_SPEED_LARGE, $OPTIONS['max-download-limit']); - } - } + } + + private static function curlSetAdvancedOptions($OPTIONS) + { + if (isset($OPTIONS['http-user']) && isset($OPTIONS['http-passwd'])) { + curl_setopt(self::$CurlHandler, CURLOPT_HTTPAUTH, CURLAUTH_ANY); + curl_setopt(self::$CurlHandler, CURLOPT_USERPWD, $OPTIONS['http-user'] . ':' . $OPTIONS['http-passwd']); + } + if (isset($OPTIONS['ftp-user']) && isset($OPTIONS['ftp-passwd'])) { + curl_setopt(self::$CurlHandler, CURLOPT_HTTPAUTH, CURLAUTH_ANY); + curl_setopt(self::$CurlHandler, CURLOPT_USERPWD, $OPTIONS['ftp-user'] . ':' . $OPTIONS['ftp-passwd']); + } + if (isset($OPTIONS['ftp-pasv'])) { + curl_setopt(self::$CurlHandler, CURLOPT_FTP_USE_EPSV, $OPTIONS['ftp-pasv']); + } + if (isset($OPTIONS['all-proxy'])) { + curl_setopt(self::$CurlHandler, CURLOPT_PROXY, $OPTIONS['all-proxy']); + if (isset($OPTIONS['all-proxy-user']) && isset($OPTIONS['all-proxy-passwd'])) { + curl_setopt(self::$CurlHandler, CURLOPT_PROXYUSERPWD, $OPTIONS['all-proxy-user'] . ':' . $OPTIONS['all-proxy-passwd']); + } + } + if (isset($OPTIONS['max-download-limit'])) { + $OPTIONS['max-download-limit'] =(rtrim($OPTIONS['max-download-limit'], 'K')) * 1024; + curl_setopt(self::$CurlHandler, CURLOPT_MAX_RECV_SPEED_LARGE, $OPTIONS['max-download-limit']); + } + } } -set_time_limit (0); -OCD::Load ($argv[1], urldecode ($argv[2]), json_decode (urldecode ($argv[3]), true, 512, JSON_HEX_APOS | JSON_HEX_QUOT)); \ No newline at end of file +set_time_limit(0); +OCD::load($argv[1], urldecode($argv[2]), json_decode(urldecode($argv[3]), true, 512, JSON_HEX_APOS | JSON_HEX_QUOT)); diff --git a/appinfo/app.php b/appinfo/app.php index 5a52886..8998473 100644 --- a/appinfo/app.php +++ b/appinfo/app.php @@ -11,17 +11,16 @@ namespace OCA\ocDownloader\AppInfo; -$l = \OC::$server->getL10N ('ocdownloader'); -$g = \OC::$server->getURLGenerator (); +$l = \OC::$server->getL10N('ocdownloader'); +$g = \OC::$server->getURLGenerator(); -\OCP\App::addNavigationEntry -([ +\OCP\App::addNavigationEntry([ 'id' => 'ocdownloader', 'order' => 10, - 'href' => $g->linkToRoute ('ocdownloader.Index.Add'), - 'icon' => $g->imagePath ('ocdownloader', 'ocdownloader.svg'), + 'href' => $g->linkToRoute('ocdownloader.Index.Add'), + 'icon' => $g->imagePath('ocdownloader', 'ocdownloader.svg'), 'name' => 'ocDownloader' ]); -\OCP\App::registerAdmin ('ocdownloader', 'settings/admin'); -\OCP\App::registerPersonal ('ocdownloader', 'settings/personal'); \ No newline at end of file +\OCP\App::registerAdmin('ocdownloader', 'settings/admin'); +\OCP\App::registerPersonal('ocdownloader', 'settings/personal'); diff --git a/appinfo/application.php b/appinfo/application.php index 6ecb15f..fe0bd00 100644 --- a/appinfo/application.php +++ b/appinfo/application.php @@ -26,112 +26,93 @@ class Application extends App { - public function __construct (Array $URLParams = Array ()) - { - parent::__construct ('ocdownloader', $URLParams); - $container = $this->getContainer (); - - $container->registerService ('CurrentUID', function (IContainer $Container) - { - $User = $Container->query ('ServerContainer')->getUserSession ()->getUser (); - return ($User) ? $User->getUID () : ''; - }); - - $container->registerService ('IndexController', function (IContainer $Container) - { - return new Index - ( - $Container->query ('AppName'), - $Container->query ('Request'), - $Container->query ('CurrentUID'), - $Container->getServer ()->getL10N ('ocdownloader') - ); - }); - - $container->registerService ('HttpDownloaderController', function (IContainer $Container) - { - return new HttpDownloader - ( - $Container->query ('AppName'), - $Container->query ('Request'), - $Container->query ('CurrentUID'), - $Container->getServer ()->getL10N ('ocdownloader') - ); - }); - - $container->registerService ('FtpDownloaderController', function (IContainer $Container) - { - return new FtpDownloader - ( - $Container->query ('AppName'), - $Container->query ('Request'), - $Container->query ('CurrentUID'), - $Container->getServer ()->getL10N ('ocdownloader') - ); - }); - - $container->registerService ('YTDownloaderController', function (IContainer $Container) - { - return new YTDownloader - ( - $Container->query ('AppName'), - $Container->query ('Request'), - $Container->query ('CurrentUID'), - $Container->getServer ()->getL10N ('ocdownloader') - ); - }); - - $container->registerService ('BTDownloaderController', function (IContainer $Container) - { - return new BTDownloader - ( - $Container->query ('AppName'), - $Container->query ('Request'), - $Container->query ('CurrentUID'), - $Container->getServer ()->getL10N ('ocdownloader') - ); - }); - - $container->registerService ('QueueController', function (IContainer $Container) - { - return new Queue - ( - $Container->query ('AppName'), - $Container->query ('Request'), - $Container->query ('CurrentUID'), - $Container->getServer ()->getL10N ('ocdownloader') - ); - }); - - $container->registerService ('UpdaterController', function (IContainer $Container) - { - return new Updater - ( - $Container->query ('AppName'), - $Container->query ('Request'), - $Container->getServer ()->getL10N ('ocdownloader') - ); - }); - - $container->registerService ('AdminSettingsController', function (IContainer $Container) - { - return new AdminSettings - ( - $Container->query ('AppName'), - $Container->query ('Request'), - $Container->getServer ()->getL10N ('ocdownloader') - ); - }); - - $container->registerService ('PersonalSettingsController', function (IContainer $Container) - { - return new PersonalSettings - ( - $Container->query ('AppName'), - $Container->query ('Request'), - $Container->query ('CurrentUID'), - $Container->getServer ()->getL10N ('ocdownloader') - ); - }); - } -} \ No newline at end of file + public function __construct(array $URLParams = array()) + { + parent::__construct('ocdownloader', $URLParams); + $container = $this->getContainer(); + + $container->registerService('CurrentUID', function (IContainer $Container) { + $User = $Container->query('ServerContainer')->getUserSession()->getUser(); + return($User) ? $User->getUID() : ''; + }); + + $container->registerService('IndexController', function (IContainer $Container) { + return new Index( + $Container->query('AppName'), + $Container->query('Request'), + $Container->query('CurrentUID'), + $Container->getServer()->getL10N('ocdownloader') + ); + }); + + $container->registerService('HttpDownloaderController', function (IContainer $Container) { + return new HttpDownloader( + $Container->query('AppName'), + $Container->query('Request'), + $Container->query('CurrentUID'), + $Container->getServer()->getL10N('ocdownloader') + ); + }); + + $container->registerService('FtpDownloaderController', function (IContainer $Container) { + return new FtpDownloader( + $Container->query('AppName'), + $Container->query('Request'), + $Container->query('CurrentUID'), + $Container->getServer()->getL10N('ocdownloader') + ); + }); + + $container->registerService('YTDownloaderController', function (IContainer $Container) { + return new YTDownloader( + $Container->query('AppName'), + $Container->query('Request'), + $Container->query('CurrentUID'), + $Container->getServer()->getL10N('ocdownloader') + ); + }); + + $container->registerService('BTDownloaderController', function (IContainer $Container) { + return new BTDownloader( + $Container->query('AppName'), + $Container->query('Request'), + $Container->query('CurrentUID'), + $Container->getServer()->getL10N('ocdownloader') + ); + }); + + $container->registerService('QueueController', function (IContainer $Container) { + return new Queue( + $Container->query('AppName'), + $Container->query('Request'), + $Container->query('CurrentUID'), + $Container->getServer()->getL10N('ocdownloader') + ); + }); + + $container->registerService('UpdaterController', function (IContainer $Container) { + return new Updater( + $Container->query('AppName'), + $Container->query('Request'), + $Container->getServer()->getL10N('ocdownloader') + ); + }); + + $container->registerService('AdminSettingsController', function (IContainer $Container) { + return new AdminSettings( + $Container->query('AppName'), + $Container->query('Request'), + $Container->getServer()->getL10N('ocdownloader') + ); + }); + + $container->registerService('PersonalSettingsController', function (IContainer $Container) { + return new PersonalSettings( + $Container->query('AppName'), + $Container->query('Request'), + $Container->query('CurrentUID'), + $Container->getServer()->getL10N('ocdownloader') + ); + }); + } +} diff --git a/appinfo/routes.php b/appinfo/routes.php index e03f642..b6af8dd 100644 --- a/appinfo/routes.php +++ b/appinfo/routes.php @@ -11,8 +11,8 @@ namespace OCA\ocDownloader\AppInfo; -$Application = new Application (); -$Application->registerRoutes ($this, Array ( +$Application = new Application(); +$Application->registerRoutes($this, array( 'routes' => [ // Index ['name' => 'Index#Add', 'url' => '/add', 'verb' => 'GET'], @@ -63,6 +63,32 @@ )); $APIBasePath = '/apps/ocdownloader/api/'; -\OCP\API::register ('POST', $APIBasePath . 'version', function ($URLParams) { return new \OC_OCS_Result (\OCA\ocDownloader\Controller\Lib\API::CheckAddonVersion ($_POST['AddonVersion'])); }, 'ocdownloader', \OC_API::USER_AUTH); -\OCP\API::register ('GET', $APIBasePath . 'queue/get', function ($URLParams) { return new \OC_OCS_Result (\OCA\ocDownloader\Controller\Lib\API::GetQueue ()); }, 'ocdownloader', \OC_API::USER_AUTH); -\OCP\API::register ('POST', $APIBasePath . 'add', function ($URLParams) { return new \OC_OCS_Result (\OCA\ocDownloader\Controller\Lib\API::Add ($_POST['URL'])); }, 'ocdownloader', \OC_API::USER_AUTH); +\OCP\API::register( + 'POST', + $APIBasePath.'version', + function ($URLParams) { + return new \OC_OCS_Result(\OCA\ocDownloader\Controller\Lib\API::checkAddonVersion($_POST['AddonVersion'])); + }, + 'ocdownloader', + \OC_API::USER_AUTH +); + +\OCP\API::register( + 'GET', + $APIBasePath.'queue/get', + function ($URLParams) { + return new \OC_OCS_Result(\OCA\ocDownloader\Controller\Lib\API::getQueue()); + }, + 'ocdownloader', + \OC_API::USER_AUTH +); + +\OCP\API::register( + 'POST', + $APIBasePath.'add', + function ($URLParams) { + return new \OC_OCS_Result(\OCA\ocDownloader\Controller\Lib\API::add($_POST['URL'])); + }, + 'ocdownloader', + \OC_API::USER_AUTH +); diff --git a/controller/adminsettings.php b/controller/adminsettings.php index 95a4fca..e52845f 100644 --- a/controller/adminsettings.php +++ b/controller/adminsettings.php @@ -8,7 +8,7 @@ * @author Xavier Beurois * @copyright Xavier Beurois 2015 */ - + namespace OCA\ocDownloader\Controller; use OCP\AppFramework\Controller; @@ -22,216 +22,169 @@ class AdminSettings extends Controller { - private $DbType = 0; - private $L10N; - private $OCDSettingKeys = Array ('YTDLBinary', 'ProxyAddress', 'ProxyPort', 'ProxyUser', 'ProxyPasswd', 'CheckForUpdates', 'WhichDownloader', 'ProxyOnlyWithYTDL', 'AllowProtocolHTTP', 'AllowProtocolFTP', 'AllowProtocolYT', 'AllowProtocolBT', 'MaxDownloadSpeed', 'BTMaxUploadSpeed'); - private $Settings = null; - - public function __construct ($AppName, IRequest $Request, IL10N $L10N) - { - parent::__construct($AppName, $Request); + private $DbType = 0; + private $L10N; + private $OCDSettingKeys = array( + 'YTDLBinary', 'ProxyAddress', 'ProxyPort', 'ProxyUser', 'ProxyPasswd', 'CheckForUpdates', 'WhichDownloader', + 'ProxyOnlyWithYTDL', 'AllowProtocolHTTP', 'AllowProtocolFTP', 'AllowProtocolYT', 'AllowProtocolBT', + 'MaxDownloadSpeed', 'BTMaxUploadSpeed' + ); + private $Settings = null; + + public function __construct($AppName, IRequest $Request, IL10N $L10N) + { + parent::__construct($AppName, $Request); + + if (strcmp(Config::getSystemValue('dbtype'), 'pgsql') == 0) { + $this->DbType = 1; + } + + $this->L10N = $L10N; + + $this->Settings = new Settings(); + } + + /** + * @AdminRequired + * @NoCSRFRequired + */ + public function save() + { + \OCP\JSON::setContentTypeHeader('application/json'); + + $Error = false; + $Message = null; + + if (isset($_POST['KEY']) && strlen(trim($_POST['KEY'])) > 0 && isset($_POST['VAL']) + && strlen(trim($_POST['VAL'])) >= 0) { + $PostKey = $_POST['KEY']; + $PostValue = $_POST['VAL']; - if (strcmp (Config::getSystemValue ('dbtype'), 'pgsql') == 0) - { - $this->DbType = 1; - } - - $this->L10N = $L10N; - - $this->Settings = new Settings (); - } - - /** - * @AdminRequired - * @NoCSRFRequired - */ - public function Save () - { - \OCP\JSON::setContentTypeHeader ('application/json'); - - $Error = false; - $Message = null; - - if (isset ($_POST['KEY']) && strlen (trim ($_POST['KEY'])) > 0 && isset ($_POST['VAL']) && strlen (trim ($_POST['VAL'])) >= 0) - { - $PostKey = $_POST['KEY']; - $PostValue = $_POST['VAL']; - - if (in_array ($PostKey, $this->OCDSettingKeys)) - { - $this->Settings->SetKey ($PostKey); - - if (strlen (trim ($PostValue)) > 0) - { - if (strcmp ($PostKey, 'YTDLBinary') == 0) - { - $PostValue = trim (str_replace (' ', '\ ', $PostValue)); - if (!file_exists ($PostValue)) - { - $PostValue = null; - $Error = true; - $Message = (string)$this->L10N->t ('Unable to find YouTube-DL binary'); - } - } - elseif (strcmp ($PostKey, 'ProxyAddress') == 0) - { - if (!Tools::CheckURL ($PostValue) && strlen (trim ($PostValue)) > 0) - { - $PostValue = null; - $Error = true; - $Message = (string)$this->L10N->t ('Invalid proxy address URL'); - } - } - elseif (strcmp ($PostKey, 'ProxyPort') == 0) - { - if (!is_numeric ($PostValue)) - { - $PostValue = null; - $Error = true; - $Message = (string)$this->L10N->t ('Proxy port should be a numeric value'); - } - elseif ($PostValue <= 0 || $PostValue > 65536) - { - $PostValue = null; - $Error = true; - $Message = (string)$this->L10N->t ('Proxy port should be a value from 1 to 65536'); - } - } - elseif (strcmp ($PostKey, 'ProxyUser') == 0) - { - $Error = false; - } - elseif (strcmp ($PostKey, 'ProxyPasswd') == 0) - { - $Error = false; - } - elseif (strcmp ($PostKey, 'CheckForUpdates') == 0) - { - if (!in_array ($PostValue, Array ('Y', 'N'))) - { - $PostValue = 'Y'; - } - } - elseif (strcmp ($PostKey, 'WhichDownloader') == 0) - { - if (!in_array ($PostValue, Array ('ARIA2', 'CURL'))) - { - $PostValue = 'ARIA2'; - } - elseif (strcmp ($PostValue, 'ARIA2') != 0) - { - Tools::ResetAria2 ($this->DbType); - } - } - elseif (strcmp ($PostKey, 'ProxyOnlyWithYTDL') == 0) - { - if (!in_array ($PostValue, Array ('Y', 'N'))) - { - $PostValue = 'N'; - } - } - elseif (strcmp ($PostKey, 'AllowProtocolHTTP') == 0) - { - if (!in_array ($PostValue, Array ('Y', 'N'))) - { - $PostValue = 'N'; - } - } - elseif (strcmp ($PostKey, 'AllowProtocolFTP') == 0) - { - if (!in_array ($PostValue, Array ('Y', 'N'))) - { - $PostValue = 'N'; - } - } - elseif (strcmp ($PostKey, 'AllowProtocolYT') == 0) - { - if (!in_array ($PostValue, Array ('Y', 'N'))) - { - $PostValue = 'N'; - } - } - elseif (strcmp ($PostKey, 'AllowProtocolBT') == 0) - { - if (!in_array ($PostValue, Array ('Y', 'N'))) - { - $PostValue = 'N'; - } - } - elseif (strcmp ($PostKey, 'MaxDownloadSpeed') == 0) - { - if (!is_numeric ($PostValue)) - { - $PostValue = null; - $Error = true; - $Message = (string)$this->L10N->t ('Max download speed setting should be a numeric value'); - } - } - elseif (strcmp ($PostKey, 'BTMaxUploadSpeed') == 0) - { - if (!is_numeric ($PostValue)) - { - $PostValue = null; - $Error = true; - $Message = (string)$this->L10N->t ('BitTorrent protocol max upload speed setting should be a numeric value'); - } - } - else - { - $PostValue = null; - $Error = true; - } + if (in_array($PostKey, $this->OCDSettingKeys)) { + $this->Settings->setKey($PostKey); + + if (strlen(trim($PostValue)) > 0) { + if (strcmp($PostKey, 'YTDLBinary') == 0) { + $PostValue = trim(str_replace(' ', '\ ', $PostValue)); + if (!file_exists($PostValue)) { + $PostValue = null; + $Error = true; + $Message =(string)$this->L10N->t('Unable to find YouTube-DL binary'); } - - if ($this->Settings->CheckIfKeyExists ()) - { - $this->Settings->UpdateValue ($PostValue); + } elseif (strcmp($PostKey, 'ProxyAddress') == 0) { + if (!Tools::checkURL($PostValue) && strlen(trim($PostValue)) > 0) { + $PostValue = null; + $Error = true; + $Message =(string)$this->L10N->t('Invalid proxy address URL'); } - else - { - $this->Settings->InsertValue ($PostValue); + } elseif (strcmp($PostKey, 'ProxyPort') == 0) { + if (!is_numeric($PostValue)) { + $PostValue = null; + $Error = true; + $Message =(string)$this->L10N->t('Proxy port should be a numeric value'); + } elseif ($PostValue <= 0 || $PostValue > 65536) { + $PostValue = null; + $Error = true; + $Message =(string)$this->L10N->t('Proxy port should be a value from 1 to 65536'); } - } - } - - return new JSONResponse (Array ('ERROR' => $Error, 'MESSAGE' => is_null ($Message) ? (string)$this->L10N->t ('Saved') : $Message)); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function Get () - { - \OCP\JSON::setContentTypeHeader ('application/json'); - - $AdminSettings = Array (); - foreach ($_POST['KEYS'] as $PostKey) - { - if (in_array ($PostKey, $this->OCDSettingKeys)) - { - $this->Settings->SetKey ($PostKey); - $AdminSettings[$PostKey] = $this->Settings->GetValue (); - - // Set default if not set in the database - if (is_null ($AdminSettings[$PostKey])) - { - switch ($PostKey) - { - case 'YTDLBinary': - $AdminSettings[$PostKey] = '/usr/local/bin/youtube-dl'; - break; - case 'CheckForUpdates': - $AdminSettings[$PostKey] = 'Y'; - break; - case 'WhichDownloader': - $AdminSettings[$PostKey] = 'ARIA2'; - break; - } + } elseif (strcmp($PostKey, 'ProxyUser') == 0) { + $Error = false; + } elseif (strcmp($PostKey, 'ProxyPasswd') == 0) { + $Error = false; + } elseif (strcmp($PostKey, 'CheckForUpdates') == 0) { + if (!in_array($PostValue, array('Y', 'N'))) { + $PostValue = 'Y'; + } + } elseif (strcmp($PostKey, 'WhichDownloader') == 0) { + if (!in_array($PostValue, array('ARIA2', 'CURL'))) { + $PostValue = 'ARIA2'; + } elseif (strcmp($PostValue, 'ARIA2') != 0) { + Tools::resetAria2($this->DbType); } - } + } elseif (strcmp($PostKey, 'ProxyOnlyWithYTDL') == 0) { + if (!in_array($PostValue, array('Y', 'N'))) { + $PostValue = 'N'; + } + } elseif (strcmp($PostKey, 'AllowProtocolHTTP') == 0) { + if (!in_array($PostValue, array('Y', 'N'))) { + $PostValue = 'N'; + } + } elseif (strcmp($PostKey, 'AllowProtocolFTP') == 0) { + if (!in_array($PostValue, array('Y', 'N'))) { + $PostValue = 'N'; + } + } elseif (strcmp($PostKey, 'AllowProtocolYT') == 0) { + if (!in_array($PostValue, array('Y', 'N'))) { + $PostValue = 'N'; + } + } elseif (strcmp($PostKey, 'AllowProtocolBT') == 0) { + if (!in_array($PostValue, array('Y', 'N'))) { + $PostValue = 'N'; + } + } elseif (strcmp($PostKey, 'MaxDownloadSpeed') == 0) { + if (!is_numeric($PostValue)) { + $PostValue = null; + $Error = true; + $Message =(string)$this->L10N->t('Max download speed setting should be a numeric value'); + } + } elseif (strcmp($PostKey, 'BTMaxUploadSpeed') == 0) { + if (!is_numeric($PostValue)) { + $PostValue = null; + $Error = true; + $Message =(string)$this->L10N->t( + 'BitTorrent protocol max upload speed setting should be a numeric value' + ); + } + } else { + $PostValue = null; + $Error = true; + } + } + + if ($this->Settings->checkIfKeyExists()) { + $this->Settings->updateValue($PostValue); + } else { + $this->Settings->insertValue($PostValue); + } } + } + + return new JSONResponse( + array('ERROR' => $Error, 'MESSAGE' => is_null($Message) ?(string)$this->L10N->t('Saved') : $Message) + ); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function get() + { + \OCP\JSON::setContentTypeHeader('application/json'); + + $AdminSettings = array(); + foreach ($_POST['KEYS'] as $PostKey) { + if (in_array($PostKey, $this->OCDSettingKeys)) { + $this->Settings->setKey($PostKey); + $AdminSettings[$PostKey] = $this->Settings->getValue(); - return new JSONResponse (Array ('ERROR' => false, 'VALS' => $AdminSettings)); - } -} \ No newline at end of file + // Set default if not set in the database + if (is_null($AdminSettings[$PostKey])) { + switch ($PostKey) { + case 'YTDLBinary': + $AdminSettings[$PostKey] = '/usr/local/bin/youtube-dl'; + break; + case 'CheckForUpdates': + $AdminSettings[$PostKey] = 'Y'; + break; + case 'WhichDownloader': + $AdminSettings[$PostKey] = 'ARIA2'; + break; + } + } + } + } + + return new JSONResponse(array('ERROR' => false, 'VALS' => $AdminSettings)); + } +} diff --git a/controller/btdownloader.php b/controller/btdownloader.php index aa5984b..df1305d 100644 --- a/controller/btdownloader.php +++ b/controller/btdownloader.php @@ -23,276 +23,282 @@ class BTDownloader extends Controller { - private $CurrentUID = null; - private $DownloadsFolder = null; - private $TorrentsFolder = null; - private $AbsoluteDownloadsFolder = null; - private $AbsoluteTorrentsFolder = null; - private $DbType = 0; - private $ProxyAddress = null; - private $ProxyPort = 0; - private $ProxyUser = null; - private $ProxyPasswd = null; - private $ProxyOnlyWithYTDL = null; - private $Settings = null; - private $L10N = null; - private $AllowProtocolBT = null; - private $MaxDownloadSpeed = null; - private $BTMaxUploadSpeed = null; - private $BTRatioToReach = null; - private $SeedTime = null; - - public function __construct ($AppName, IRequest $Request, $CurrentUID, IL10N $L10N) - { - parent::__construct ($AppName, $Request); - - if (strcmp (Config::getSystemValue ('dbtype'), 'pgsql') == 0) - { - $this->DbType = 1; + private $CurrentUID = null; + private $DownloadsFolder = null; + private $TorrentsFolder = null; + private $AbsoluteDownloadsFolder = null; + private $AbsoluteTorrentsFolder = null; + private $DbType = 0; + private $ProxyAddress = null; + private $ProxyPort = 0; + private $ProxyUser = null; + private $ProxyPasswd = null; + private $ProxyOnlyWithYTDL = null; + private $Settings = null; + private $L10N = null; + private $AllowProtocolBT = null; + private $MaxDownloadSpeed = null; + private $BTMaxUploadSpeed = null; + private $BTRatioToReach = null; + private $SeedTime = null; + + public function __construct($AppName, IRequest $Request, $CurrentUID, IL10N $L10N) + { + parent::__construct($AppName, $Request); + + if (strcmp(Config::getSystemValue('dbtype'), 'pgsql') == 0) { + $this->DbType = 1; + } + + $this->CurrentUID = $CurrentUID; + + $this->Settings = new Settings(); + + $this->Settings->setKey('ProxyAddress'); + $this->ProxyAddress = $this->Settings->getValue(); + $this->Settings->setKey('ProxyPort'); + $this->ProxyPort = intval($this->Settings->getValue()); + $this->Settings->setKey('ProxyUser'); + $this->ProxyUser = $this->Settings->getValue(); + $this->Settings->setKey('ProxyPasswd'); + $this->ProxyPasswd = $this->Settings->getValue(); + $this->Settings->setKey('ProxyOnlyWithYTDL'); + $this->ProxyOnlyWithYTDL = $this->Settings->getValue(); + $this->ProxyOnlyWithYTDL = is_null($this->ProxyOnlyWithYTDL)?false:(strcmp($this->ProxyOnlyWithYTDL, 'Y') == 0); + + $this->Settings->setKey('MaxDownloadSpeed'); + $this->MaxDownloadSpeed = $this->Settings->getValue(); + $this->Settings->setKey('BTMaxUploadSpeed'); + $this->BTMaxUploadSpeed = $this->Settings->getValue(); + + $this->Settings->setKey('AllowProtocolBT'); + $this->AllowProtocolBT = $this->Settings->getValue(); + $this->AllowProtocolBT = is_null($this->AllowProtocolBT) ? true : strcmp($this->AllowProtocolBT, 'Y') == 0; + + $this->Settings->setTable('personal'); + $this->Settings->setUID($this->CurrentUID); + $this->Settings->setKey('DownloadsFolder'); + $this->DownloadsFolder = $this->Settings->getValue(); + $this->Settings->setKey('TorrentsFolder'); + $this->TorrentsFolder = $this->Settings->getValue(); + $this->Settings->setKey('BTRatioToReach'); + $this->BTRatioToReach = $this->Settings->getValue(); + $this->BTRatioToReach = is_null($this->BTRatioToReach) ? '0.0' : $this->BTRatioToReach; + + $this->Settings->setKey('BTSeedTimeToReach_BTSeedTimeToReachUnit'); + $this->SeedTime = $this->Settings->getValue(); + if (!is_null($this->SeedTime)) { + $this->SeedTime = explode('_', $this->SeedTime); + if (count($this->SeedTime) == 2) { + $this->SeedTime = Tools::getMinutes($this->SeedTime[0], $this->SeedTime[1]); } - - $this->CurrentUID = $CurrentUID; - - $this->Settings = new Settings (); - - $this->Settings->SetKey ('ProxyAddress'); - $this->ProxyAddress = $this->Settings->GetValue (); - $this->Settings->SetKey ('ProxyPort'); - $this->ProxyPort = intval ($this->Settings->GetValue ()); - $this->Settings->SetKey ('ProxyUser'); - $this->ProxyUser = $this->Settings->GetValue (); - $this->Settings->SetKey ('ProxyPasswd'); - $this->ProxyPasswd = $this->Settings->GetValue (); - $this->Settings->SetKey ('ProxyOnlyWithYTDL'); - $this->ProxyOnlyWithYTDL = $this->Settings->GetValue (); - $this->ProxyOnlyWithYTDL = is_null ($this->ProxyOnlyWithYTDL) ? false : (strcmp ($this->ProxyOnlyWithYTDL, 'Y') == 0); - - $this->Settings->SetKey ('MaxDownloadSpeed'); - $this->MaxDownloadSpeed = $this->Settings->GetValue (); - $this->Settings->SetKey ('BTMaxUploadSpeed'); - $this->BTMaxUploadSpeed = $this->Settings->GetValue (); - - $this->Settings->SetKey ('AllowProtocolBT'); - $this->AllowProtocolBT = $this->Settings->GetValue (); - $this->AllowProtocolBT = is_null ($this->AllowProtocolBT) ? true : strcmp ($this->AllowProtocolBT, 'Y') == 0; - - $this->Settings->SetTable ('personal'); - $this->Settings->SetUID ($this->CurrentUID); - $this->Settings->SetKey ('DownloadsFolder'); - $this->DownloadsFolder = $this->Settings->GetValue (); - $this->Settings->SetKey ('TorrentsFolder'); - $this->TorrentsFolder = $this->Settings->GetValue (); - $this->Settings->SetKey ('BTRatioToReach'); - $this->BTRatioToReach = $this->Settings->GetValue (); - $this->BTRatioToReach = is_null ($this->BTRatioToReach) ? '0.0' : $this->BTRatioToReach; - - $this->Settings->SetKey ('BTSeedTimeToReach_BTSeedTimeToReachUnit'); - $this->SeedTime = $this->Settings->GetValue (); - if (!is_null ($this->SeedTime)) - { - $this->SeedTime = explode ('_', $this->SeedTime); - if (count ($this->SeedTime) == 2) - { - $this->SeedTime = Tools::GetMinutes ($this->SeedTime[0], $this->SeedTime[1]); - } + } else { + $this->SeedTime = 10080; // minutes in 1 week - default + } + + $this->DownloadsFolder = '/' .(is_null($this->DownloadsFolder) ? 'Downloads' : $this->DownloadsFolder); + $this->TorrentsFolder = '/'.(is_null($this->TorrentsFolder)?'Downloads/Files/Torrents':$this->TorrentsFolder); + + $this->AbsoluteDownloadsFolder = \OC\Files\Filesystem::getLocalFolder($this->DownloadsFolder); + $this->AbsoluteTorrentsFolder = \OC\Files\Filesystem::getLocalFolder($this->TorrentsFolder); + + $this->L10N = $L10N; + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function add() + { + \OCP\JSON::setContentTypeHeader('application/json'); + + if (isset($_POST['FILE']) && strlen(trim($_POST['FILE'])) > 0 + && (Tools::checkURL($_POST['FILE']) || Tools::checkFilepath($this->TorrentsFolder . '/' . $_POST['FILE'])) + && isset($_POST['OPTIONS'])) { + try { + if (!$this->AllowProtocolBT && !\OC_User::isAdminUser($this->CurrentUID)) { + throw new \Exception((string)$this->L10N->t('You are not allowed to use the BitTorrent protocol')); + } + + $Target = Tools::cleanString(str_replace('.torrent', '', $_POST['FILE'])); + + $OPTIONS = array( + 'dir' => rtrim($this->AbsoluteDownloadsFolder, '/').'/'.$Target, + 'seed-ratio' => $this->BTRatioToReach, + 'seed-time' => $this->SeedTime + ); + // If target file exists, create a new one + if (!\OC\Files\Filesystem::is_dir(rtrim($this->DownloadsFolder, '/') . '/' . $Target)) { + // Create the target file + \OC\Files\Filesystem::mkdir(rtrim($this->DownloadsFolder, '/') . '/' . $Target); + } else { + $OPTIONS['bt-hash-check-seed'] = true; + $OPTIONS['check-integrity'] = true; + } + if (!is_null($this->MaxDownloadSpeed) && $this->MaxDownloadSpeed > 0) { + $OPTIONS['max-download-limit'] = $this->MaxDownloadSpeed . 'K'; + } + if (!is_null($this->BTMaxUploadSpeed) && $this->BTMaxUploadSpeed > 0) { + $OPTIONS['max-upload-limit'] = $this->BTMaxUploadSpeed . 'K'; + } + if (!$this->ProxyOnlyWithYTDL && !is_null($this->ProxyAddress) + && $this->ProxyPort > 0 && $this->ProxyPort <= 65536) { + $OPTIONS['all-proxy'] = rtrim($this->ProxyAddress, '/') . ':' . $this->ProxyPort; + if (!is_null($this->ProxyUser) && !is_null($this->ProxyPasswd)) { + $OPTIONS['all-proxy-user'] = $this->ProxyUser; + $OPTIONS['all-proxy-passwd'] = $this->ProxyPasswd; + } + } + + $AddTorrent = Aria2::addTorrent( + base64_encode(file_get_contents(rtrim($this->AbsoluteTorrentsFolder, '/').'/' . $_POST['FILE'])), + array(), + array('Params' => $OPTIONS) + ); + + if (isset($AddTorrent['result']) && !is_null($AddTorrent['result'])) { + $SQL = 'INSERT INTO `*PREFIX*ocdownloader_queue` + (`UID`, `GID`, `FILENAME`, `PROTOCOL`, `STATUS`, `TIMESTAMP`) VALUES(?, ?, ?, ?, ?, ?)'; + if ($this->DbType == 1) { + $SQL = 'INSERT INTO *PREFIX*ocdownloader_queue + ("UID", "GID", "FILENAME", "PROTOCOL", "STATUS", "TIMESTAMP") VALUES(?, ?, ?, ?, ?, ?)'; + } + + $Query = \OCP\DB::prepare($SQL); + $Result = $Query->execute(array( + $this->CurrentUID, + $AddTorrent['result'], + $Target, + 'BitTorrent', + 1, + time() + )); + + if (isset($_POST['OPTIONS']['BTRMTorrent']) + && strcmp($_POST['OPTIONS']['BTRMTorrent'], "true") == 0) { + \OC\Files\Filesystem::unlink($this->TorrentsFolder . '/' . $_POST['FILE']); + } + + sleep(1); + $Status = Aria2::tellStatus($AddTorrent['result']); + $Progress = $Status['result']['completedLength'] / $Status['result']['totalLength']; + return new JSONResponse(array( + 'ERROR' => false, + 'MESSAGE' =>(string)$this->L10N->t('Download started'), + 'GID' => $AddTorrent['result'], + 'PROGRESSVAL' => round((($Progress) * 100), 2) . '%', + 'PROGRESS' => Tools::getProgressString( + $Status['result']['completedLength'], + $Status['result']['totalLength'], + $Progress + ).' - '.$this->L10N->t('Seeders').': '.$Status['result']['numSeeders'], + 'STATUS' => isset($Status['result']['status']) + ?(string)$this->L10N->t(ucfirst($Status['result']['status'])) + :(string)$this->L10N->t('N/A'), + 'STATUSID' => Tools::getDownloadStatusID($Status['result']['status']), + 'SPEED' => isset($Status['result']['downloadSpeed']) + ?Tools::formatSizeUnits($Status['result']['downloadSpeed']).'/s' + :(string)$this->L10N->t('N/A'), + 'FILENAME' => $Target, + 'FILENAME_SHORT' => Tools::getShortFilename($Target), + 'PROTO' => 'BitTorrent', + 'ISTORRENT' => true + )); + } else { + return new JSONResponse( + array( + 'ERROR' => true, + 'MESSAGE' =>(string)$this->L10N->t('Returned GID is null ! Is Aria2c running as a daemon ?') + ) + ); + } + } catch (Exception $E) { + return new JSONResponse(array('ERROR' => true, 'MESSAGE' => $E->getMessage())); } - else - { - $this->SeedTime = 10080; // minutes in 1 week - default + } else { + return new JSONResponse( + array( + 'ERROR' => true, + 'MESSAGE' =>(string)$this->L10N->t('Please check the URL or filepath you\'ve just provided') + ) + ); + } + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function listTorrentFiles() + { + \OCP\JSON::setContentTypeHeader('application/json'); + + try { + if (!$this->AllowProtocolBT && !\OC_User::isAdminUser($this->CurrentUID)) { + throw new \Exception((string)$this->L10N->t('You are not allowed to use the BitTorrent protocol')); } - $this->DownloadsFolder = '/' . (is_null ($this->DownloadsFolder) ? 'Downloads' : $this->DownloadsFolder); - $this->TorrentsFolder = '/' . (is_null ($this->TorrentsFolder) ? 'Downloads/Files/Torrents' : $this->TorrentsFolder); - - $this->AbsoluteDownloadsFolder = \OC\Files\Filesystem::getLocalFolder ($this->DownloadsFolder); - $this->AbsoluteTorrentsFolder = \OC\Files\Filesystem::getLocalFolder ($this->TorrentsFolder); - - $this->L10N = $L10N; - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function add () - { - \OCP\JSON::setContentTypeHeader ('application/json'); - - if (isset ($_POST['FILE']) && strlen (trim ($_POST['FILE'])) > 0 && (Tools::CheckURL ($_POST['FILE']) || Tools::CheckFilepath ($this->TorrentsFolder . '/' . $_POST['FILE'])) && isset ($_POST['OPTIONS'])) - { - try - { - if (!$this->AllowProtocolBT && !\OC_User::isAdminUser ($this->CurrentUID)) - { - throw new \Exception ((string)$this->L10N->t ('You are not allowed to use the BitTorrent protocol')); - } - - $Target = Tools::CleanString (str_replace ('.torrent', '', $_POST['FILE'])); - - $OPTIONS = Array ('dir' => rtrim ($this->AbsoluteDownloadsFolder, '/') . '/' . $Target, 'seed-ratio' => $this->BTRatioToReach, 'seed-time' => $this->SeedTime); - // If target file exists, create a new one - if (!\OC\Files\Filesystem::is_dir (rtrim ($this->DownloadsFolder, '/') . '/' . $Target)) - { - // Create the target file - \OC\Files\Filesystem::mkdir (rtrim ($this->DownloadsFolder, '/') . '/' . $Target); - } - else - { - $OPTIONS['bt-hash-check-seed'] = true; - $OPTIONS['check-integrity'] = true; - } - if (!is_null ($this->MaxDownloadSpeed) && $this->MaxDownloadSpeed > 0) - { - $OPTIONS['max-download-limit'] = $this->MaxDownloadSpeed . 'K'; - } - if (!is_null ($this->BTMaxUploadSpeed) && $this->BTMaxUploadSpeed > 0) - { - $OPTIONS['max-upload-limit'] = $this->BTMaxUploadSpeed . 'K'; - } - if (!$this->ProxyOnlyWithYTDL && !is_null ($this->ProxyAddress) && $this->ProxyPort > 0 && $this->ProxyPort <= 65536) - { - $OPTIONS['all-proxy'] = rtrim ($this->ProxyAddress, '/') . ':' . $this->ProxyPort; - if (!is_null ($this->ProxyUser) && !is_null ($this->ProxyPasswd)) - { - $OPTIONS['all-proxy-user'] = $this->ProxyUser; - $OPTIONS['all-proxy-passwd'] = $this->ProxyPasswd; - } - } - - $AddTorrent = Aria2::AddTorrent (base64_encode (file_get_contents (rtrim ($this->AbsoluteTorrentsFolder, '/') . '/' . $_POST['FILE'])), Array (), Array ('Params' => $OPTIONS)); - - if (isset ($AddTorrent['result']) && !is_null ($AddTorrent['result'])) - { - $SQL = 'INSERT INTO `*PREFIX*ocdownloader_queue` (`UID`, `GID`, `FILENAME`, `PROTOCOL`, `STATUS`, `TIMESTAMP`) VALUES (?, ?, ?, ?, ?, ?)'; - if ($this->DbType == 1) - { - $SQL = 'INSERT INTO *PREFIX*ocdownloader_queue ("UID", "GID", "FILENAME", "PROTOCOL", "STATUS", "TIMESTAMP") VALUES (?, ?, ?, ?, ?, ?)'; - } - - $Query = \OCP\DB::prepare ($SQL); - $Result = $Query->execute (Array ( - $this->CurrentUID, - $AddTorrent['result'], - $Target, - 'BitTorrent', - 1, - time() - )); - - if (isset ($_POST['OPTIONS']['BTRMTorrent']) && strcmp ($_POST['OPTIONS']['BTRMTorrent'], "true") == 0) - { - \OC\Files\Filesystem::unlink ($this->TorrentsFolder . '/' . $_POST['FILE']); - } - - sleep (1); - $Status = Aria2::TellStatus ($AddTorrent['result']); - $Progress = $Status['result']['completedLength'] / $Status['result']['totalLength']; - return new JSONResponse (Array ( - 'ERROR' => false, - 'MESSAGE' => (string)$this->L10N->t ('Download started'), - 'GID' => $AddTorrent['result'], - 'PROGRESSVAL' => round((($Progress) * 100), 2) . '%', - 'PROGRESS' => Tools::GetProgressString ($Status['result']['completedLength'], $Status['result']['totalLength'], $Progress) . ' - ' . $this->L10N->t ('Seeders') . ': ' . $Status['result']['numSeeders'], - 'STATUS' => isset ($Status['result']['status']) ? (string)$this->L10N->t (ucfirst ($Status['result']['status'])) : (string)$this->L10N->t ('N/A'), - 'STATUSID' => Tools::GetDownloadStatusID ($Status['result']['status']), - 'SPEED' => isset ($Status['result']['downloadSpeed']) ? Tools::FormatSizeUnits ($Status['result']['downloadSpeed']) . '/s' : (string)$this->L10N->t ('N/A'), - 'FILENAME' => (mb_strlen ($Target, "UTF-8") > 40 ? mb_substr ($Target, 0, 40, "UTF-8") . '...' : $Target), - 'PROTO' => 'BitTorrent', - 'ISTORRENT' => true - )); - } - else - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ('Returned GID is null ! Is Aria2c running as a daemon ?'))); - } - } - catch (Exception $E) - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => $E->getMessage ())); - } - } - else - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ('Please check the URL or filepath you\'ve just provided'))); - } - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function ListTorrentFiles () - { - \OCP\JSON::setContentTypeHeader ('application/json'); - - try - { - if (!$this->AllowProtocolBT && !\OC_User::isAdminUser ($this->CurrentUID)) - { - throw new \Exception ((string)$this->L10N->t ('You are not allowed to use the BitTorrent protocol')); - } - - if (!\OC\Files\Filesystem::is_dir ($this->TorrentsFolder)) - { - \OC\Files\Filesystem::mkdir ($this->TorrentsFolder); - } - - $this->TorrentsFolder = \OC\Files\Filesystem::normalizePath($this->TorrentsFolder); - - $Files = \OCA\Files\Helper::getFiles ($this->TorrentsFolder, 'name', 'desc', 'application/octet-stream'); - $Files = \OCA\Files\Helper::formatFileInfos ($Files); - - return new JSONResponse (Array ('ERROR' => false, 'FILES' => $Files)); - } - catch (Exception $E) - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => $E->getMessage ())); - } - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function UploadFiles () - { - \OCP\JSON::setContentTypeHeader ('text/plain'); - - if (!$this->AllowProtocolBT && !\OC_User::isAdminUser ($this->CurrentUID)) - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ('You are not allowed to use the BitTorrent protocol'))); + if (!\OC\Files\Filesystem::is_dir($this->TorrentsFolder)) { + \OC\Files\Filesystem::mkdir($this->TorrentsFolder); } - if (!isset ($_FILES['files'])) - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ('Error while uploading torrent file'))); + $this->TorrentsFolder = \OC\Files\Filesystem::normalizePath($this->TorrentsFolder); + + $Files = \OCA\Files\Helper::getFiles($this->TorrentsFolder, 'name', 'desc', 'application/octet-stream'); + $Files = \OCA\Files\Helper::formatFileInfos($Files); + + return new JSONResponse(array('ERROR' => false, 'FILES' => $Files)); + } catch (Exception $E) { + return new JSONResponse(array('ERROR' => true, 'MESSAGE' => $E->getMessage())); + } + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function uploadFiles() + { + \OCP\JSON::setContentTypeHeader('text/plain'); + + if (!$this->AllowProtocolBT && !\OC_User::isAdminUser($this->CurrentUID)) { + return new JSONResponse( + array( + 'ERROR' => true, + 'MESSAGE' =>(string)$this->L10N->t('You are not allowed to use the BitTorrent protocol') + ) + ); + } + + if (!isset($_FILES['files'])) { + return new JSONResponse( + array('ERROR' => true, 'MESSAGE' =>(string)$this->L10N->t('Error while uploading torrent file')) + ); + } else { + if (!isset($_FILES['files']['name'][0])) { + throw new \Exception('Unable to find the uploaded file'); } - else - { - if (!isset ($_FILES['files']['name'][0])) - { - throw new \Exception ('Unable to find the uploaded file'); - } - - $Target = rtrim ($this->TorrentsFolder, '/') . '/' . $_FILES['files']['name'][0]; - try - { - if (is_uploaded_file ($_FILES['files']['tmp_name'][0]) && \OC\Files\Filesystem::fromTmpFile ($_FILES['files']['tmp_name'][0], $Target)) - { - $StorageStats = \OCA\Files\Helper::buildFileStorageStatistics ($this->TorrentsFolder); - - if (\OC\Files\Filesystem::getFileInfo ($Target) !== false) - { - return new JSONResponse (Array ('ERROR' => false, 'MESSAGE' => (string)$this->L10N->t ('Upload OK'))); - } - } else { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ('Error while uploading torrent file'))); - } - } - catch (Exception $E) - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => $E->getMessage ())); - } + + $Target = rtrim($this->TorrentsFolder, '/') . '/' . $_FILES['files']['name'][0]; + try { + if (is_uploaded_file($_FILES['files']['tmp_name'][0]) + && \OC\Files\Filesystem::fromTmpFile($_FILES['files']['tmp_name'][0], $Target)) { + $StorageStats = \OCA\Files\Helper::buildFileStorageStatistics($this->TorrentsFolder); + + if (\OC\Files\Filesystem::getFileInfo($Target) !== false) { + return new JSONResponse( + array('ERROR' => false, 'MESSAGE' =>(string)$this->L10N->t('Upload OK')) + ); + } + } else { + return new JSONResponse( + array('ERROR' => true, 'MESSAGE' =>(string)$this->L10N->t('Error while uploading torrent file')) + ); + } + } catch (Exception $E) { + return new JSONResponse(array('ERROR' => true, 'MESSAGE' => $E->getMessage())); } - } -} \ No newline at end of file + } + } +} diff --git a/controller/ftpdownloader.php b/controller/ftpdownloader.php index 0c58a8e..83b3a37 100644 --- a/controller/ftpdownloader.php +++ b/controller/ftpdownloader.php @@ -24,195 +24,205 @@ class FtpDownloader extends Controller { - private $AbsoluteDownloadsFolder = null; - private $DownloadsFolder = null; - private $DbType = 0; - private $ProxyAddress = null; - private $ProxyPort = 0; - private $ProxyUser = null; - private $ProxyPasswd = null; - private $ProxyOnlyWithYTDL = null; - private $WhichDownloader = 0; - private $CurrentUID = null; - private $L10N = null; - private $AllowProtocolFTP = null; - private $MaxDownloadSpeed = null; - - public function __construct ($AppName, IRequest $Request, $CurrentUID, IL10N $L10N) - { - parent::__construct ($AppName, $Request); - - if (strcmp (Config::getSystemValue ('dbtype'), 'pgsql') == 0) - { - $this->DbType = 1; - } - - $this->CurrentUID = $CurrentUID; - - $Settings = new Settings (); - - $Settings->SetKey ('ProxyAddress'); - $this->ProxyAddress = $Settings->GetValue (); - $Settings->SetKey ('ProxyPort'); - $this->ProxyPort = intval ($Settings->GetValue ()); - $Settings->SetKey ('ProxyUser'); - $this->ProxyUser = $Settings->GetValue (); - $Settings->SetKey ('ProxyPasswd'); - $this->ProxyPasswd = $Settings->GetValue (); - $Settings->SetKey ('ProxyOnlyWithYTDL'); - $this->ProxyOnlyWithYTDL = $Settings->GetValue (); - $this->ProxyOnlyWithYTDL = is_null ($this->ProxyOnlyWithYTDL) ? false : (strcmp ($this->ProxyOnlyWithYTDL, 'Y') == 0); - $Settings->SetKey ('WhichDownloader'); - $this->WhichDownloader = $Settings->GetValue (); - $this->WhichDownloader = is_null ($this->WhichDownloader) ? 0 : (strcmp ($this->WhichDownloader, 'ARIA2') == 0 ? 0 : 1); // 0 means ARIA2, 1 means CURL - $Settings->SetKey ('MaxDownloadSpeed'); - $this->MaxDownloadSpeed = $Settings->GetValue (); - $Settings->SetKey ('AllowProtocolFTP'); - $this->AllowProtocolFTP = $Settings->GetValue (); - $this->AllowProtocolFTP = is_null ($this->AllowProtocolFTP) ? true : strcmp ($this->AllowProtocolFTP, 'Y') == 0; - - $Settings->SetTable ('personal'); - $Settings->SetUID ($this->CurrentUID); - $Settings->SetKey ('DownloadsFolder'); - $this->DownloadsFolder = $Settings->GetValue (); - - $this->DownloadsFolder = '/' . (is_null ($this->DownloadsFolder) ? 'Downloads' : $this->DownloadsFolder); - $this->AbsoluteDownloadsFolder = \OC\Files\Filesystem::getLocalFolder ($this->DownloadsFolder); - - $this->L10N = $L10N; - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function Add () - { - \OCP\JSON::setContentTypeHeader ('application/json'); - - if (isset ($_POST['FILE']) && strlen ($_POST['FILE']) > 0 && Tools::CheckURL ($_POST['FILE']) && isset ($_POST['OPTIONS'])) - { - try - { - if (!$this->AllowProtocolFTP && !\OC_User::isAdminUser ($this->CurrentUID)) - { - throw new \Exception ((string)$this->L10N->t ('You are not allowed to use the FTP protocol')); - } - - $Target = Tools::CleanString (substr($_POST['FILE'], strrpos ($_POST['FILE'], '/') + 1)); - - // If target file exists, create a new one - if (\OC\Files\Filesystem::file_exists ($this->DownloadsFolder . '/' . $Target)) - { - $Target = time () . '_' . $Target; - } - - // Create the target file if the downloader is Aria2 - if ($this->WhichDownloader == 0) - { - \OC\Files\Filesystem::touch ($this->DownloadsFolder . '/' . $Target); - } - else - { - if (!\OC\Files\Filesystem::is_dir ($this->DownloadsFolder)) - { - \OC\Files\Filesystem::mkdir ($this->DownloadsFolder); - } - } - - // Build OPTIONS array - $OPTIONS = Array ('dir' => $this->AbsoluteDownloadsFolder, 'out' => $Target, 'follow-torrent' => false); - if (isset ($_POST['OPTIONS']['FTPUser']) && strlen (trim ($_POST['OPTIONS']['FTPUser'])) > 0 && isset ($_POST['OPTIONS']['FTPPasswd']) && strlen (trim ($_POST['OPTIONS']['FTPPasswd'])) > 0) - { - $OPTIONS['ftp-user'] = $_POST['OPTIONS']['FTPUser']; - $OPTIONS['ftp-passwd'] = $_POST['OPTIONS']['FTPPasswd']; - } - if (isset ($_POST['OPTIONS']['FTPReferer']) && strlen (trim ($_POST['OPTIONS']['FTPReferer'])) > 0) - { + private $AbsoluteDownloadsFolder = null; + private $DownloadsFolder = null; + private $DbType = 0; + private $ProxyAddress = null; + private $ProxyPort = 0; + private $ProxyUser = null; + private $ProxyPasswd = null; + private $ProxyOnlyWithYTDL = null; + private $WhichDownloader = 0; + private $CurrentUID = null; + private $L10N = null; + private $AllowProtocolFTP = null; + private $MaxDownloadSpeed = null; + + public function __construct($AppName, IRequest $Request, $CurrentUID, IL10N $L10N) + { + parent::__construct($AppName, $Request); + + if (strcmp(Config::getSystemValue('dbtype'), 'pgsql') == 0) { + $this->DbType = 1; + } + + $this->CurrentUID = $CurrentUID; + + $Settings = new Settings(); + + $Settings->setKey('ProxyAddress'); + $this->ProxyAddress = $Settings->getValue(); + $Settings->setKey('ProxyPort'); + $this->ProxyPort = intval($Settings->getValue()); + $Settings->setKey('ProxyUser'); + $this->ProxyUser = $Settings->getValue(); + $Settings->setKey('ProxyPasswd'); + $this->ProxyPasswd = $Settings->getValue(); + $Settings->setKey('ProxyOnlyWithYTDL'); + $this->ProxyOnlyWithYTDL = $Settings->getValue(); + $this->ProxyOnlyWithYTDL = is_null($this->ProxyOnlyWithYTDL)?false:(strcmp($this->ProxyOnlyWithYTDL, 'Y') == 0); + $Settings->setKey('WhichDownloader'); + $this->WhichDownloader = $Settings->getValue(); + $this->WhichDownloader = is_null($this->WhichDownloader) + ?0:(strcmp($this->WhichDownloader, 'ARIA2') == 0 ? 0 : 1); // 0 means ARIA2, 1 means CURL + $Settings->setKey('MaxDownloadSpeed'); + $this->MaxDownloadSpeed = $Settings->getValue(); + $Settings->setKey('AllowProtocolFTP'); + $this->AllowProtocolFTP = $Settings->getValue(); + $this->AllowProtocolFTP = is_null($this->AllowProtocolFTP) ? true : strcmp($this->AllowProtocolFTP, 'Y') == 0; + + $Settings->setTable('personal'); + $Settings->setUID($this->CurrentUID); + $Settings->setKey('DownloadsFolder'); + $this->DownloadsFolder = $Settings->getValue(); + + $this->DownloadsFolder = '/' .(is_null($this->DownloadsFolder) ? 'Downloads' : $this->DownloadsFolder); + $this->AbsoluteDownloadsFolder = \OC\Files\Filesystem::getLocalFolder($this->DownloadsFolder); + + $this->L10N = $L10N; + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function add() + { + \OCP\JSON::setContentTypeHeader('application/json'); + + if (isset($_POST['FILE']) && strlen($_POST['FILE']) > 0 + && Tools::checkURL($_POST['FILE']) && isset($_POST['OPTIONS'])) { + try { + if (!$this->AllowProtocolFTP && !\OC_User::isAdminUser($this->CurrentUID)) { + throw new \Exception((string)$this->L10N->t('You are not allowed to use the FTP protocol')); + } + + $Target = Tools::cleanString(substr($_POST['FILE'], strrpos($_POST['FILE'], '/') + 1)); + + // If target file exists, create a new one + if (\OC\Files\Filesystem::file_exists($this->DownloadsFolder . '/' . $Target)) { + $Target = time() . '_' . $Target; + } + + // Create the target file if the downloader is Aria2 + if ($this->WhichDownloader == 0) { + \OC\Files\Filesystem::touch($this->DownloadsFolder . '/' . $Target); + } else { + if (!\OC\Files\Filesystem::is_dir($this->DownloadsFolder)) { + \OC\Files\Filesystem::mkdir($this->DownloadsFolder); + } + } + + // Build OPTIONS array + $OPTIONS = array('dir' => $this->AbsoluteDownloadsFolder, 'out' => $Target, 'follow-torrent' => false); + if (isset($_POST['OPTIONS']['FTPUser']) && strlen(trim($_POST['OPTIONS']['FTPUser'])) > 0 + && isset($_POST['OPTIONS']['FTPPasswd']) && strlen(trim($_POST['OPTIONS']['FTPPasswd'])) > 0) { + $OPTIONS['ftp-user'] = $_POST['OPTIONS']['FTPUser']; + $OPTIONS['ftp-passwd'] = $_POST['OPTIONS']['FTPPasswd']; + } + if (isset ($_POST['OPTIONS']['FTPReferer']) && strlen (trim ($_POST['OPTIONS']['FTPReferer'])) > 0) { $OPTIONS['referer'] = $_POST['OPTIONS']['FTPReferer']; } - - if (isset ($_POST['OPTIONS']['FTPUseragent']) && strlen (trim ($_POST['OPTIONS']['FTPUseragent'])) > 0) - { + if (isset ($_POST['OPTIONS']['FTPUseragent']) && strlen (trim ($_POST['OPTIONS']['FTPUseragent'])) > 0) { $OPTIONS['user-agent'] = $_POST['OPTIONS']['FTPUseragent']; } - - if (isset ($_POST['OPTIONS']['FTPPasv']) && strlen (trim ($_POST['OPTIONS']['FTPPasv'])) > 0) - { - $OPTIONS['ftp-pasv'] = strcmp ($_POST['OPTIONS']['FTPPasv'], "true") == 0 ? true : false; - } - if (!$this->ProxyOnlyWithYTDL && !is_null ($this->ProxyAddress) && $this->ProxyPort > 0 && $this->ProxyPort <= 65536) - { - $OPTIONS['all-proxy'] = rtrim ($this->ProxyAddress, '/') . ':' . $this->ProxyPort; - if (!is_null ($this->ProxyUser) && !is_null ($this->ProxyPasswd)) - { - $OPTIONS['all-proxy-user'] = $this->ProxyUser; - $OPTIONS['all-proxy-passwd'] = $this->ProxyPasswd; - } - } - if (!is_null ($this->MaxDownloadSpeed) && $this->MaxDownloadSpeed > 0) - { - $OPTIONS['max-download-limit'] = $this->MaxDownloadSpeed . 'K'; - } - - $AddURI = ($this->WhichDownloader == 0 ? Aria2::AddUri (Array ($_POST['FILE']), Array ('Params' => $OPTIONS)) : CURL::AddUri ($_POST['FILE'], $OPTIONS)); - - if (isset ($AddURI['result']) && !is_null ($AddURI['result'])) - { - $SQL = 'INSERT INTO `*PREFIX*ocdownloader_queue` (`UID`, `GID`, `FILENAME`, `PROTOCOL`, `STATUS`, `TIMESTAMP`) VALUES (?, ?, ?, ?, ?, ?)'; - if ($this->DbType == 1) - { - $SQL = 'INSERT INTO *PREFIX*ocdownloader_queue ("UID", "GID", "FILENAME", "PROTOCOL", "STATUS", "TIMESTAMP") VALUES (?, ?, ?, ?, ?, ?)'; - } - - $Query = \OCP\DB::prepare ($SQL); - $Result = $Query->execute (Array ( - $this->CurrentUID, - $AddURI['result'], - $Target, - strtoupper(substr($_POST['FILE'], 0, strpos($_POST['FILE'], ':'))), - 1, - time() - )); - - sleep (1); - $Status = ($this->WhichDownloader == 0 ? Aria2::TellStatus ($AddURI['result']) : CURL::TellStatus ($AddURI['result'])); - - $Progress = 0; - if ($Status['result']['totalLength'] > 0) - { - $Progress = $Status['result']['completedLength'] / $Status['result']['totalLength']; - } - - $ProgressString = Tools::GetProgressString ($Status['result']['completedLength'], $Status['result']['totalLength'], $Progress); - - return new JSONResponse (Array ( - 'ERROR' => false, - 'MESSAGE' => (string)$this->L10N->t ('Download started'), - 'GID' => $AddURI['result'], - 'PROGRESSVAL' => round((($Progress) * 100), 2) . '%', - 'PROGRESS' => is_null ($ProgressString) ? (string)$this->L10N->t ('N/A') : $ProgressString, - 'STATUS' => isset ($Status['result']['status']) ? (string)$this->L10N->t (ucfirst ($Status['result']['status'])) : (string)$this->L10N->t ('N/A'), - 'STATUSID' => Tools::GetDownloadStatusID ($Status['result']['status']), - 'SPEED' => isset ($Status['result']['downloadSpeed']) ? Tools::FormatSizeUnits ($Status['result']['downloadSpeed']) . '/s' : (string)$this->L10N->t ('N/A'), - 'FILENAME' => (mb_strlen ($Target, "UTF-8") > 40 ? mb_substr ($Target, 0, 40, "UTF-8") . '...' : $Target), - 'PROTO' => strtoupper(substr($_POST['FILE'], 0, strpos($_POST['FILE'], ':'))), - 'ISTORRENT' => false - )); - } - else - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ($this->WhichDownloader == 0 ? 'Returned GID is null ! Is Aria2c running as a daemon ?' : 'An error occurred while running the CURL download'))); - } - } - catch (Exception $E) - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => $E->getMessage ())); - } - } - else - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ('Please check the URL you\'ve just provided'))); + if (isset($_POST['OPTIONS']['FTPPasv']) && strlen(trim($_POST['OPTIONS']['FTPPasv'])) > 0) { + $OPTIONS['ftp-pasv'] = strcmp($_POST['OPTIONS']['FTPPasv'], "true") == 0 ? true : false; + } + if (!$this->ProxyOnlyWithYTDL && !is_null($this->ProxyAddress) + && $this->ProxyPort > 0 && $this->ProxyPort <= 65536) { + $OPTIONS['all-proxy'] = rtrim($this->ProxyAddress, '/') . ':' . $this->ProxyPort; + if (!is_null($this->ProxyUser) && !is_null($this->ProxyPasswd)) { + $OPTIONS['all-proxy-user'] = $this->ProxyUser; + $OPTIONS['all-proxy-passwd'] = $this->ProxyPasswd; + } + } + if (!is_null($this->MaxDownloadSpeed) && $this->MaxDownloadSpeed > 0) { + $OPTIONS['max-download-limit'] = $this->MaxDownloadSpeed . 'K'; + } + + $AddURI =( + $this->WhichDownloader == 0 + ?Aria2::addUri(array($_POST['FILE']), array('Params' => $OPTIONS)) + :CURL::addUri($_POST['FILE'], $OPTIONS) + ); + + if (isset($AddURI['result']) && !is_null($AddURI['result'])) { + $SQL = 'INSERT INTO `*PREFIX*ocdownloader_queue` + (`UID`, `GID`, `FILENAME`, `PROTOCOL`, `STATUS`, `TIMESTAMP`) VALUES(?, ?, ?, ?, ?, ?)'; + if ($this->DbType == 1) { + $SQL = 'INSERT INTO *PREFIX*ocdownloader_queue + ("UID", "GID", "FILENAME", "PROTOCOL", "STATUS", "TIMESTAMP") VALUES(?, ?, ?, ?, ?, ?)'; + } + + $Query = \OCP\DB::prepare($SQL); + $Result = $Query->execute(array( + $this->CurrentUID, + $AddURI['result'], + $Target, + strtoupper(substr($_POST['FILE'], 0, strpos($_POST['FILE'], ':'))), + 1, + time() + )); + + sleep(1); + $Status =( + $this->WhichDownloader == 0 + ?Aria2::tellStatus($AddURI['result']) + :CURL::tellStatus($AddURI['result']) + ); + + $Progress = 0; + if ($Status['result']['totalLength'] > 0) { + $Progress = $Status['result']['completedLength'] / $Status['result']['totalLength']; + } + + $ProgressString = Tools::getProgressString( + $Status['result']['completedLength'], + $Status['result']['totalLength'], + $Progress + ); + + return new JSONResponse(array( + 'ERROR' => false, + 'MESSAGE' =>(string)$this->L10N->t('Download started'), + 'GID' => $AddURI['result'], + 'PROGRESSVAL' => round((($Progress) * 100), 2) . '%', + 'PROGRESS' => is_null($ProgressString) ?(string)$this->L10N->t('N/A') : $ProgressString, + 'STATUS' => isset($Status['result']['status']) + ?(string)$this->L10N->t(ucfirst($Status['result']['status'])) + :(string)$this->L10N->t('N/A'), + 'STATUSID' => Tools::getDownloadStatusID($Status['result']['status']), + 'SPEED' => isset($Status['result']['downloadSpeed']) + ?Tools::formatSizeUnits($Status['result']['downloadSpeed']).'/s' + :(string)$this->L10N->t('N/A'), + 'FILENAME' => $Target, + 'FILENAME_SHORT' => Tools::getShortFilename($Target), + 'PROTO' => strtoupper(substr($_POST['FILE'], 0, strpos($_POST['FILE'], ':'))), + 'ISTORRENT' => false + )); + } else { + return new JSONResponse( + array( + 'ERROR' => true, + 'MESSAGE' =>(string)$this->L10N->t( + $this->WhichDownloader == 0 + ?'Returned GID is null ! Is Aria2c running as a daemon ?' + :'An error occurred while running the CURL download' + ) + ) + ); + } + } catch (Exception $E) { + return new JSONResponse(array('ERROR' => true, 'MESSAGE' => $E->getMessage())); } - } + } else { + return new JSONResponse( + array( + 'ERROR' => true, + 'MESSAGE' =>(string)$this->L10N->t('Please check the URL you\'ve just provided') + ) + ); + } + } } diff --git a/controller/httpdownloader.php b/controller/httpdownloader.php index 93b065f..54b0329 100644 --- a/controller/httpdownloader.php +++ b/controller/httpdownloader.php @@ -24,191 +24,198 @@ class HttpDownloader extends Controller { - private $AbsoluteDownloadsFolder = null; - private $DownloadsFolder = null; - private $DbType = 0; - private $ProxyAddress = null; - private $ProxyPort = 0; - private $ProxyUser = null; - private $ProxyPasswd = null; - private $ProxyOnlyWithYTDL = null; - private $WhichDownloader = 0; - private $CurrentUID = null; - private $L10N = null; - private $AllowProtocolHTTP = null; - private $MaxDownloadSpeed = null; - - public function __construct ($AppName, IRequest $Request, $CurrentUID, IL10N $L10N) - { - parent::__construct ($AppName, $Request); - - if (strcmp (Config::getSystemValue ('dbtype'), 'pgsql') == 0) - { - $this->DbType = 1; - } - - $this->CurrentUID = $CurrentUID; - - $Settings = new Settings (); - $Settings->SetKey ('ProxyAddress'); - $this->ProxyAddress = $Settings->GetValue (); - $Settings->SetKey ('ProxyPort'); - $this->ProxyPort = intval ($Settings->GetValue ()); - $Settings->SetKey ('ProxyUser'); - $this->ProxyUser = $Settings->GetValue (); - $Settings->SetKey ('ProxyPasswd'); - $this->ProxyPasswd = $Settings->GetValue (); - $Settings->SetKey ('ProxyOnlyWithYTDL'); - $this->ProxyOnlyWithYTDL = $Settings->GetValue (); - $this->ProxyOnlyWithYTDL = is_null ($this->ProxyOnlyWithYTDL) ? false : (strcmp ($this->ProxyOnlyWithYTDL, 'Y') == 0); - $Settings->SetKey ('WhichDownloader'); - $this->WhichDownloader = $Settings->GetValue (); - $this->WhichDownloader = is_null ($this->WhichDownloader) ? 0 : (strcmp ($this->WhichDownloader, 'ARIA2') == 0 ? 0 : 1); // 0 means ARIA2, 1 means CURL - $Settings->SetKey ('MaxDownloadSpeed'); - $this->MaxDownloadSpeed = $Settings->GetValue (); - $Settings->SetKey ('AllowProtocolHTTP'); - $this->AllowProtocolHTTP = $Settings->GetValue (); - $this->AllowProtocolHTTP = is_null ($this->AllowProtocolHTTP) ? true : strcmp ($this->AllowProtocolHTTP, 'Y') == 0; - - $Settings->SetTable ('personal'); - $Settings->SetUID ($this->CurrentUID); - $Settings->SetKey ('DownloadsFolder'); - $this->DownloadsFolder = $Settings->GetValue (); - - $this->DownloadsFolder = '/' . (is_null ($this->DownloadsFolder) ? 'Downloads' : $this->DownloadsFolder); - $this->AbsoluteDownloadsFolder = \OC\Files\Filesystem::getLocalFolder ($this->DownloadsFolder); - - $this->L10N = $L10N; - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function Add () - { - \OCP\JSON::setContentTypeHeader ('application/json'); - - if (isset ($_POST['FILE']) && strlen ($_POST['FILE']) > 0 && Tools::CheckURL ($_POST['FILE']) && isset ($_POST['OPTIONS'])) - { - try - { - if (!$this->AllowProtocolHTTP && !\OC_User::isAdminUser ($this->CurrentUID)) - { - throw new \Exception ((string)$this->L10N->t ('You are not allowed to use the HTTP protocol')); - } - - $Target = Tools::CleanString (substr($_POST['FILE'], strrpos ($_POST['FILE'], '/') + 1)); - - // If target file exists, create a new one - if (\OC\Files\Filesystem::file_exists ($this->DownloadsFolder . '/' . $Target)) - { - $Target = time () . '_' . $Target; - } - - // Create the target file if the downloader is ARIA2 - if ($this->WhichDownloader == 0) - { - \OC\Files\Filesystem::touch ($this->DownloadsFolder . '/' . $Target); - } - else - { - if (!\OC\Files\Filesystem::is_dir ($this->DownloadsFolder)) - { - \OC\Files\Filesystem::mkdir ($this->DownloadsFolder); - } - } - - // Download in the user root folder - $OPTIONS = Array ('dir' => $this->AbsoluteDownloadsFolder, 'out' => $Target, 'follow-torrent' => false); - if (isset ($_POST['OPTIONS']['HTTPUser']) && strlen (trim ($_POST['OPTIONS']['HTTPUser'])) > 0 && isset ($_POST['OPTIONS']['HTTPPasswd']) && strlen (trim ($_POST['OPTIONS']['HTTPPasswd'])) > 0) - { - $OPTIONS['http-user'] = $_POST['OPTIONS']['HTTPUser']; - $OPTIONS['http-passwd'] = $_POST['OPTIONS']['HTTPPasswd']; - } - - if (isset ($_POST['OPTIONS']['HTTPReferer']) && strlen (trim ($_POST['OPTIONS']['HTTPReferer'])) > 0) - { + private $AbsoluteDownloadsFolder = null; + private $DownloadsFolder = null; + private $DbType = 0; + private $ProxyAddress = null; + private $ProxyPort = 0; + private $ProxyUser = null; + private $ProxyPasswd = null; + private $ProxyOnlyWithYTDL = null; + private $WhichDownloader = 0; + private $CurrentUID = null; + private $L10N = null; + private $AllowProtocolHTTP = null; + private $MaxDownloadSpeed = null; + + public function __construct($AppName, IRequest $Request, $CurrentUID, IL10N $L10N) + { + parent::__construct($AppName, $Request); + + if (strcmp(Config::getSystemValue('dbtype'), 'pgsql') == 0) { + $this->DbType = 1; + } + + $this->CurrentUID = $CurrentUID; + + $Settings = new Settings(); + $Settings->setKey('ProxyAddress'); + $this->ProxyAddress = $Settings->getValue(); + $Settings->setKey('ProxyPort'); + $this->ProxyPort = intval($Settings->getValue()); + $Settings->setKey('ProxyUser'); + $this->ProxyUser = $Settings->getValue(); + $Settings->setKey('ProxyPasswd'); + $this->ProxyPasswd = $Settings->getValue(); + $Settings->setKey('ProxyOnlyWithYTDL'); + $this->ProxyOnlyWithYTDL = $Settings->getValue(); + $this->ProxyOnlyWithYTDL = is_null($this->ProxyOnlyWithYTDL)?false:(strcmp($this->ProxyOnlyWithYTDL, 'Y') == 0); + $Settings->setKey('WhichDownloader'); + $this->WhichDownloader = $Settings->getValue(); + $this->WhichDownloader = is_null($this->WhichDownloader) + ?0:(strcmp($this->WhichDownloader, 'ARIA2') == 0 ? 0 : 1); // 0 means ARIA2, 1 means CURL + $Settings->setKey('MaxDownloadSpeed'); + $this->MaxDownloadSpeed = $Settings->getValue(); + $Settings->setKey('AllowProtocolHTTP'); + $this->AllowProtocolHTTP = $Settings->getValue(); + $this->AllowProtocolHTTP = is_null($this->AllowProtocolHTTP)?true:strcmp($this->AllowProtocolHTTP, 'Y') == 0; + + $Settings->setTable('personal'); + $Settings->setUID($this->CurrentUID); + $Settings->setKey('DownloadsFolder'); + $this->DownloadsFolder = $Settings->getValue(); + + $this->DownloadsFolder = '/' .(is_null($this->DownloadsFolder) ? 'Downloads' : $this->DownloadsFolder); + $this->AbsoluteDownloadsFolder = \OC\Files\Filesystem::getLocalFolder($this->DownloadsFolder); + + $this->L10N = $L10N; + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function add() + { + \OCP\JSON::setContentTypeHeader('application/json'); + + if (isset($_POST['FILE']) && strlen($_POST['FILE']) > 0 && Tools::checkURL($_POST['FILE']) + && isset($_POST['OPTIONS'])) { + try { + if (!$this->AllowProtocolHTTP && !\OC_User::isAdminUser($this->CurrentUID)) { + throw new \Exception((string)$this->L10N->t('You are not allowed to use the HTTP protocol')); + } + + $Target = Tools::cleanString(substr($_POST['FILE'], strrpos($_POST['FILE'], '/') + 1)); + + // If target file exists, create a new one + if (\OC\Files\Filesystem::file_exists($this->DownloadsFolder . '/' . $Target)) { + $Target = time() . '_' . $Target; + } + + // Create the target file if the downloader is ARIA2 + if ($this->WhichDownloader == 0) { + \OC\Files\Filesystem::touch($this->DownloadsFolder . '/' . $Target); + } else { + if (!\OC\Files\Filesystem::is_dir($this->DownloadsFolder)) { + \OC\Files\Filesystem::mkdir($this->DownloadsFolder); + } + } + + // Download in the user root folder + $OPTIONS = array('dir' => $this->AbsoluteDownloadsFolder, 'out' => $Target, 'follow-torrent' => false); + if (isset($_POST['OPTIONS']['HTTPUser']) && strlen(trim($_POST['OPTIONS']['HTTPUser'])) > 0 + && isset($_POST['OPTIONS']['HTTPPasswd']) && strlen(trim($_POST['OPTIONS']['HTTPPasswd'])) > 0) { + $OPTIONS['http-user'] = $_POST['OPTIONS']['HTTPUser']; + $OPTIONS['http-passwd'] = $_POST['OPTIONS']['HTTPPasswd']; + } + if (isset ($_POST['OPTIONS']['HTTPReferer']) && strlen (trim ($_POST['OPTIONS']['HTTPReferer'])) > 0) { $OPTIONS['referer'] = $_POST['OPTIONS']['HTTPReferer']; - } - - if (isset ($_POST['OPTIONS']['HTTPUseragent']) && strlen (trim ($_POST['OPTIONS']['HTTPUseragent'])) > 0) - { + } + if (isset ($_POST['OPTIONS']['HTTPUseragent']) && strlen (trim ($_POST['OPTIONS']['HTTPUseragent'])) > 0) { $OPTIONS['user-agent'] = $_POST['OPTIONS']['HTTPUseragent']; - } - - if (!$this->ProxyOnlyWithYTDL && !is_null ($this->ProxyAddress) && $this->ProxyPort > 0 && $this->ProxyPort <= 65536) - { - $OPTIONS['all-proxy'] = rtrim ($this->ProxyAddress, '/') . ':' . $this->ProxyPort; - if (!is_null ($this->ProxyUser) && !is_null ($this->ProxyPasswd)) - { - $OPTIONS['all-proxy-user'] = $this->ProxyUser; - $OPTIONS['all-proxy-passwd'] = $this->ProxyPasswd; - } - } - if (!is_null ($this->MaxDownloadSpeed) && $this->MaxDownloadSpeed > 0) - { - $OPTIONS['max-download-limit'] = $this->MaxDownloadSpeed . 'K'; - } - - $AddURI = ($this->WhichDownloader == 0 ? Aria2::AddUri (Array ($_POST['FILE']), Array ('Params' => $OPTIONS)) : CURL::AddUri ($_POST['FILE'], $OPTIONS)); - - if (isset ($AddURI['result']) && !is_null ($AddURI['result'])) - { - $SQL = 'INSERT INTO `*PREFIX*ocdownloader_queue` (`UID`, `GID`, `FILENAME`, `PROTOCOL`, `STATUS`, `TIMESTAMP`) VALUES (?, ?, ?, ?, ?, ?)'; - if ($this->DbType == 1) - { - $SQL = 'INSERT INTO *PREFIX*ocdownloader_queue ("UID", "GID", "FILENAME", "PROTOCOL", "STATUS", "TIMESTAMP") VALUES (?, ?, ?, ?, ?, ?)'; - } - - $Query = \OCP\DB::prepare ($SQL); - $Result = $Query->execute (Array ( - $this->CurrentUID, - $AddURI['result'], - $Target, - strtoupper(substr($_POST['FILE'], 0, strpos($_POST['FILE'], ':'))), - 1, - time() - )); - - sleep (1); - $Status = ($this->WhichDownloader == 0 ? Aria2::TellStatus ($AddURI['result']) : CURL::TellStatus ($AddURI['result'])); - - $Progress = 0; - if ($Status['result']['totalLength'] > 0) - { - $Progress = $Status['result']['completedLength'] / $Status['result']['totalLength']; - } - - $ProgressString = Tools::GetProgressString ($Status['result']['completedLength'], $Status['result']['totalLength'], $Progress); - - return new JSONResponse (Array ( - 'ERROR' => false, - 'MESSAGE' => (string)$this->L10N->t ('Download started'), - 'GID' => $AddURI['result'], - 'PROGRESSVAL' => round((($Progress) * 100), 2) . '%', - 'PROGRESS' => is_null ($ProgressString) ? (string)$this->L10N->t ('N/A') : $ProgressString, - 'STATUS' => isset ($Status['result']['status']) ? (string)$this->L10N->t (ucfirst ($Status['result']['status'])) : (string)$this->L10N->t ('N/A'), - 'STATUSID' => Tools::GetDownloadStatusID ($Status['result']['status']), - 'SPEED' => isset ($Status['result']['downloadSpeed']) ? Tools::FormatSizeUnits ($Status['result']['downloadSpeed']) . '/s' : (string)$this->L10N->t ('N/A'), - 'FILENAME' => (mb_strlen ($Target, "UTF-8") > 40 ? mb_substr ($Target, 0, 40, "UTF-8") . '...' : $Target), - 'PROTO' => strtoupper(substr($_POST['FILE'], 0, strpos($_POST['FILE'], ':'))), - 'ISTORRENT' => false - )); - } - else - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ($this->WhichDownloader == 0 ? 'Returned GID is null ! Is Aria2c running as a daemon ?' : 'An error occurred while running the CURL download'))); - } - } - catch (Exception $E) - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => $E->getMessage ())); - } - } - else - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ('Please check the URL you\'ve just provided'))); + } + if (!$this->ProxyOnlyWithYTDL && !is_null($this->ProxyAddress) + && $this->ProxyPort > 0 && $this->ProxyPort <= 65536) { + $OPTIONS['all-proxy'] = rtrim($this->ProxyAddress, '/') . ':' . $this->ProxyPort; + if (!is_null($this->ProxyUser) && !is_null($this->ProxyPasswd)) { + $OPTIONS['all-proxy-user'] = $this->ProxyUser; + $OPTIONS['all-proxy-passwd'] = $this->ProxyPasswd; + } + } + if (!is_null($this->MaxDownloadSpeed) && $this->MaxDownloadSpeed > 0) { + $OPTIONS['max-download-limit'] = $this->MaxDownloadSpeed . 'K'; + } + + $AddURI =( + $this->WhichDownloader == 0 + ?Aria2::addUri(array($_POST['FILE']), array('Params' => $OPTIONS)) + : CURL::addUri($_POST['FILE'], $OPTIONS) + ); + + if (isset($AddURI['result']) && !is_null($AddURI['result'])) { + $SQL = 'INSERT INTO `*PREFIX*ocdownloader_queue` + (`UID`, `GID`, `FILENAME`, `PROTOCOL`, `STATUS`, `TIMESTAMP`) VALUES(?, ?, ?, ?, ?, ?)'; + if ($this->DbType == 1) { + $SQL = 'INSERT INTO *PREFIX*ocdownloader_queue + ("UID", "GID", "FILENAME", "PROTOCOL", "STATUS", "TIMESTAMP") VALUES(?, ?, ?, ?, ?, ?)'; + } + + $Query = \OCP\DB::prepare($SQL); + $Result = $Query->execute(array( + $this->CurrentUID, + $AddURI['result'], + $Target, + strtoupper(substr($_POST['FILE'], 0, strpos($_POST['FILE'], ':'))), + 1, + time() + )); + + sleep(1); + $Status =( + $this->WhichDownloader == 0 + ?Aria2::tellStatus($AddURI['result']) + :CURL::tellStatus($AddURI['result']) + ); + + $Progress = 0; + if ($Status['result']['totalLength'] > 0) { + $Progress = $Status['result']['completedLength'] / $Status['result']['totalLength']; + } + + $ProgressString = Tools::getProgressString( + $Status['result']['completedLength'], + $Status['result']['totalLength'], + $Progress + ); + + return new JSONResponse(array( + 'ERROR' => false, + 'MESSAGE' =>(string)$this->L10N->t('Download started'), + 'GID' => $AddURI['result'], + 'PROGRESSVAL' => round((($Progress) * 100), 2) . '%', + 'PROGRESS' => is_null($ProgressString) ?(string)$this->L10N->t('N/A') : $ProgressString, + 'STATUS' => isset($Status['result']['status']) + ?(string)$this->L10N->t(ucfirst($Status['result']['status'])) + :(string)$this->L10N->t('N/A'), + 'STATUSID' => Tools::getDownloadStatusID($Status['result']['status']), + 'SPEED' => isset($Status['result']['downloadSpeed']) + ?Tools::formatSizeUnits($Status['result']['downloadSpeed']).'/s' + :(string)$this->L10N->t('N/A'), + 'FILENAME' => $Target, + 'FILENAME_SHORT' => Tools::getShortFilename($Target), + 'PROTO' => strtoupper(substr($_POST['FILE'], 0, strpos($_POST['FILE'], ':'))), + 'ISTORRENT' => false + )); + } else { + return new JSONResponse( + array( + 'ERROR' => true, + 'MESSAGE' =>(string)$this->L10N->t( + $this->WhichDownloader == 0 + ?'Returned GID is null ! Is Aria2c running as a daemon ?' + : 'An error occurred while running the CURL download' + ) + ) + ); + } + } catch (Exception $E) { + return new JSONResponse(array('ERROR' => true, 'MESSAGE' => $E->getMessage())); } - } + } else { + return new JSONResponse( + array('ERROR' => true, 'MESSAGE' =>(string)$this->L10N->t('Please check the URL you\'ve just provided')) + ); + } + } } diff --git a/controller/index.php b/controller/index.php index b101fc1..362f166 100644 --- a/controller/index.php +++ b/controller/index.php @@ -22,188 +22,190 @@ class Index extends Controller { - private $DbType = 0; - private $CurrentUID = null; - private $CanCheckForUpdate = false; - private $Settings = null; - private $WhichDownloader = null; - private $L10N = null; - private $AllowProtocolHTTP = null; - private $AllowProtocolFTP = null; - private $AllowProtocolYT = null; - private $AllowProtocolBT = null; - private $DownloadsFolder = null; - - public function __construct ($AppName, IRequest $Request, $CurrentUID, IL10N $L10N) - { - parent::__construct ($AppName, $Request); - $this->CurrentUID = $CurrentUID; - $this->L10N = $L10N; - - if (strcmp (Config::getSystemValue ('dbtype'), 'pgsql') == 0) - { - $this->DbType = 1; - } - - $this->CanCheckForUpdate = Tools::CanCheckForUpdate (); - - $this->Settings = new Settings (); - $this->Settings->SetKey ('WhichDownloader'); - $this->WhichDownloader = $this->Settings->GetValue (); - $this->WhichDownloader = is_null ($this->WhichDownloader) ? 'ARIA2' : $this->WhichDownloader; - - $this->Settings->SetKey ('AllowProtocolHTTP'); - $this->AllowProtocolHTTP = $this->Settings->GetValue (); - $this->AllowProtocolHTTP = is_null ($this->AllowProtocolHTTP) || \OC_User::isAdminUser ($this->CurrentUID) ? true : strcmp ($this->AllowProtocolHTTP, 'Y') == 0; - $this->Settings->SetKey ('AllowProtocolFTP'); - $this->AllowProtocolFTP = $this->Settings->GetValue (); - $this->AllowProtocolFTP = is_null ($this->AllowProtocolFTP) || \OC_User::isAdminUser ($this->CurrentUID) ? true : strcmp ($this->AllowProtocolFTP, 'Y') == 0; - $this->Settings->SetKey ('AllowProtocolYT'); - $this->AllowProtocolYT = $this->Settings->GetValue (); - $this->AllowProtocolYT = is_null ($this->AllowProtocolYT) || \OC_User::isAdminUser ($this->CurrentUID) ? true : strcmp ($this->AllowProtocolYT, 'Y') == 0; - $this->Settings->SetKey ('AllowProtocolBT'); - $this->AllowProtocolBT = $this->Settings->GetValue (); - $this->AllowProtocolBT = is_null ($this->AllowProtocolBT) || \OC_User::isAdminUser ($this->CurrentUID) ? true : strcmp ($this->AllowProtocolBT, 'Y') == 0; - - $this->Settings->SetTable ('personal'); - $this->Settings->SetUID ($this->CurrentUID); - - $this->Settings->SetKey ('DownloadsFolder'); - $this->DownloadsFolder = $this->Settings->GetValue (); - $this->DownloadsFolder = '/' . (is_null ($this->DownloadsFolder) ? 'Downloads' : $this->DownloadsFolder); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function Add () - { - $this->Settings->SetTable ('personal'); - $this->Settings->SetUID ($this->CurrentUID); - $this->Settings->SetKey ('TorrentsFolder'); - $TorrentsFolder = $this->Settings->GetValue (); - - return new TemplateResponse ('ocdownloader', 'add', [ - 'PAGE' => 0, - 'TTSFOLD' => $TorrentsFolder, - 'CANCHECKFORUPDATE' => $this->CanCheckForUpdate, - 'WD' => $this->WhichDownloader, - 'AllowProtocolHTTP' => $this->AllowProtocolHTTP, - 'AllowProtocolFTP' => $this->AllowProtocolFTP, - 'AllowProtocolYT' => $this->AllowProtocolYT, - 'AllowProtocolBT' => $this->AllowProtocolBT - ]); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function All () - { - self::syncDownloadsFolder(); - return new TemplateResponse ('ocdownloader', 'all', [ - 'PAGE' => 1, - 'CANCHECKFORUPDATE' => $this->CanCheckForUpdate, - 'WD' => $this->WhichDownloader - ]); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function Completes () - { - self::syncDownloadsFolder(); - return new TemplateResponse ('ocdownloader', 'completes', [ - 'PAGE' => 2, - 'CANCHECKFORUPDATE' => $this->CanCheckForUpdate, - 'WD' => $this->WhichDownloader - ]); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function Actives () - { - self::syncDownloadsFolder(); - return new TemplateResponse('ocdownloader', 'actives', [ - 'PAGE' => 3, - 'CANCHECKFORUPDATE' => $this->CanCheckForUpdate, - 'WD' => $this->WhichDownloader - ]); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function Waitings () - { - self::syncDownloadsFolder(); - if (strcmp ($this->WhichDownloader, 'ARIA2') != 0) - { - //return $this->L10N->t ('You are using %s ! This page is only available with the following engines : ', $this->WhichDownloader) . 'ARIA2'; - } - return new TemplateResponse('ocdownloader', 'waitings', [ - 'PAGE' => 4, - 'CANCHECKFORUPDATE' => $this->CanCheckForUpdate, - 'WD' => $this->WhichDownloader - ]); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function Stopped () - { - self::syncDownloadsFolder(); - if (strcmp ($this->WhichDownloader, 'ARIA2') != 0) - { - //return $this->L10N->t ('You are using %s ! This page is only available with the following engines : ', $this->WhichDownloader) . 'ARIA2'; - } - return new TemplateResponse('ocdownloader', 'stopped', [ - 'PAGE' => 5, - 'CANCHECKFORUPDATE' => $this->CanCheckForUpdate, - 'WD' => $this->WhichDownloader - ]); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function Removed () - { - self::syncDownloadsFolder(); - return new TemplateResponse('ocdownloader', 'removed', [ - 'PAGE' => 6, - 'CANCHECKFORUPDATE' => $this->CanCheckForUpdate, - 'WD' => $this->WhichDownloader - ]); - } - - /** - * Testfunction by Nibbels - * Fix for https://github.com/DjazzLab/ocdownloader/issues/44 - */ - protected function syncDownloadsFolder () { - $user = $this->CurrentUID; //or normally \OC::$server->getUserSession()->getUser()->getUID(); - $scanner = new \OC\Files\Utils\Scanner( $user , \OC::$server->getDatabaseConnection(), \OC::$server->getLogger() ); - $path = '/'.$user.'/files/'.ltrim($this->DownloadsFolder,'/\\'); - try { - $scanner->scan($path); - } catch (ForbiddenException $e) { - //$arr['forbidden'] = 1; - //"Home storage for user $user not writable" "Make sure you're running the scan command only as the user the web server runs as" - } catch (\Exception $e) { - //$arr['exception'] = 1; - //'Exception during scan: ' . $e->getMessage() . "\n" . $e->getTraceAsString() . ''); - } - } -} \ No newline at end of file + private $DbType = 0; + private $CurrentUID = null; + private $CanCheckForUpdate = false; + private $Settings = null; + private $WhichDownloader = null; + private $L10N = null; + private $AllowProtocolHTTP = null; + private $AllowProtocolFTP = null; + private $AllowProtocolYT = null; + private $AllowProtocolBT = null; + private $DownloadsFolder = null; + + public function __construct($AppName, IRequest $Request, $CurrentUID, IL10N $L10N) + { + parent::__construct($AppName, $Request); + $this->CurrentUID = $CurrentUID; + $this->L10N = $L10N; + + if (strcmp(Config::getSystemValue('dbtype'), 'pgsql') == 0) { + $this->DbType = 1; + } + + $this->CanCheckForUpdate = Tools::canCheckForUpdate(); + + $this->Settings = new Settings(); + $this->Settings->setKey('WhichDownloader'); + $this->WhichDownloader = $this->Settings->getValue(); + $this->WhichDownloader = is_null($this->WhichDownloader) ? 'ARIA2' : $this->WhichDownloader; + + $this->Settings->setKey('AllowProtocolHTTP'); + $this->AllowProtocolHTTP = $this->Settings->getValue(); + $this->AllowProtocolHTTP = is_null($this->AllowProtocolHTTP) || \OC_User::isAdminUser($this->CurrentUID) + ? true : strcmp($this->AllowProtocolHTTP, 'Y') == 0; + $this->Settings->setKey('AllowProtocolFTP'); + $this->AllowProtocolFTP = $this->Settings->getValue(); + $this->AllowProtocolFTP = is_null($this->AllowProtocolFTP) || \OC_User::isAdminUser($this->CurrentUID) + ? true : strcmp($this->AllowProtocolFTP, 'Y') == 0; + $this->Settings->setKey('AllowProtocolYT'); + $this->AllowProtocolYT = $this->Settings->getValue(); + $this->AllowProtocolYT = is_null($this->AllowProtocolYT) || \OC_User::isAdminUser($this->CurrentUID) + ? true : strcmp($this->AllowProtocolYT, 'Y') == 0; + $this->Settings->setKey('AllowProtocolBT'); + $this->AllowProtocolBT = $this->Settings->getValue(); + $this->AllowProtocolBT = is_null($this->AllowProtocolBT) || \OC_User::isAdminUser($this->CurrentUID) + ? true : strcmp($this->AllowProtocolBT, 'Y') == 0; + + $this->Settings->setTable('personal'); + $this->Settings->setUID($this->CurrentUID); + + $this->Settings->setKey('DownloadsFolder'); + $this->DownloadsFolder = $this->Settings->getValue(); + $this->DownloadsFolder = '/' .(is_null($this->DownloadsFolder) ? 'Downloads' : $this->DownloadsFolder); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function add() + { + $this->Settings->setTable('personal'); + $this->Settings->setUID($this->CurrentUID); + $this->Settings->setKey('TorrentsFolder'); + $TorrentsFolder = $this->Settings->getValue(); + + return new TemplateResponse('ocdownloader', 'add', [ + 'PAGE' => 0, + 'TTSFOLD' => $TorrentsFolder, + 'CANCHECKFORUPDATE' => $this->CanCheckForUpdate, + 'WD' => $this->WhichDownloader, + 'AllowProtocolHTTP' => $this->AllowProtocolHTTP, + 'AllowProtocolFTP' => $this->AllowProtocolFTP, + 'AllowProtocolYT' => $this->AllowProtocolYT, + 'AllowProtocolBT' => $this->AllowProtocolBT + ]); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function all() + { + self::syncDownloadsFolder(); + return new TemplateResponse('ocdownloader', 'all', [ + 'PAGE' => 1, + 'CANCHECKFORUPDATE' => $this->CanCheckForUpdate, + 'WD' => $this->WhichDownloader + ]); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function completes() + { + self::syncDownloadsFolder(); + return new TemplateResponse('ocdownloader', 'completes', [ + 'PAGE' => 2, + 'CANCHECKFORUPDATE' => $this->CanCheckForUpdate, + 'WD' => $this->WhichDownloader + ]); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function actives() + { + self::syncDownloadsFolder(); + return new TemplateResponse('ocdownloader', 'actives', [ + 'PAGE' => 3, + 'CANCHECKFORUPDATE' => $this->CanCheckForUpdate, + 'WD' => $this->WhichDownloader + ]); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function waitings() + { + self::syncDownloadsFolder(); + if (strcmp($this->WhichDownloader, 'ARIA2') != 0) { + //return $this->L10N->t('You are using %s ! This page is only available with the following engines : ', $this->WhichDownloader) . 'ARIA2'; + } + return new TemplateResponse('ocdownloader', 'waitings', [ + 'PAGE' => 4, + 'CANCHECKFORUPDATE' => $this->CanCheckForUpdate, + 'WD' => $this->WhichDownloader + ]); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function stopped() + { + self::syncDownloadsFolder(); + if (strcmp($this->WhichDownloader, 'ARIA2') != 0) { + //return $this->L10N->t('You are using %s ! This page is only available with the following engines : ', $this->WhichDownloader) . 'ARIA2'; + } + return new TemplateResponse('ocdownloader', 'stopped', [ + 'PAGE' => 5, + 'CANCHECKFORUPDATE' => $this->CanCheckForUpdate, + 'WD' => $this->WhichDownloader + ]); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function removed() + { + self::syncDownloadsFolder(); + return new TemplateResponse('ocdownloader', 'removed', [ + 'PAGE' => 6, + 'CANCHECKFORUPDATE' => $this->CanCheckForUpdate, + 'WD' => $this->WhichDownloader + ]); + } + + /** + * Testfunction by Nibbels + * Fix for https://github.com/DjazzLab/ocdownloader/issues/44 + */ + protected function syncDownloadsFolder() + { + $user = $this->CurrentUID; //or normally \OC::$server->getUserSession()->getUser()->getUID(); + $scanner = new \OC\Files\Utils\Scanner($user, \OC::$server->getDatabaseConnection(), \OC::$server->getLogger()); + $path = '/'.$user.'/files/'.ltrim($this->DownloadsFolder, '/\\'); + try { + $scanner->scan($path); + } catch (ForbiddenException $e) { + //$arr['forbidden'] = 1; + //"Home storage for user $user not writable" "Make sure you're running the scan command only as the user the web server runs as" + } catch (\Exception $e) { + //$arr['exception'] = 1; + //'Exception during scan: ' . $e->getMessage() . "\n" . $e->getTraceAsString() . ''); + } + } +} diff --git a/controller/lib/api.php b/controller/lib/api.php index dfa56c2..2a8f616 100644 --- a/controller/lib/api.php +++ b/controller/lib/api.php @@ -20,320 +20,329 @@ class API { - private static $AbsoluteDownloadsFolder = null; - private static $DownloadsFolder = null; - private static $DbType = 0; - private static $YTDLBinary = null; - private static $ProxyAddress = null; - private static $ProxyPort = 0; - private static $ProxyUser = null; - private static $ProxyPasswd = null; - private static $WhichDownloader = 0; - private static $CurrentUID = null; - private static $L10N = null; - private static $AllowProtocolHTTP = null; - private static $AllowProtocolFTP = null; - private static $AllowProtocolYT = null; - private static $AllowProtocolBT = null; - private static $MaxDownloadSpeed = null; - - public static function Add ($URL) - { - try - { - self::Load (); + private static $AbsoluteDownloadsFolder = null; + private static $DownloadsFolder = null; + private static $DbType = 0; + private static $YTDLBinary = null; + private static $ProxyAddress = null; + private static $ProxyPort = 0; + private static $ProxyUser = null; + private static $ProxyPasswd = null; + private static $WhichDownloader = 0; + private static $CurrentUID = null; + private static $L10N = null; + private static $AllowProtocolHTTP = null; + private static $AllowProtocolFTP = null; + private static $AllowProtocolYT = null; + private static $AllowProtocolBT = null; + private static $MaxDownloadSpeed = null; + + public static function add($URL) + { + try { + self::load(); + + $URL = urldecode($URL); + if (Tools::checkURL($URL)) { + if (preg_match('/^https{0,1}:\/\/www\.youtube\.com\/watch\?v=.*$/', $URL) == 1) { + if (!self::$AllowProtocolYT && !\OC_User::isAdminUser(self::$CurrentUID)) { + return array('ERROR' => true, 'MESSAGE' => 'Notallowedtouseprotocolyt'); + } + + $YouTube = new YouTube(self::$YTDLBinary, $URL); - $URL = urldecode ($URL); - if (Tools::CheckURL ($URL)) - { - if (preg_match ('/^https{0,1}:\/\/www\.youtube\.com\/watch\?v=.*$/', $URL) == 1) - { - if (!self::$AllowProtocolYT && !\OC_User::isAdminUser (self::$CurrentUID)) - { - return Array ('ERROR' => true, 'MESSAGE' => 'Notallowedtouseprotocolyt'); - } - - $YouTube = new YouTube (self::$YTDLBinary, $URL); - - if (!is_null (self::$ProxyAddress) && self::$ProxyPort > 0 && self::$ProxyPort <= 65536) - { - $YouTube->SetProxy (self::$ProxyAddress, self::$ProxyPort); - } - - $VideoData = $YouTube->GetVideoData (); - if (!isset ($VideoData['VIDEO']) || !isset ($VideoData['FULLNAME'])) - { - return Array ('ERROR' => true, 'MESSAGE' => 'UnabletoretrievetrueYouTubevideoURL'); - } - $DL = Array ( - 'URL' => $VideoData['VIDEO'], - 'FILENAME' => Tools::CleanString ($VideoData['FULLNAME']), - 'PROTO' => 'Video' - ); - } - else - { - if (!self::$AllowProtocolHTTP && !\OC_User::isAdminUser (self::$CurrentUID) && Tools::StartsWith (strtolower ($URL), 'http')) - { - return Array ('ERROR' => true, 'MESSAGE' => 'Notallowedtouseprotocolhttp'); - } - elseif (!self::$AllowProtocolFTP && !\OC_User::isAdminUser (self::$CurrentUID) && Tools::StartsWith (strtolower ($URL), 'ftp')) - { - return Array ('ERROR' => true, 'MESSAGE' => 'Notallowedtouseprotocolftp'); - } - - $DL = Array ( - 'URL' => $URL, - 'FILENAME' => Tools::CleanString (substr($URL, strrpos($URL, '/') + 1)), - 'PROTO' => strtoupper (substr ($URL, 0, strpos ($URL, ':'))) - ); - } - - - $OPTIONS = Array ('dir' => self::$AbsoluteDownloadsFolder, 'out' => $DL['FILENAME'], 'follow-torrent' => false); - if (!is_null (self::$ProxyAddress) && self::$ProxyPort > 0 && self::$ProxyPort <= 65536) - { - $OPTIONS['all-proxy'] = rtrim (self::$ProxyAddress, '/') . ':' . self::$ProxyPort; - if (!is_null (self::$ProxyUser) && !is_null (self::$ProxyPasswd)) - { - $OPTIONS['all-proxy-user'] = self::$ProxyUser; - $OPTIONS['all-proxy-passwd'] = self::$ProxyPasswd; - } - } - - $AddURI = (self::$WhichDownloader == 0 ? Aria2::AddUri (Array ($DL['URL']), Array ('Params' => $OPTIONS)) : CURL::AddUri ($DL['URL'], $OPTIONS)); - - if (isset ($AddURI['result']) && !is_null ($AddURI['result'])) - { - $SQL = 'INSERT INTO `*PREFIX*ocdownloader_queue` (`UID`, `GID`, `FILENAME`, `PROTOCOL`, `IS_CLEANED`, `STATUS`, `TIMESTAMP`) VALUES (?, ?, ?, ?, ?, ?, ?)'; - if (self::$DbType == 1) - { - $SQL = 'INSERT INTO *PREFIX*ocdownloader_queue ("UID", "GID", "FILENAME", "PROTOCOL", "IS_CLEANED", "STATUS", "TIMESTAMP") VALUES (?, ?, ?, ?, ?, ?, ?)'; - } - - $Query = \OCP\DB::prepare ($SQL); - $Result = $Query->execute (Array ( - self::$CurrentUID, - $AddURI['result'], - $DL['FILENAME'], - (strcmp ($DL['PROTO'], 'Video') == 0 ? 'YT ' . (string)self::$L10N->t ('Video') : $DL['PROTO']), - 1, 1, - time() - )); - - return Array ('ERROR' => false, 'FILENAME' => $DL['FILENAME']); - } - else - { - return Array ('ERROR' => true, 'MESSAGE' => 'ReturnedGIDisnullIsAria2crunningasadaemon'); - } - } - else - { - return Array ('ERROR' => true, 'MESSAGE' => 'InvalidURL'); - } + if (!is_null(self::$ProxyAddress) && self::$ProxyPort > 0 && self::$ProxyPort <= 65536) { + $YouTube->setProxy(self::$ProxyAddress, self::$ProxyPort); + } + + $VideoData = $YouTube->getVideoData(); + if (!isset($VideoData['VIDEO']) || !isset($VideoData['FULLNAME'])) { + return array('ERROR' => true, 'MESSAGE' => 'UnabletoretrievetrueYouTubevideoURL'); + } + $DL = array( + 'URL' => $VideoData['VIDEO'], + 'FILENAME' => Tools::cleanString($VideoData['FULLNAME']), + 'PROTO' => 'Video' + ); + } else { + if (!self::$AllowProtocolHTTP && !\OC_User::isAdminUser(self::$CurrentUID) + && Tools::startsWith(strtolower($URL), 'http')) { + return array('ERROR' => true, 'MESSAGE' => 'Notallowedtouseprotocolhttp'); + } elseif (!self::$AllowProtocolFTP && !\OC_User::isAdminUser(self::$CurrentUID) + && Tools::startsWith(strtolower($URL), 'ftp')) { + return array('ERROR' => true, 'MESSAGE' => 'Notallowedtouseprotocolftp'); + } + + $DL = array( + 'URL' => $URL, + 'FILENAME' => Tools::cleanString(substr($URL, strrpos($URL, '/') + 1)), + 'PROTO' => strtoupper(substr($URL, 0, strpos($URL, ':'))) + ); + } + + + $OPTIONS = array( + 'dir' => self::$AbsoluteDownloadsFolder, + 'out' => $DL['FILENAME'], + 'follow-torrent' => false + ); + if (!is_null(self::$ProxyAddress) && self::$ProxyPort > 0 && self::$ProxyPort <= 65536) { + $OPTIONS['all-proxy'] = rtrim(self::$ProxyAddress, '/') . ':' . self::$ProxyPort; + if (!is_null(self::$ProxyUser) && !is_null(self::$ProxyPasswd)) { + $OPTIONS['all-proxy-user'] = self::$ProxyUser; + $OPTIONS['all-proxy-passwd'] = self::$ProxyPasswd; + } + } + + $AddURI =( + self::$WhichDownloader == 0 + ?Aria2::addUri(array($DL['URL']), array('Params' => $OPTIONS)) + :CURL::addUri($DL['URL'], $OPTIONS) + ); + + if (isset($AddURI['result']) && !is_null($AddURI['result'])) { + $SQL = 'INSERT INTO `*PREFIX*ocdownloader_queue` + (`UID`, `GID`, `FILENAME`, `PROTOCOL`, `IS_CLEANED`, `STATUS`, `TIMESTAMP`) + VALUES(?, ?, ?, ?, ?, ?, ?)'; + if (self::$DbType == 1) { + $SQL = 'INSERT INTO *PREFIX*ocdownloader_queue + ("UID", "GID", "FILENAME", "PROTOCOL", "IS_CLEANED", "STATUS", "TIMESTAMP") + VALUES(?, ?, ?, ?, ?, ?, ?)'; + } + + $Query = \OCP\DB::prepare($SQL); + $Result = $Query->execute(array( + self::$CurrentUID, + $AddURI['result'], + $DL['FILENAME'], + (strcmp($DL['PROTO'], 'Video') == 0?'YT ' .(string)self::$L10N->t('Video'):$DL['PROTO']), + 1, 1, + time() + )); + + return array('ERROR' => false, 'FILENAME' => $DL['FILENAME']); + } else { + return array('ERROR' => true, 'MESSAGE' => 'ReturnedGIDisnullIsAria2crunningasadaemon'); + } + } else { + return array('ERROR' => true, 'MESSAGE' => 'InvalidURL'); } - catch (Exception $E) - { - return Array ('ERROR' => true, 'MESSAGE' => 'Unabletolaunchthedownload'); + } catch (Exception $E) { + return array('ERROR' => true, 'MESSAGE' => 'Unabletolaunchthedownload'); + } + } + + public static function checkAddonVersion($Version) + { + $AppVersion = Config::getAppValue('ocdownloader', 'installed_version'); + return array('RESULT' => version_compare($Version, $AppVersion, '<=')); + } + + public static function getQueue() + { + self::load(); + + try { + $Params = array(self::$CurrentUID); + $StatusReq = '(?, ?, ?, ?, ?)'; + $Params[] = 0; + $Params[] = 1; + $Params[] = 2; + $Params[] = 3; + $Params[] = 4; + $IsCleanedReq = '(?, ?)'; + $Params[] = 0; + $Params[] = 1; + + $SQL = 'SELECT * FROM `*PREFIX*ocdownloader_queue` + WHERE `UID` = ? AND `STATUS` IN '.$StatusReq.' AND `IS_CLEANED` IN '.$IsCleanedReq + .' ORDER BY `TIMESTAMP` ASC'; + if (self::$DbType == 1) { + $SQL = 'SELECT * FROM *PREFIX*ocdownloader_queue + WHERE "UID" = ? AND "STATUS" IN '.$StatusReq.' AND "IS_CLEANED" IN '.$IsCleanedReq + .' ORDER BY "TIMESTAMP" ASC'; } - } - - public static function CheckAddonVersion ($Version) - { - $AppVersion = Config::getAppValue ('ocdownloader', 'installed_version'); - return Array ('RESULT' => version_compare ($Version, $AppVersion, '<=')); - } - - public static function GetQueue () - { - self::Load (); + $Query = \OCP\DB::prepare($SQL); + $Request = $Query->execute($Params); + + $Queue = []; - try - { - $Params = Array (self::$CurrentUID); - $StatusReq = '(?, ?, ?, ?, ?)'; - $Params[] = 0; $Params[] = 1; $Params[] = 2; $Params[] = 3; $Params[] = 4; - $IsCleanedReq = '(?, ?)'; - $Params[] = 0; $Params[] = 1; + while ($Row = $Request->fetchRow()) { + $Status =(self::$WhichDownloader == 0?Aria2::tellStatus($Row['GID']):CURL::tellStatus($Row['GID'])); + $DLStatus = 5; // Error + + if (!is_null($Status)) { + if (!isset($Status['error'])) { + $Progress = 0; + if ($Status['result']['totalLength'] > 0) { + $Progress = $Status['result']['completedLength'] / $Status['result']['totalLength']; + } - $SQL = 'SELECT * FROM `*PREFIX*ocdownloader_queue` WHERE `UID` = ? AND `STATUS` IN ' . $StatusReq . ' AND `IS_CLEANED` IN ' . $IsCleanedReq . ' ORDER BY `TIMESTAMP` ASC'; - if (self::$DbType == 1) - { - $SQL = 'SELECT * FROM *PREFIX*ocdownloader_queue WHERE "UID" = ? AND "STATUS" IN ' . $StatusReq . ' AND "IS_CLEANED" IN ' . $IsCleanedReq . ' ORDER BY "TIMESTAMP" ASC'; - } - $Query = \OCP\DB::prepare ($SQL); - $Request = $Query->execute ($Params); - - $Queue = []; - - while ($Row = $Request->fetchRow ()) - { - $Status = (self::$WhichDownloader == 0 ? Aria2::TellStatus ($Row['GID']) : CURL::TellStatus ($Row['GID'])); - $DLStatus = 5; // Error + $DLStatus = Tools::getDownloadStatusID($Status['result']['status']); + $ProgressString = Tools::getProgressString( + $Status['result']['completedLength'], + $Status['result']['totalLength'], + $Progress + ); - if (!is_null ($Status)) - { - if (!isset ($Status['error'])) - { - $Progress = 0; - if ($Status['result']['totalLength'] > 0) - { - $Progress = $Status['result']['completedLength'] / $Status['result']['totalLength']; - } - - $DLStatus = Tools::GetDownloadStatusID ($Status['result']['status']); - $ProgressString = Tools::GetProgressString ($Status['result']['completedLength'], $Status['result']['totalLength'], $Progress); - - $Queue[] = Array ( - 'GID' => $Row['GID'], - 'PROGRESSVAL' => round((($Progress) * 100), 2), - 'PROGRESS' => Array ( - 'Message' => null, - 'ProgressString' => is_null ($ProgressString) ? 'N_A' : $ProgressString, - 'NumSeeders' => isset ($Status['result']['bittorrent']) && $Progress < 1 ? $Status['result']['numSeeders'] : null, - 'UploadLength' => isset ($Status['result']['bittorrent']) && $Progress == 1 ? Tools::FormatSizeUnits ($Status['result']['uploadLength']) : null, - 'Ratio' => isset ($Status['result']['bittorrent']) ? round (($Status['result']['uploadLength'] / $Status['result']['completedLength']), 2) : null - ), - 'STATUS' => Array ( - 'Value' => isset ($Status['result']['status']) ? ($Row['STATUS'] == 4 ? 'Removed' : ucfirst ($Status['result']['status'])) : 'N_A', - 'Seeding' => isset ($Status['result']['bittorrent']) && $Progress == 1 && $DLStatus != 3 ? true : false - ), - 'STATUSID' => $Row['STATUS'] == 4 ? 4 : $DLStatus, - 'SPEED' => isset ($Status['result']['downloadSpeed']) ? ($Progress == 1 ? (isset ($Status['result']['bittorrent']) ? ($Status['result']['uploadSpeed'] == 0 ? '--' : Tools::FormatSizeUnits ($Status['result']['uploadSpeed']) . '/s') : '--') : ($DLStatus == 4 ? '--' : Tools::FormatSizeUnits ($Status['result']['downloadSpeed']) . '/s')) : 'N_A', - 'FILENAME' => $Row['FILENAME'], - 'PROTO' => $Row['PROTOCOL'], - 'ISTORRENT' => isset ($Status['result']['bittorrent']), - ); - - if ($Row['STATUS'] != $DLStatus) - { - $SQL = 'UPDATE `*PREFIX*ocdownloader_queue` SET `STATUS` = ? WHERE `UID` = ? AND `GID` = ? AND `STATUS` != ?'; - if (self::$DbType == 1) - { - $SQL = 'UPDATE *PREFIX*ocdownloader_queue SET "STATUS" = ? WHERE "UID" = ? AND "GID" = ? AND "STATUS" != ?'; - } - - $Query = \OCP\DB::prepare ($SQL); - $Result = $Query->execute (Array ( - $DLStatus, - self::$CurrentUID, - $Row['GID'], - 4 - )); - } - } - else - { - $Queue[] = Array ( - 'GID' => $Row['GID'], - 'PROGRESSVAL' => 0, - 'PROGRESS' => Array ( - 'Message' => 'ErrorGIDnotfound', - 'ProgressString' => null, - 'NumSeeders' => null, - 'UploadLength' => null, - 'Ratio' => null - ), - 'STATUS' => Array( - 'Value' => 'N_A', - 'Seeding' => null - ), - 'STATUSID' => $DLStatus, - 'SPEED' => 'N_A', - 'FILENAME' => $Row['FILENAME'], - 'PROTO' => $Row['PROTOCOL'], - 'ISTORRENT' => isset ($Status['result']['bittorrent']) - ); - } - } - else - { - $Queue[] = Array ( - 'GID' => $Row['GID'], - 'PROGRESSVAL' => 0, - 'PROGRESS' => Array ( - 'Message' => self::$WhichDownloader == 0 ? 'ReturnedstatusisnullIsAria2crunningasadaemon' : 'Unabletofinddownloadstatusfile', - 'ProgressString' => null, - 'NumSeeders' => null, - 'UploadLength' => null, - 'Ratio' => null - ), - 'STATUS' => Array( - 'Value' => 'N_A', - 'Seeding' => null - ), - 'STATUSID' => $DLStatus, - 'SPEED' => 'N_A', - 'FILENAME' => $Row['FILENAME'], - 'PROTO' => $Row['PROTOCOL'], - 'ISTORRENT' => isset ($Status['result']['bittorrent']) - ); + $Queue[] = array( + 'GID' => $Row['GID'], + 'PROGRESSVAL' => round((($Progress) * 100), 2), + 'PROGRESS' => array( + 'Message' => null, + 'ProgressString' => is_null($ProgressString)?'N_A':$ProgressString, + 'NumSeeders' => isset($Status['result']['bittorrent']) && $Progress < 1?$Status['result']['numSeeders']:null, + 'UploadLength' => isset($Status['result']['bittorrent']) && $Progress == 1?Tools::formatSizeUnits($Status['result']['uploadLength']):null, + 'Ratio' => isset($Status['result']['bittorrent'])?round(($Status['result']['uploadLength'] / $Status['result']['completedLength']), 2):null + ), + 'STATUS' => array( + 'Value' => isset($Status['result']['status']) ?($Row['STATUS'] == 4?'Removed':ucfirst($Status['result']['status'])):'N_A', + 'Seeding' => isset($Status['result']['bittorrent']) && $Progress == 1 && $DLStatus != 3?true:false + ), + 'STATUSID' => $Row['STATUS'] == 4?4:$DLStatus, + 'SPEED' => isset($Status['result']['downloadSpeed']) + ?($Progress == 1 + ?(isset($Status['result']['bittorrent']) + ?($Status['result']['uploadSpeed'] == 0 + ?'--' + :Tools::formatSizeUnits($Status['result']['uploadSpeed']).'/s') + :'--') + :($DLStatus == 4 + ?'--' + :Tools::formatSizeUnits($Status['result']['downloadSpeed']).'/s')) + :'N_A', + 'FILENAME' => $Row['FILENAME'], + 'PROTO' => $Row['PROTOCOL'], + 'ISTORRENT' => isset($Status['result']['bittorrent']), + ); + + if ($Row['STATUS'] != $DLStatus) { + $SQL = 'UPDATE `*PREFIX*ocdownloader_queue` + SET `STATUS` = ? WHERE `UID` = ? AND `GID` = ? AND `STATUS` != ?'; + if (self::$DbType == 1) { + $SQL = 'UPDATE *PREFIX*ocdownloader_queue + SET "STATUS" = ? WHERE "UID" = ? AND "GID" = ? AND "STATUS" != ?'; + } + + $Query = \OCP\DB::prepare($SQL); + $Result = $Query->execute(array( + $DLStatus, + self::$CurrentUID, + $Row['GID'], + 4 + )); } - } - return Array ('ERROR' => false, 'MESSAGE' => null, 'QUEUE' => $Queue, 'COUNTER' => Tools::GetCounters (self::$DbType, self::$CurrentUID)); - } - catch (Exception $E) - { - return Array ('ERROR' => true, 'MESSAGE' => $E->getMessage (), 'QUEUE' => null, 'COUNTER' => null); - } - } - - /********** PRIVATE STATIC METHODS **********/ - private static function Load () - { - if (strcmp (Config::getSystemValue ('dbtype'), 'pgsql') == 0) - { - self::$DbType = 1; - } - - self::$CurrentUID = \OC::$server->getUserSession ()->getUser (); - self::$CurrentUID = (self::$CurrentUID) ? self::$CurrentUID->getUID () : ''; - - self::$L10N = \OC::$server->getL10N ('ocdownloader'); - - $Settings = new Settings (); - - $Settings->SetKey ('ProxyAddress'); - self::$ProxyAddress = $Settings->GetValue (); - $Settings->SetKey ('ProxyPort'); - self::$ProxyPort = intval ($Settings->GetValue ()); - $Settings->SetKey ('ProxyUser'); - self::$ProxyUser = $Settings->GetValue (); - $Settings->SetKey ('ProxyPasswd'); - self::$ProxyPasswd = $Settings->GetValue (); - $Settings->SetKey ('WhichDownloader'); - self::$WhichDownloader = $Settings->GetValue (); - self::$WhichDownloader = is_null (self::$WhichDownloader) ? 0 : (strcmp (self::$WhichDownloader, 'ARIA2') == 0 ? 0 : 1); // 0 means ARIA2, 1 means CURL - - $Settings->SetKey ('AllowProtocolHTTP'); - self::$AllowProtocolHTTP = $Settings->GetValue (); - self::$AllowProtocolHTTP = is_null (self::$AllowProtocolHTTP) ? true : strcmp (self::$AllowProtocolHTTP, 'Y') == 0; - $Settings->SetKey ('AllowProtocolFTP'); - self::$AllowProtocolFTP = $Settings->GetValue (); - self::$AllowProtocolFTP = is_null (self::$AllowProtocolFTP) ? true : strcmp (self::$AllowProtocolFTP, 'Y') == 0; - $Settings->SetKey ('AllowProtocolYT'); - self::$AllowProtocolYT = $Settings->GetValue (); - self::$AllowProtocolYT = is_null (self::$AllowProtocolYT) ? true : strcmp (self::$AllowProtocolYT, 'Y') == 0; - $Settings->SetKey ('AllowProtocolBT'); - self::$AllowProtocolBT = $Settings->GetValue (); - self::$AllowProtocolBT = is_null (self::$AllowProtocolBT) ? true : strcmp (self::$AllowProtocolBT, 'Y') == 0; - - $Settings->SetTable ('personal'); - $Settings->SetUID (self::$CurrentUID); - $Settings->SetKey ('DownloadsFolder'); - self::$DownloadsFolder = $Settings->GetValue (); - - self::$DownloadsFolder = '/' . (is_null (self::$DownloadsFolder) ? 'Downloads' : self::$DownloadsFolder); - self::$AbsoluteDownloadsFolder = \OC\Files\Filesystem::getLocalFolder (self::$DownloadsFolder); - - $Settings->SetKey ('YTDLBinary'); - $YTDLBinary = $Settings->GetValue (); - - self::$YTDLBinary = '/usr/local/bin/youtube-dl'; // default path - if (!is_null ($YTDLBinary)) - { - self::$YTDLBinary = $YTDLBinary; + } else { + $Queue[] = array( + 'GID' => $Row['GID'], + 'PROGRESSVAL' => 0, + 'PROGRESS' => array( + 'Message' => 'ErrorGIDnotfound', + 'ProgressString' => null, + 'NumSeeders' => null, + 'UploadLength' => null, + 'Ratio' => null + ), + 'STATUS' => array( + 'Value' => 'N_A', + 'Seeding' => null + ), + 'STATUSID' => $DLStatus, + 'SPEED' => 'N_A', + 'FILENAME' => $Row['FILENAME'], + 'PROTO' => $Row['PROTOCOL'], + 'ISTORRENT' => isset($Status['result']['bittorrent']) + ); + } + } else { + $Queue[] = array( + 'GID' => $Row['GID'], + 'PROGRESSVAL' => 0, + 'PROGRESS' => array( + 'Message' => self::$WhichDownloader == 0 + ?'ReturnedstatusisnullIsAria2crunningasadaemon' + :'Unabletofinddownloadstatusfile', + 'ProgressString' => null, + 'NumSeeders' => null, + 'UploadLength' => null, + 'Ratio' => null + ), + 'STATUS' => array( + 'Value' => 'N_A', + 'Seeding' => null + ), + 'STATUSID' => $DLStatus, + 'SPEED' => 'N_A', + 'FILENAME' => $Row['FILENAME'], + 'PROTO' => $Row['PROTOCOL'], + 'ISTORRENT' => isset($Status['result']['bittorrent']) + ); + } } - } -} \ No newline at end of file + return array( + 'ERROR' => false, + 'MESSAGE' => null, + 'QUEUE' => $Queue, + 'COUNTER' => Tools::getCounters(self::$DbType, self::$CurrentUID) + ); + } catch (Exception $E) { + return array('ERROR' => true, 'MESSAGE' => $E->getMessage(), 'QUEUE' => null, 'COUNTER' => null); + } + } + + /********** PRIVATE STATIC METHODS **********/ + private static function load() + { + if (strcmp(Config::getSystemValue('dbtype'), 'pgsql') == 0) { + self::$DbType = 1; + } + + self::$CurrentUID = \OC::$server->getUserSession()->getUser(); + self::$CurrentUID =(self::$CurrentUID)?self::$CurrentUID->getUID():''; + + self::$L10N = \OC::$server->getL10N('ocdownloader'); + + $Settings = new Settings(); + + $Settings->setKey('ProxyAddress'); + self::$ProxyAddress = $Settings->getValue(); + $Settings->setKey('ProxyPort'); + self::$ProxyPort = intval($Settings->getValue()); + $Settings->setKey('ProxyUser'); + self::$ProxyUser = $Settings->getValue(); + $Settings->setKey('ProxyPasswd'); + self::$ProxyPasswd = $Settings->getValue(); + $Settings->setKey('WhichDownloader'); + self::$WhichDownloader = $Settings->getValue(); + self::$WhichDownloader = is_null(self::$WhichDownloader)?0 :(strcmp(self::$WhichDownloader, 'ARIA2') == 0?0:1); // 0 means ARIA2, 1 means CURL + + $Settings->setKey('AllowProtocolHTTP'); + self::$AllowProtocolHTTP = $Settings->getValue(); + self::$AllowProtocolHTTP = is_null(self::$AllowProtocolHTTP)?true:strcmp(self::$AllowProtocolHTTP, 'Y') == 0; + $Settings->setKey('AllowProtocolFTP'); + self::$AllowProtocolFTP = $Settings->getValue(); + self::$AllowProtocolFTP = is_null(self::$AllowProtocolFTP)?true:strcmp(self::$AllowProtocolFTP, 'Y') == 0; + $Settings->setKey('AllowProtocolYT'); + self::$AllowProtocolYT = $Settings->getValue(); + self::$AllowProtocolYT = is_null(self::$AllowProtocolYT)?true:strcmp(self::$AllowProtocolYT, 'Y') == 0; + $Settings->setKey('AllowProtocolBT'); + self::$AllowProtocolBT = $Settings->getValue(); + self::$AllowProtocolBT = is_null(self::$AllowProtocolBT)?true:strcmp(self::$AllowProtocolBT, 'Y') == 0; + + $Settings->setTable('personal'); + $Settings->setUID(self::$CurrentUID); + $Settings->setKey('DownloadsFolder'); + self::$DownloadsFolder = $Settings->getValue(); + + self::$DownloadsFolder = '/' .(is_null(self::$DownloadsFolder)?'Downloads':self::$DownloadsFolder); + self::$AbsoluteDownloadsFolder = \OC\Files\Filesystem::getLocalFolder(self::$DownloadsFolder); + + $Settings->setKey('YTDLBinary'); + $YTDLBinary = $Settings->getValue(); + + self::$YTDLBinary = '/usr/local/bin/youtube-dl'; // default path + if (!is_null($YTDLBinary)) { + self::$YTDLBinary = $YTDLBinary; + } + } +} diff --git a/controller/lib/aria2.php b/controller/lib/aria2.php index 0c890b7..a9d087e 100644 --- a/controller/lib/aria2.php +++ b/controller/lib/aria2.php @@ -15,79 +15,91 @@ class Aria2 private static $Server = null; private static $CurlHandler; - public static function __callStatic ($Name, $Args) + public static function __callStatic($Name, $Args) { self::$Server = 'http://127.0.0.1:6800/jsonrpc'; - $Args = (strcmp ($Name, 'AddTorrent') == 0 ? self::RebuildTorrentArgs ($Args) : self::RebuildArgs ($Args)); - - self::Load (); - - $Data = Array ( - 'jsonrpc' => '2.0', - 'id' => 'ocdownloader', - 'method' => 'aria2.' . lcfirst ($Name), - 'params' => $Args + $Args =(strcmp($Name, 'addTorrent') == 0 ? self::rebuildTorrentArgs($Args) : self::rebuildArgs($Args)); + + self::load(); + + $Data = array( + 'jsonrpc' => '2.0', + 'id' => 'ocdownloader', + 'method' => 'aria2.' . lcfirst($Name), + 'params' => $Args ); - - return json_decode (self::Request ($Data), 1); + + return json_decode(self::request($Data), 1); } /********** PRIVATE STATIC METHODS **********/ - private static function Load () + private static function load() { - self::$CurlHandler = curl_init (self::$Server); - - curl_setopt_array (self::$CurlHandler, Array ( - CURLOPT_POST => true, - CURLOPT_RETURNTRANSFER => true, - CURLOPT_HEADER => false + self::$CurlHandler = curl_init(self::$Server); + + curl_setopt_array(self::$CurlHandler, array( + CURLOPT_POST => true, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_HEADER => false )); } - private static function Request ($Data) + private static function request($Data) { - curl_setopt (self::$CurlHandler, CURLOPT_POSTFIELDS, json_encode ($Data)); - $Data = curl_exec (self::$CurlHandler); - curl_close (self::$CurlHandler); - + curl_setopt(self::$CurlHandler, CURLOPT_POSTFIELDS, json_encode($Data)); + $Data = curl_exec(self::$CurlHandler); + curl_close(self::$CurlHandler); + return $Data; } - private static function RebuildArgs ($Args) + private static function rebuildArgs($Args) { - if(!is_array($Args)) return array(); //Nibbels: Test: Is this muting another fault or possible state of Args?? >See https://github.com/e-alfred/ocdownloader/issues/11 - if(!count($Args)) return array(); //Nibbels: Test: Is this muting another fault or possible state of Args?? >See https://github.com/e-alfred/ocdownloader/issues/11 - if (isset ($Args[1]['Server']) && !is_null ($Args[1]['Server'])) - { + if (!is_array($Args)) { + //TODO Nibbels: Test: Is this muting another fault or possible state of Args?? + //See https://github.com/e-alfred/ocdownloader/issues/11 + return array(); + } + if (!count($Args)) { + //TODO Nibbels: Test: Is this muting another fault or possible state of Args?? + //See https://github.com/e-alfred/ocdownloader/issues/11 + return array(); + } + if (isset($Args[1]['Server']) && !is_null($Args[1]['Server'])) { self::$Server = $Args[1]['Server']; } - - $RebuildArgs = Array ($Args[0]); - - if (isset ($Args[1]['Params'])) - { + + $RebuildArgs = array($Args[0]); + + if (isset($Args[1]['Params'])) { $RebuildArgs[1] = $Args[1]['Params']; } - + return $RebuildArgs; } - private static function RebuildTorrentArgs ($Args) + private static function rebuildTorrentArgs($Args) { - if(!is_array($Args)) return array(); //Nibbels: Test: Is this muting another fault or possible state of Args?? >See https://github.com/e-alfred/ocdownloader/issues/11 - if(!count($Args)) return array(); //Nibbels: Test: Is this muting another fault or possible state of Args?? >See https://github.com/e-alfred/ocdownloader/issues/11 - if (isset ($Args[2]['Server']) && !is_null ($Args[2]['Server'])) - { + if (!is_array($Args)) { + //TODO Nibbels: Test: Is this muting another fault or possible state of Args?? + //See https://github.com/e-alfred/ocdownloader/issues/11 + return array(); + } + if (!count($Args)) { + //TODO Nibbels: Test: Is this muting another fault or possible state of Args?? + //See https://github.com/e-alfred/ocdownloader/issues/11 + return array(); + } + if (isset($Args[2]['Server']) && !is_null($Args[2]['Server'])) { self::$Server = $Args[2]['Server']; } - - $RebuildArgs = Array ($Args[0], Array ()); - - if (isset ($Args[2]['Params'])) - { + + $RebuildArgs = array($Args[0], array()); + + if (isset($Args[2]['Params'])) { $RebuildArgs[2] = $Args[2]['Params']; } - + return $RebuildArgs; } -} \ No newline at end of file +} diff --git a/controller/lib/curl.php b/controller/lib/curl.php index 30b15a9..88a8be0 100644 --- a/controller/lib/curl.php +++ b/controller/lib/curl.php @@ -12,108 +12,110 @@ class CURL { - private static $GID = null; - private static $URI = null; - private static $OPTIONS = null; - - public static function AddUri ($URI, $OPTIONS) - { - self::$GID = uniqid (); - self::$URI = $URI; - self::$OPTIONS = $OPTIONS; - - self::Run (); - - return Array ('result' => self::$GID); - } - - public static function TellStatus ($GID) - { - if (file_exists ('/tmp/' . $GID . '.curl')) - { - $Line = null; - - $TFHandle = fopen ('/tmp/' . $GID . '.curl', 'r'); - $Cursor = -1; - - fseek ($TFHandle, $Cursor, SEEK_END); - $Char = fgetc ($TFHandle); - - while ($Char === "\n" || $Char === "\r") - { - fseek ($TFHandle, $Cursor--, SEEK_END); - $Char = fgetc ($TFHandle); - } - - while ($Char !== false && $Char !== "\n" && $Char !== "\r") - { - $Line = $Char . $Line; - fseek ($TFHandle, $Cursor--, SEEK_END); - $Char = fgetc ($TFHandle); - } - - $StatusArray = Array ('status' => 'waiting', 'completedLength' => 0, 'totalLength' => 0, 'downloadSpeed' => 0, 'PID' => 0, 'GID' => $GID); - - if (!is_null ($Line)) - { - $Status = explode (';', $Line); - if (count ($Status) == 5) - { - $StatusArray['status'] = $Status[0]; - $StatusArray['completedLength'] = $Status[1]; - $StatusArray['totalLength'] = $Status[2]; - $StatusArray['downloadSpeed'] = $Status[3]; - $StatusArray['PID'] = $Status[4]; - } - } - return Array ( - 'result' => $StatusArray - ); - } - else - { - return Array ( - 'error' => true - ); - } - } - - public static function Remove ($Status) - { - $Return = null; - if (isset ($Status['PID']) && is_numeric ($Status['PID']) && isset ($Status['GID'])) - { - if (posix_kill ($Status['PID'], 15) === false) - { - $Return = null; - } - - if (file_exists ('/tmp/' . $Status['GID'] . '.curl')) - { - $PFHandle = fopen ('/tmp/' . $Status['GID'] . '.curl', 'a'); - if (is_resource ($PFHandle)) - { - fwrite ($PFHandle, 'removed;' . $Status['completedLength'] . ';' . $Status['totalLength'] . ';' . $Status['downloadSpeed'] . ';' . $Status['PID'] . "\n"); - fclose ($PFHandle); - - $Return = Array ('result' => $Status['GID']); - } - } - } - return $Return; - } - - public static function RemoveDownloadResult ($GID) - { - if (file_exists ('/tmp/' . $GID . '.curl')) - { - unlink ('/tmp/' . $GID . '.curl'); - } - } - - /********** PRIVATE STATIC METHODS **********/ - private static function Run () - { - shell_exec (rtrim (dirname (__FILE__), '/') . '/../../SERVER/fallback.sh "' . self::$GID . '" "' . urlencode (self::$URI) . '" "' . urlencode (json_encode (self::$OPTIONS, JSON_HEX_APOS | JSON_HEX_QUOT)) . '"'); - } -} \ No newline at end of file + private static $GID = null; + private static $URI = null; + private static $OPTIONS = null; + + public static function addUri($URI, $OPTIONS) + { + self::$GID = uniqid(); + self::$URI = $URI; + self::$OPTIONS = $OPTIONS; + + self::run(); + + return array('result' => self::$GID); + } + + public static function tellStatus($GID) + { + if (file_exists('/tmp/' . $GID . '.curl')) { + $Line = null; + + $TFHandle = fopen('/tmp/' . $GID . '.curl', 'r'); + $Cursor = -1; + + fseek($TFHandle, $Cursor, SEEK_END); + $Char = fgetc($TFHandle); + + while ($Char === "\n" || $Char === "\r") { + fseek($TFHandle, $Cursor--, SEEK_END); + $Char = fgetc($TFHandle); + } + + while ($Char !== false && $Char !== "\n" && $Char !== "\r") { + $Line = $Char . $Line; + fseek($TFHandle, $Cursor--, SEEK_END); + $Char = fgetc($TFHandle); + } + + $StatusArray = array( + 'status' => 'waiting', + 'completedLength' => 0, + 'totalLength' => 0, + 'downloadSpeed' => 0, + 'PID' => 0, + 'GID' => $GID + ); + + if (!is_null($Line)) { + $Status = explode(';', $Line); + if (count($Status) == 5) { + $StatusArray['status'] = $Status[0]; + $StatusArray['completedLength'] = $Status[1]; + $StatusArray['totalLength'] = $Status[2]; + $StatusArray['downloadSpeed'] = $Status[3]; + $StatusArray['PID'] = $Status[4]; + } + } + return array( + 'result' => $StatusArray + ); + } else { + return array( + 'error' => true + ); + } + } + + public static function remove($Status) + { + $Return = null; + if (isset($Status['PID']) && is_numeric($Status['PID']) && isset($Status['GID'])) { + if (posix_kill($Status['PID'], 15) === false) { + $Return = null; + } + + if (file_exists('/tmp/' . $Status['GID'] . '.curl')) { + $PFHandle = fopen('/tmp/' . $Status['GID'] . '.curl', 'a'); + if (is_resource($PFHandle)) { + fwrite( + $PFHandle, + 'removed;'.$Status['completedLength'].';'.$Status['totalLength'].';'.$Status['downloadSpeed'] + .';'.$Status['PID']."\n" + ); + fclose($PFHandle); + + $Return = array('result' => $Status['GID']); + } + } + } + return $Return; + } + + public static function removeDownloadResult($GID) + { + if (file_exists('/tmp/' . $GID . '.curl')) { + unlink('/tmp/' . $GID . '.curl'); + } + } + + /********** PRIVATE STATIC METHODS **********/ + private static function run() + { + shell_exec( + rtrim(dirname(__FILE__), '/') . '/../../SERVER/fallback.sh "' . self::$GID . '" "' + .urlencode(self::$URI) . '" "' . urlencode(json_encode(self::$OPTIONS, JSON_HEX_APOS | JSON_HEX_QUOT)).'"' + ); + } +} diff --git a/controller/lib/settings.php b/controller/lib/settings.php index 72f47a4..18782af 100644 --- a/controller/lib/settings.php +++ b/controller/lib/settings.php @@ -15,144 +15,130 @@ class Settings { - private $Key = null; - private $DbType = 0; - private $Table = null; - private $UID = null; - - public function __construct ($Table = 'admin') - { - if (strcmp (Config::getSystemValue ('dbtype'), 'pgsql') == 0) - { + private $Key = null; + private $DbType = 0; + private $Table = null; + private $UID = null; + + public function __construct($Table = 'admin') + { + if (strcmp(Config::getSystemValue('dbtype'), 'pgsql') == 0) { $this->DbType = 1; } - - $this->Table = $Table; - } - - public function SetKey ($Key) - { - $this->Key = $Key; - } - - public function SetUID ($UID) - { - $this->UID = $UID; - } - - public function SetTable ($Table) - { - $this->Table = $Table; - } - - public function CheckIfKeyExists () - { - if (is_null ($this->Key)) - { - return false; - } - - $SQL = 'SELECT `VAL` FROM `*PREFIX*ocdownloader_' . $this->Table . 'settings` WHERE `KEY` = ?' . (!is_null ($this->UID) ? ' AND `UID` = ?' : '') . ' LIMIT 1'; - if ($this->DbType == 1) - { - $SQL = 'SELECT "VAL" FROM *PREFIX*ocdownloader_' . $this->Table . 'settings WHERE "KEY" = ?' . (!is_null ($this->UID) ? ' AND "UID" = ?' : '') . ' LIMIT 1'; - } - $Query = \OCP\DB::prepare ($SQL); - if (!is_null ($this->UID)) - { - $Query->execute (Array ($this->Key, $this->UID)); - } - else - { - $Query->execute (Array ($this->Key)); - } - - if ($Query->rowCount () == 1) - { - return true; - } - return false; - } - - public function GetValue () - { - $SQL = 'SELECT `VAL` FROM `*PREFIX*ocdownloader_' . $this->Table . 'settings` WHERE `KEY` = ?' . (!is_null ($this->UID) ? ' AND `UID` = ?' : '') . ' LIMIT 1'; - if ($this->DbType == 1) - { - $SQL = 'SELECT "VAL" FROM *PREFIX*ocdownloader_' . $this->Table . 'settings WHERE "KEY" = ?' . (!is_null ($this->UID) ? ' AND "UID" = ?' : '') . ' LIMIT 1'; + + $this->Table = $Table; + } + + public function setKey($Key) + { + $this->Key = $Key; + } + + public function setUID($UID) + { + $this->UID = $UID; + } + + public function setTable($Table) + { + $this->Table = $Table; + } + + public function checkIfKeyExists() + { + if (is_null($this->Key)) { + return false; } - $Query = \OCP\DB::prepare ($SQL); - - if (!is_null ($this->UID)) - { - $Result = $Query->execute (Array ($this->Key, $this->UID)); - } - else - { - $Result = $Query->execute (Array ($this->Key)); - } - - if ($Query->rowCount () == 1) - { - return $Result->fetchOne (); - } - return null; - } - - public function GetAllValues () - { - $SQL = 'SELECT `KEY`, `VAL` FROM `*PREFIX*ocdownloader_' . $this->Table . 'settings`' . (!is_null ($this->UID) ? ' WHERE `UID` = ?' : ''); - if ($this->DbType == 1) - { - $SQL = 'SELECT "KEY", "VAL" FROM *PREFIX*ocdownloader_' . $this->Table . 'settings' . (!is_null ($this->UID) ? ' WHERE "UID" = ?' : ''); - } - $Query = \OCP\DB::prepare ($SQL); - - if (!is_null ($this->UID)) - { - return $Query->execute (Array ($this->UID)); - } - else - { - return $Query->execute (); - } - } - - public function UpdateValue ($Value) - { - $SQL = 'UPDATE `*PREFIX*ocdownloader_' . $this->Table . 'settings` SET `VAL` = ? WHERE `KEY` = ?' . (!is_null ($this->UID) ? ' AND `UID` = ?' : ''); - if ($this->DbType == 1) - { - $SQL = 'UPDATE *PREFIX*ocdownloader_' . $this->Table . 'settings SET "VAL" = ? WHERE "KEY" = ?' . (!is_null ($this->UID) ? ' AND "UID" = ?' : ''); - } - $Query = \OCP\DB::prepare ($SQL); - - if (!is_null ($this->UID)) - { - $Query->execute (Array ($Value, $this->Key, $this->UID)); - } - else - { - $Query->execute (Array ($Value, $this->Key)); - } - } - - public function InsertValue ($Value) - { - $SQL = 'INSERT INTO `*PREFIX*ocdownloader_' . $this->Table . 'settings` (`KEY`, `VAL`' . (!is_null ($this->UID) ? ', `UID`' : '') . ') VALUES (?, ?' . (!is_null ($this->UID) ? ', ?' : '') . ')'; - if ($this->DbType == 1) - { - $SQL = 'INSERT INTO *PREFIX*ocdownloader_' . $this->Table . 'settings ("KEY", "VAL"' . (!is_null ($this->UID) ? ', "UID"' : '') . ') VALUES (?, ?' . (!is_null ($this->UID) ? ', ?' : '') . ')'; - } - $Query = \OCP\DB::prepare ($SQL); - - if (!is_null ($this->UID)) - { - $Query->execute (Array ($this->Key, $Value, $this->UID)); - } - else - { - $Query->execute (Array ($this->Key, $Value)); - } - } -} \ No newline at end of file + + $SQL = 'SELECT `VAL` FROM `*PREFIX*ocdownloader_'.$this->Table.'settings` WHERE `KEY` = ?' + .(!is_null($this->UID) ? ' AND `UID` = ?' : '') . ' LIMIT 1'; + if ($this->DbType == 1) { + $SQL = 'SELECT "VAL" FROM *PREFIX*ocdownloader_'.$this->Table.'settings WHERE "KEY" = ?' + .(!is_null($this->UID) ? ' AND "UID" = ?' : '').' LIMIT 1'; + } + $Query = \OCP\DB::prepare($SQL); + if (!is_null($this->UID)) { + $Query->execute(array($this->Key, $this->UID)); + } else { + $Query->execute(array($this->Key)); + } + + if ($Query->rowCount() == 1) { + return true; + } + return false; + } + + public function getValue() + { + $SQL = 'SELECT `VAL` FROM `*PREFIX*ocdownloader_'.$this->Table.'settings` WHERE `KEY` = ?' + .(!is_null($this->UID) ? ' AND `UID` = ?' : '').' LIMIT 1'; + if ($this->DbType == 1) { + $SQL = 'SELECT "VAL" FROM *PREFIX*ocdownloader_'.$this->Table.'settings WHERE "KEY" = ?' + .(!is_null($this->UID) ? ' AND "UID" = ?' : '').' LIMIT 1'; + } + $Query = \OCP\DB::prepare($SQL); + + if (!is_null($this->UID)) { + $Result = $Query->execute(array($this->Key, $this->UID)); + } else { + $Result = $Query->execute(array($this->Key)); + } + + if ($Query->rowCount() == 1) { + return $Result->fetchOne(); + } + return null; + } + + public function getAllValues() + { + $SQL = 'SELECT `KEY`, `VAL` FROM `*PREFIX*ocdownloader_'.$this->Table.'settings`' + .(!is_null($this->UID) ? ' WHERE `UID` = ?' : ''); + if ($this->DbType == 1) { + $SQL = 'SELECT "KEY", "VAL" FROM *PREFIX*ocdownloader_'.$this->Table.'settings' + .(!is_null($this->UID) ? ' WHERE "UID" = ?' : ''); + } + $Query = \OCP\DB::prepare($SQL); + + if (!is_null($this->UID)) { + return $Query->execute(array($this->UID)); + } else { + return $Query->execute(); + } + } + + public function updateValue($Value) + { + $SQL = 'UPDATE `*PREFIX*ocdownloader_' . $this->Table . 'settings` SET `VAL` = ? WHERE `KEY` = ?' + .(!is_null($this->UID) ? ' AND `UID` = ?' : ''); + if ($this->DbType == 1) { + $SQL = 'UPDATE *PREFIX*ocdownloader_' . $this->Table . 'settings SET "VAL" = ? WHERE "KEY" = ?' + .(!is_null($this->UID) ? ' AND "UID" = ?' : ''); + } + $Query = \OCP\DB::prepare($SQL); + + if (!is_null($this->UID)) { + $Query->execute(array($Value, $this->Key, $this->UID)); + } else { + $Query->execute(array($Value, $this->Key)); + } + } + + public function insertValue($Value) + { + $SQL = 'INSERT INTO `*PREFIX*ocdownloader_'.$this->Table.'settings`(`KEY`, `VAL`' + .(!is_null($this->UID) ? ', `UID`' : '') . ') VALUES(?, ?' .(!is_null($this->UID) ? ', ?' : '').')'; + if ($this->DbType == 1) { + $SQL = 'INSERT INTO *PREFIX*ocdownloader_'.$this->Table.'settings("KEY", "VAL"' + .(!is_null($this->UID) ? ', "UID"' : '') . ') VALUES(?, ?' .(!is_null($this->UID) ? ', ?' : '').')'; + } + $Query = \OCP\DB::prepare($SQL); + + if (!is_null($this->UID)) { + $Query->execute(array($this->Key, $Value, $this->UID)); + } else { + $Query->execute(array($this->Key, $Value)); + } + } +} diff --git a/controller/lib/tools.php b/controller/lib/tools.php index 9dfc92f..2755283 100644 --- a/controller/lib/tools.php +++ b/controller/lib/tools.php @@ -15,241 +15,227 @@ class Tools { - public static function CheckURL ($URL) - { - $URLPattern = '%^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@|\d{1,3}(?:\.\d{1,3}){3}|(?:(?:[a-z\d\x{00a1}-\x{ffff}]+-?)*[a-z\d\x{00a1}-\x{ffff}]+)(?:\.(?:[a-z\d\x{00a1}-\x{ffff}]+-?)*[a-z\d\x{00a1}-\x{ffff}]+)*(?:\.[a-z\x{00a1}-\x{ffff}]{2,6}))(?::\d+)?(?:[^\s]*)?$%iu'; - - preg_match ($URLPattern, $URL, $Matches); - if (count ($Matches) === 1) - { - return true; - } - return false; - } - - public static function CheckFilepath ($FP) - { - if (\OC\Files\Filesystem::file_exists ($FP)) - { - return true; - } - return false; - } - - public static function GetProgressString ($Completed, $Total, $Progress) - { - $CompletedStr = self::FormatSizeUnits ($Completed); - $TotalStr = self::FormatSizeUnits ($Total); - - if ($Progress < 1 && $Progress > 0) - { - return $CompletedStr . ' / ' . $TotalStr . ' (' . round ((($Completed / $Total) * 100), 2) . '%)'; - } - elseif ($Progress >= 1) - { - return $TotalStr . ' (' . round ((($Completed / $Total) * 100), 2) . '%)'; - } - return null; - } - - public static function FormatSizeUnits ($Bytes) + public static function checkURL($URL) { - if ($Bytes >= 1073741824) - { - $Bytes = number_format ($Bytes / 1073741824, 2) . ' GB'; + $URLPattern = '%^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@|\d{1,3}(?:\.\d{1,3}){3}|(?:(?:[a-z\d\x{00a1}-\x{ffff}' + .']+-?)*[a-z\d\x{00a1}-\x{ffff}]+)(?:\.(?:[a-z\d\x{00a1}-\x{ffff}]+-?)*[a-z\d\x{00a1}-\x{ffff}]+)*(?:\.' + .'[a-z\x{00a1}-\x{ffff}]{2,6}))(?::\d+)?(?:[^\s]*)?$%iu'; + + preg_match($URLPattern, $URL, $Matches); + if (count($Matches) === 1) { + return true; } - elseif ($Bytes >= 1048576) - { - $Bytes = number_format ($Bytes / 1048576, 2) . ' MB'; + return false; + } + + public static function checkFilepath($FP) + { + if (\OC\Files\Filesystem::file_exists($FP)) { + return true; } - elseif ($Bytes >= 1024) - { - $Bytes = number_format ($Bytes / 1024, 2) . ' KB'; + return false; + } + + public static function getProgressString($Completed, $Total, $Progress) + { + $CompletedStr = self::formatSizeUnits($Completed); + $TotalStr = self::formatSizeUnits($Total); + + if ($Progress < 1 && $Progress > 0) { + return $CompletedStr . ' / ' . $TotalStr . '(' . round((($Completed / $Total) * 100), 2) . '%)'; + } elseif ($Progress >= 1) { + return $TotalStr . '(' . round((($Completed / $Total) * 100), 2) . '%)'; } - else - { + return null; + } + + public static function formatSizeUnits($Bytes) + { + if ($Bytes >= 1073741824) { + $Bytes = number_format($Bytes / 1073741824, 2) . ' GB'; + } elseif ($Bytes >= 1048576) { + $Bytes = number_format($Bytes / 1048576, 2) . ' MB'; + } elseif ($Bytes >= 1024) { + $Bytes = number_format($Bytes / 1024, 2) . ' KB'; + } else { $Bytes = $Bytes . ' B'; } return $Bytes; - } - - public static function CheckBinary ($Binary) - { - exec ('which ' . $Binary, $Output, $Return); - - if ($Return == 0) - { - return true; - } - return false; - } - - public static function CleanString ($Text) - { - $UTF8 = Array - ( - '/[áàâãªä]/u' => 'a', - '/[ÁÀÂÃÄ]/u' => 'A', - '/[ÍÌÎÏ]/u' => 'I', - '/[íìîï]/u' => 'i', - '/[éèêë]/u' => 'e', - '/[ÉÈÊË]/u' => 'E', - '/[óòôõºö]/u' => 'o', - '/[ÓÒÔÕÖ]/u' => 'O', - '/[úùûü]/u' => 'u', - '/[ÚÙÛÜ]/u' => 'U', - '/ç/' => 'c', - '/Ç/' => 'C', - '/ñ/' => 'n', - '/Ñ/' => 'N', - '/–/' => '-', // UTF-8 hyphen to "normal" hyphen - '/[’‘‹›‚]/u' => '', // Literally a single quote - '/[“”«»„]/u' => '', // Double quote - '/ /' => '_', // nonbreaking space (equiv. to 0x160) - ); - return preg_replace (array_keys ($UTF8), array_values ($UTF8), $Text); - } - - public static function GetDownloadStatusID ($Status) - { - switch (strtolower ($Status)) - { - case 'complete': - $DLStatus = 0; - break; - case 'active': - $DLStatus = 1; - break; - case 'waiting': - $DLStatus = 2; - break; - case 'paused': - $DLStatus = 3; - break; - case 'removed': - $DLStatus = 4; - break; - default: - $DLStatus = 5; - break; - } - return $DLStatus; - } - - public static function GetCounters ($DbType, $UID) - { - $SQL = 'SELECT (SELECT COUNT(*) FROM `*PREFIX*ocdownloader_queue` WHERE `STATUS` < ? AND `UID` = ?) as `ALL`,' . - '(SELECT COUNT(*) FROM `*PREFIX*ocdownloader_queue` WHERE `STATUS` = ? AND `UID` = ?) as `COMPLETES`,' . - '(SELECT COUNT(*) FROM `*PREFIX*ocdownloader_queue` WHERE `STATUS` = ? AND `UID` = ?) as `ACTIVES`,' . - '(SELECT COUNT(*) FROM `*PREFIX*ocdownloader_queue` WHERE `STATUS` = ? AND `UID` = ?) as `WAITINGS`,' . - '(SELECT COUNT(*) FROM `*PREFIX*ocdownloader_queue` WHERE `STATUS` = ? AND `UID` = ?) as `STOPPED`,' . - '(SELECT COUNT(*) FROM `*PREFIX*ocdownloader_queue` WHERE `STATUS` = ? AND `UID` = ?) as `REMOVED`'; - if ($DbType == 1) - { - $SQL = 'SELECT (SELECT COUNT(*) FROM *PREFIX*ocdownloader_queue WHERE "STATUS" < ? AND "UID" = ?) as "ALL",' . - '(SELECT COUNT(*) FROM *PREFIX*ocdownloader_queue WHERE "STATUS" = ? AND "UID" = ?) as "COMPLETES",' . - '(SELECT COUNT(*) FROM *PREFIX*ocdownloader_queue WHERE "STATUS" = ? AND "UID" = ?) as "ACTIVES",' . - '(SELECT COUNT(*) FROM *PREFIX*ocdownloader_queue WHERE "STATUS" = ? AND "UID" = ?) as "WAITINGS",' . - '(SELECT COUNT(*) FROM *PREFIX*ocdownloader_queue WHERE "STATUS" = ? AND "UID" = ?) as "STOPPED",' . - '(SELECT COUNT(*) FROM *PREFIX*ocdownloader_queue WHERE "STATUS" = ? AND "UID" = ?) as "REMOVED"'; - } - $Query = \OCP\DB::prepare ($SQL); - $Request = $Query->execute (Array (5, $UID, 0, $UID, 1, $UID, 2, $UID, 3, $UID, 4, $UID)); - - return $Request->fetchRow (); - } - - public static function StartsWith ($Haystack, $Needle) - { - return $Needle === "" || strrpos ($Haystack, $Needle, -strlen ($Haystack)) !== FALSE; - } - - public static function EndsWith ($Haystack, $Needle) - { - return $Needle === "" || (($Temp = strlen ($Haystack) - strlen ($Needle)) >= 0 && strpos ($Haystack, $Needle, $Temp) !== FALSE); - } - - public static function GetLastVersionNumber () - { - $CH = curl_init ('https://raw.githubusercontent.com/e-alfred/ocdownloader/master/appinfo/version'); - - curl_setopt_array ($CH, Array ( - CURLOPT_RETURNTRANSFER => true, - CURLOPT_TIMEOUT => 10, - CURLOPT_CONNECTTIMEOUT => 10, - CURLOPT_RETURNTRANSFER => true, - CURLOPT_FOLLOWLOCATION => true, - CURLOPT_MAXREDIRS => 10 - )); - - $Data = curl_exec ($CH); - curl_close ($CH); - - return $Data; - } - - public static function CanCheckForUpdate () - { - // Is the user in the admin group ? - if (\OC_User::isAdminUser (\OC_User::getUser ())) - { - // Is the ocdownloader option to automatically check is enable ? - $Settings = new Settings (); - $Settings->SetKey ('CheckForUpdates'); - $CheckForUpdates = $Settings->GetValue (); - if (strcmp ($CheckForUpdates, 'Y') == 0 || is_null ($CheckForUpdates)) - { - return true; - } + } + + public static function checkBinary($Binary) + { + exec('which ' . $Binary, $Output, $Return); + + if ($Return == 0) { + return true; + } + return false; + } + + public static function cleanString($Text) + { + $UTF8 = array + ( + '/[áàâãªä]/u' => 'a', + '/[ÁÀÂÃÄ]/u' => 'A', + '/[ÍÌÎÏ]/u' => 'I', + '/[íìîï]/u' => 'i', + '/[éèêë]/u' => 'e', + '/[ÉÈÊË]/u' => 'E', + '/[óòôõºö]/u' => 'o', + '/[ÓÒÔÕÖ]/u' => 'O', + '/[úùûü]/u' => 'u', + '/[ÚÙÛÜ]/u' => 'U', + '/ç/' => 'c', + '/Ç/' => 'C', + '/ñ/' => 'n', + '/Ñ/' => 'N', + '/–/' => '-', // UTF-8 hyphen to "normal" hyphen + '/[’‘‹›‚]/u' => '', // Literally a single quote + '/[“”«»„]/u' => '', // Double quote + '/ /' => '_', // nonbreaking space(equiv. to 0x160) + ); + return preg_replace(array_keys($UTF8), array_values($UTF8), $Text); + } + + public static function getDownloadStatusID($Status) + { + switch (strtolower($Status)) { + case 'complete': + $DLStatus = 0; + break; + case 'active': + $DLStatus = 1; + break; + case 'waiting': + $DLStatus = 2; + break; + case 'paused': + $DLStatus = 3; + break; + case 'removed': + $DLStatus = 4; + break; + default: + $DLStatus = 5; + break; + } + return $DLStatus; + } + + public static function getCounters($DbType, $UID) + { + $SQL = 'SELECT(SELECT COUNT(*) FROM `*PREFIX*ocdownloader_queue` WHERE `STATUS` < ? AND `UID` = ?) as `ALL`,' + .'(SELECT COUNT(*) FROM `*PREFIX*ocdownloader_queue` WHERE `STATUS` = ? AND `UID` = ?) as `COMPLETES`,' + .'(SELECT COUNT(*) FROM `*PREFIX*ocdownloader_queue` WHERE `STATUS` = ? AND `UID` = ?) as `ACTIVES`,' + .'(SELECT COUNT(*) FROM `*PREFIX*ocdownloader_queue` WHERE `STATUS` = ? AND `UID` = ?) as `WAITINGS`,' + .'(SELECT COUNT(*) FROM `*PREFIX*ocdownloader_queue` WHERE `STATUS` = ? AND `UID` = ?) as `STOPPED`,' + .'(SELECT COUNT(*) FROM `*PREFIX*ocdownloader_queue` WHERE `STATUS` = ? AND `UID` = ?) as `REMOVED`'; + if ($DbType == 1) { + $SQL = 'SELECT(SELECT COUNT(*) FROM *PREFIX*ocdownloader_queue WHERE "STATUS" < ? AND "UID" = ?) as "ALL",' + .'(SELECT COUNT(*) FROM *PREFIX*ocdownloader_queue WHERE "STATUS" = ? AND "UID" = ?) as "COMPLETES",' + .'(SELECT COUNT(*) FROM *PREFIX*ocdownloader_queue WHERE "STATUS" = ? AND "UID" = ?) as "ACTIVES",' + .'(SELECT COUNT(*) FROM *PREFIX*ocdownloader_queue WHERE "STATUS" = ? AND "UID" = ?) as "WAITINGS",' + .'(SELECT COUNT(*) FROM *PREFIX*ocdownloader_queue WHERE "STATUS" = ? AND "UID" = ?) as "STOPPED",' + .'(SELECT COUNT(*) FROM *PREFIX*ocdownloader_queue WHERE "STATUS" = ? AND "UID" = ?) as "REMOVED"'; + } + $Query = \OCP\DB::prepare($SQL); + $Request = $Query->execute(array(5, $UID, 0, $UID, 1, $UID, 2, $UID, 3, $UID, 4, $UID)); + + return $Request->fetchRow(); + } + + public static function startsWith($Haystack, $Needle) + { + return $Needle === "" || strrpos($Haystack, $Needle, -strlen($Haystack)) !== false; + } + + public static function endsWith($Haystack, $Needle) + { + return $Needle === "" ||(($Temp = strlen($Haystack) - strlen($Needle)) >= 0 + && strpos($Haystack, $Needle, $Temp) !== false); + } + + public static function getLastVersionNumber() + { + $CH = curl_init('https://raw.githubusercontent.com/e-alfred/ocdownloader/master/appinfo/version'); + + curl_setopt_array($CH, array( + CURLOPT_RETURNTRANSFER => true, + CURLOPT_TIMEOUT => 10, + CURLOPT_CONNECTTIMEOUT => 10, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_MAXREDIRS => 10 + )); + + $Data = curl_exec($CH); + curl_close($CH); + + return $Data; + } + + public static function canCheckForUpdate() + { + // Is the user in the admin group ? + if (\OC_User::isAdminUser(\OC_User::getUser())) { + // Is the ocdownloader option to automatically check is enable ? + $Settings = new Settings(); + $Settings->setKey('CheckForUpdates'); + $CheckForUpdates = $Settings->getValue(); + if (strcmp($CheckForUpdates, 'Y') == 0 || is_null($CheckForUpdates)) { + return true; + } + } + return false; + } + + public static function resetAria2($DbType) + { + $SQL = 'SELECT * FROM `*PREFIX*ocdownloader_queue`'; + if ($DbType == 1) { + $SQL = 'SELECT * FROM *PREFIX*ocdownloader_queue'; + } + $Query = \OCP\DB::prepare($SQL); + $Request = $Query->execute(); + + while ($Row = $Request->fetchRow()) { + $Status = Aria2::tellStatus($Row['GID']); //$GID was wrong, but $Row['GID']? untested!! + + if (!isset($Status['error']) && strcmp($Status['result']['status'], 'error') != 0 + && strcmp($Status['result']['status'], 'complete') != 0) { + Aria2::remove($Row['GID']); //$GID was wrong, but $Row['GID']? untested!! + } + } + + $Purge = Aria2::purgeDownloadResult(); + if (isset($Purge['result']) && strcmp($Purge['result'], 'OK') == 0) { + $SQL = 'TRUNCATE TABLE `*PREFIX*ocdownloader_queue`'; + if ($DbType == 1) { + $SQL = 'TRUNCATE TABLE *PREFIX*ocdownloader_queue'; + } + $Query = \OCP\DB::prepare($SQL); + $Request = $Query->execute(); } - return false; - } - - public static function ResetAria2 ($DbType) - { - $SQL = 'SELECT * FROM `*PREFIX*ocdownloader_queue`'; - if ($DbType == 1) - { - $SQL = 'SELECT * FROM *PREFIX*ocdownloader_queue'; - } - $Query = \OCP\DB::prepare ($SQL); - $Request = $Query->execute (); - - while ($Row = $Request->fetchRow ()) - { - $Status = Aria2::TellStatus ($Row['GID']); //$GID was wrong, but $Row['GID']? untested!! - - if (!isset ($Status['error']) && strcmp ($Status['result']['status'], 'error') != 0 && strcmp ($Status['result']['status'], 'complete') != 0) - { - Aria2::Remove ($Row['GID']); //$GID was wrong, but $Row['GID']? untested!! - } - } - - $Purge = Aria2::PurgeDownloadResult (); - if (isset ($Purge['result']) && strcmp ($Purge['result'], 'OK') == 0) - { - $SQL = 'TRUNCATE TABLE `*PREFIX*ocdownloader_queue`'; - if ($DbType == 1) - { - $SQL = 'TRUNCATE TABLE *PREFIX*ocdownloader_queue'; - } - $Query = \OCP\DB::prepare ($SQL); - $Request = $Query->execute (); - } - } - - public static function GetMinutes ($Number, $UnitLetter) - { - if (strcmp ($UnitLetter, 'i') == 0) - { - return $Number; - } - - $Units = array ('h' => 'hour', 'd' => 'day', 'w' => 'week', 'm' => 'month', 'y' => 'year'); - - $To = strtotime ('+' . $Number . ' ' . $Units[$UnitLetter] . ($Number > 1 ? 's' : '')); - $From = strtotime ('now'); - return round (abs ($To - $From) / 60,2); - } -} \ No newline at end of file + } + + public static function getMinutes($Number, $UnitLetter) + { + if (strcmp($UnitLetter, 'i') == 0) { + return $Number; + } + + $Units = array('h' => 'hour', 'd' => 'day', 'w' => 'week', 'm' => 'month', 'y' => 'year'); + + $To = strtotime('+' . $Number . ' ' . $Units[$UnitLetter] .($Number > 1 ? 's' : '')); + $From = strtotime('now'); + return round(abs($To - $From) / 60, 2); + } + + public static function getShortFilename($filename) + { + return mb_strlen($filename, "UTF-8") > 40 ? mb_substr($filename, 0, 40, "UTF-8") . '...' : $filename; + } +} diff --git a/controller/lib/youtube.php b/controller/lib/youtube.php index 6da7180..0c26a90 100644 --- a/controller/lib/youtube.php +++ b/controller/lib/youtube.php @@ -19,28 +19,27 @@ class YouTube private $ProxyAddress = null; private $ProxyPort = 0; - public function __construct ($YTDLBinary, $URL) + public function __construct($YTDLBinary, $URL) { $this->YTDLBinary = $YTDLBinary; $this->URL = $URL; } - public function SetForceIPv4 ($ForceIPv4) + public function setForceIPv4($ForceIPv4) { $this->ForceIPv4 = $ForceIPv4; } - public function SetProxy ($ProxyAddress, $ProxyPort) + public function setProxy($ProxyAddress, $ProxyPort) { $this->ProxyAddress = $ProxyAddress; $this->ProxyPort = $ProxyPort; } - public function GetVideoData ($ExtractAudio = false) + public function getVideoData($ExtractAudio = false) { $Proxy = null; - if (!is_null ($this->ProxyAddress) && $this->ProxyPort > 0 && $this->ProxyPort <= 65536) - { + if (!is_null($this->ProxyAddress) && $this->ProxyPort > 0 && $this->ProxyPort <= 65536) { $Proxy = ' --proxy ' . rtrim($this->ProxyAddress, '/') . ':' . $this->ProxyPort; } @@ -48,32 +47,29 @@ public function GetVideoData ($ExtractAudio = false) //youtube multibyte support putenv('LANG=en_US.UTF-8'); - $Output = shell_exec ($this->YTDLBinary . ' -i \'' . $this->URL . '\' --get-url --get-filename' . ($ExtractAudio ? ' -f bestaudio -x' : ' -f best') . ($this->ForceIPv4 ? ' -4' : '') . (is_null ($Proxy) ? '' : $Proxy)); + $Output = shell_exec( + $this->YTDLBinary.' -i \''.$this->URL.'\' --get-url --get-filename' + .($ExtractAudio?' -f bestaudio -x':' -f best').($this->ForceIPv4 ? ' -4' : '') + .(is_null($Proxy) ? '' : $Proxy) + ); - $index=(preg_match('/&index=(\d+)/', $this->URL, $current))?$current[1]:1; + $index=(preg_match('/&index=(\d+)/', $this->URL, $current))?$current[1]:1; - if (!is_null ($Output)) - { - $Output = explode ("\n", $Output); + if (!is_null($Output)) { + $Output = explode("\n", $Output); - if (count ($Output) >= 2) - { - $OutProcessed = Array (); + if (count($Output) >= 2) { + $OutProcessed = array(); $current_index=1; - for ($I = 0; $I < count ($Output); $I++) - { - if (mb_strlen (trim ($Output[$I])) > 0) - { - if (mb_strpos (urldecode ($Output[$I]), 'https://') === 0 && mb_strpos (urldecode ($Output[$I]), '&mime=video/') !== false) - { + for ($I = 0; $I < count($Output); $I++) { + if (mb_strlen(trim($Output[$I])) > 0) { + if (mb_strpos(urldecode($Output[$I]), 'https://') === 0 + && mb_strpos(urldecode($Output[$I]), '&mime=video/') !== false) { $OutProcessed['VIDEO'] = $Output[$I]; - } - elseif (mb_strpos (urldecode ($Output[$I]), 'https://') === 0 && mb_strpos (urldecode ($Output[$I]), '&mime=audio/') !== false) - { + } elseif (mb_strpos(urldecode($Output[$I]), 'https://') === 0 + && mb_strpos(urldecode($Output[$I]), '&mime=audio/') !== false) { $OutProcessed['AUDIO'] = $Output[$I]; - } - else - { + } else { $OutProcessed['FULLNAME'] = $Output[$I]; } } @@ -82,10 +78,8 @@ public function GetVideoData ($ExtractAudio = false) if ($index == $current_index) { break; - } - else - { - $OutProcessed = Array (); + } else { + $OutProcessed = array(); $current_index++; } } diff --git a/controller/personalsettings.php b/controller/personalsettings.php index 1757918..384f337 100644 --- a/controller/personalsettings.php +++ b/controller/personalsettings.php @@ -21,113 +21,106 @@ class PersonalSettings extends Controller { - private $CurrentUID = null; - private $OCDSettingKeys = Array ('DownloadsFolder', 'TorrentsFolder', 'BTRatioToReach', 'BTSeedTimeToReach_BTSeedTimeToReachUnit'); - private $Settings = null; - private $L10N = null; + private $CurrentUID = null; + private $OCDSettingKeys = array( + 'DownloadsFolder', 'TorrentsFolder', 'BTRatioToReach', 'BTSeedTimeToReach_BTSeedTimeToReachUnit' + ); + private $Settings = null; + private $L10N = null; - public function __construct ($AppName, IRequest $Request, $CurrentUID, IL10N $L10N) - { - parent::__construct($AppName, $Request); - $this->CurrentUID = $CurrentUID; + public function __construct($AppName, IRequest $Request, $CurrentUID, IL10N $L10N) + { + parent::__construct($AppName, $Request); + $this->CurrentUID = $CurrentUID; - $this->Settings = new Settings ('personal'); - $this->Settings->SetUID ($this->CurrentUID); + $this->Settings = new Settings('personal'); + $this->Settings->setUID($this->CurrentUID); - $this->L10N = $L10N; - } + $this->L10N = $L10N; + } /** * @NoAdminRequired * @NoCSRFRequired */ - public function Save () - { - \OCP\JSON::setContentTypeHeader ('application/json'); + public function save() + { + \OCP\JSON::setContentTypeHeader('application/json'); - $Error = false; - $Message = ''; + $Error = false; + $Message = ''; - if (isset ($_POST['KEY']) && strlen (trim ($_POST['KEY'])) > 0 && isset ($_POST['VAL']) && strlen (trim ($_POST['VAL'])) > 0) - { - $PostKey = str_replace ('OCD', '', $_POST['KEY']); - $PostValue = ltrim (trim (str_replace (' ', '\ ', $_POST['VAL'])), '/'); + if (isset($_POST['KEY']) && strlen(trim($_POST['KEY'])) > 0 + && isset($_POST['VAL']) && strlen(trim($_POST['VAL'])) > 0) { + $PostKey = str_replace('OCD', '', $_POST['KEY']); + $PostValue = ltrim(trim(str_replace(' ', '\ ', $_POST['VAL'])), '/'); - if (in_array ($PostKey, $this->OCDSettingKeys)) - { - $this->Settings->SetKey ($PostKey); + if (in_array($PostKey, $this->OCDSettingKeys)) { + $this->Settings->setKey($PostKey); - // Pre-Save process - if (strcmp ($PostKey, 'DownloadsFolder') == 0 || strcmp ($PostKey, 'TorrentsFolder') == 0) - { - // check folder exists, if not create it - if (!\OC\Files\Filesystem::is_dir ($PostValue)) - { - // Create the target file - \OC\Files\Filesystem::mkdir ($PostValue); + // Pre-Save process + if (strcmp($PostKey, 'DownloadsFolder') == 0 || strcmp($PostKey, 'TorrentsFolder') == 0) { + // check folder exists, if not create it + if (!\OC\Files\Filesystem::is_dir($PostValue)) { + // Create the target file + \OC\Files\Filesystem::mkdir($PostValue); - $Message .= $this->L10N->t ('The folder doesn\'t exist. It has been created.'); - } - } + $Message .= $this->L10N->t('The folder doesn\'t exist. It has been created.'); + } + } - if (strlen (trim ($PostValue)) <= 0) - { - $PostValue = null; - } + if (strlen(trim($PostValue)) <= 0) { + $PostValue = null; + } - if ($this->Settings->CheckIfKeyExists ()) - { - $this->Settings->UpdateValue ($PostValue); - } - else - { - $this->Settings->InsertValue ($PostValue); - } - } - else - { - $Error = true; - $Message = $this->L10N->t ('Unknown field'); - } - } - else - { - $Error = true; - $Message = $this->L10N->t ('Undefined field'); + if ($this->Settings->checkIfKeyExists()) { + $this->Settings->updateValue($PostValue); + } else { + $this->Settings->insertValue($PostValue); + } + } else { + $Error = true; + $Message = $this->L10N->t('Unknown field'); } + } else { + $Error = true; + $Message = $this->L10N->t('Undefined field'); + } - return new JSONResponse (Array ('ERROR' => $Error, 'MESSAGE' => (strlen (trim ($Message)) == 0 ? (string)$this->L10N->t ('Saved') : $Message))); - } + return new JSONResponse( + array( + 'ERROR' => $Error, + 'MESSAGE' =>(strlen(trim($Message)) == 0 ?(string)$this->L10N->t('Saved') : $Message) + ) + ); + } /** * @NoAdminRequired * @NoCSRFRequired */ - public function Get () - { - \OCP\JSON::setContentTypeHeader ('application/json'); + public function get() + { + \OCP\JSON::setContentTypeHeader('application/json'); - $PersonalSettings = Array (); - foreach ($this->OCDSettingKeys as $SettingKey) - { - $this->Settings->SetKey ($SettingKey); - $PersonalSettings[$SettingKey] = $this->Settings->GetValue (); + $PersonalSettings = array(); + foreach ($this->OCDSettingKeys as $SettingKey) { + $this->Settings->setKey($SettingKey); + $PersonalSettings[$SettingKey] = $this->Settings->getValue(); - // Set default if not set in the database - if (is_null ($PersonalSettings[$SettingKey])) - { - switch ($SettingKey) - { - case 'DownloadsFolder': - $PersonalSettings[$SettingKey] = 'Downloads'; - break; - case 'TorrentsFolder': - $PersonalSettings[$SettingKey] = 'Downloads/Files/Torrents'; - break; - } - } + // Set default if not set in the database + if (is_null($PersonalSettings[$SettingKey])) { + switch ($SettingKey) { + case 'DownloadsFolder': + $PersonalSettings[$SettingKey] = 'Downloads'; + break; + case 'TorrentsFolder': + $PersonalSettings[$SettingKey] = 'Downloads/Files/Torrents'; + break; + } } + } - return new JSONResponse (Array ('ERROR' => false, 'VALS' => $PersonalSettings)); - } -} \ No newline at end of file + return new JSONResponse(array('ERROR' => false, 'VALS' => $PersonalSettings)); + } +} diff --git a/controller/queue.php b/controller/queue.php index a7a2e2b..b0fa0cd 100644 --- a/controller/queue.php +++ b/controller/queue.php @@ -24,605 +24,655 @@ class Queue extends Controller { - private $UserStorage; - private $DbType; - private $CurrentUID; - private $WhichDownloader = 0; - - public function __construct ($AppName, IRequest $Request, $CurrentUID, IL10N $L10N) - { - parent::__construct($AppName, $Request); - - $this->DbType = 0; - if (strcmp (Config::getSystemValue ('dbtype'), 'pgsql') == 0) - { - $this->DbType = 1; - } + private $UserStorage; + private $DbType; + private $CurrentUID; + private $WhichDownloader = 0; - $this->CurrentUID = $CurrentUID; + public function __construct($AppName, IRequest $Request, $CurrentUID, IL10N $L10N) + { + parent::__construct($AppName, $Request); - $Settings = new Settings (); - $Settings->SetKey ('WhichDownloader'); - $this->WhichDownloader = $Settings->GetValue (); - $this->WhichDownloader = is_null ($this->WhichDownloader) ? 0 : (strcmp ($this->WhichDownloader, 'ARIA2') == 0 ? 0 : 1); // 0 means ARIA2, 1 means CURL + $this->DbType = 0; + if (strcmp(Config::getSystemValue('dbtype'), 'pgsql') == 0) { + $this->DbType = 1; + } - $this->L10N = $L10N; - } + $this->CurrentUID = $CurrentUID; - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function Get () - { - \OCP\JSON::setContentTypeHeader ('application/json'); - - try - { - if (isset ($_POST['VIEW']) && strlen (trim ($_POST['VIEW'])) > 0) - { - $Params = Array ($this->CurrentUID); - switch ($_POST['VIEW']) - { - case 'completes': - $StatusReq = '(?)'; - $Params[] = 0; - $IsCleanedReq = '(?, ?)'; - $Params[] = 0; $Params[] = 1; - break; - case 'removed': - $StatusReq = '(?)'; - $Params[] = 4; - $IsCleanedReq = '(?, ?)'; - $Params[] = 0; $Params[] = 1; - break; - case 'actives': - $StatusReq = '(?)'; - $Params[] = 1; - $IsCleanedReq = '(?, ?)'; - $Params[] = 0; $Params[] = 1; - break; - case 'stopped': - $StatusReq = '(?)'; - $Params[] = 3; - $IsCleanedReq = '(?, ?)'; - $Params[] = 0; $Params[] = 1; - break; - case 'waitings': - $StatusReq = '(?)'; - $Params[] = 2; - $IsCleanedReq = '(?, ?)'; - $Params[] = 0; $Params[] = 1; - break; - case 'all': - $StatusReq = '(?, ?, ?, ?, ?)'; - $Params[] = 0; $Params[] = 1; $Params[] = 2; $Params[] = 3; $Params[] = 4; - $IsCleanedReq = '(?, ?)'; - $Params[] = 0; $Params[] = 1; - break; - default: // add view - $StatusReq = '(?, ?, ?, ?)'; - $Params[] = 0; $Params[] = 1; $Params[] = 2; $Params[] = 3; // STATUS - $IsCleanedReq = '(?)'; - $Params[] = 0; // IS_CLEANED - break; - } + $Settings = new Settings(); + $Settings->setKey('WhichDownloader'); + $this->WhichDownloader = $Settings->getValue(); + $this->WhichDownloader = is_null($this->WhichDownloader) ? 0 :(strcmp($this->WhichDownloader, 'ARIA2') == 0 ? 0 : 1); // 0 means ARIA2, 1 means CURL - $SQL = 'SELECT * FROM `*PREFIX*ocdownloader_queue` WHERE `UID` = ? AND `STATUS` IN ' . $StatusReq . ' AND `IS_CLEANED` IN ' . $IsCleanedReq . ' ORDER BY `TIMESTAMP` ASC'; - if ($this->DbType == 1) - { - $SQL = 'SELECT * FROM *PREFIX*ocdownloader_queue WHERE "UID" = ? AND "STATUS" IN ' . $StatusReq . ' AND "IS_CLEANED" IN ' . $IsCleanedReq . ' ORDER BY "TIMESTAMP" ASC'; - } - $Query = \OCP\DB::prepare ($SQL); - $Request = $Query->execute ($Params); - - $Queue = []; - - while ($Row = $Request->fetchRow ()) - { - $Status = ($this->WhichDownloader == 0 ? Aria2::TellStatus ($Row['GID']) : CURL::TellStatus ($Row['GID'])); - $DLStatus = 5; // Error - - if (!is_null ($Status)) - { - if (!isset ($Status['error'])) - { - $Progress = 0; - if ($Status['result']['totalLength'] > 0) - { - $Progress = $Status['result']['completedLength'] / $Status['result']['totalLength']; - } - - $DLStatus = Tools::GetDownloadStatusID ($Status['result']['status']); - $ProgressString = Tools::GetProgressString ($Status['result']['completedLength'], $Status['result']['totalLength'], $Progress); - - $Queue[] = Array ( - 'GID' => $Row['GID'], - 'PROGRESSVAL' => round((($Progress) * 100), 2) . '%', - 'PROGRESS' => (is_null ($ProgressString) ? (string)$this->L10N->t ('N/A') : $ProgressString) . (isset ($Status['result']['bittorrent']) && $Progress < 1 ? ' - ' . $this->L10N->t ('Seeders') . ': ' . $Status['result']['numSeeders'] : (isset ($Status['result']['bittorrent']) && $Progress == 1 ? ' - ' . $this->L10N->t ('Uploaded') . ': ' . Tools::FormatSizeUnits ($Status['result']['uploadLength']) . ' - ' . $this->L10N->t ('Ratio') . ': ' . round (($Status['result']['uploadLength'] / $Status['result']['completedLength']), 2) : '')), - 'STATUS' => isset ($Status['result']['status']) ? $this->L10N->t ($Row['STATUS'] == 4 ? 'Removed' : ucfirst ($Status['result']['status'])) . (isset ($Status['result']['bittorrent']) && $Progress == 1 && $DLStatus != 3 ? ' - ' . $this->L10N->t ('Seeding') : '') : (string)$this->L10N->t ('N/A'), - 'STATUSID' => $Row['STATUS'] == 4 ? 4 : $DLStatus, - 'SPEED' => isset ($Status['result']['downloadSpeed']) ? ($Progress == 1 ? (isset ($Status['result']['bittorrent']) ? ($Status['result']['uploadSpeed'] == 0 ? '--' : Tools::FormatSizeUnits ($Status['result']['uploadSpeed']) . '/s') : '--') : ($DLStatus == 4 ? '--' : Tools::FormatSizeUnits ($Status['result']['downloadSpeed']) . '/s')) : (string)$this->L10N->t ('N/A'), - 'FILENAME' => (mb_strlen ($Row['FILENAME'], "UTF-8") > 40 ? mb_substr ($Row['FILENAME'], 0, 40, "UTF-8") . '...' : $Row['FILENAME']), 'PROTO' => $Row['PROTOCOL'], - 'ISTORRENT' => isset ($Status['result']['bittorrent']) - ); - - if ($Row['STATUS'] != $DLStatus) - { - $SQL = 'UPDATE `*PREFIX*ocdownloader_queue` SET `STATUS` = ? WHERE `UID` = ? AND `GID` = ? AND `STATUS` != ?'; - if ($this->DbType == 1) - { - $SQL = 'UPDATE *PREFIX*ocdownloader_queue SET "STATUS" = ? WHERE "UID" = ? AND "GID" = ? AND "STATUS" != ?'; - } - - $Query = \OCP\DB::prepare ($SQL); - $Result = $Query->execute (Array ( - $DLStatus, - $this->CurrentUID, - $Row['GID'], - 4 - )); - } - } - else - { - $Queue[] = Array ( - 'GID' => $Row['GID'], - 'PROGRESSVAL' => 0, - 'PROGRESS' => (string)$this->L10N->t ('Error, GID not found !'), - 'STATUS' => (string)$this->L10N->t ('N/A'), - 'STATUSID' => $DLStatus, - 'SPEED' => (string)$this->L10N->t ('N/A'), - 'FILENAME' => (mb_strlen ($Row['FILENAME'], "UTF-8") > 40 ? mb_substr ($Row['FILENAME'], 0, 40, "UTF-8") . '...' : $Row['FILENAME']), - 'PROTO' => $Row['PROTOCOL'], - 'ISTORRENT' => isset ($Status['result']['bittorrent']) - ); - } - } - else - { - $Queue[] = Array ( - 'GID' => $Row['GID'], - 'PROGRESSVAL' => 0, - 'PROGRESS' => $this->WhichDownloader == 0 ? (string)$this->L10N->t ('Returned status is null ! Is Aria2c running as a daemon ?') : (string)$this->L10N->t ('Unable to find download status file %s', '/tmp/' . $Row['GID'] . '.curl'), - 'STATUS' => (string)$this->L10N->t ('N/A'), - 'STATUSID' => $DLStatus, - 'SPEED' => (string)$this->L10N->t ('N/A'), - 'FILENAME' => (mb_strlen ($Row['FILENAME'], "UTF-8") > 40 ? mb_substr ($Row['FILENAME'], 0, 40, "UTF-8") . '...' : $Row['FILENAME']), - 'PROTO' => $Row['PROTOCOL'], - 'ISTORRENT' => isset ($Status['result']['bittorrent']) - ); - } - } - return new JSONResponse (Array ('ERROR' => false, 'QUEUE' => $Queue, 'COUNTER' => Tools::GetCounters ($this->DbType, $this->CurrentUID))); - } - } - catch (Exception $E) - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => $E->getMessage ())); - } - } + $this->L10N = $L10N; + } /** * @NoAdminRequired * @NoCSRFRequired */ - public function Count () - { - \OCP\JSON::setContentTypeHeader ('application/json'); - - try - { - return new JSONResponse (Array ('ERROR' => false, 'COUNTER' => Tools::GetCounters ($this->DbType, $this->CurrentUID))); - } - catch (Exception $E) - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => $E->getMessage ())); + public function get() + { + \OCP\JSON::setContentTypeHeader('application/json'); + + try { + if (isset($_POST['VIEW']) && strlen(trim($_POST['VIEW'])) > 0) { + $Params = array($this->CurrentUID); + switch ($_POST['VIEW']) { + case 'completes': + $StatusReq = '(?)'; + $Params[] = 0; + $IsCleanedReq = '(?, ?)'; + $Params[] = 0; + $Params[] = 1; + break; + case 'removed': + $StatusReq = '(?)'; + $Params[] = 4; + $IsCleanedReq = '(?, ?)'; + $Params[] = 0; + $Params[] = 1; + break; + case 'actives': + $StatusReq = '(?)'; + $Params[] = 1; + $IsCleanedReq = '(?, ?)'; + $Params[] = 0; + $Params[] = 1; + break; + case 'stopped': + $StatusReq = '(?)'; + $Params[] = 3; + $IsCleanedReq = '(?, ?)'; + $Params[] = 0; + $Params[] = 1; + break; + case 'waitings': + $StatusReq = '(?)'; + $Params[] = 2; + $IsCleanedReq = '(?, ?)'; + $Params[] = 0; + $Params[] = 1; + break; + case 'all': + $StatusReq = '(?, ?, ?, ?, ?)'; + $Params[] = 0; + $Params[] = 1; + $Params[] = 2; + $Params[] = 3; + $Params[] = 4; + $IsCleanedReq = '(?, ?)'; + $Params[] = 0; + $Params[] = 1; + break; + default: // add view + $StatusReq = '(?, ?, ?, ?)'; + $Params[] = 0; + $Params[] = 1; + $Params[] = 2; + $Params[] = 3; // STATUS + $IsCleanedReq = '(?)'; + $Params[] = 0; // IS_CLEANED + break; + } + + $SQL = 'SELECT * FROM `*PREFIX*ocdownloader_queue` WHERE `UID` = ? AND `STATUS` IN ' + . $StatusReq . ' AND `IS_CLEANED` IN ' . $IsCleanedReq . ' ORDER BY `TIMESTAMP` ASC'; + + if ($this->DbType == 1) { + $SQL = 'SELECT * FROM *PREFIX*ocdownloader_queue WHERE "UID" = ? AND "STATUS" IN ' + . $StatusReq . ' AND "IS_CLEANED" IN ' . $IsCleanedReq . ' ORDER BY "TIMESTAMP" ASC'; + } + $Query = \OCP\DB::prepare($SQL); + $Request = $Query->execute($Params); + + $Queue = []; + + while ($Row = $Request->fetchRow()) { + $Status =($this->WhichDownloader == 0 + ?Aria2::tellStatus($Row['GID']):CURL::tellStatus($Row['GID'])); + $DLStatus = 5; // Error + + if (!is_null($Status)) { + if (!isset($Status['error'])) { + $Progress = 0; + if ($Status['result']['totalLength'] > 0) { + $Progress = $Status['result']['completedLength'] / $Status['result']['totalLength']; + } + + $DLStatus = Tools::getDownloadStatusID($Status['result']['status']); + $ProgressString = Tools::getProgressString( + $Status['result']['completedLength'], + $Status['result']['totalLength'], + $Progress + ); + + $Queue[] = array( + 'GID' => $Row['GID'], + 'PROGRESSVAL' => round((($Progress) * 100), 2) . '%', + 'PROGRESS' =>(is_null($ProgressString) + ?(string)$this->L10N->t('N/A') + :$ProgressString).(isset($Status['result']['bittorrent']) && $Progress < 1 + ?' - '.$this->L10N->t('Seeders').': '.$Status['result']['numSeeders'] + :(isset($Status['result']['bittorrent']) && $Progress == 1 + ?' - '.$this->L10N->t('Uploaded').': '.Tools::formatSizeUnits($Status['result']['uploadLength']).' - ' . $this->L10N->t('Ratio') . ': ' . round(($Status['result']['uploadLength'] / $Status['result']['completedLength']), 2) : '')), + 'STATUS' => isset($Status['result']['status']) + ? $this->L10N->t( + $Row['STATUS'] == 4?'Removed':ucfirst($Status['result']['status']) + ).(isset($Status['result']['bittorrent']) && $Progress == 1 && $DLStatus != 3?' - ' + .$this->L10N->t('Seeding') : '') :(string)$this->L10N->t('N/A'), + 'STATUSID' => $Row['STATUS'] == 4 ? 4 : $DLStatus, + 'SPEED' => isset($Status['result']['downloadSpeed']) + ?($Progress == 1 + ?(isset($Status['result']['bittorrent']) + ?($Status['result']['uploadSpeed'] == 0 + ?'--' + :Tools::formatSizeUnits($Status['result']['uploadSpeed']).'/s') + :'--') + :($DLStatus == 4 + ?'--' + :Tools::formatSizeUnits($Status['result']['downloadSpeed']).'/s')) + :(string)$this->L10N->t('N/A'), + 'FILENAME' => $Row['FILENAME'], + 'FILENAME_SHORT' => Tools::getShortFilename($Row['FILENAME']), + 'PROTO' => $Row['PROTOCOL'], + 'ISTORRENT' => isset($Status['result']['bittorrent']) + ); + + if ($Row['STATUS'] != $DLStatus) { + $SQL = 'UPDATE `*PREFIX*ocdownloader_queue` + SET `STATUS` = ? WHERE `UID` = ? AND `GID` = ? AND `STATUS` != ?'; + if ($this->DbType == 1) { + $SQL = 'UPDATE *PREFIX*ocdownloader_queue + SET "STATUS" = ? WHERE "UID" = ? AND "GID" = ? AND "STATUS" != ?'; + } + + $Query = \OCP\DB::prepare($SQL); + $Result = $Query->execute(array( + $DLStatus, + $this->CurrentUID, + $Row['GID'], + 4 + )); + } + } else { + $Queue[] = array( + 'GID' => $Row['GID'], + 'PROGRESSVAL' => 0, + 'PROGRESS' =>(string)$this->L10N->t('Error, GID not found !'), + 'STATUS' =>(string)$this->L10N->t('N/A'), + 'STATUSID' => $DLStatus, + 'SPEED' =>(string)$this->L10N->t('N/A'), + 'FILENAME' => $Row['FILENAME'], + 'FILENAME_SHORT' => Tools::getShortFilename($Row['FILENAME']), + 'PROTO' => $Row['PROTOCOL'], + 'ISTORRENT' => isset($Status['result']['bittorrent']) + ); + } + } else { + $Queue[] = array( + 'GID' => $Row['GID'], + 'PROGRESSVAL' => 0, + 'PROGRESS' => $this->WhichDownloader==0 + ?(string)$this->L10N->t('Returned status is null ! Is Aria2c running as a daemon ?') + :(string)$this->L10N->t('Unable to find download status file %s', '/tmp/' + .$Row['GID'].'.curl'), + 'STATUS' =>(string)$this->L10N->t('N/A'), + 'STATUSID' => $DLStatus, + 'SPEED' =>(string)$this->L10N->t('N/A'), + 'FILENAME' => $Row['FILENAME'], + 'FILENAME_SHORT' => Tools::getShortFilename($Row['FILENAME']), + 'PROTO' => $Row['PROTOCOL'], + 'ISTORRENT' => isset($Status['result']['bittorrent']) + ); + } + } + return new JSONResponse( + array( + 'ERROR' => false, + 'QUEUE' => $Queue, + 'COUNTER' => Tools::getCounters($this->DbType, $this->CurrentUID) + ) + ); } - } + } catch (Exception $E) { + return new JSONResponse(array('ERROR' => true, 'MESSAGE' => $E->getMessage())); + } + } /** * @NoAdminRequired * @NoCSRFRequired */ - public function Pause () - { - \OCP\JSON::setContentTypeHeader ('application/json'); - - try - { - if ($this->WhichDownloader == 0) - { - if (isset ($_POST['GID']) && strlen (trim ($_POST['GID'])) > 0) - { - $Status = Aria2::TellStatus ($_POST['GID']); - - $Pause['result'] = $_POST['GID']; - if (!isset ($Status['error']) && strcmp ($Status['result']['status'], 'error') != 0 && strcmp ($Status['result']['status'], 'complete') != 0 && strcmp ($Status['result']['status'], 'active') == 0) - { - $Pause = Aria2::Pause ($_POST['GID']); - } - - if (strcmp ($Pause['result'], $_POST['GID']) == 0) - { - $SQL = 'UPDATE `*PREFIX*ocdownloader_queue` SET `STATUS` = ? WHERE `UID` = ? AND `GID` = ?'; - if ($this->DbType == 1) - { - $SQL = 'UPDATE *PREFIX*ocdownloader_queue SET "STATUS" = ? WHERE "UID" = ? AND "GID" = ?'; - } - - $Query = \OCP\DB::prepare ($SQL); - $Result = $Query->execute (Array ( - 3, - $this->CurrentUID, - $_POST['GID'] - )); - - return new JSONResponse (Array ('ERROR' => false, 'MESSAGE' => (string)$this->L10N->t ('The download has been paused'))); - } - else - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ('An error occurred while pausing the download'))); - } - } - else - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ('Bad GID'))); - } - } - } - catch (Exception $E) - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => $E->getMessage ())); - } - } + public function count() + { + \OCP\JSON::setContentTypeHeader('application/json'); + + try { + return new JSONResponse( + array('ERROR' => false, 'COUNTER' => Tools::getCounters($this->DbType, $this->CurrentUID)) + ); + } catch (Exception $E) { + return new JSONResponse(array('ERROR' => true, 'MESSAGE' => $E->getMessage())); + } + } /** * @NoAdminRequired * @NoCSRFRequired */ - public function UnPause () - { - \OCP\JSON::setContentTypeHeader ('application/json'); - - try - { - if ($this->WhichDownloader == 0) - { - if (isset ($_POST['GID']) && strlen (trim ($_POST['GID'])) > 0) - { - $Status = Aria2::TellStatus ($_POST['GID']); - - $UnPause['result'] = $_POST['GID']; - if (!isset ($Status['error']) && strcmp ($Status['result']['status'], 'error') != 0 && strcmp ($Status['result']['status'], 'complete') != 0 && strcmp ($Status['result']['status'], 'paused') == 0) - { - $UnPause = Aria2::Unpause ($_POST['GID']); - } - - if (strcmp ($UnPause['result'], $_POST['GID']) == 0) - { - $SQL = 'UPDATE `*PREFIX*ocdownloader_queue` SET `STATUS` = ? WHERE `UID` = ? AND `GID` = ?'; - if ($this->DbType == 1) - { - $SQL = 'UPDATE *PREFIX*ocdownloader_queue SET "STATUS" = ? WHERE "UID" = ? AND "GID" = ?'; - } - - $Query = \OCP\DB::prepare ($SQL); - $Result = $Query->execute (Array ( - 1, - $this->CurrentUID, - $_POST['GID'] - )); - - return new JSONResponse (Array ('ERROR' => false, 'MESSAGE' => (string)$this->L10N->t ('The download has been unpaused'))); - } - else - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ('An error occurred while unpausing the download'))); - } - } - else - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ('Bad GID'))); + public function pause() + { + \OCP\JSON::setContentTypeHeader('application/json'); + + try { + if ($this->WhichDownloader == 0) { + if (isset($_POST['GID']) && strlen(trim($_POST['GID'])) > 0) { + $Status = Aria2::tellStatus($_POST['GID']); + + $Pause['result'] = $_POST['GID']; + if (!isset($Status['error']) && strcmp($Status['result']['status'], 'error') != 0 + && strcmp($Status['result']['status'], 'complete') != 0 + && strcmp($Status['result']['status'], 'active') == 0) { + $Pause = Aria2::pause($_POST['GID']); + } + + if (strcmp($Pause['result'], $_POST['GID']) == 0) { + $SQL = 'UPDATE `*PREFIX*ocdownloader_queue` SET `STATUS` = ? WHERE `UID` = ? AND `GID` = ?'; + if ($this->DbType == 1) { + $SQL = 'UPDATE *PREFIX*ocdownloader_queue SET "STATUS" = ? WHERE "UID" = ? AND "GID" = ?'; } - } - } - catch (Exception $E) - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => $E->getMessage ())); + + $Query = \OCP\DB::prepare($SQL); + $Result = $Query->execute(array( + 3, + $this->CurrentUID, + $_POST['GID'] + )); + + return new JSONResponse( + array('ERROR' => false, 'MESSAGE' =>(string)$this->L10N->t('The download has been paused')) + ); + } else { + return new JSONResponse( + array( + 'ERROR' => true, + 'MESSAGE' =>(string)$this->L10N->t('An error occurred while pausing the download') + ) + ); + } + } else { + return new JSONResponse(array('ERROR' => true, 'MESSAGE' =>(string)$this->L10N->t('Bad GID'))); + } } - } + } catch (Exception $E) { + return new JSONResponse(array('ERROR' => true, 'MESSAGE' => $E->getMessage())); + } + } /** * @NoAdminRequired * @NoCSRFRequired */ - public function Hide () - { - \OCP\JSON::setContentTypeHeader ('application/json'); - - try - { - if (isset ($_POST['GID']) && strlen (trim ($_POST['GID'])) > 0) - { - $SQL = 'UPDATE `*PREFIX*ocdownloader_queue` SET `IS_CLEANED` = ? WHERE `UID` = ? AND `GID` = ?'; - if ($this->DbType == 1) - { - $SQL = 'UPDATE *PREFIX*ocdownloader_queue SET "IS_CLEANED" = ? WHERE "UID" = ? AND "GID" = ?'; + public function unPause() + { + \OCP\JSON::setContentTypeHeader('application/json'); + + try { + if ($this->WhichDownloader == 0) { + if (isset($_POST['GID']) && strlen(trim($_POST['GID'])) > 0) { + $Status = Aria2::tellStatus($_POST['GID']); + + $UnPause['result'] = $_POST['GID']; + if (!isset($Status['error']) && strcmp($Status['result']['status'], 'error') != 0 + && strcmp($Status['result']['status'], 'complete') != 0 + && strcmp($Status['result']['status'], 'paused') == 0) { + $UnPause = Aria2::unpause($_POST['GID']); + } + + if (strcmp($UnPause['result'], $_POST['GID']) == 0) { + $SQL = 'UPDATE `*PREFIX*ocdownloader_queue` SET `STATUS` = ? WHERE `UID` = ? AND `GID` = ?'; + if ($this->DbType == 1) { + $SQL = 'UPDATE *PREFIX*ocdownloader_queue SET "STATUS" = ? WHERE "UID" = ? AND "GID" = ?'; } - $Query = \OCP\DB::prepare ($SQL); - $Result = $Query->execute (Array ( + $Query = \OCP\DB::prepare($SQL); + $Result = $Query->execute(array( 1, $this->CurrentUID, $_POST['GID'] )); - return new JSONResponse (Array ('ERROR' => false, 'MESSAGE' => (string)$this->L10N->t ('The download has been cleaned'))); - } - else - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ('Bad GID'))); - } + return new JSONResponse( + array( + 'ERROR' => false, + 'MESSAGE' =>(string)$this->L10N->t('The download has been unpaused') + ) + ); + } else { + return new JSONResponse( + array( + 'ERROR' => true, + 'MESSAGE' =>(string)$this->L10N->t('An error occurred while unpausing the download') + ) + ); + } + } else { + return new JSONResponse(array('ERROR' => true, 'MESSAGE' =>(string)$this->L10N->t('Bad GID'))); + } } - catch (Exception $E) - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => $E->getMessage ())); - } - } + } catch (Exception $E) { + return new JSONResponse(array('ERROR' => true, 'MESSAGE' => $E->getMessage())); + } + } /** * @NoAdminRequired * @NoCSRFRequired */ - public function HideAll () - { - \OCP\JSON::setContentTypeHeader ('application/json'); - - try - { - if (isset ($_POST['GIDS']) && count ($_POST['GIDS']) > 0) - { - $Queue = Array (); - - foreach ($_POST['GIDS'] as $GID) - { - $SQL = 'UPDATE `*PREFIX*ocdownloader_queue` SET `IS_CLEANED` = ? WHERE `UID` = ? AND `GID` = ?'; - if ($this->DbType == 1) - { - $SQL = 'UPDATE *PREFIX*ocdownloader_queue SET "IS_CLEANED" = ? WHERE "UID" = ? AND "GID" = ?'; - } - - $Query = \OCP\DB::prepare ($SQL); - $Result = $Query->execute (Array ( - 1, - $this->CurrentUID, - $GID - )); - - $Queue[] = Array ( - 'GID' => $GID - ); - } - - return new JSONResponse (Array ('ERROR' => false, 'MESSAGE' => (string)$this->L10N->t ('All downloads have been cleaned'), 'QUEUE' => $Queue)); - } - else - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ('No GIDS in the download queue'))); - } + public function hide() + { + \OCP\JSON::setContentTypeHeader('application/json'); + + try { + if (isset($_POST['GID']) && strlen(trim($_POST['GID'])) > 0) { + $SQL = 'UPDATE `*PREFIX*ocdownloader_queue` SET `IS_CLEANED` = ? WHERE `UID` = ? AND `GID` = ?'; + if ($this->DbType == 1) { + $SQL = 'UPDATE *PREFIX*ocdownloader_queue SET "IS_CLEANED" = ? WHERE "UID" = ? AND "GID" = ?'; + } + + $Query = \OCP\DB::prepare($SQL); + $Result = $Query->execute(array( + 1, + $this->CurrentUID, + $_POST['GID'] + )); + + return new JSONResponse( + array('ERROR' => false, 'MESSAGE' =>(string)$this->L10N->t('The download has been cleaned')) + ); + } else { + return new JSONResponse(array('ERROR' => true, 'MESSAGE' =>(string)$this->L10N->t('Bad GID'))); } - catch (Exception $E) - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => $E->getMessage ())); - } - } + } catch (Exception $E) { + return new JSONResponse(array('ERROR' => true, 'MESSAGE' => $E->getMessage())); + } + } /** * @NoAdminRequired * @NoCSRFRequired */ - public function Remove () - { - \OCP\JSON::setContentTypeHeader ('application/json'); - - try - { - if (isset ($_POST['GID']) && strlen (trim ($_POST['GID'])) > 0) - { - $Status = ($this->WhichDownloader == 0 ? Aria2::TellStatus ($_POST['GID']) : CURL::TellStatus ($_POST['GID'])); - - $Remove['result'] = $_POST['GID']; - if (!isset ($Status['error']) && strcmp ($Status['result']['status'], 'error') != 0 && strcmp ($Status['result']['status'], 'complete') != 0) - { - $Remove = ($this->WhichDownloader == 0 ? Aria2::Remove ($_POST['GID']) : CURL::Remove ($Status['result'])); - } - elseif ($this->WhichDownloader != 0 && strcmp ($Status['result']['status'], 'complete') == 0) - { - $Remove = CURL::Remove ($Status['result']); - } - - if (!is_null ($Remove) && strcmp ($Remove['result'], $_POST['GID']) == 0) - { - $SQL = 'UPDATE `*PREFIX*ocdownloader_queue` SET `STATUS` = ?, `IS_CLEANED` = ? WHERE `UID` = ? AND `GID` = ?'; - if ($this->DbType == 1) - { - $SQL = 'UPDATE *PREFIX*ocdownloader_queue SET "STATUS" = ?, "IS_CLEANED" = ? WHERE "UID" = ? AND "GID" = ?'; - } - - $Query = \OCP\DB::prepare ($SQL); - $Result = $Query->execute (Array ( - 4, 1, - $this->CurrentUID, - $_POST['GID'] - )); - - return new JSONResponse (Array ('ERROR' => false, 'MESSAGE' => (string)$this->L10N->t ('The download has been removed'))); - } - else - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ('An error occurred while removing the download'))); - } - } - else - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ('Bad GID'))); - } + public function hideAll() + { + \OCP\JSON::setContentTypeHeader('application/json'); + + try { + if (isset($_POST['GIDS']) && count($_POST['GIDS']) > 0) { + $Queue = array(); + + foreach ($_POST['GIDS'] as $GID) { + $SQL = 'UPDATE `*PREFIX*ocdownloader_queue` SET `IS_CLEANED` = ? WHERE `UID` = ? AND `GID` = ?'; + if ($this->DbType == 1) { + $SQL = 'UPDATE *PREFIX*ocdownloader_queue SET "IS_CLEANED" = ? WHERE "UID" = ? AND "GID" = ?'; + } + + $Query = \OCP\DB::prepare($SQL); + $Result = $Query->execute(array( + 1, + $this->CurrentUID, + $GID + )); + + $Queue[] = array( + 'GID' => $GID + ); + } + + return new JSONResponse( + array( + 'ERROR' => false, + 'MESSAGE' =>(string)$this->L10N->t('All downloads have been cleaned'), + 'QUEUE' => $Queue + ) + ); + } else { + return new JSONResponse( + array( + 'ERROR' => true, + 'MESSAGE' =>(string)$this->L10N->t('No GIDS in the download queue') + ) + ); } - catch (Exception $E) - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => $E->getMessage ())); - } - } + } catch (Exception $E) { + return new JSONResponse(array('ERROR' => true, 'MESSAGE' => $E->getMessage())); + } + } /** * @NoAdminRequired * @NoCSRFRequired */ - public function RemoveAll () - { - \OCP\JSON::setContentTypeHeader ('application/json'); - - try - { - if (isset ($_POST['GIDS']) && count ($_POST['GIDS']) > 0) - { - $GIDS = Array (); - - foreach ($_POST['GIDS'] as $GID) - { - $Status = ($this->WhichDownloader == 0 ? Aria2::TellStatus ($GID) : CURL::TellStatus ($GID)); - $Remove = Array ('result' => $GID); - - if (!isset ($Status['error']) && strcmp ($Status['result']['status'], 'error') != 0 && strcmp ($Status['result']['status'], 'complete') != 0) - { - $Remove = ($this->WhichDownloader == 0 ? Aria2::Remove ($GID) : CURL::Remove ($Status['result'])); - } - - if (!is_null ($Remove) && strcmp ($Remove['result'], $GID) == 0) - { - $SQL = 'UPDATE `*PREFIX*ocdownloader_queue` SET `STATUS` = ?, `IS_CLEANED` = ? WHERE `UID` = ? AND `GID` = ?'; - if ($this->DbType == 1) - { - $SQL = 'UPDATE *PREFIX*ocdownloader_queue SET "STATUS" = ?, "IS_CLEANED" = ? WHERE "UID" = ? AND "GID" = ?'; - } - - $Query = \OCP\DB::prepare ($SQL); - $Result = $Query->execute (Array ( - 4, 1, - $this->CurrentUID, - $GID - )); - - $GIDS[] = $GID; - } - } - - return new JSONResponse (Array ('ERROR' => false, 'MESSAGE' => (string)$this->L10N->t ('All downloads have been removed'), 'GIDS' => $GIDS)); - } - else - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ('No GIDS in the download queue'))); - } + public function remove() + { + \OCP\JSON::setContentTypeHeader('application/json'); + + try { + if (isset($_POST['GID']) && strlen(trim($_POST['GID'])) > 0) { + $Status =( + $this->WhichDownloader == 0 + ?Aria2::tellStatus($_POST['GID']) + :CURL::tellStatus($_POST['GID']) + ); + + $Remove['result'] = $_POST['GID']; + if (!isset($Status['error']) && strcmp($Status['result']['status'], 'error') != 0 + && strcmp($Status['result']['status'], 'complete') != 0) { + $Remove =( + $this->WhichDownloader == 0 + ? Aria2::remove($_POST['GID']) + :CURL::remove($Status['result']) + ); + } elseif ($this->WhichDownloader != 0 && strcmp($Status['result']['status'], 'complete') == 0) { + $Remove = CURL::remove($Status['result']); + } + + if (!is_null($Remove) && strcmp($Remove['result'], $_POST['GID']) == 0) { + $SQL = 'UPDATE `*PREFIX*ocdownloader_queue` + SET `STATUS` = ?, `IS_CLEANED` = ? WHERE `UID` = ? AND `GID` = ?'; + if ($this->DbType == 1) { + $SQL = 'UPDATE *PREFIX*ocdownloader_queue + SET "STATUS" = ?, "IS_CLEANED" = ? WHERE "UID" = ? AND "GID" = ?'; + } + + $Query = \OCP\DB::prepare($SQL); + $Result = $Query->execute(array( + 4, 1, + $this->CurrentUID, + $_POST['GID'] + )); + + return new JSONResponse( + array( + 'ERROR' => false, + 'MESSAGE' =>(string)$this->L10N->t('The download has been removed') + ) + ); + } else { + return new JSONResponse( + array( + 'ERROR' => true, + 'MESSAGE' =>(string)$this->L10N->t('An error occurred while removing the download') + ) + ); + } + } else { + return new JSONResponse(array('ERROR' => true, 'MESSAGE' =>(string)$this->L10N->t('Bad GID'))); } - catch (Exception $E) - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => $E->getMessage ())); - } - } + } catch (Exception $E) { + return new JSONResponse(array('ERROR' => true, 'MESSAGE' => $E->getMessage())); + } + } /** * @NoAdminRequired * @NoCSRFRequired */ - public function CompletelyRemove () - { - \OCP\JSON::setContentTypeHeader ('application/json'); - - try - { - if (isset ($_POST['GID']) && strlen (trim ($_POST['GID'])) > 0) - { - $Status = ($this->WhichDownloader == 0 ? Aria2::TellStatus ($_POST['GID']) : CURL::TellStatus ($_POST['GID'])); - - if (!isset ($Status['error']) && strcmp ($Status['result']['status'], 'removed') == 0) - { - $Remove = ($this->WhichDownloader == 0 ? Aria2::RemoveDownloadResult ($_POST['GID']) : CURL::RemoveDownloadResult ($_POST['GID'])); - } - - $SQL = 'DELETE FROM `*PREFIX*ocdownloader_queue` WHERE `UID` = ? AND `GID` = ?'; - if ($this->DbType == 1) - { - $SQL = 'DELETE FROM *PREFIX*ocdownloader_queue WHERE "UID" = ? AND "GID" = ?'; + public function removeAll() + { + \OCP\JSON::setContentTypeHeader('application/json'); + + try { + if (isset($_POST['GIDS']) && count($_POST['GIDS']) > 0) { + $GIDS = array(); + + foreach ($_POST['GIDS'] as $GID) { + $Status =($this->WhichDownloader == 0 ? Aria2::tellStatus($GID) : CURL::tellStatus($GID)); + $Remove = array('result' => $GID); + + if (!isset($Status['error']) && strcmp($Status['result']['status'], 'error') != 0 + && strcmp($Status['result']['status'], 'complete') != 0) { + $Remove =($this->WhichDownloader == 0 ? Aria2::remove($GID) : CURL::remove($Status['result'])); + } + + if (!is_null($Remove) && strcmp($Remove['result'], $GID) == 0) { + $SQL = 'UPDATE `*PREFIX*ocdownloader_queue` + SET `STATUS` = ?, `IS_CLEANED` = ? WHERE `UID` = ? AND `GID` = ?'; + if ($this->DbType == 1) { + $SQL = 'UPDATE *PREFIX*ocdownloader_queue + SET "STATUS" = ?, "IS_CLEANED" = ? WHERE "UID" = ? AND "GID" = ?'; } - $Query = \OCP\DB::prepare ($SQL); - $Result = $Query->execute (Array ( + $Query = \OCP\DB::prepare($SQL); + $Result = $Query->execute(array( + 4, 1, $this->CurrentUID, - $_POST['GID'] + $GID )); - return new JSONResponse (Array ('ERROR' => false, 'MESSAGE' => (string)$this->L10N->t ('The download has been totally removed'))); - } - else - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ('Bad GID'))); - } - } - catch (Exception $E) - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => $E->getMessage ())); + $GIDS[] = $GID; + } + } + + return new JSONResponse( + array( + 'ERROR' => false, + 'MESSAGE' =>(string)$this->L10N->t('All downloads have been removed'), + 'GIDS' => $GIDS + ) + ); + } else { + return new JSONResponse( + array( + 'ERROR' => true, + 'MESSAGE' =>(string)$this->L10N->t('No GIDS in the download queue') + ) + ); } - } + } catch (Exception $E) { + return new JSONResponse(array('ERROR' => true, 'MESSAGE' => $E->getMessage())); + } + } /** * @NoAdminRequired * @NoCSRFRequired */ - public function CompletelyRemoveAll () - { - \OCP\JSON::setContentTypeHeader ('application/json'); - - try - { - if (isset ($_POST['GIDS']) && count ($_POST['GIDS']) > 0) - { - $GIDS = Array (); - - foreach ($_POST['GIDS'] as $GID) - { - $Status = ($this->WhichDownloader == 0 ? Aria2::TellStatus ($GID) : CURL::TellStatus ($GID)); - - if (!isset ($Status['error']) && strcmp ($Status['result']['status'], 'removed') == 0) - { - $Remove = ($this->WhichDownloader == 0 ? Aria2::RemoveDownloadResult ($GID) : CURL::RemoveDownloadResult ($GID)); - } - - $SQL = 'DELETE FROM `*PREFIX*ocdownloader_queue` WHERE `UID` = ? AND `GID` = ?'; - if ($this->DbType == 1) - { - $SQL = 'DELETE FROM *PREFIX*ocdownloader_queue WHERE "UID" = ? AND "GID" = ?'; - } - - $Query = \OCP\DB::prepare ($SQL); - $Result = $Query->execute (Array ( - $this->CurrentUID, - $GID - )); - - $GIDS[] = $GID; - } - - return new JSONResponse (Array ('ERROR' => false, 'MESSAGE' => (string)$this->L10N->t ('The download has been totally removed'), 'GIDS' => $GIDS)); - } - else - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ('Bad GID'))); - } + public function completelyRemove() + { + \OCP\JSON::setContentTypeHeader('application/json'); + + try { + if (isset($_POST['GID']) && strlen(trim($_POST['GID'])) > 0) { + $Status =( + $this->WhichDownloader == 0 + ?Aria2::tellStatus($_POST['GID']) + :CURL::tellStatus($_POST['GID']) + ); + + if (!isset($Status['error']) && strcmp($Status['result']['status'], 'removed') == 0) { + $Remove =( + $this->WhichDownloader == 0 + ? Aria2::removeDownloadResult($_POST['GID']) + :CURL::removeDownloadResult($_POST['GID']) + ); + } + + $SQL = 'DELETE FROM `*PREFIX*ocdownloader_queue` WHERE `UID` = ? AND `GID` = ?'; + if ($this->DbType == 1) { + $SQL = 'DELETE FROM *PREFIX*ocdownloader_queue WHERE "UID" = ? AND "GID" = ?'; + } + + $Query = \OCP\DB::prepare($SQL); + $Result = $Query->execute(array( + $this->CurrentUID, + $_POST['GID'] + )); + + return new JSONResponse( + array( + 'ERROR' => false, + 'MESSAGE' =>(string)$this->L10N->t('The download has been totally removed') + ) + ); + } else { + return new JSONResponse(array('ERROR' => true, 'MESSAGE' =>(string)$this->L10N->t('Bad GID'))); } - catch (Exception $E) - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => $E->getMessage ())); + } catch (Exception $E) { + return new JSONResponse(array('ERROR' => true, 'MESSAGE' => $E->getMessage())); + } + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function completelyRemoveAll() + { + \OCP\JSON::setContentTypeHeader('application/json'); + + try { + if (isset($_POST['GIDS']) && count($_POST['GIDS']) > 0) { + $GIDS = array(); + + foreach ($_POST['GIDS'] as $GID) { + $Status =($this->WhichDownloader == 0 ? Aria2::tellStatus($GID) : CURL::tellStatus($GID)); + + if (!isset($Status['error']) && strcmp($Status['result']['status'], 'removed') == 0) { + $Remove =( + $this->WhichDownloader == 0 + ?Aria2::removeDownloadResult($GID) + :CURL::removeDownloadResult($GID) + ); + } + + $SQL = 'DELETE FROM `*PREFIX*ocdownloader_queue` WHERE `UID` = ? AND `GID` = ?'; + if ($this->DbType == 1) { + $SQL = 'DELETE FROM *PREFIX*ocdownloader_queue WHERE "UID" = ? AND "GID" = ?'; + } + + $Query = \OCP\DB::prepare($SQL); + $Result = $Query->execute(array( + $this->CurrentUID, + $GID + )); + + $GIDS[] = $GID; + } + + return new JSONResponse( + array( + 'ERROR' => false, + 'MESSAGE' =>(string)$this->L10N->t('The download has been totally removed'), + 'GIDS' => $GIDS + ) + ); + } else { + return new JSONResponse(array('ERROR' => true, 'MESSAGE' =>(string)$this->L10N->t('Bad GID'))); } - } + } catch (Exception $E) { + return new JSONResponse(array('ERROR' => true, 'MESSAGE' => $E->getMessage())); + } + } } diff --git a/controller/updater.php b/controller/updater.php index f61265b..1924708 100644 --- a/controller/updater.php +++ b/controller/updater.php @@ -22,43 +22,43 @@ class Updater extends Controller { - private $Settings = null; - private $Allow = false; - private $L10N = null; + private $Settings = null; + private $Allow = false; + private $L10N = null; - public function __construct ($AppName, IRequest $Request, IL10N $L10N) - { - $this->L10N = $L10N; - $this->Allow = Tools::CanCheckForUpdate (); - } + public function __construct($AppName, IRequest $Request, IL10N $L10N) + { + $this->L10N = $L10N; + $this->Allow = Tools::canCheckForUpdate(); + } /** * @AdminRequired * @NoCSRFRequired */ - public function Check () - { - \OCP\JSON::setContentTypeHeader ('application/json'); + public function check() + { + \OCP\JSON::setContentTypeHeader('application/json'); - if ($this->Allow) - { - try - { - $LastVersionNumber = Tools::GetLastVersionNumber (); - $AppVersion = \OCP\App::getAppVersion ('ocdownloader'); + if ($this->Allow) { + try { + $LastVersionNumber = Tools::getLastVersionNumber(); + $AppVersion = \OCP\App::getAppVersion('ocdownloader'); - $Response = Array ('ERROR' => false, 'RESULT' => version_compare ($AppVersion, $LastVersionNumber, '<')); - } - catch (Exception $E) - { - $Response = Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ('Error while checking application version on GitHub')); - } - } - else - { - $Response = Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ('You are not allowed to check for application updates')); + $Response = array('ERROR' => false, 'RESULT' => version_compare($AppVersion, $LastVersionNumber, '<')); + } catch (Exception $E) { + $Response = array( + 'ERROR' => true, + 'MESSAGE' =>(string)$this->L10N->t('Error while checking application version on GitHub') + ); } + } else { + $Response = array( + 'ERROR' => true, + 'MESSAGE' =>(string)$this->L10N->t('You are not allowed to check for application updates') + ); + } - return new JSONResponse ($Response); - } -} \ No newline at end of file + return new JSONResponse($Response); + } +} diff --git a/controller/ytdownloader.php b/controller/ytdownloader.php index c6bf3e3..7b3ceb5 100644 --- a/controller/ytdownloader.php +++ b/controller/ytdownloader.php @@ -25,220 +25,223 @@ class YTDownloader extends Controller { - private $AbsoluteDownloadsFolder = null; - private $DownloadsFolder = null; - private $DbType = 0; - private $YTDLBinary = null; - private $ProxyAddress = null; - private $ProxyPort = 0; - private $ProxyUser = null; - private $ProxyPasswd = null; - private $ProxyOnlyWithYTDL = null; - private $WhichDownloader = 0; - private $CurrentUID = null; - private $L10N = null; - private $AllowProtocolYT = null; - private $MaxDownloadSpeed = null; - - public function __construct ($AppName, IRequest $Request, $CurrentUID, IL10N $L10N) - { - parent::__construct ($AppName, $Request); - - if (strcmp (Config::getSystemValue ('dbtype'), 'pgsql') == 0) - { - $this->DbType = 1; - } - - $this->CurrentUID = $CurrentUID; - - $Settings = new Settings (); - $Settings->SetKey ('YTDLBinary'); - $YTDLBinary = $Settings->GetValue (); - - $this->YTDLBinary = '/usr/local/bin/youtube-dl'; // default path - if (!is_null ($YTDLBinary)) - { - $this->YTDLBinary = $YTDLBinary; - } - - $Settings->SetKey ('ProxyAddress'); - $this->ProxyAddress = $Settings->GetValue (); - $Settings->SetKey ('ProxyPort'); - $this->ProxyPort = intval ($Settings->GetValue ()); - $Settings->SetKey ('ProxyUser'); - $this->ProxyUser = $Settings->GetValue (); - $Settings->SetKey ('ProxyPasswd'); - $this->ProxyPasswd = $Settings->GetValue (); - $Settings->SetKey ('WhichDownloader'); - $this->WhichDownloader = $Settings->GetValue (); - $this->WhichDownloader = is_null ($this->WhichDownloader) ? 0 : (strcmp ($this->WhichDownloader, 'ARIA2') == 0 ? 0 : 1); // 0 means ARIA2, 1 means CURL - $Settings->SetKey ('MaxDownloadSpeed'); - $this->MaxDownloadSpeed = $Settings->GetValue (); - $Settings->SetKey ('AllowProtocolYT'); - $this->AllowProtocolYT = $Settings->GetValue (); - $this->AllowProtocolYT = is_null ($this->AllowProtocolYT) ? true : strcmp ($this->AllowProtocolYT, 'Y') == 0; - - $Settings->SetTable ('personal'); - $Settings->SetUID ($this->CurrentUID); - $Settings->SetKey ('DownloadsFolder'); - $this->DownloadsFolder = $Settings->GetValue (); - - $this->DownloadsFolder = '/' . (is_null ($this->DownloadsFolder) ? 'Downloads' : $this->DownloadsFolder); - $this->AbsoluteDownloadsFolder = \OC\Files\Filesystem::getLocalFolder ($this->DownloadsFolder); - - $this->L10N = $L10N; - } + private $AbsoluteDownloadsFolder = null; + private $DownloadsFolder = null; + private $DbType = 0; + private $YTDLBinary = null; + private $ProxyAddress = null; + private $ProxyPort = 0; + private $ProxyUser = null; + private $ProxyPasswd = null; + private $ProxyOnlyWithYTDL = null; + private $WhichDownloader = 0; + private $CurrentUID = null; + private $L10N = null; + private $AllowProtocolYT = null; + private $MaxDownloadSpeed = null; + + public function __construct($AppName, IRequest $Request, $CurrentUID, IL10N $L10N) + { + parent::__construct($AppName, $Request); + + if (strcmp(Config::getSystemValue('dbtype'), 'pgsql') == 0) { + $this->DbType = 1; + } + + $this->CurrentUID = $CurrentUID; + + $Settings = new Settings(); + $Settings->setKey('YTDLBinary'); + $YTDLBinary = $Settings->getValue(); + + $this->YTDLBinary = '/usr/local/bin/youtube-dl'; // default path + if (!is_null($YTDLBinary)) { + $this->YTDLBinary = $YTDLBinary; + } + + $Settings->setKey('ProxyAddress'); + $this->ProxyAddress = $Settings->getValue(); + $Settings->setKey('ProxyPort'); + $this->ProxyPort = intval($Settings->getValue()); + $Settings->setKey('ProxyUser'); + $this->ProxyUser = $Settings->getValue(); + $Settings->setKey('ProxyPasswd'); + $this->ProxyPasswd = $Settings->getValue(); + $Settings->setKey('WhichDownloader'); + $this->WhichDownloader = $Settings->getValue(); + $this->WhichDownloader = is_null($this->WhichDownloader) ? 0 :(strcmp($this->WhichDownloader, 'ARIA2') == 0 ? 0 : 1); // 0 means ARIA2, 1 means CURL + $Settings->setKey('MaxDownloadSpeed'); + $this->MaxDownloadSpeed = $Settings->getValue(); + $Settings->setKey('AllowProtocolYT'); + $this->AllowProtocolYT = $Settings->getValue(); + $this->AllowProtocolYT = is_null($this->AllowProtocolYT) ? true : strcmp($this->AllowProtocolYT, 'Y') == 0; + + $Settings->setTable('personal'); + $Settings->setUID($this->CurrentUID); + $Settings->setKey('DownloadsFolder'); + $this->DownloadsFolder = $Settings->getValue(); + + $this->DownloadsFolder = '/' .(is_null($this->DownloadsFolder) ? 'Downloads' : $this->DownloadsFolder); + $this->AbsoluteDownloadsFolder = \OC\Files\Filesystem::getLocalFolder($this->DownloadsFolder); + + $this->L10N = $L10N; + } /** * @NoAdminRequired * @NoCSRFRequired */ - public function Add () - { - \OCP\JSON::setContentTypeHeader ('application/json'); - - if (isset ($_POST['FILE']) && strlen ($_POST['FILE']) > 0 && Tools::CheckURL ($_POST['FILE']) && isset ($_POST['OPTIONS'])) - { - try - { - if (!$this->AllowProtocolYT && !\OC_User::isAdminUser ($this->CurrentUID)) - { - throw new \Exception ((string)$this->L10N->t ('You are not allowed to use the YouTube protocol')); - } - - $YouTube = new YouTube ($this->YTDLBinary, $_POST['FILE']); - - if (!is_null ($this->ProxyAddress) && $this->ProxyPort > 0 && $this->ProxyPort <= 65536) - { - $YouTube->SetProxy ($this->ProxyAddress, $this->ProxyPort); - } - - if (isset ($_POST['OPTIONS']['YTForceIPv4']) && strcmp ($_POST['OPTIONS']['YTForceIPv4'], 'false') == 0) - { - $YouTube->SetForceIPv4 (false); - } - - // Extract Audio YES - if (isset ($_POST['OPTIONS']['YTExtractAudio']) && strcmp ($_POST['OPTIONS']['YTExtractAudio'], 'true') == 0) - { - $VideoData = $YouTube->GetVideoData (true); - if (!isset ($VideoData['AUDIO']) || !isset ($VideoData['FULLNAME'])) - { - return new JSONResponse (Array ( - 'ERROR' => true, - 'MESSAGE' => (string)$this->L10N->t ('Unable to retrieve true YouTube audio URL') - )); - } - $DL = Array ('URL' => $VideoData['AUDIO'], 'FILENAME' => Tools::CleanString ($VideoData['FULLNAME']), 'TYPE' => 'YT Audio'); - } - else // No audio extract - { - $VideoData = $YouTube->GetVideoData (); - if (!isset ($VideoData['VIDEO']) || !isset ($VideoData['FULLNAME'])) - { - return new JSONResponse (Array ( - 'ERROR' => true, - 'MESSAGE' => (string)$this->L10N->t ('Unable to retrieve true YouTube video URL') - )); - } - $DL = Array ('URL' => $VideoData['VIDEO'], 'FILENAME' => Tools::CleanString ($VideoData['FULLNAME']), 'TYPE' => 'YT Video'); - } - - // If target file exists, create a new one - if (\OC\Files\Filesystem::file_exists ($this->DownloadsFolder . '/' . $DL['FILENAME'])) - { - $DL['FILENAME'] = time () . '_' . $DL['FILENAME']; - } - - // Create the target file if the downloader is ARIA2 - if ($this->WhichDownloader == 0) - { - \OC\Files\Filesystem::touch ($this->DownloadsFolder . '/' . $DL['FILENAME']); - } - else - { - if (!\OC\Files\Filesystem::is_dir ($this->DownloadsFolder)) - { - \OC\Files\Filesystem::mkdir ($this->DownloadsFolder); - } - } - - $OPTIONS = Array ('dir' => $this->AbsoluteDownloadsFolder, 'out' => $DL['FILENAME']); - if (!is_null ($this->ProxyAddress) && $this->ProxyPort > 0 && $this->ProxyPort <= 65536) - { - $OPTIONS['all-proxy'] = rtrim ($this->ProxyAddress, '/') . ':' . $this->ProxyPort; - if (!is_null ($this->ProxyUser) && !is_null ($this->ProxyPasswd)) - { - $OPTIONS['all-proxy-user'] = $this->ProxyUser; - $OPTIONS['all-proxy-passwd'] = $this->ProxyPasswd; - } - } - if (!is_null ($this->MaxDownloadSpeed) && $this->MaxDownloadSpeed > 0) - { - $OPTIONS['max-download-limit'] = $this->MaxDownloadSpeed . 'K'; - } - - $AddURI = ($this->WhichDownloader == 0 ? Aria2::AddUri (Array ($DL['URL']), Array ('Params' => $OPTIONS)) : CURL::AddUri ($DL['URL'], $OPTIONS)); - - if (isset ($AddURI['result']) && !is_null ($AddURI['result'])) - { - $SQL = 'INSERT INTO `*PREFIX*ocdownloader_queue` (`UID`, `GID`, `FILENAME`, `PROTOCOL`, `STATUS`, `TIMESTAMP`) VALUES (?, ?, ?, ?, ?, ?)'; - if ($this->DbType == 1) - { - $SQL = 'INSERT INTO *PREFIX*ocdownloader_queue ("UID", "GID", "FILENAME", "PROTOCOL", "STATUS", "TIMESTAMP") VALUES (?, ?, ?, ?, ?, ?)'; - } - - $Query = \OCP\DB::prepare ($SQL); - $Result = $Query->execute (Array ( - $this->CurrentUID, - $AddURI['result'], - $DL['FILENAME'], - $DL['TYPE'], - 1, - time() - )); - - sleep (1); - $Status = Aria2::TellStatus ($AddURI['result']); - - $Progress = 0; - if ($Status['result']['totalLength'] > 0) - { - $Progress = $Status['result']['completedLength'] / $Status['result']['totalLength']; - } - - $ProgressString = Tools::GetProgressString ($Status['result']['completedLength'], $Status['result']['totalLength'], $Progress); - - return new JSONResponse (Array ( - 'ERROR' => false, - 'MESSAGE' => (string)$this->L10N->t ('Download started'), - 'GID' => $AddURI['result'], - 'PROGRESSVAL' => round((($Progress) * 100), 2) . '%', - 'PROGRESS' => is_null ($ProgressString) ? (string)$this->L10N->t ('N/A') : $ProgressString, - 'STATUS' => isset ($Status['result']['status']) ? (string)$this->L10N->t (ucfirst ($Status['result']['status'])) : (string)$this->L10N->t ('N/A'), - 'STATUSID' => Tools::GetDownloadStatusID ($Status['result']['status']), - 'SPEED' => isset ($Status['result']['downloadSpeed']) ? Tools::FormatSizeUnits ($Status['result']['downloadSpeed']) . '/s' : (string)$this->L10N->t ('N/A'), - 'FILENAME' => (mb_strlen ($DL['FILENAME'], "UTF-8") > 40 ? mb_substr ($DL['FILENAME'], 0, 40, "UTF-8") . '...' : $DL['FILENAME']), - 'PROTO' => $DL['TYPE'], - 'ISTORRENT' => false - )); - } - else - { - return new JSONResponse (Array ( - 'ERROR' => true, - 'MESSAGE' => (string)$this->L10N->t ('Returned GID is null ! Is Aria2c running as a daemon ?') - )); - } - } - catch (Exception $E) - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => $E->getMessage ())); - } - } - else - { - return new JSONResponse (Array ('ERROR' => true, 'MESSAGE' => (string)$this->L10N->t ('Please check the URL you\'ve just provided'))); + public function add() + { + \OCP\JSON::setContentTypeHeader('application/json'); + + if (isset($_POST['FILE']) && strlen($_POST['FILE']) > 0 + && Tools::checkURL($_POST['FILE']) && isset($_POST['OPTIONS'])) { + try { + if (!$this->AllowProtocolYT && !\OC_User::isAdminUser($this->CurrentUID)) { + throw new \Exception((string)$this->L10N->t('You are not allowed to use the YouTube protocol')); + } + + $YouTube = new YouTube($this->YTDLBinary, $_POST['FILE']); + + if (!is_null($this->ProxyAddress) && $this->ProxyPort > 0 && $this->ProxyPort <= 65536) { + $YouTube->SetProxy($this->ProxyAddress, $this->ProxyPort); + } + + if (isset($_POST['OPTIONS']['YTForceIPv4']) && strcmp($_POST['OPTIONS']['YTForceIPv4'], 'false') == 0) { + $YouTube->SetForceIPv4(false); + } + + // Extract Audio YES + if (isset($_POST['OPTIONS']['YTExtractAudio']) + && strcmp($_POST['OPTIONS']['YTExtractAudio'], 'true') == 0) { + $VideoData = $YouTube->getVideoData(true); + if (!isset($VideoData['AUDIO']) || !isset($VideoData['FULLNAME'])) { + return new JSONResponse(array( + 'ERROR' => true, + 'MESSAGE' =>(string)$this->L10N->t('Unable to retrieve true YouTube audio URL') + )); + } + $DL = array( + 'URL' => $VideoData['AUDIO'], + 'FILENAME' => Tools::cleanString($VideoData['FULLNAME']), + 'TYPE' => 'YT Audio' + ); + } else // No audio extract + { + $VideoData = $YouTube->getVideoData(); + if (!isset($VideoData['VIDEO']) || !isset($VideoData['FULLNAME'])) { + return new JSONResponse(array( + 'ERROR' => true, + 'MESSAGE' =>(string)$this->L10N->t('Unable to retrieve true YouTube video URL') + )); + } + $DL = array( + 'URL' => $VideoData['VIDEO'], + 'FILENAME' => Tools::cleanString($VideoData['FULLNAME']), + 'TYPE' => 'YT Video' + ); + } + + // If target file exists, create a new one + if (\OC\Files\Filesystem::file_exists($this->DownloadsFolder . '/' . $DL['FILENAME'])) { + $DL['FILENAME'] = time() . '_' . $DL['FILENAME']; + } + + // Create the target file if the downloader is ARIA2 + if ($this->WhichDownloader == 0) { + \OC\Files\Filesystem::touch($this->DownloadsFolder . '/' . $DL['FILENAME']); + } else { + if (!\OC\Files\Filesystem::is_dir($this->DownloadsFolder)) { + \OC\Files\Filesystem::mkdir($this->DownloadsFolder); + } + } + + $OPTIONS = array('dir' => $this->AbsoluteDownloadsFolder, 'out' => $DL['FILENAME']); + if (!is_null($this->ProxyAddress) && $this->ProxyPort > 0 && $this->ProxyPort <= 65536) { + $OPTIONS['all-proxy'] = rtrim($this->ProxyAddress, '/') . ':' . $this->ProxyPort; + if (!is_null($this->ProxyUser) && !is_null($this->ProxyPasswd)) { + $OPTIONS['all-proxy-user'] = $this->ProxyUser; + $OPTIONS['all-proxy-passwd'] = $this->ProxyPasswd; + } + } + if (!is_null($this->MaxDownloadSpeed) && $this->MaxDownloadSpeed > 0) { + $OPTIONS['max-download-limit'] = $this->MaxDownloadSpeed . 'K'; + } + + $AddURI =($this->WhichDownloader == 0 + ?Aria2::addUri(array($DL['URL']), array('Params' => $OPTIONS)) + :CURL::addUri($DL['URL'], $OPTIONS)); + + if (isset($AddURI['result']) && !is_null($AddURI['result'])) { + $SQL = 'INSERT INTO `*PREFIX*ocdownloader_queue` + (`UID`, `GID`, `FILENAME`, `PROTOCOL`, `STATUS`, `TIMESTAMP`) + VALUES(?, ?, ?, ?, ?, ?)'; + + if ($this->DbType == 1) { + $SQL = 'INSERT INTO *PREFIX*ocdownloader_queue + ("UID", "GID", "FILENAME", "PROTOCOL", "STATUS", "TIMESTAMP") + VALUES(?, ?, ?, ?, ?, ?)'; + } + + $Query = \OCP\DB::prepare($SQL); + $Result = $Query->execute(array( + $this->CurrentUID, + $AddURI['result'], + $DL['FILENAME'], + $DL['TYPE'], + 1, + time() + )); + + sleep(1); + $Status = Aria2::tellStatus($AddURI['result']); + + $Progress = 0; + if ($Status['result']['totalLength'] > 0) { + $Progress = $Status['result']['completedLength'] / $Status['result']['totalLength']; + } + + $ProgressString = Tools::getProgressString( + $Status['result']['completedLength'], + $Status['result']['totalLength'], + $Progress + ); + + return new JSONResponse(array( + 'ERROR' => false, + 'MESSAGE' =>(string)$this->L10N->t('Download started'), + 'GID' => $AddURI['result'], + 'PROGRESSVAL' => round((($Progress) * 100), 2) . '%', + 'PROGRESS' => is_null($ProgressString) ?(string)$this->L10N->t('N/A') : $ProgressString, + 'STATUS' => isset($Status['result']['status']) + ?(string)$this->L10N->t(ucfirst($Status['result']['status'])) + :(string)$this->L10N->t('N/A'), + 'STATUSID' => Tools::getDownloadStatusID($Status['result']['status']), + 'SPEED' => isset($Status['result']['downloadSpeed']) + ?Tools::formatSizeUnits($Status['result']['downloadSpeed']) + .'/s' :(string)$this->L10N->t('N/A'), + 'FILENAME' =>$DL['FILENAME'], + 'FILENAME_SHORT' => Tools::getShortFilename($DL['FILENAME']), + 'PROTO' => $DL['TYPE'], + 'ISTORRENT' => false + )); + } else { + return new JSONResponse(array( + 'ERROR' => true, + 'MESSAGE' =>(string)$this->L10N->t('Returned GID is null ! Is Aria2c running as a daemon ?') + )); + } + } catch (Exception $E) { + return new JSONResponse(array('ERROR' => true, 'MESSAGE' => $E->getMessage())); } - } + } else { + return new JSONResponse( + array( + 'ERROR' => true, + 'MESSAGE' =>(string)$this->L10N->t('Please check the URL you\'ve just provided') + ) + ); + } + } } diff --git a/js/ocdownloader.js b/js/ocdownloader.js index 9abfd6d..89d127a 100644 --- a/js/ocdownloader.js +++ b/js/ocdownloader.js @@ -127,8 +127,8 @@ OCDLR = {}; if (Value.PROGRESSVAL == '100%') { - $(QueueElt + ' > td[data-rel="FILENAME"]').html ('' + Value.FILENAME + ''); - + $(QueueElt + ' > td[data-rel="FILENAME"]').html ('' + Value.FILENAME_SHORT + ''); + if (Value.ISTORRENT && Value.SPEED != '--') { $(QueueElt + ' > td[data-rel="SPEED"]').html ('
' + Value.SPEED); @@ -642,8 +642,8 @@ OCDLR = {}; PrependToQueue: function (Data, View) { - $(OCDLRSelf.Queue + '> tbody').prepend ('' + - '' + Data.FILENAME + '' + + $(OCDLRSelf.Queue + '> tbody').prepend ('' + + '' + Data.FILENAME_SHORT + '' + '' + t ('ocdownloader', Data.PROTO) + '' + '
' + Data.PROGRESS + '
' + (['add', 'actives', 'all'].indexOf (View) > -1 ? '' + Data.SPEED + '' : '') + diff --git a/js/ocdownloader.min.js b/js/ocdownloader.min.js index f5b6e61..3d06a4a 100644 --- a/js/ocdownloader.min.js +++ b/js/ocdownloader.min.js @@ -7,4 +7,4 @@ * @author Xavier Beurois * @copyright Xavier Beurois 2015 */ -OCDLR={},function(){OCDLR.Utils={BaseURL:"/apps/ocdownloader/",BaseID:"#app-content-wrapper ",MenuID:"#app-navigation ",Queue:"",QueueHeader:"",QueueElt:"",DownloadsFolder:"",TorrentsFolder:"",WhichDownloader:"",BadgerStatus:[],ValidURL:function(e){return/^([a-z]([a-z]|\d|\+|-|\.)*):(\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?((\[(|(v[\da-f]{1,}\.(([a-z]|\d|-|\.|_|~)|[!\$&'\(\)\*\+,;=]|:)+))\])|((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=])*)(:\d*)?)(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*|(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)){0})(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(e)},PrintError:function(e){$(OCDLRSelf.BaseID+"span.muted").removeClass("info alert"),$(OCDLRSelf.BaseID+"span.muted").addClass("alert").text(e)},PrintInfo:function(e){$(OCDLRSelf.BaseID+"span.muted").removeClass("info alert"),$(OCDLRSelf.BaseID+"span.muted").addClass("info").text(e)},CheckVersion:function(){$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"updater/check"),method:"GET",dataType:"json",async:!0,cache:!1,timeout:3e4,success:function(e){!e.ERROR&&e.RESULT&&($(OCDLRSelf.MenuID+".nav-updater").show(),$(OCDLRSelf.MenuID+".nav-updater .button").bind("click",function(){OCDLRSelf.AddDownload($(this),"http","https://github.com/DjazzLab/ocdownloader/archive/master.zip",{HTTPUser:"",HTTPPasswd:""})}))}})},UpdateQueue:function(e,a){var t=setInterval(function(){clearInterval(t),$(OCDLRSelf.QueueElt).length>0&&($(OCDLRSelf.BaseID+".loadingtext").show(),$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"queue/get"),method:"POST",data:{VIEW:a},dataType:"json",async:!0,cache:!1,timeout:3e4,success:function(t){if(t.ERROR)OCDLRSelf.PrintError(t.MESSAGE);else{0!=$(OCDLRSelf.QueueElt+'[data-rel="LOADER"]').length&&$(OCDLRSelf.QueueElt+'[data-rel="LOADER"]').remove(),$("#ball").Badger(t.COUNTER.ALL),$("#bcompletes").Badger(t.COUNTER.COMPLETES),$("#bactives").Badger(t.COUNTER.ACTIVES),$("#bwaitings").Badger(t.COUNTER.WAITINGS),$("#bstopped").Badger(t.COUNTER.STOPPED),$("#bremoved").Badger(t.COUNTER.REMOVED);var l=[];$.each(t.QUEUE,function(t,d){var n=OCDLRSelf.QueueElt+'[data-rel="'+d.GID+'"]';l.push(d.GID),e&&0==$(n).length&&OCDLRSelf.PrependToQueue(d,a),0==$(n+' > td[data-rel="ACTION"] > div.icon-pause').length&&1==d.STATUSID&&OCDLRSelf.ActionPause($(n+' > td[data-rel="ACTION"]'),a),0==$(n+' > td[data-rel="ACTION"] > div.icon-play').length&&3==d.STATUSID&&OCDLRSelf.ActionUnPause($(n+' > td[data-rel="ACTION"]'),a),"100%"==d.PROGRESSVAL?($(n+' > td[data-rel="FILENAME"]').html(''+d.FILENAME+""),d.ISTORRENT&&"--"!=d.SPEED?$(n+' > td[data-rel="SPEED"]').html('
'+d.SPEED):($(n+' > td[data-rel="SPEED"]').html(d.SPEED),d.ISTORRENT||($(n+' > td[data-rel="ACTION"] > div.icon-pause').remove(),$(n+' > td[data-rel="ACTION"] > div.icon-play').remove()))):$(n+' > td[data-rel="SPEED"]').html("--"!=d.SPEED?'
'+d.SPEED:d.SPEED),$(n+' > td[data-rel="MESSAGE"] > div.pb-wrap > div.pb-value > div.pb-text').html(d.PROGRESS),$(n+' > td[data-rel="MESSAGE"] > div.pb-wrap > div.pb-value').css("width",d.PROGRESSVAL),$(n+' > td[data-rel="STATUS"]').text(d.STATUS)}),OCDLRSelf.RemoveQueueItems(l)}$(OCDLRSelf.BaseID+".loadingtext").hide()}})),OCDLRSelf.UpdateQueue("add"==a?!1:!0,a)},3e3)},RemoveQueueItem:function(e){1==e.parent().children().length&&$(OCDLRSelf.Queue+' th[data-rel="ACTION"] > div').remove(),e.remove()},RemoveQueueItems:function(e){$(OCDLRSelf.QueueElt).each(function(){-1==e.indexOf($(this).attr("data-rel"))&&$(this).remove()}),0==$(OCDLRSelf.QueueElt).length&&$(OCDLRSelf.Queue+'> thead th[data-rel="ACTION"] > div').remove()},HideFromQueue:function(e){e.addClass("icon-loading-small"),e.removeClass("icon-close");var a=e.parent().parent(),l=a.attr("data-rel");l?$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"queue/hide"),method:"POST",dataType:"json",data:{GID:l},async:!0,cache:!1,timeout:3e4,success:function(t){t.ERROR?(OCDLRSelf.PrintError(t.MESSAGE),e.addClass("icon-close"),e.removeClass("icon-loading-small")):(OCDLRSelf.PrintInfo(t.MESSAGE+" ("+l+")"),OCDLRSelf.RemoveQueueItem(a))}}):OCDLRSelf.PrintError(t("ocdownloader","Unable to find the GID for this download ..."))},HideAllFromQueue:function(e){e.addClass("icon-loading-small"),e.removeClass("icon-close");var a=[];$(OCDLRSelf.QueueElt+' td[data-rel="ACTION"] > div.icon-close').each(function(){$(this).addClass("icon-loading-small"),$(this).removeClass("icon-close"),a.push($(this).parent().parent().attr("data-rel"))}),a.length>0?$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"queue/hideall"),method:"POST",dataType:"json",data:{GIDS:a},async:!0,cache:!1,timeout:3e4,success:function(e){e.ERROR?OCDLRSelf.PrintError(e.MESSAGE):(OCDLRSelf.PrintInfo(e.MESSAGE),$.each(e.QUEUE,function(e,a){$(OCDLRSelf.QueueElt+'[data-rel="'+a.GID+'"]').remove()}),$(OCDLRSelf.Queue+' th[data-rel="ACTION"] > div.icon-loading-small').remove())}}):OCDLRSelf.PrintError(t("ocdownloader","No downloads in the queue ..."))},PauseDownload:function(e,a){e.addClass("icon-loading-small"),e.removeClass("icon-pause"),$("#bactives").Badger("-1"),$("#bstopped").Badger("+1");var l=e.parent().parent(),d=l.attr("data-rel");d?$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"queue/pause"),method:"POST",dataType:"json",data:{GID:d},async:!0,cache:!1,timeout:3e4,success:function(n){n.ERROR?(OCDLRSelf.PrintError(n.MESSAGE),e.addClass("icon-pause")):(OCDLRSelf.PrintInfo(n.MESSAGE+" ("+d+")"),["add","all"].indexOf(a)>-1?(e.addClass("icon-play"),e.parent().parent().children('td[data-rel="STATUS"]').attr("data-statusid",3),e.parent().parent().children('td[data-rel="STATUS"]').text(t("ocdownloader","Paused")),e.unbind("click"),e.bind("click",function(){OCDLRSelf.UnPauseDownload($(this),a)})):OCDLRSelf.RemoveQueueItem(l)),e.removeClass("icon-loading-small")}}):OCDLRSelf.PrintError(t("ocdownloader","Unable to find the GID for this download ..."))},UnPauseDownload:function(e,a){e.addClass("icon-loading-small"),e.removeClass("icon-play"),$("#bactives").Badger("+1"),$("#bstopped").Badger("-1");var l=e.parent().parent(),d=l.attr("data-rel");d?$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"queue/unpause"),method:"POST",dataType:"json",data:{GID:d},async:!0,cache:!1,timeout:3e4,success:function(n){n.ERROR?(OCDLRSelf.PrintError(n.MESSAGE),e.addClass("icon-play")):(OCDLRSelf.PrintInfo(n.MESSAGE+" ("+d+")"),["add","all"].indexOf(a)>-1?(e.addClass("icon-pause"),e.parent().parent().children('td[data-rel="STATUS"]').attr("data-statusid",1),e.parent().parent().children('td[data-rel="STATUS"]').text(t("ocdownloader","Active")),e.unbind("click"),e.bind("click",function(){OCDLRSelf.PauseDownload($(this),a)})):OCDLRSelf.RemoveQueueItem(l)),e.removeClass("icon-loading-small")}}):OCDLRSelf.PrintError(t("ocdownloader","Unable to find the GID for this download ..."))},RemoveFromQueue:function(e,a,l){e.addClass("icon-loading-small"),e.removeClass("icon-delete");var d=e.parent().parent(),n=d.attr("data-rel");n?$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"queue/"+a+"remove"),method:"POST",dataType:"json",data:{GID:n},async:!0,cache:!1,timeout:3e4,success:function(o){if(o.ERROR)OCDLRSelf.PrintError(o.MESSAGE),e.addClass("icon-delete"),e.removeClass("icon-loading-small");else if(OCDLRSelf.PrintInfo(o.MESSAGE+" ("+n+")"),"all"!=l||a.length>0)OCDLRSelf.RemoveQueueItem(d);else if("3"==d.children('td[data-rel="STATUS"]').attr("data-statusid"))$("#bremoved").Badger("-1"),$("#ball").Badger("-1"),OCDLRSelf.RemoveFromQueue(e,"completely",l);else{var i=e.parent();i.children("div").remove(),i.parent().children('td[data-rel="STATUS"]').text(t("ocdownloader","Removed")),OCDLRSelf.ActionDeleteCompletely(i)}}}):OCDLRSelf.PrintError(t("ocdownloader","Unable to find the GID for this download ..."))},RemoveAllFromQueue:function(e,a,l){e.addClass("icon-loading-small"),e.removeClass("icon-delete");var d=[];$(OCDLRSelf.QueueElt+' td[data-rel="ACTION"] > div.icon-delete').each(function(){$(this).addClass("icon-loading-small"),$(this).removeClass("icon-delete"),d.push($(this).parent().parent().attr("data-rel"))}),d.length>0?$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"queue/"+a+"removeall"),method:"POST",dataType:"json",data:{GIDS:d},async:!0,cache:!1,timeout:3e4,success:function(e){e.ERROR?OCDLRSelf.PrintError(e.MESSAGE):(OCDLRSelf.PrintInfo(e.MESSAGE),OCDLRSelf.RemoveQueueItems(e.GIDS),a.length>0?($("#bremoved").Badger("-"+d.length),$("#ball").Badger("-"+d.length)):($("#bremoved").Badger("+"+d.length),$("#b"+l).Badger("-"+d.length)))}}):OCDLRSelf.PrintError(t("ocdownloader","Unable to find the GID for this download ..."))},GetPersonalSettings:function(){$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"personalsettings/get"),method:"GET",dataType:"json",async:!1,cache:!1,timeout:3e4,success:function(Data){Data.ERROR||$.each(Data.VALS,function(Key,Value){eval("OCDLRSelf."+Key+'="'+Value+'"')})}})},GetAdminSettings:function(KEYS){$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"adminsettings/get"),method:"POST",dataType:"json",data:{KEYS:KEYS},async:!1,cache:!1,timeout:3e4,success:function(Data){Data.ERROR||$.each(Data.VALS,function(Key,Value){eval("OCDLRSelf."+Key+'="'+Value+'"')})}})},GetTorrentsList:function(e){e.is(":visible")?e.hide():(e.empty(),e.append('
  • '),e.show(),$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"btdownloader/listtorrentfiles"),method:"POST",dataType:"json",async:!0,cache:!1,timeout:3e4,success:function(a){if(a.ERROR)OCDLRSelf.PrintError(a.MESSAGE);else if(e.empty(),0==a.FILES.length)e.append("
  • "+t("ocdownloader","No Torrent Files")+', '+t("ocdownloader","Upload")+"

  • ");else{for(var l=0;l

    '+a.FILES[l].name+"

    ");e.children("li").children("p.clickable").bind("click",function(){e.parent().children("a").prop("data-rel","File"),e.parent().children("a").html($(this).text()+'
    ')})}}}))},GetCounters:function(){$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"queue/count"),method:"POST",dataType:"json",async:!0,cache:!1,timeout:3e4,success:function(e){e.ERROR?OCDLRSelf.PrintError(e.MESSAGE):($("#ball").Badger(e.COUNTER.ALL),$("#bcompletes").Badger(e.COUNTER.COMPLETES),$("#bactives").Badger(e.COUNTER.ACTIVES),$("#bwaitings").Badger(e.COUNTER.WAITINGS),$("#bstopped").Badger(e.COUNTER.STOPPED),$("#bremoved").Badger(e.COUNTER.REMOVED))}})},PrependToQueue:function(e,a){$(OCDLRSelf.Queue+"> tbody").prepend(''+e.FILENAME+''+t("ocdownloader",e.PROTO)+'
    '+e.PROGRESS+"
    "+(["add","actives","all"].indexOf(a)>-1?''+e.SPEED+"":"")+(["add","all"].indexOf(a)>-1?''+e.STATUS+"":"")+'');var l=$(OCDLRSelf.QueueElt+'[data-rel="'+e.GID+'"] > td[data-rel="ACTION"]');if(["add"].indexOf(a)>-1){OCDLRSelf.ActionHide(l),1==e.STATUSID?OCDLRSelf.ActionPause(l,a):3==e.STATUSID&&OCDLRSelf.ActionPlay(l,a);var d=OCDLRSelf.Queue+'> thead th[data-rel="ACTION"] > div.icon-close';0==$(d).length&&($(OCDLRSelf.Queue+'> thead th[data-rel="ACTION"]').append('
    '),$(d).bind("click",function(){OCDLRSelf.HideAllFromQueue($(this))}))}if(["completes","waitings","stopped","actives"].indexOf(a)>-1){OCDLRSelf.ActionDelete(l,OCDLRSelf.BadgerStatus[e.STATUSID],a);var n=OCDLRSelf.Queue+'> thead th[data-rel="ACTION"] > div.icon-delete';0==$(n).length&&($(OCDLRSelf.Queue+'> thead th[data-rel="ACTION"]').append('
    '),$(n).bind("click",function(){OCDLRSelf.RemoveAllFromQueue($(this),"",a)}))}if("all"==a&&(4==e.STATUSID?OCDLRSelf.ActionDeleteCompletely(l):(OCDLRSelf.ActionDelete(l,OCDLRSelf.BadgerStatus[e.STATUSID],a),1==e.STATUSID?OCDLRSelf.ActionPause(l,a):3==e.STATUSID&&OCDLRSelf.ActionPlay(l,a))),"actives"==a&&OCDLRSelf.ActionPause(l,a),"stopped"==a&&OCDLRSelf.ActionPlay(l,a),"removed"==a){OCDLRSelf.ActionDeleteCompletely(l);var o=OCDLRSelf.Queue+'> thead th[data-rel="ACTION"] > div.icon-delete';0==$(o).length&&($(OCDLRSelf.Queue+'> thead th[data-rel="ACTION"]').append('
    '),$(o).bind("click",function(){OCDLRSelf.RemoveAllFromQueue($(this),"completely",a)}))}},AddDownload:function(e,a,t,l){var d=!1;return e.hasClass("icon-loading-small")||(e.children("a").css("display","none"),e.addClass("icon-loading-small"),$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+a+"downloader/add"),method:"POST",dataType:"json",data:{FILE:t,OPTIONS:l},async:!0,cache:!1,timeout:3e4,success:function(a){a.ERROR?OCDLRSelf.PrintError(a.MESSAGE):(OCDLRSelf.PrintInfo(a.MESSAGE+" ("+a.GID+")"),OCDLRSelf.PrependToQueue(a,"add"),$("#ball").Badger("+1"),1==a.STATUSID&&$("#bactives").Badger("+1"),3==a.STATUSID&&$("#bwaitings").Badger("+1"),d=!0),e.children("a").css("display","block"),e.removeClass("icon-loading-small")}})),d},ActionHide:function(e){e.append('
    '),e.children("div.icon-close").bind("click",function(){OCDLRSelf.HideFromQueue($(this))})},ActionPause:function(e,a){"ARIA2"==OCDLRSelf.WhichDownloader&&(e.append('
    '),e.children("div.icon-pause").bind("click",function(){OCDLRSelf.PauseDownload($(this),a)}))},ActionPlay:function(e,a){"ARIA2"==OCDLRSelf.WhichDownloader&&(e.append('
    '),e.children("div.icon-play").bind("click",function(){OCDLRSelf.UnPauseDownload($(this),a)}))},ActionDelete:function(e,a,t){e.append('
    '),e.children("div.icon-delete").bind("click",function(){$("#bremoved").Badger("+1"),$("#b"+a).Badger("-1"),OCDLRSelf.RemoveFromQueue($(this),"",t)})},ActionDeleteCompletely:function(e){e.append('
    '),e.children("div.icon-delete").bind("click",function(){$("#bremoved").Badger("-1"),$("#ball").Badger("-1"),OCDLRSelf.RemoveFromQueue($(this),"completely","removed")})}};var OCDLRSelf=OCDLR.Utils;OCDLRSelf.GetPersonalSettings(),OCDLRSelf.GetAdminSettings(["WhichDownloader"]),OCDLRSelf.Queue=OCDLRSelf.BaseID+"#Queue ",OCDLRSelf.QueueHeader=OCDLRSelf.Queue+"thead tr",OCDLRSelf.QueueElt=OCDLRSelf.Queue+"tbody tr",OCDLRSelf.BadgerStatus=["completes","actives","waitings","stopped"]}(); \ No newline at end of file +OCDLR={},function(){OCDLR.Utils={BaseURL:"/apps/ocdownloader/",BaseID:"#app-content-wrapper ",MenuID:"#app-navigation ",Queue:"",QueueHeader:"",QueueElt:"",DownloadsFolder:"",TorrentsFolder:"",WhichDownloader:"",BadgerStatus:[],ValidURL:function(e){return/^([a-z]([a-z]|\d|\+|-|\.)*):(\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?((\[(|(v[\da-f]{1,}\.(([a-z]|\d|-|\.|_|~)|[!\$&'\(\)\*\+,;=]|:)+))\])|((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=])*)(:\d*)?)(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*|(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)){0})(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(e)},PrintError:function(e){$(OCDLRSelf.BaseID+"span.muted").removeClass("info alert"),$(OCDLRSelf.BaseID+"span.muted").addClass("alert").text(e)},PrintInfo:function(e){$(OCDLRSelf.BaseID+"span.muted").removeClass("info alert"),$(OCDLRSelf.BaseID+"span.muted").addClass("info").text(e)},CheckVersion:function(){$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"updater/check"),method:"GET",dataType:"json",async:!0,cache:!1,timeout:3e4,success:function(e){!e.ERROR&&e.RESULT&&($(OCDLRSelf.MenuID+".nav-updater").show(),$(OCDLRSelf.MenuID+".nav-updater .button").bind("click",function(){OCDLRSelf.AddDownload($(this),"http","https://github.com/DjazzLab/ocdownloader/archive/master.zip",{HTTPUser:"",HTTPPasswd:""})}))}})},UpdateQueue:function(e,a){var t=setInterval(function(){clearInterval(t),$(OCDLRSelf.QueueElt).length>0&&($(OCDLRSelf.BaseID+".loadingtext").show(),$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"queue/get"),method:"POST",data:{VIEW:a},dataType:"json",async:!0,cache:!1,timeout:3e4,success:function(t){if(t.ERROR)OCDLRSelf.PrintError(t.MESSAGE);else{0!=$(OCDLRSelf.QueueElt+'[data-rel="LOADER"]').length&&$(OCDLRSelf.QueueElt+'[data-rel="LOADER"]').remove(),$("#ball").Badger(t.COUNTER.ALL),$("#bcompletes").Badger(t.COUNTER.COMPLETES),$("#bactives").Badger(t.COUNTER.ACTIVES),$("#bwaitings").Badger(t.COUNTER.WAITINGS),$("#bstopped").Badger(t.COUNTER.STOPPED),$("#bremoved").Badger(t.COUNTER.REMOVED);var l=[];$.each(t.QUEUE,function(t,d){var n=OCDLRSelf.QueueElt+'[data-rel="'+d.GID+'"]';l.push(d.GID),e&&0==$(n).length&&OCDLRSelf.PrependToQueue(d,a),0==$(n+' > td[data-rel="ACTION"] > div.icon-pause').length&&1==d.STATUSID&&OCDLRSelf.ActionPause($(n+' > td[data-rel="ACTION"]'),a),0==$(n+' > td[data-rel="ACTION"] > div.icon-play').length&&3==d.STATUSID&&OCDLRSelf.ActionUnPause($(n+' > td[data-rel="ACTION"]'),a),"100%"==d.PROGRESSVAL?($(n+' > td[data-rel="FILENAME"]').html(''+d.FILENAME_SHORT+""),d.ISTORRENT&&"--"!=d.SPEED?$(n+' > td[data-rel="SPEED"]').html('
    '+d.SPEED):($(n+' > td[data-rel="SPEED"]').html(d.SPEED),d.ISTORRENT||($(n+' > td[data-rel="ACTION"] > div.icon-pause').remove(),$(n+' > td[data-rel="ACTION"] > div.icon-play').remove()))):$(n+' > td[data-rel="SPEED"]').html("--"!=d.SPEED?'
    '+d.SPEED:d.SPEED),$(n+' > td[data-rel="MESSAGE"] > div.pb-wrap > div.pb-value > div.pb-text').html(d.PROGRESS),$(n+' > td[data-rel="MESSAGE"] > div.pb-wrap > div.pb-value').css("width",d.PROGRESSVAL),$(n+' > td[data-rel="STATUS"]').text(d.STATUS)}),OCDLRSelf.RemoveQueueItems(l)}$(OCDLRSelf.BaseID+".loadingtext").hide()}})),OCDLRSelf.UpdateQueue("add"==a?!1:!0,a)},3e3)},RemoveQueueItem:function(e){1==e.parent().children().length&&$(OCDLRSelf.Queue+' th[data-rel="ACTION"] > div').remove(),e.remove()},RemoveQueueItems:function(e){$(OCDLRSelf.QueueElt).each(function(){-1==e.indexOf($(this).attr("data-rel"))&&$(this).remove()}),0==$(OCDLRSelf.QueueElt).length&&$(OCDLRSelf.Queue+'> thead th[data-rel="ACTION"] > div').remove()},HideFromQueue:function(e){e.addClass("icon-loading-small"),e.removeClass("icon-close");var a=e.parent().parent(),l=a.attr("data-rel");l?$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"queue/hide"),method:"POST",dataType:"json",data:{GID:l},async:!0,cache:!1,timeout:3e4,success:function(t){t.ERROR?(OCDLRSelf.PrintError(t.MESSAGE),e.addClass("icon-close"),e.removeClass("icon-loading-small")):(OCDLRSelf.PrintInfo(t.MESSAGE+" ("+l+")"),OCDLRSelf.RemoveQueueItem(a))}}):OCDLRSelf.PrintError(t("ocdownloader","Unable to find the GID for this download ..."))},HideAllFromQueue:function(e){e.addClass("icon-loading-small"),e.removeClass("icon-close");var a=[];$(OCDLRSelf.QueueElt+' td[data-rel="ACTION"] > div.icon-close').each(function(){$(this).addClass("icon-loading-small"),$(this).removeClass("icon-close"),a.push($(this).parent().parent().attr("data-rel"))}),a.length>0?$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"queue/hideall"),method:"POST",dataType:"json",data:{GIDS:a},async:!0,cache:!1,timeout:3e4,success:function(e){e.ERROR?OCDLRSelf.PrintError(e.MESSAGE):(OCDLRSelf.PrintInfo(e.MESSAGE),$.each(e.QUEUE,function(e,a){$(OCDLRSelf.QueueElt+'[data-rel="'+a.GID+'"]').remove()}),$(OCDLRSelf.Queue+' th[data-rel="ACTION"] > div.icon-loading-small').remove())}}):OCDLRSelf.PrintError(t("ocdownloader","No downloads in the queue ..."))},PauseDownload:function(e,a){e.addClass("icon-loading-small"),e.removeClass("icon-pause"),$("#bactives").Badger("-1"),$("#bstopped").Badger("+1");var l=e.parent().parent(),d=l.attr("data-rel");d?$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"queue/pause"),method:"POST",dataType:"json",data:{GID:d},async:!0,cache:!1,timeout:3e4,success:function(n){n.ERROR?(OCDLRSelf.PrintError(n.MESSAGE),e.addClass("icon-pause")):(OCDLRSelf.PrintInfo(n.MESSAGE+" ("+d+")"),["add","all"].indexOf(a)>-1?(e.addClass("icon-play"),e.parent().parent().children('td[data-rel="STATUS"]').attr("data-statusid",3),e.parent().parent().children('td[data-rel="STATUS"]').text(t("ocdownloader","Paused")),e.unbind("click"),e.bind("click",function(){OCDLRSelf.UnPauseDownload($(this),a)})):OCDLRSelf.RemoveQueueItem(l)),e.removeClass("icon-loading-small")}}):OCDLRSelf.PrintError(t("ocdownloader","Unable to find the GID for this download ..."))},UnPauseDownload:function(e,a){e.addClass("icon-loading-small"),e.removeClass("icon-play"),$("#bactives").Badger("+1"),$("#bstopped").Badger("-1");var l=e.parent().parent(),d=l.attr("data-rel");d?$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"queue/unpause"),method:"POST",dataType:"json",data:{GID:d},async:!0,cache:!1,timeout:3e4,success:function(n){n.ERROR?(OCDLRSelf.PrintError(n.MESSAGE),e.addClass("icon-play")):(OCDLRSelf.PrintInfo(n.MESSAGE+" ("+d+")"),["add","all"].indexOf(a)>-1?(e.addClass("icon-pause"),e.parent().parent().children('td[data-rel="STATUS"]').attr("data-statusid",1),e.parent().parent().children('td[data-rel="STATUS"]').text(t("ocdownloader","Active")),e.unbind("click"),e.bind("click",function(){OCDLRSelf.PauseDownload($(this),a)})):OCDLRSelf.RemoveQueueItem(l)),e.removeClass("icon-loading-small")}}):OCDLRSelf.PrintError(t("ocdownloader","Unable to find the GID for this download ..."))},RemoveFromQueue:function(e,a,l){e.addClass("icon-loading-small"),e.removeClass("icon-delete");var d=e.parent().parent(),n=d.attr("data-rel");n?$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"queue/"+a+"remove"),method:"POST",dataType:"json",data:{GID:n},async:!0,cache:!1,timeout:3e4,success:function(o){if(o.ERROR)OCDLRSelf.PrintError(o.MESSAGE),e.addClass("icon-delete"),e.removeClass("icon-loading-small");else if(OCDLRSelf.PrintInfo(o.MESSAGE+" ("+n+")"),"all"!=l||a.length>0)OCDLRSelf.RemoveQueueItem(d);else if("3"==d.children('td[data-rel="STATUS"]').attr("data-statusid"))$("#bremoved").Badger("-1"),$("#ball").Badger("-1"),OCDLRSelf.RemoveFromQueue(e,"completely",l);else{var i=e.parent();i.children("div").remove(),i.parent().children('td[data-rel="STATUS"]').text(t("ocdownloader","Removed")),OCDLRSelf.ActionDeleteCompletely(i)}}}):OCDLRSelf.PrintError(t("ocdownloader","Unable to find the GID for this download ..."))},RemoveAllFromQueue:function(e,a,l){e.addClass("icon-loading-small"),e.removeClass("icon-delete");var d=[];$(OCDLRSelf.QueueElt+' td[data-rel="ACTION"] > div.icon-delete').each(function(){$(this).addClass("icon-loading-small"),$(this).removeClass("icon-delete"),d.push($(this).parent().parent().attr("data-rel"))}),d.length>0?$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"queue/"+a+"removeall"),method:"POST",dataType:"json",data:{GIDS:d},async:!0,cache:!1,timeout:3e4,success:function(e){e.ERROR?OCDLRSelf.PrintError(e.MESSAGE):(OCDLRSelf.PrintInfo(e.MESSAGE),OCDLRSelf.RemoveQueueItems(e.GIDS),a.length>0?($("#bremoved").Badger("-"+d.length),$("#ball").Badger("-"+d.length)):($("#bremoved").Badger("+"+d.length),$("#b"+l).Badger("-"+d.length)))}}):OCDLRSelf.PrintError(t("ocdownloader","Unable to find the GID for this download ..."))},GetPersonalSettings:function(){$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"personalsettings/get"),method:"GET",dataType:"json",async:!1,cache:!1,timeout:3e4,success:function(Data){Data.ERROR||$.each(Data.VALS,function(Key,Value){eval("OCDLRSelf."+Key+'="'+Value+'"')})}})},GetAdminSettings:function(KEYS){$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"adminsettings/get"),method:"POST",dataType:"json",data:{KEYS:KEYS},async:!1,cache:!1,timeout:3e4,success:function(Data){Data.ERROR||$.each(Data.VALS,function(Key,Value){eval("OCDLRSelf."+Key+'="'+Value+'"')})}})},GetTorrentsList:function(e){e.is(":visible")?e.hide():(e.empty(),e.append('
  • '),e.show(),$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"btdownloader/listtorrentfiles"),method:"POST",dataType:"json",async:!0,cache:!1,timeout:3e4,success:function(a){if(a.ERROR)OCDLRSelf.PrintError(a.MESSAGE);else if(e.empty(),0==a.FILES.length)e.append("
  • "+t("ocdownloader","No Torrent Files")+', '+t("ocdownloader","Upload")+"

  • ");else{for(var l=0;l

    '+a.FILES[l].name+"

    ");e.children("li").children("p.clickable").bind("click",function(){e.parent().children("a").prop("data-rel","File"),e.parent().children("a").html($(this).text()+'
    ')})}}}))},GetCounters:function(){$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+"queue/count"),method:"POST",dataType:"json",async:!0,cache:!1,timeout:3e4,success:function(e){e.ERROR?OCDLRSelf.PrintError(e.MESSAGE):($("#ball").Badger(e.COUNTER.ALL),$("#bcompletes").Badger(e.COUNTER.COMPLETES),$("#bactives").Badger(e.COUNTER.ACTIVES),$("#bwaitings").Badger(e.COUNTER.WAITINGS),$("#bstopped").Badger(e.COUNTER.STOPPED),$("#bremoved").Badger(e.COUNTER.REMOVED))}})},PrependToQueue:function(e,a){$(OCDLRSelf.Queue+"> tbody").prepend(''+e.FILENAME_SHORT+''+t("ocdownloader",e.PROTO)+'
    '+e.PROGRESS+"
    "+(["add","actives","all"].indexOf(a)>-1?''+e.SPEED+"":"")+(["add","all"].indexOf(a)>-1?''+e.STATUS+"":"")+'');var l=$(OCDLRSelf.QueueElt+'[data-rel="'+e.GID+'"] > td[data-rel="ACTION"]');if(["add"].indexOf(a)>-1){OCDLRSelf.ActionHide(l),1==e.STATUSID?OCDLRSelf.ActionPause(l,a):3==e.STATUSID&&OCDLRSelf.ActionPlay(l,a);var d=OCDLRSelf.Queue+'> thead th[data-rel="ACTION"] > div.icon-close';0==$(d).length&&($(OCDLRSelf.Queue+'> thead th[data-rel="ACTION"]').append('
    '),$(d).bind("click",function(){OCDLRSelf.HideAllFromQueue($(this))}))}if(["completes","waitings","stopped","actives"].indexOf(a)>-1){OCDLRSelf.ActionDelete(l,OCDLRSelf.BadgerStatus[e.STATUSID],a);var n=OCDLRSelf.Queue+'> thead th[data-rel="ACTION"] > div.icon-delete';0==$(n).length&&($(OCDLRSelf.Queue+'> thead th[data-rel="ACTION"]').append('
    '),$(n).bind("click",function(){OCDLRSelf.RemoveAllFromQueue($(this),"",a)}))}if("all"==a&&(4==e.STATUSID?OCDLRSelf.ActionDeleteCompletely(l):(OCDLRSelf.ActionDelete(l,OCDLRSelf.BadgerStatus[e.STATUSID],a),1==e.STATUSID?OCDLRSelf.ActionPause(l,a):3==e.STATUSID&&OCDLRSelf.ActionPlay(l,a))),"actives"==a&&OCDLRSelf.ActionPause(l,a),"stopped"==a&&OCDLRSelf.ActionPlay(l,a),"removed"==a){OCDLRSelf.ActionDeleteCompletely(l);var o=OCDLRSelf.Queue+'> thead th[data-rel="ACTION"] > div.icon-delete';0==$(o).length&&($(OCDLRSelf.Queue+'> thead th[data-rel="ACTION"]').append('
    '),$(o).bind("click",function(){OCDLRSelf.RemoveAllFromQueue($(this),"completely",a)}))}},AddDownload:function(e,a,t,l){var d=!1;return e.hasClass("icon-loading-small")||(e.children("a").css("display","none"),e.addClass("icon-loading-small"),$.ajax({url:OC.generateUrl(OCDLRSelf.BaseURL+a+"downloader/add"),method:"POST",dataType:"json",data:{FILE:t,OPTIONS:l},async:!0,cache:!1,timeout:3e4,success:function(a){a.ERROR?OCDLRSelf.PrintError(a.MESSAGE):(OCDLRSelf.PrintInfo(a.MESSAGE+" ("+a.GID+")"),OCDLRSelf.PrependToQueue(a,"add"),$("#ball").Badger("+1"),1==a.STATUSID&&$("#bactives").Badger("+1"),3==a.STATUSID&&$("#bwaitings").Badger("+1"),d=!0),e.children("a").css("display","block"),e.removeClass("icon-loading-small")}})),d},ActionHide:function(e){e.append('
    '),e.children("div.icon-close").bind("click",function(){OCDLRSelf.HideFromQueue($(this))})},ActionPause:function(e,a){"ARIA2"==OCDLRSelf.WhichDownloader&&(e.append('
    '),e.children("div.icon-pause").bind("click",function(){OCDLRSelf.PauseDownload($(this),a)}))},ActionPlay:function(e,a){"ARIA2"==OCDLRSelf.WhichDownloader&&(e.append('
    '),e.children("div.icon-play").bind("click",function(){OCDLRSelf.UnPauseDownload($(this),a)}))},ActionDelete:function(e,a,t){e.append('
    '),e.children("div.icon-delete").bind("click",function(){$("#bremoved").Badger("+1"),$("#b"+a).Badger("-1"),OCDLRSelf.RemoveFromQueue($(this),"",t)})},ActionDeleteCompletely:function(e){e.append('
    '),e.children("div.icon-delete").bind("click",function(){$("#bremoved").Badger("-1"),$("#ball").Badger("-1"),OCDLRSelf.RemoveFromQueue($(this),"completely","removed")})}};var OCDLRSelf=OCDLR.Utils;OCDLRSelf.GetPersonalSettings(),OCDLRSelf.GetAdminSettings(["WhichDownloader"]),OCDLRSelf.Queue=OCDLRSelf.BaseID+"#Queue ",OCDLRSelf.QueueHeader=OCDLRSelf.Queue+"thead tr",OCDLRSelf.QueueElt=OCDLRSelf.Queue+"tbody tr",OCDLRSelf.BadgerStatus=["completes","actives","waitings","stopped"]}(); diff --git a/settings/admin.php b/settings/admin.php index 4b099a4..1ea1420 100644 --- a/settings/admin.php +++ b/settings/admin.php @@ -7,24 +7,23 @@ * * @author Xavier Beurois * @copyright Xavier Beurois 2015 - */ + */ use OCA\ocDownloader\Controller\Lib\Settings; -\OC_Util::checkAdminUser (); +\OC_Util::checkAdminUser(); // Display template -style ('ocdownloader', 'settings/admin'); -script ('ocdownloader', 'settings/admin'); +style('ocdownloader', 'settings/admin'); +script('ocdownloader', 'settings/admin'); -$Tmpl = new OCP\Template ('ocdownloader', 'settings/admin'); +$Tmpl = new OCP\Template('ocdownloader', 'settings/admin'); -$Settings = new Settings (); -$Rows = $Settings->GetAllValues (); +$Settings = new Settings(); +$Rows = $Settings->getAllValues(); -while ($Row = $Rows->fetchRow ()) -{ - $Tmpl->assign ('OCDS_' . $Row['KEY'], $Row['VAL']); +while ($Row = $Rows->fetchRow()) { + $Tmpl->assign('OCDS_' . $Row['KEY'], $Row['VAL']); } -return $Tmpl->fetchPage (); \ No newline at end of file +return $Tmpl->fetchPage(); diff --git a/settings/personal.php b/settings/personal.php index 5426131..997cda7 100644 --- a/settings/personal.php +++ b/settings/personal.php @@ -7,32 +7,31 @@ * * @author Xavier Beurois * @copyright Xavier Beurois 2015 - */ + */ use OCA\ocDownloader\Controller\Lib\Settings; -\OCP\User::checkLoggedIn (); +\OCP\User::checkLoggedIn(); // Display template -style ('ocdownloader', 'settings/personal'); -script ('ocdownloader', 'settings/personal'); +style('ocdownloader', 'settings/personal'); +script('ocdownloader', 'settings/personal'); -$Tmpl = new OCP\Template ('ocdownloader', 'settings/personal'); +$Tmpl = new OCP\Template('ocdownloader', 'settings/personal'); -$Settings = new Settings (); -$Settings->SetKey ('AllowProtocolBT'); -$AllowProtocolBT = $Settings->GetValue (); -$AllowProtocolBT = is_null ($AllowProtocolBT) ? true : strcmp ($AllowProtocolBT, 'Y') == 0; +$Settings = new Settings(); +$Settings->setKey('AllowProtocolBT'); +$AllowProtocolBT = $Settings->getValue(); +$AllowProtocolBT = is_null($AllowProtocolBT) ? true : strcmp($AllowProtocolBT, 'Y') == 0; -$Tmpl->assign ('AllowProtocolBT', $AllowProtocolBT); +$Tmpl->assign('AllowProtocolBT', $AllowProtocolBT); -$Settings->SetTable ('personal'); -$Settings->SetUID (OC_User::getUser ()); -$Rows = $Settings->GetAllValues (); +$Settings->setTable('personal'); +$Settings->setUID(OC_User::getUser()); +$Rows = $Settings->getAllValues(); -while ($Row = $Rows->fetchRow ()) -{ - $Tmpl->assign ('OCDS_' . $Row['KEY'], $Row['VAL']); +while ($Row = $Rows->fetchRow()) { + $Tmpl->assign('OCDS_' . $Row['KEY'], $Row['VAL']); } -return $Tmpl->fetchPage (); \ No newline at end of file +return $Tmpl->fetchPage();