added admin option for configuring Aria2 globally;option for diallowing aria2 settings for non-privileged users;cleanining up

This commit is contained in:
huangjx
2022-07-31 22:30:32 +08:00
parent e85b8b87ba
commit b1b8bcf988
16 changed files with 284 additions and 129 deletions

View File

@@ -29,7 +29,8 @@ class Application extends App
}); });
$container->registerService('Aria2', function (IContainer $container) { $container->registerService('Aria2', function (IContainer $container) {
return new Aria2(Helper::getAria2Config($this->uid)); $config = Helper::getAria2Config($this->uid);
return new Aria2($config);
}); });
$container->registerService('Ytdl', function (IContainer $container) { $container->registerService('Ytdl', function (IContainer $container) {
@@ -93,5 +94,4 @@ class Application extends App
}); });
} }
} }
} }

View File

@@ -15,17 +15,17 @@ return [
['name' => 'Ytdl#Redownload', 'url' => '/ytdl/redownload', 'verb' => 'POST'], ['name' => 'Ytdl#Redownload', 'url' => '/ytdl/redownload', 'verb' => 'POST'],
['name' => 'Search#Execute', 'url' => '/search', 'verb' => 'POST'], ['name' => 'Search#Execute', 'url' => '/search', 'verb' => 'POST'],
// AdminSettings // AdminSettings
['name' => 'Settings#Admin', 'url' => '/admin/save', 'verb' => 'POST'], ['name' => 'Settings#saveAdmin', 'url' => '/admin/save', 'verb' => 'POST'],
['name' => 'Settings#saveAria2Admin', 'url' => '/admin/aria2/save', 'verb' => 'POST'], ['name' => 'Settings#saveGlobalAria2', 'url' => '/admin/aria2/save', 'verb' => 'POST'],
['name' => 'Settings#getAria2Admin', 'url' => '/admin/aria2/get', 'verb' => 'GET'], ['name' => 'Settings#getGlobalAria2', 'url' => '/admin/aria2/get', 'verb' => 'GET'],
// PersonalSettings // PersonalSettings
['name' => 'Settings#Personal', 'url' => '/personal/save', 'verb' => 'POST'], ['name' => 'Settings#saveCustom', 'url' => '/personal/save', 'verb' => 'POST'],
['name' => 'Settings#aria2Get', 'url' => '/personal/aria2/get', 'verb' => 'POST'], ['name' => 'Settings#getCustomAria2', 'url' => '/personal/aria2/get', 'verb' => 'POST'],
['name' => 'Settings#aria2Save', 'url' => '/personal/aria2/save', 'verb' => 'POST'], ['name' => 'Settings#saveCustomAria2', 'url' => '/personal/aria2/save', 'verb' => 'POST'],
['name' => 'Settings#aria2Delete', 'url' => '/personal/aria2/delete', 'verb' => 'POST'], ['name' => 'Settings#deleteCustomAria2', 'url' => '/personal/aria2/delete', 'verb' => 'POST'],
['name' => 'Settings#ytdlGet', 'url' => '/personal/ytdl/get', 'verb' => 'POST'], ['name' => 'Settings#getYtdl', 'url' => '/personal/ytdl/get', 'verb' => 'POST'],
['name' => 'Settings#ytdlSave', 'url' => '/personal/ytdl/save', 'verb' => 'POST'], ['name' => 'Settings#saveYtdl', 'url' => '/personal/ytdl/save', 'verb' => 'POST'],
['name' => 'Settings#ytdlDelete', 'url' => '/personal/ytdl/delete', 'verb' => 'POST'], ['name' => 'Settings#deleteYtdl', 'url' => '/personal/ytdl/delete', 'verb' => 'POST'],
['name' => 'Settings#getSettings', 'url' => '/getsettings', 'verb' => 'POST'], ['name' => 'Settings#getSettings', 'url' => '/getsettings', 'verb' => 'POST'],
], ],
]; ];

View File

@@ -9,6 +9,8 @@ use OCA\NCDownloader\Tools\Helper;
class Aria2 class Aria2
{ {
//global Aria2 Config
private $config = [];
//extra Aria2 download options //extra Aria2 download options
private $options = array(); private $options = array();
//optional token for authenticating with Aria2 //optional token for authenticating with Aria2
@@ -25,18 +27,33 @@ class Aria2
private $filterResponse = true; private $filterResponse = true;
//absolute download path //absolute download path
private $downloadDir; private $downloadDir;
//top-level aria2 configuration dir
private $confDir;
//aria2 session file
private $sessionFile;
//aria2 rpc url
private $rpcUrl;
//php binary path;
private $php;
public function __construct($options = array()) public function __construct($options = array())
{ {
$options += array( $options += [
'host' => '127.0.0.1', 'rpcHost' => '127.0.0.1',
'port' => 6800, 'rpcPort' => 6800,
'dir' => '/tmp/Downloads', 'dir' => '/tmp/Downloads',
'torrents_dir' => '/tmp/Torrents', 'torrentsDir' => '/tmp/Torrents',
'token' => null, 'token' => 'ncdownloader123',
'conf_dir' => '/tmp/aria2', 'confDir' => '/tmp/aria2',
'completeHook' => $_SERVER['DOCUMENT_ROOT'] . "/apps/ncdownloader/hooks/completeHook.sh", //settings for each aria2 downloads
'settings' => [], 'settings' => [],
); //options wich which aria2c starts
'aria2Conf' => []
];
//set the hooks if no user-defined equivalents
$options["aria2Conf"] += [
'on-download-complete' => $_SERVER['DOCUMENT_ROOT'] . "/apps/ncdownloader/hooks/completeHook.sh",
'on-download-start' => $_SERVER['DOCUMENT_ROOT'] . "/apps/ncdownloader/hooks/startHook.sh",
];
//turn keys in $options into variables //turn keys in $options into variables
extract($options); extract($options);
if (isset($binary) && $this->isExecutable($binary)) { if (isset($binary) && $this->isExecutable($binary)) {
@@ -47,27 +64,12 @@ class Aria2
if ($this->isInstalled() && !$this->isExecutable()) { if ($this->isInstalled() && !$this->isExecutable()) {
chmod($this->bin, 0744); chmod($this->bin, 0744);
} }
$this->setDownloadDir($dir); $this->confDir = $confDir;
$this->setTorrentsDir($torrents_dir);
if (!empty($settings)) {
foreach ($settings as $key => $value) {
$this->setOption($key, $value);
}
}
$this->php = Helper::findBinaryPath('php'); $this->php = Helper::findBinaryPath('php');
$this->completeHook = $completeHook; $this->rpcUrl = sprintf("http://%s:%s/jsonrpc", $rpcHost, $rpcPort);
$this->startHook = $startHook; $this->sessionFile = $sessionFile ?? $this->confDir . "/aria2.session";
$this->rpcUrl = sprintf("http://%s:%s/jsonrpc", $host, $port); $this->configureGlobalAria2($options);
$this->tokenString = $token ?? 'ncdownloader123'; $this->configureLocalAria2($options);
$this->rpcPort = $rpcPort ?? 6800;
$this->dlSpeed = $dlSpeed ?? 0;
$this->upSpeed = $upSpeed ?? "1M";
$this->logLevel = $logLevel ?? 'warn';
$this->setToken($this->tokenString);
$this->confDir = $conf_dir;
$this->sessionFile = $this->confDir . "/aria2.session";
//$this->confFile = $this->confDir . "/aria2.conf";
$this->logFile = $this->confDir . "/aria2.log";
} }
public function init() public function init()
{ {
@@ -81,6 +83,32 @@ class Aria2
$this->configure(); $this->configure();
} }
private function configureLocalAria2(array $options)
{
$this->setDownloadDir($options["dir"]);
$this->setTorrentsDir($options["torrentsDir"]);
$this->setToken($options["token"]);
if (!empty($options["settings"])) {
foreach ($options["settings"] as $key => $value) {
$this->setOption($key, $value);
}
}
}
private function configureGlobalAria2(array $options)
{
$runOptions = new RunOptions($options["aria2Conf"]);
$runOptions->add("--rpc-secret=" . $options["token"]);
$runOptions->add("--rpc-listen-port=" . $options["rpcPort"]);
$runOptions->add("--save-session=" . $this->sessionFile);
$runOptions->add("--input-file=" . $this->sessionFile);
$runOptions->add("--log=" . $this->confDir . "/aria2.log");
//$this->logFile = $this->confDir . "/aria2.log";
$this->config = $runOptions->getOptions();
}
public function setonDownloadStart($path) public function setonDownloadStart($path)
{ {
$this->onDownloadStart = $path; $this->onDownloadStart = $path;
@@ -284,11 +312,6 @@ class Aria2
{ {
return $this->tellStatus($gid); return $this->tellStatus($gid);
} }
public function restart()
{
$this->stop();
$this->start();
}
public function download(String $url) public function download(String $url)
{ {
@@ -325,35 +348,19 @@ class Aria2
return false; return false;
} }
public function getDefaults() public function restart()
{ {
return [ $this->stop();
'--continue', $this->start();
'--daemon=true',
'--enable-rpc=true',
'--rpc-secret=' . $this->tokenString,
'--listen-port=51413',
'--save-session=' . $this->sessionFile,
'--input-file=' . $this->sessionFile,
'--log=' . $this->logFile,
'--rpc-listen-port=' . $this->rpcPort,
'--follow-torrent=true',
'--enable-dht=true',
'--enable-peer-exchange=true',
'--peer-id-prefix=-TR2770-',
'--user-agent=Transmission/2.77',
'--log-level=' . $this->logLevel,
'--seed-ratio=1.0',
'--bt-seed-unverified=true',
'--max-overall-upload-limit=' . $this->upSpeed,
'--max-overall-download-limit=' . $this->dlSpeed,
'--max-connection-per-server=4',
'--max-concurrent-downloads=10',
'--check-certificate=false',
'--on-download-complete=' . $this->completeHook,
'--on-download-start=' . $this->startHook,
];
} }
public function stop()
{
$resp = $this->shutdown();
sleep(3);
return $resp ?? null;
}
public function start($bin = null) public function start($bin = null)
{ {
//aria2c refuses to start with no errors when input-file is set but missing //aria2c refuses to start with no errors when input-file is set but missing
@@ -362,9 +369,8 @@ class Aria2
} }
//$process = new Process([$this->bin, "--conf-path=" . $this->confFile]); //$process = new Process([$this->bin, "--conf-path=" . $this->confFile]);
$defaults = $this->getDefaults(); array_unshift($this->config, $this->bin);
array_unshift($defaults, $this->bin); $process = new Process($this->config);
$process = new Process($defaults);
try { try {
$process->mustRun(); $process->mustRun();
$output = $process->getOutput(); $output = $process->getOutput();
@@ -399,10 +405,4 @@ class Aria2
{ {
return $this->bin; return $this->bin;
} }
public function stop()
{
$resp = $this->shutdown();
sleep(3);
return $resp ?? null;
}
} }

82
lib/Aria2/RunOptions.php Normal file
View File

@@ -0,0 +1,82 @@
<?php
namespace OCA\NCDownloader\Aria2;
class RunOptions
{
protected $options = [
'--continue',
'--daemon=true',
'--enable-rpc=true',
'--rpc-secret=ncdownloader123',
'--listen-port=51413',
'--rpc-listen-port=6800',
'--follow-torrent=true',
'--enable-dht=true',
'--enable-peer-exchange=true',
'--peer-id-prefix=-TR2770-',
'--user-agent=Transmission/2.77',
'--log-level=notice',
'--seed-ratio=1.0',
'--bt-seed-unverified=true',
// '--max-overall-upload-limit=' . $this->upSpeed,
// '--max-overall-download-limit=' . $this->dlSpeed,
'--max-connection-per-server=4',
'--max-concurrent-downloads=10',
'--check-certificate=false',
];
public function __construct($options)
{
foreach ($options as $name => $value) {
$name = trim($name);
$value = trim($value);
if (!str_starts_with($value, "--")) {
$name = "--" . $name;
}
if ($value) {
$option = $name . "=" . $value;
} else {
$option = $name;
}
$this->add($option);
}
}
public function add($option)
{
$option = trim($option);
if ($i = $this->find($option)) {
$this->options[$i] = $option;
return $this;
}
array_push($this->options, $option);
return $this;
}
protected function find($option)
{
if (!str_starts_with($option, "--")) {
$option = "--" . $option;
}
if (($i = stripos($option, '=')) === false) {
return $i;
}
$name = substr($option, 0, $i);
foreach ($this->options as $index => $value) {
list($optionName,) = explode("=", $value);
if ($name == $optionName) {
return $index;
}
}
return false;
}
public function has($option)
{
return (bool) array_search($option, $this->options);
}
public function getOptions()
{
return $this->options;
}
}

View File

@@ -42,7 +42,7 @@ class MainController extends Controller
$this->ytdl = $ytdl; $this->ytdl = $ytdl;
$this->isAdmin = \OC_User::isAdminUser($this->uid); $this->isAdmin = \OC_User::isAdminUser($this->uid);
$this->hideError = Helper::getSettings("ncd_hide_errors", false); $this->hideError = Helper::getSettings("ncd_hide_errors", false);
$this->disable_bt_nonadmin = Helper::getSettings("ncd_disable_bt", false, Settings::TYPE["SYSTEM"]); $this->disable_bt_nonadmin = Helper::getAdminSettings("ncd_disable_bt");
$this->accessDenied = $this->l10n->t("Sorry,only admin users can download files via BT!"); $this->accessDenied = $this->l10n->t("Sorry,only admin users can download files via BT!");
} }
/** /**
@@ -117,6 +117,7 @@ class MainController extends Controller
'ncd_hide_errors' => $this->hideError, 'ncd_hide_errors' => $this->hideError,
'ncd_disable_bt' => $this->disable_bt_nonadmin, 'ncd_disable_bt' => $this->disable_bt_nonadmin,
'ncd_downloader_dir' => Helper::getSettings("ncd_downloader_dir"), 'ncd_downloader_dir' => Helper::getSettings("ncd_downloader_dir"),
'disallow_aria2_settings' => Helper::getAdminSettings('disallow_aria2_settings'),
]); ]);
return $params; return $params;
} }
@@ -217,5 +218,4 @@ class MainController extends Controller
$counter = $this->counters->getCounters(); $counter = $this->counters->getCounters();
return new JSONResponse(['counter' => $counter]); return new JSONResponse(['counter' => $counter]);
} }
} }

View File

@@ -41,7 +41,7 @@ class SettingsController extends Controller
* @NoAdminRequired * @NoAdminRequired
* @NoCSRFRequired * @NoCSRFRequired
*/ */
public function personal() public function saveCustom()
{ {
$params = $this->request->getParams(); $params = $this->request->getParams();
foreach ($params as $key => $value) { foreach ($params as $key => $value) {
@@ -54,31 +54,33 @@ class SettingsController extends Controller
* @NoAdminRequired * @NoAdminRequired
* @NoCSRFRequired * @NoCSRFRequired
*/ */
public function aria2Get() public function getCustomAria2()
{ {
$data = json_decode($this->settings->get("custom_aria2_settings")); $data = json_decode($this->settings->get("custom_aria2_settings"));
return new JSONResponse($data); return new JSONResponse($data);
} }
public function admin() public function saveAdmin()
{ {
$this->settings->setType($this->settings::TYPE['SYSTEM']);
$params = $this->request->getParams(); $params = $this->request->getParams();
$data = $this->settings->setType(Settings::TYPE["SYSTEM"])->get("ncd_admin_settings", []);
foreach ($params as $key => $value) { foreach ($params as $key => $value) {
$resp = $this->save($key, $value); if (substr($key, 0, 1) == '_') {
continue;
} }
$data[$key] = $value;
}
$resp = $this->save("ncd_admin_settings", $data, Settings::TYPE["SYSTEM"]);
return new JSONResponse($resp); return new JSONResponse($resp);
} }
public function saveAria2Admin() public function saveGlobalAria2()
{ {
$this->settings->setType($this->settings::TYPE['SYSTEM']);
$params = $this->request->getParams(); $params = $this->request->getParams();
$data = Helper::filterData($params, Helper::aria2Options()); $data = Helper::filterData($params, Helper::aria2Options());
Helper::log($data); $resp = $this->save("global_aria2_config", $data, $this->settings::TYPE['SYSTEM']);
$resp = $this->settings->save("admin_aria2_settings", $data);
return new JSONResponse($resp); return new JSONResponse($resp);
} }
@@ -86,16 +88,21 @@ class SettingsController extends Controller
* *
* @NoCSRFRequired * @NoCSRFRequired
*/ */
public function getAria2Admin() public function getGlobalAria2()
{ {
return new JSONResponse(Helper::getSettings("admin_aria2_settings", "", $this->settings::TYPE['SYSTEM'])); return new JSONResponse(Helper::getSettings("global_aria2_config", "", $this->settings::TYPE['SYSTEM']));
} }
/** /**
* @NoAdminRequired * @NoAdminRequired
* @NoCSRFRequired * @NoCSRFRequired
*/ */
public function aria2Save() public function saveCustomAria2()
{ {
$noAria2Settings = (bool) Helper::getAdminSettings("disallow_aria2_settings");
if (!$noAria2Settings) {
$resp = ["error" => "forbidden", "status" => false];
return new JSONResponse($resp);
}
$params = $this->request->getParams(); $params = $this->request->getParams();
$data = Helper::filterData($params, Helper::aria2Options()); $data = Helper::filterData($params, Helper::aria2Options());
$resp = $this->settings->save("custom_aria2_settings", json_encode($data)); $resp = $this->settings->save("custom_aria2_settings", json_encode($data));
@@ -105,7 +112,7 @@ class SettingsController extends Controller
* @NoAdminRequired * @NoAdminRequired
* @NoCSRFRequired * @NoCSRFRequired
*/ */
public function aria2Delete() public function deleteCustomAria2()
{ {
$saved = json_decode($this->settings->get("custom_aria2_settings"), 1); $saved = json_decode($this->settings->get("custom_aria2_settings"), 1);
$params = $this->request->getParams(); $params = $this->request->getParams();
@@ -121,13 +128,13 @@ class SettingsController extends Controller
* @NoAdminRequired * @NoAdminRequired
* @NoCSRFRequired * @NoCSRFRequired
*/ */
public function ytdlGet() public function getYtdl()
{ {
$data = json_decode($this->settings->get("custom_ytdl_settings")); $data = json_decode($this->settings->get("custom_ytdl_settings"));
return new JSONResponse($data); return new JSONResponse($data);
} }
public function ytdlSave() public function saveYtdl()
{ {
$params = $this->request->getParams(); $params = $this->request->getParams();
$data = array_filter($params, function ($key) { $data = array_filter($params, function ($key) {
@@ -140,7 +147,7 @@ class SettingsController extends Controller
* @NoAdminRequired * @NoAdminRequired
* @NoCSRFRequired * @NoCSRFRequired
*/ */
public function ytdlDelete() public function deleteYtdl()
{ {
$saved = json_decode($this->settings->get("custom_ytdl_settings"), 1); $saved = json_decode($this->settings->get("custom_ytdl_settings"), 1);
$params = $this->request->getParams(); $params = $this->request->getParams();
@@ -150,15 +157,22 @@ class SettingsController extends Controller
$resp = $this->settings->save("custom_ytdl_settings", json_encode($saved)); $resp = $this->settings->save("custom_ytdl_settings", json_encode($saved));
return new JSONResponse($resp); return new JSONResponse($resp);
} }
public function save($key, $value) public function save($key, $value, $type = Settings::TYPE["USER"])
{ {
//key starting with _ is invalid //key starting with _ is invalid
if (substr($key, 0, 1) == '_') { if (substr($key, 0, 1) == '_') {
return; return;
} }
$key = Helper::sanitize($key); $key = Helper::sanitize($key);
if (is_array($value)) {
foreach ($value as $k => &$v) {
$value[$k] = Helper::sanitize($v);
}
} else {
$value = Helper::sanitize($value); $value = Helper::sanitize($value);
}
try { try {
$this->settings->setType($type);
$this->settings->save($key, $value); $this->settings->save($key, $value);
} catch (\Exception $e) { } catch (\Exception $e) {
return ['error' => $e->getMessage(), "status" => false]; return ['error' => $e->getMessage(), "status" => false];

View File

@@ -8,6 +8,8 @@ use OCP\IConfig;
use OCP\IDBConnection; use OCP\IDBConnection;
use OCP\Settings\ISettings; use OCP\Settings\ISettings;
use OCA\NCDownloader\Db\Settings; use OCA\NCDownloader\Db\Settings;
use OCA\NCDownloader\Tools\Helper;
class Admin implements ISettings class Admin implements ISettings
{ {
@@ -36,16 +38,13 @@ class Admin implements ISettings
*/ */
public function getForm() public function getForm()
{ {
$this->settings->setType($this->settings::TYPE['SYSTEM']); $settings = Helper::getAllAdminSettings();
$parameters = [ $settings += [
'settings' => [
"path" => "/apps/ncdownloader/admin/save", "path" => "/apps/ncdownloader/admin/save",
"ncd_yt_binary" => $this->settings->get("ncd_yt_binary"),
"ncd_aria2_binary" => $this->settings->get("ncd_aria2_binary"), ];
"ncd_rpctoken" => $this->settings->get("ncd_rpctoken"), $parameters = [
"ncd_aria2_rpc_host" => $this->settings->get("ncd_aria2_rpc_host"), 'settings' => $settings,
"ncd_aria2_rpc_port" => $this->settings->get("ncd_aria2_rpc_port"),
]
]; ];
return new TemplateResponse('ncdownloader', 'settings/Admin', $parameters, ''); return new TemplateResponse('ncdownloader', 'settings/Admin', $parameters, '');
} }

View File

@@ -45,6 +45,7 @@ class Personal implements ISettings
'ncd_seed_time_unit' => $this->settings->get("ncd_seed_time_unit"), 'ncd_seed_time_unit' => $this->settings->get("ncd_seed_time_unit"),
'ncd_seed_time' => $this->settings->get("ncd_seed_time"), 'ncd_seed_time' => $this->settings->get("ncd_seed_time"),
"path" => '/apps/ncdownloader/personal/save', "path" => '/apps/ncdownloader/personal/save',
"disallow_aria2_settings" => Helper::getAdminSettings("disallow_aria2_settings"),
] ]
]; ];

View File

@@ -454,22 +454,28 @@ class Helper
$torrentsDir = Helper::getRealTorrentsDir(); $torrentsDir = Helper::getRealTorrentsDir();
$appPath = self::getAppPath(); $appPath = self::getAppPath();
$dataDir = self::getDataDir(); $dataDir = self::getDataDir();
$aria2_dir = $dataDir . "/aria2"; $aria2Dir = $dataDir . "/aria2";
$options['seed_time'] = $settings->get("ncd_seed_time"); $options['seed_time'] = $settings->get("ncd_seed_time");
$options['seed_ratio'] = $settings->get("ncd_seed_ratio"); $options['seed_ratio'] = $settings->get("ncd_seed_ratio");
if (is_array($customSettings = $settings->getAria2())) { if (is_array($customSettings = $settings->getAria2())) {
$options = array_merge($customSettings, $options); $options = array_merge($customSettings, $options);
} }
$token = $settings->setType(Settings::TYPE['SYSTEM'])->get('ncd_rpctoken'); $token = Helper::getAdminSettings("ncd_aria2_rpc_token");
$rpcHost = Helper::getAdminSettings("ncd_aria2_rpc_host");
$rpcPort = Helper::getAdminSettings("ncd_aria2_rpc_port");
$binary = Helper::getAdminSettings("ncd_aria2_binary");
$config = [ $config = [
'dir' => $realDownloadDir, 'dir' => $realDownloadDir,
'torrents_dir' => $torrentsDir, 'torrentsDir' => $torrentsDir,
'conf_dir' => $aria2_dir, 'confDir' => $aria2Dir,
'token' => $token, 'token' => $token ? $token : "ncdownloader123",
'settings' => $options, 'settings' => $options,
'binary' => $settings->setType(Settings::TYPE['SYSTEM'])->get('ncd_aria2_binary'), 'rpcHost' => $rpcHost ? $rpcHost : "127.0.0.1",
'rpcPort' => $rpcPort ? $rpcPort : "6800",
'binary' => $binary,
'startHook' => $appPath . "/hooks/startHook.sh", 'startHook' => $appPath . "/hooks/startHook.sh",
'completeHook' => $appPath . "/hooks/completeHook.sh", 'completeHook' => $appPath . "/hooks/completeHook.sh",
'aria2Conf' => Helper::getSettings("global_aria2_config", [], $settings::TYPE['SYSTEM'])
]; ];
return $config; return $config;
} }
@@ -522,4 +528,13 @@ class Helper
{ {
return self::isLegacyVersion() ? \OC::$server->getDatabaseConnection() : \OC::$server->get(\OCP\IDBConnection::class); return self::isLegacyVersion() ? \OC::$server->getDatabaseConnection() : \OC::$server->get(\OCP\IDBConnection::class);
} }
public static function getAdminSettings($key): string
{
$settings = self::getAllAdminSettings();
return $settings[$key] ?? "";
}
public static function getAllAdminSettings(): array
{
return Helper::getSettings("ncd_admin_settings", [], Settings::TYPE["SYSTEM"]);
}
} }

View File

@@ -10,6 +10,15 @@
:path="option.path" :path="option.path"
/> />
</div> </div>
<div class="section">
<toggleButton
:defaultStatus="pStatus"
disabledText="No Aria2 Settings for non-admin Users"
enabledText="No Aria2 Settings for non-admin Users"
@changed="toggle"
name="disallow_aria2_settings"
></toggleButton>
</div>
<customOptions <customOptions
name="admin-aria2-settings" name="admin-aria2-settings"
@mounted="render" @mounted="render"
@@ -25,6 +34,7 @@ import customOptions from "./components/customOptions";
import helper from "./utils/helper"; import helper from "./utils/helper";
import aria2Options from "./utils/aria2Options"; import aria2Options from "./utils/aria2Options";
import settingsRow from "./components/settingsRow"; import settingsRow from "./components/settingsRow";
import toggleButton from "./components/toggleButton";
export default { export default {
name: "adminSettings", name: "adminSettings",
@@ -32,13 +42,31 @@ export default {
return { return {
options: [], options: [],
validOptions: aria2Options, validOptions: aria2Options,
settings: [],
pStatus: false,
}; };
}, },
components: { components: {
customOptions, customOptions,
settingsRow, settingsRow,
toggleButton,
}, },
methods: { methods: {
toggle(name, value) {
let data = {};
data[name] = value ? 1 : 0;
let path = "/apps/ncdownloader/admin/save";
const url = helper.generateUrl(path);
helper
.httpClient(url)
.setData(data)
.setHandler((resp) => {
if (resp["message"]) {
helper.message(helper.t(resp["message"]), 1000);
}
})
.send();
},
render(event, $vm) { render(event, $vm) {
helper helper
.httpClient(helper.generateUrl("/apps/ncdownloader/admin/aria2/get")) .httpClient(helper.generateUrl("/apps/ncdownloader/admin/aria2/get"))
@@ -67,6 +95,8 @@ export default {
try { try {
let data = this.$el.parentElement.getAttribute("data-settings"); let data = this.$el.parentElement.getAttribute("data-settings");
data = JSON.parse(data); data = JSON.parse(data);
this.settings = data;
this.pStatus = helper.str2Boolean(data["disallow_aria2_settings"]);
let path = "/apps/ncdownloader/admin/save"; let path = "/apps/ncdownloader/admin/save";
this.options = [ this.options = [
{ {
@@ -87,7 +117,9 @@ export default {
label: "Aria2 RPC Token", label: "Aria2 RPC Token",
id: "ncd_aria2_rpc_token", id: "ncd_aria2_rpc_token",
value: data.ncd_aria2_rpc_token, value: data.ncd_aria2_rpc_token,
placeholder: data.ncd_aria2_rpc_token ? data.ncd_aria2_rpc_token : "ncdownloader123", placeholder: data.ncd_aria2_rpc_token
? data.ncd_aria2_rpc_token
: "ncdownloader123",
path: path, path: path,
}, },
{ {

View File

@@ -18,7 +18,7 @@
</button> </button>
<button <button
class="custom-settings-save-btn" class="custom-settings-save-btn"
@click.prevent="saveOptions($event)" @click.prevent="saveOptions"
:data-rel="id" :data-rel="id"
> >
<slot name="save">Save</slot> <slot name="save">Save</slot>

View File

@@ -9,7 +9,7 @@
placeholder="Leave empty if no value needed" placeholder="Leave empty if no value needed"
class="form-input-text" class="form-input-text"
/> />
<button class="has-content icon-close" @click="remove($event)"></button> <button class="has-content icon-close" @click="remove"></button>
</div> </div>
</template> </template>
<script> <script>

View File

@@ -8,7 +8,7 @@
:name="id" :name="id"
:value="value" :value="value"
:placeholder="placeholder" :placeholder="placeholder"
@blur="saveHandler($event)" @change="saveHandler"
:data-rel="container" :data-rel="container"
/> />
<input <input
@@ -16,7 +16,7 @@
type="button" type="button"
value="save" value="save"
:data-rel="container" :data-rel="container"
@click.prevent="saveHandler($event)" @click.prevent="saveHandler"
/> />
</div> </div>
</template> </template>
@@ -36,14 +36,15 @@ export default {
}, },
}, },
data() { data() {
let id = this.id.replaceAll("_", "-");
return { return {
classes: this.id.replace("_", "-") + "-input", classes: id + "-input",
container: this.id.replace("_", "-") + "-container", container: id + "-container",
}; };
}, },
methods: { methods: {
saveHandler(e) { saveHandler(e) {
if (e.type == "blur" && this.useBtn) { if (e.type == "change" && this.useBtn) {
return; return;
} }
e.stopPropagation(); e.stopPropagation();
@@ -56,6 +57,9 @@ export default {
.httpClient(url) .httpClient(url)
.setData(data) .setData(data)
.setHandler(function (resp) { .setHandler(function (resp) {
if (!resp) {
return;
}
if (resp.error) { if (resp.error) {
helper.error(resp.error); helper.error(resp.error);
return; return;

View File

@@ -36,10 +36,12 @@ class settingsForm {
let items: dataItems = { let items: dataItems = {
id: keyId, id: keyId,
name: '', name: '',
value: '' value: '',
placeholder: ""
} }
div.appendChild(this._createInput(items)); div.appendChild(this._createInput(items));
items.id = valueId items.id = valueId
items.placeholder = 'Leave empty if no value needed'
div.appendChild(this._createInput(items)); div.appendChild(this._createInput(items));
div.appendChild(this._createCancelBtn()); div.appendChild(this._createCancelBtn());
return div; return div;
@@ -81,7 +83,7 @@ class settingsForm {
_createInput(data: dataItems): HTMLElement { _createInput(data: dataItems): HTMLElement {
let input = document.createElement('input'); let input = document.createElement('input');
let type = data.type || "text"; let type = data.type || "text";
let placeholder = data.placeholder || 'Leave empty if no value needed'; let placeholder = data.placeholder;
let value = data.value || ''; let value = data.value || '';
input.setAttribute('type', type); input.setAttribute('type', type);
input.setAttribute('id', data.id); input.setAttribute('id', data.id);

View File

@@ -13,6 +13,7 @@
/> />
</div> </div>
<customOptions <customOptions
v-if="!disallowAria2Settings"
name="custom-aria2-settings" name="custom-aria2-settings"
title="Personal Aria2 Settings" title="Personal Aria2 Settings"
@mounted="renderAria2" @mounted="renderAria2"
@@ -45,6 +46,7 @@ export default {
options: [], options: [],
aria2Options: aria2Options, aria2Options: aria2Options,
ytdlOptions: ytdlOptions, ytdlOptions: ytdlOptions,
disallowAria2Settings: false,
}; };
}, },
components: { components: {
@@ -99,6 +101,7 @@ export default {
let data = this.$el.parentElement.getAttribute("data-settings"); let data = this.$el.parentElement.getAttribute("data-settings");
data = JSON.parse(data); data = JSON.parse(data);
let path = "/apps/ncdownloader/personal/save"; let path = "/apps/ncdownloader/personal/save";
this.disallowAria2Settings = helper.str2Boolean(data["disallow_aria2_settings"]);
this.options = [ this.options = [
{ {
label: "Downloads Folder ", label: "Downloads Folder ",

View File

@@ -356,6 +356,9 @@ const helper = {
} }
} }
return data return data
},
isEmptyObject(obj) {
return Object.keys(obj).length === 0
} }
} }