From 3326c9232e2667e5e51cffd676678728eb1eef7d Mon Sep 17 00:00:00 2001 From: HFO4 <912394456@qq.com> Date: Tue, 17 Apr 2018 19:59:13 +0800 Subject: [PATCH] add download task list and optimize temp file recovery --- .../index/controller/RemoteDownload.php | 38 ++++++++++- application/index/model/Aria2.php | 47 ++++++++++++- application/index/view/home/Download.html | 25 +------ static/js/remoteDownload.js | 68 +++++++++++++++++-- 4 files changed, 146 insertions(+), 32 deletions(-) diff --git a/application/index/controller/RemoteDownload.php b/application/index/controller/RemoteDownload.php index 1411b651..b9076321 100644 --- a/application/index/controller/RemoteDownload.php +++ b/application/index/controller/RemoteDownload.php @@ -96,14 +96,50 @@ class RemoteDownload extends Controller{ ->where("owner",$this->userObj->uid) ->where("status","<>","complete") ->where("status","<>","error") + ->where("status","<>","canceled") + //取消的 ->select(); foreach ($toBeFlushed as $key => $value) { $aria2->flushStatus($value["id"],$this->userObj->uid,$this->userObj->getPolicy()); } } + public function Cancel(){ + $aria2Options = Option::getValues(["aria2"]); + $aria2 = new Aria2($aria2Options); + $downloadItem = Db::name("download")->where("owner",$this->userObj->uid)->where("id",input("post.id"))->find(); + if(empty($downloadItem)){ + return json(['error'=>1,'message'=>"未找到下载记录"]); + } + if($aria2->Remove($downloadItem["pid"],"")){ + return json(['error'=>0,'message'=>"下载已取消"]); + }else{ + return json(['error'=>1,'message'=>"取消失败"]); + } + } + public function ListDownloading(){ - return json(["s"=>"s"]); + $downloadItems = Db::name("download")->where("owner",$this->userObj->uid)->where("status","in",["active","ready"])->order('id desc')->select(); + foreach ($downloadItems as $key => $value) { + $connectInfo = json_decode($value["info"],true); + if(isset($connectInfo["dir"])){ + $downloadItems[$key]["fileName"] = basename($connectInfo["dir"]); + $downloadItems[$key]["completedLength"] = $connectInfo["completedLength"]; + $downloadItems[$key]["totalLength"] = $connectInfo["totalLength"]; + $downloadItems[$key]["downloadSpeed"] = $connectInfo["downloadSpeed"]; + }else{ + if(floor($value["source"])==$value["source"]){ + $downloadItems[$key]["fileName"] = Db::name("files")->where("id",$value["source"])->column("orign_name"); + }else{ + $downloadItems[$key]["fileName"] = $value["source"]; + } + $downloadItems[$key]["completedLength"] = 0; + $downloadItems[$key]["totalLength"] = 0; + $downloadItems[$key]["downloadSpeed"] = 0; + } + } + return json($downloadItems); } + } \ No newline at end of file diff --git a/application/index/model/Aria2.php b/application/index/model/Aria2.php index dac3d7a4..4798a612 100644 --- a/application/index/model/Aria2.php +++ b/application/index/model/Aria2.php @@ -124,7 +124,9 @@ class Aria2 extends Model{ case 'complete': $this->setComplete($respondData["result"],$downloadInfo); break; - + case 'removed': + $this->setCanceled($respondData["result"],$downloadInfo); + break; default: # code... break; @@ -151,6 +153,31 @@ class Aria2 extends Model{ return true; } + private function setCanceled($quenInfo,$sqlData){ + @self::remove_directory(ROOT_PATH."public".DS."downloads".DS.$sqlData["path_id"]); + if(!is_dir(ROOT_PATH."public".DS."downloads".DS.$sqlData["path_id"])){ + Db::name("download")->where("id",$sqlData["id"])->update([ + "status" => "canceled", + ]); + } + } + + static function remove_directory($dir){ + if($handle=opendir("$dir")){ + while(false!==($item=readdir($handle))){ + if($item!="."&&$item!=".."){ + if(is_dir("$dir/$item")){ + self::remove_directory("$dir/$item"); + }else{ + unlink("$dir/$item"); + } + } + } + closedir($handle); + rmdir($dir); + } + } + private function updateToMuiltpe($quenInfo,$sqlData){ foreach ($quenInfo["files"] as $key => $value) { Db::name("download")->insert([ @@ -174,6 +201,7 @@ class Aria2 extends Model{ $this->setError($quenInfo,$sqlData,"您当前的上传策略无法使用离线下载"); return false; } + $this->forceRemove($sqlData["pid"]); $suffixTmp = explode('.', $quenInfo["dir"]); $fileSuffix = array_pop($suffixTmp); $uploadHandller = new UploadHandler($this->policy["id"],$this->uid); @@ -220,7 +248,7 @@ class Aria2 extends Model{ if($delete){ if(file_exists($quenInfo["files"][$sqlData["file_index"]]["path"])){ @unlink($quenInfo["files"][$sqlData["file_index"]]["path"]); - @unlink(dirname($quenInfo["files"][$sqlData["file_index"]]["path"])); + @self::remove_directory(dirname($quenInfo["files"][$sqlData["file_index"]]["path"])); } } Db::name("download")->where("id",$sqlData["id"])->update([ @@ -259,6 +287,21 @@ class Aria2 extends Model{ return false; } + public function forceRemove($gid){ + $reqFileds = [ + "params" => ["token:".$this->authToken,$gid], + "jsonrpc" => "2.0", + "id" => uniqid(), + "method" => "aria2.forceRemove" + ]; + $reqFileds = json_encode($reqFileds,JSON_OBJECT_AS_ARRAY); + $respondData = $this->sendReq($reqFileds); + if(isset($respondData["result"])){ + return true; + } + return false; + } + private function storageCheck($quenInfo,$sqlData){ if(!FileManage::sotrageCheck($this->uid,(int)$quenInfo["totalLength"])){ return false; diff --git a/application/index/view/home/Download.html b/application/index/view/home/Download.html index a24692bc..1bcdd4b3 100644 --- a/application/index/view/home/Download.html +++ b/application/index/view/home/Download.html @@ -34,32 +34,13 @@ 文件名 大小 储存位置 + 下载速度 进度 操作 - - - 1 - Mark - Otto - @mdo the Bird - @twitter - - - 2 - Jacob - Thornton - @fat the Bird - @twitter - - - 3 - Larry - the Bird - @twitter the Bird - @twitter - + + diff --git a/static/js/remoteDownload.js b/static/js/remoteDownload.js index 144ce569..29b97003 100644 --- a/static/js/remoteDownload.js +++ b/static/js/remoteDownload.js @@ -1,9 +1,63 @@ -$.get("/RemoteDownload/FlushUser", function(){ - $("#loadStatus").html("加载下载列表中"); +$.get("/RemoteDownload/FlushUser", function() { + $("#loadStatus").html("加载下载列表中..."); loadDownloadingList(); }) -function loadDownloadingList(){ - $.getJSON("/RemoteDownload/ListDownloading", function(data){ - console.log(data); - }) -} \ No newline at end of file + +function loadDownloadingList() { + $.getJSON("/RemoteDownload/ListDownloading", function(data) { + $("#itemContent").html(); + if(data.length == 0){ + $("#loadStatus").html("下载列表为空"); + } + data.forEach(function(e) { + $("#itemContent").append(function() { + var row = '' + e["id"] + '' + e["fileName"] + ''; + row = row + '' + bytesToSize(e["totalLength"]) + ''; + row = row + '' + e["save_dir"] + ''; + if (e["downloadSpeed"] == "0") { + row = row + '-'; + } else { + row = row + '' + bytesToSize(e["downloadSpeed"]) + '/s'; + } + row = row + '' + GetPercent(e["completedLength"], e["totalLength"]) + '' + row = row + '取消' + return row + ""; + }); + $("#i-" + e["id"]).css({ + "background-image": "-webkit-gradient(linear, left top, right top, from(#ecefff), to(white), color-stop("+e["completedLength"]/e["totalLength"]+", #ecefff), color-stop("+e["completedLength"]/e["totalLength"]+", white))", + + }); + $(".table-responsive").slideDown(); + $("#loadStatus").slideUp(); + }); + }) + } + + function bytesToSize(bytes) { + if (bytes === 0) return '0 B'; + var k = 1000, // or 1024 + sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], + i = Math.floor(Math.log(bytes) / Math.log(k)); + + return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i]; + } + + function GetPercent(num, total) { + num = parseFloat(num); + total = parseFloat(total); + if (isNaN(num) || isNaN(total)) { + return "-"; + } + return total <= 0 ? "0%" : (Math.round(num / total * 10000) / 100.00 + "%"); + } + + function cancel(id){ + $.post("/RemoteDownload/Cancel", {id:id}, function(data){ + console.log(data); + if(data.error){ + toastr["warning"](data.message); + }else{ + toastr["success"](data.message); + } + }) + } \ No newline at end of file