/** * @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 { $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']['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; } } $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' => strlen($Target) > 40 ? substr($Target, 0, 40) . '...' : $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'))); } }
/** * @AdminRequired * @NoCSRFRequired */ public function Check() { \OCP\JSON::setContentTypeHeader('application/json'); 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')); } return new JSONResponse($Response); }
/** * @NoAdminRequired * @NoCSRFRequired */ public function Get() { \OCP\JSON::setContentTypeHeader('application/json'); $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; } } } return new JSONResponse(array('ERROR' => false, 'VALS' => $PersonalSettings)); }
/** * @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 { $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' => strlen($DL['FILENAME']) > 40 ? substr($DL['FILENAME'], 0, 40) . '...' : $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'))); } }
/** * @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())); } }
/** * @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'); } $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())); } } }
/** * @NoAdminRequired * @NoCSRFRequired */ public function ListTorrentFiles() { \OCP\JSON::setContentTypeHeader('application/json'); try { 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'); $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 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; } } } } return new JSONResponse(array('ERROR' => false, 'VALS' => $AdminSettings)); }
/** * @AdminRequired */ public function SetuPnP($ip) { \OCP\JSON::setContentTypeHeader('application/json'); $app = new Application(); $c = $app->getContainer(); $as = $c->query('OCA\\OCIPv6\\Service\\AuthorService'); exec("upnpc -d 443 TCP", $output, $ret); $port = $as->getAppValue('upnp_port'); exec("upnpc -d {$port} TCP", $output, $ret); if (preg_match('/^[0-9.]+$/', $ip)) { exec("upnpc -a {$ip} 443 443 TCP", $output, $ret); if ($ret != 0 || !preg_match('/:443 TCP is redirected to internal/', array_pop($output), $match)) { exec("upnpc -a {$ip} 4443 4443 TCP", $output, $ret); $port = 4443; } if ($ret == 0) { $as->setAppValue('upnp', $ip); $as->setAppValue('upnp_port', $port); return new JSONResponse(array('result' => $ret)); } } $as->setAppValue('upnp', ''); $as->setAppValue('upnp_port', '443'); return new JSONResponse(array('result' => $ret)); }
/** * @NoAdminRequired * @NoCSRFRequired * @SSOCORS */ public function upload($dir = '/') { \OC::$server->getSession()->close(); // Firefox and Konqueror tries to download application/json for me. --Arthur \OCP\JSON::setContentTypeHeader('text/plain'); // If a directory token is sent along check if public upload is permitted. // If not, check the login. // If no token is sent along, rely on login only $allowedPermissions = \OCP\Constants::PERMISSION_ALL; $errorCode = null; if (\OC\Files\Filesystem::file_exists($dir) === false) { return new DataResponse(array('data' => array_merge(array('message' => 'Invalid directory.')), 'status' => 'error')); } // get array with current storage stats (e.g. max file size) $storageStats = \OCA\Files\Helper::buildFileStorageStatistics($dir); $files = $this->request->getUploadedFile('files'); if (!isset($files)) { return new DataResponse(array('data' => array_merge(array('message' => 'No file was uploaded. Unknown error'), $storageStats), 'status' => 'error')); } foreach ($files['error'] as $error) { if ($error != 0) { $errors = array(UPLOAD_ERR_OK => 'There is no error, the file uploaded with success', UPLOAD_ERR_INI_SIZE => 'The uploaded file exceeds the upload_max_filesize directive in php.ini: ' . ini_get('upload_max_filesize'), UPLOAD_ERR_FORM_SIZE => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form', UPLOAD_ERR_PARTIAL => 'The uploaded file was only partially uploaded', UPLOAD_ERR_NO_FILE => 'No file was uploaded', UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder', UPLOAD_ERR_CANT_WRITE => 'Failed to write to disk'); $errorMessage = $errors[$error]; \OC::$server->getLogger()->alert("Upload error: {$error} - {$errorMessage}", array('app' => 'files')); return new DataResponse(array('data' => array_merge(array('message' => $errorMessage), $storageStats), 'status' => 'error')); } } $error = false; $maxUploadFileSize = $storageStats['uploadMaxFilesize']; $maxHumanFileSize = \OCP\Util::humanFileSize($maxUploadFileSize); $totalSize = 0; foreach ($files['size'] as $size) { $totalSize += $size; } if ($maxUploadFileSize >= 0 and $totalSize > $maxUploadFileSize) { return new DataResponse(array('data' => array('message' => 'Not enough storage available', 'uploadMaxFilesize' => $maxUploadFileSize, ' maxHumanFilesize' => $maxHumanFileSize), 'status' => 'error')); } $result = array(); $fileCount = count($files['name']); for ($i = 0; $i < $fileCount; $i++) { // target directory for when uploading folders $relativePath = ''; $target = \OC\Files\Filesystem::normalizePath($dir . $relativePath . '/' . $files['name'][$i]); // relative dir to return to the client if (isset($publicDirectory)) { // path relative to the public root $returnedDir = $publicDirectory . $relativePath; } else { // full path $returnedDir = $dir . $relativePath; } $returnedDir = \OC\Files\Filesystem::normalizePath($returnedDir); $exists = \OC\Files\Filesystem::file_exists($target); if ($exists) { $target = \OCP\Files::buildNotExistingFileName($dir . $relativePath, $files['name'][$i]); } try { if (is_uploaded_file($files['tmp_name'][$i]) and \OC\Files\Filesystem::fromTmpFile($files['tmp_name'][$i], $target)) { // updated max file size after upload $storageStats = \OCA\Files\Helper::buildFileStorageStatistics($dir); $meta = \OC\Files\Filesystem::getFileInfo($target); if ($meta === false) { $error = 'The target folder has been moved or deleted.'; $errorCode = 'targetnotfound'; } else { $data = \OCA\Files\Helper::formatFileInfo($meta); $data['originalname'] = $files['name'][$i]; $data['uploadMaxFilesize'] = $maxUploadFileSize; $data['maxHumanFilesize'] = $maxHumanFileSize; $data['permissions'] = $meta['permissions'] & $allowedPermissions; $data['directory'] = $returnedDir; $result[] = $data; } } else { $error = 'Upload failed. Could not find uploaded file'; } } catch (Exception $ex) { $error = $ex->getMessage(); } } if ($error === false) { $result = \OCP\JSON::encode($result); return new DataResponse(array('data' => $result, 'status' => 'success')); } else { return new DataResponse(array('data' => array_merge(array('message' => $error, 'code' => $errorCode), $storageStats), 'status' => 'error')); } }