Ejemplo n.º 1
0
def taskpage(request, para1 = ""):
    '''print(para1)'''
    if (para1[-1:] == "/"):
        para1 = para1[:-1]
    import re
    usr = Control.get_username_by_session(request)
    y = Database.get_all("task", {"username": usr})
    tasks = []
    TITLE = "全部任务"
    if (re.match(r'^tasks/downloading$', para1)):
        TITLE = "正在下载"
    if (re.match(r'^tasks/completed$', para1)):
        TITLE = "已完成任务"

    for x in y:
        add = True
        if (re.match(r'^tasks/downloading$', para1)):
            req = Aria.get_task_state(usr, x)
            if not(req['state'] == 'active'):
                add = False

        if (re.match(r'^tasks/completed$', para1)):
            req = Aria.get_task_state(usr, x)
            if not(req['state'] == 'complete'):
                add = False

        if (add):
            tasks.append({"taskname": x[Database.id("task", "taskname")],
                          "gid": x[Database.id("task", "gid")],
                          "date": x[Database.id("task", "createtime")]})

    '''print(TITLE)'''
    return PageResponse.task_page(request, usr, TITLE, tasks)
Ejemplo n.º 2
0
def get_task_state(usr, x):
    req = {}
    try:
        JsonReq = json.dumps({
            'jsonrpc':
            '2.0',
            'id':
            usr + str("@") + str(x[Database.id("task", "taskname")]),
            'method':
            'aria2.tellStatus',
            'params': [
                x[Database.id("task", "gid")],
                ['totalLength', 'completedLength', 'status', 'downloadSpeed']
            ]
        }).encode('utf-8')
        c = json.loads(
            request.urlopen(Const.AriaAddress, JsonReq).read().decode('utf-8'))

        JsonReq = json.dumps({
            'jsonrpc':
            '2.0',
            'id':
            usr + str("@") + str(x[Database.id("task", "taskname")]),
            'method':
            'aria2.getFiles',
            'params': [x[Database.id("task", "gid")]]
        }).encode('utf-8')
        d = json.loads(
            request.urlopen(Const.AriaAddress, JsonReq).read().decode('utf-8'))

        filename = os.path.basename(d['result'][0]['path'])
        req['state'] = c['result']['status']
        req['filename'] = filename
        fv = int(c['result']['downloadSpeed'])
        if (req['state'] != 'active'):
            fv = 0
        req['velocity'] = Basic.bytes_to_maxunit(fv) + '/s'
        if (re.match(r'[0-9]+', c['result']['completedLength'])):
            fclen = int(c['result']['completedLength'])
            ftlen = int(c['result']['totalLength'])
            req['process'] = str(int(fclen / ftlen * 100)) + str("%")
            req['size'] = Basic.bytes_to_maxunit(
                int(c['result']['totalLength']))
            req['timeremain'] = Basic.seconds_to_hms(ftlen - fclen, fv)
        else:
            req['process'] = 'Unknown'
            req['size'] = 'Unknown'
            req['timeremain'] = 'Unknown'
    except:
        req = {
            'process': "-",
            'state': "error",
            'size': "-",
            'velocity': "-",
            'filename': "-",
            'timeremain': "-"
        }
    return req
Ejemplo n.º 3
0
def check_memoryuse(request):
    usr = get_username_by_session(request)
    from urllib import request
    import re, json
    y = Database.get_all("task", {"username": usr})
    z = []
    memory = 0
    for x in y:
        jsonreq = json.dumps({
            'jsonrpc':
            '2.0',
            'id':
            usr + str("@") + str(x[Database.id("task", "taskname")]),
            'method':
            'aria2.tellStatus',
            'params': [
                x[Database.id("task", "gid")],
                ['totalLength', 'completedLength', 'status']
            ]
        }).encode('utf-8')
        c = json.loads(
            request.urlopen('http://*****:*****@") + str(x[Database.id("task", "taskname")]),
                'method':
                'aria2.forcePause',
                'params': [x[Database.id("task", "gid")]]
            }).encode('utf-8')
            request.urlopen('http://localhost:6800/jsonrpc', jsonreq)
    return memory
Ejemplo n.º 4
0
def auto_delete():
    print('START AUTO DELETE')
    y = Database.get_all("task", {})
    for x in y:
        print(x)
        if (x[Database.id("task", "attr")] == 0):
            try:
                Aria.operate(x[Database.id("task", "username")],
                             x[Database.id("task", "taskname")],
                             x[Database.id("task", "gid")], 'aria2.forcePause')
                Aria.operate(x[Database.id("task", "username")],
                             x[Database.id("task", "taskname")],
                             x[Database.id("task",
                                           "gid")], 'aria2.forceRemove')
            except:
                print('NOT ERROR')
            remove_task(x[Database.id("task", "username")],
                        x[Database.id("task", "taskname")],
                        x[Database.id("task", "gid")])
Ejemplo n.º 5
0
def get_tasks_state(request):
    if request.is_ajax():
        import json
        if Control.check_session(request):
            usr = Control.get_username_by_session(request)

            x = Database.find_single("account", {"username": usr})
            old = x[Database.id("account", "memoryused")]

            memory = Control.check_memoryuse(request)
            if (memory >= MemoryLimit) and (old < MemoryLimit):
                return JsonResponse.memory_limit_exceeded()

            req_all = []
            data = json.loads(request.POST['data'])
            fromurl = request.POST['from']

            needreturn = {}
            for x in data:
                needreturn[x["task_name"]] = x["workid"]

            y = Database.get_all("task", {"username": usr})
            download_cnt = 0
            overall_cnt = len(y)

            for x in y:
                req = Aria.get_task_state(usr, x)
                if (req['state'] == 'active'):
                    download_cnt += 1

                if (re.match(r'^/index/tasks/completed/?$', fromurl)) and (
                        req['state']
                        == 'complete') and not (needreturn.__contains__(
                            x[Database.id("task", "taskname")])):
                    return JsonResponse.need_refresh()

                if (needreturn.__contains__(x[Database.id("task",
                                                          "taskname")])):
                    '''print(fromurl)'''
                    if (re.match(r'^/index/tasks/downloading/?$',
                                 fromurl)) and (req['state'] != 'active'):
                        return JsonResponse.need_refresh()

                if (needreturn.__contains__(x[Database.id("task",
                                                          "taskname")])):
                    req['workid'] = needreturn[x[Database.id(
                        "task", "taskname")]]
                    if (x[Database.id("task", "attr")] == 0):
                        req['attr'] = "temporary"
                    else:
                        req['attr'] = "persistent"
                    req_all.append(req)
            '''print(req_all)'''
            return JsonResponse.get_tasks_state(req_all, download_cnt,
                                                overall_cnt, memory)

        else:
            return JsonResponse.session_failed()
    else:
        return PageResponse.jump_to_not_exist()
Ejemplo n.º 6
0
def newpage(request, para1):
    usr = Control.get_username_by_session(request)
    import re
    TITLE = "新建链接任务"
    if (re.match(r'^new/newbt/?$', para1)):
        TITLE = "新建BT任务"
    elif (re.match(r'^new/newmeta/?$', para1)):
        TITLE = "新建磁力任务"
    y = Database.get_all("task", {"username": usr})
    tasks = []
    for i in y:
        tasks.append({"gid": i[Database.id("task", "gid")]})
    return PageResponse.new_task_page(request, usr, TITLE, tasks)
Ejemplo n.º 7
0
def optask(request, method):
    import json
    if request.is_ajax():
        if Control.check_session(request):
            print(method)
            op = []
            if (method == 'delete'):
                op = ['aria2.forcePause', 'aria2.forceRemove']
            elif (method == 'pause'):
                op = ['aria2.forcePause']
            elif (method == 'continue'):
                if (Control.check_memoryuse(request) >= Const.MemoryLimit):
                    return JsonResponse.memory_limit_exceeded()
                else:
                    op = ['aria2.unpause']
            elif (method == 'switch'):
                op = []
            usr = Control.get_username_by_session(request)

            y = json.loads(request.POST['jsonData'])
            for x in y:
                for xop in op:
                    try:
                        Aria.operate(usr, x["task_name"], x["gid"], xop)
                    except:
                        print('NOT ERROR')

                if (method == 'delete'):
                    Control.remove_task(usr, x["task_name"], x["gid"])

                if (method == 'switch'):
                    thisone = Database.find_single(
                        "task", {
                            "username": usr,
                            "gid": x["gid"],
                            "taskname": x["task_name"]
                        })
                    Database.update(
                        "task", {
                            "username": usr,
                            "gid": x["gid"],
                            "taskname": x["task_name"]
                        }, {"attr": 1 - thisone[Database.id("task", "attr")]})

            return JsonResponse.operation_success()
        else:
            return JsonResponse.session_failed()
    else:
        return PageResponse.jump_to_not_exist()
Ejemplo n.º 8
0
def newtask(request, para1):
    if request.is_ajax():
        if Control.check_session(request):
            usr = Control.get_username_by_session(request)
            y = Database.get_all("task", {"username": usr})

            if (Control.check_memoryuse(request) == -1):
                return JsonResponse.memory_limit_exceeded()

            if len(y) > Const.TaskNumberLimit:
                assert 0
            elif len(y) == Const.TaskNumberLimit:
                return JsonResponse.task_number_exceeded()

            for x in y:
                if (x[Database.id("task", "taskname")] == request.POST["task_name"]):
                    return JsonResponse.task_name_repeated()

            try:
                import base64
                if (para1 == 'bt'):
                    btfile = request.FILES.get("task_link", None)
                    if not btfile:
                        return JsonResponse.upload_btfile_empty()
                    if (btfile.multiple_chunks()):
                        return JsonResponse.upload_btfile_toolarge()
                    else:
                        bt = base64.b64encode(btfile.read()).decode("utf-8")
                        c = Aria.add_other_task(usr, request.POST["task_name"], bt, "aria2.addTorrent")
                elif (para1 == 'meta'):
                    metalink = base64.b64decode(request.POST["task_link"])
                    c = Aria.add_other_task(usr, request.POST["task_name"], metalink, "aria2.addMetalink")
                else:
                    c = Aria.add_url_task(usr, request.POST["task_name"], request.POST["task_link"])
                import time as Time
                Database.insert("task", {"username": usr,
                                         "gid": c["result"],
                                         "taskname": str(request.POST["task_name"]),
                                         "createtime": Time.strftime('%Y-%m-%d', Time.localtime(Time.time())),
                                         "attr": 0})
                return JsonResponse.operation_success()
            except:
                return JsonResponse.download_tool_error()
        else:
            return JsonResponse.session_failed()
    else:
        return PageResponse.jump_to_not_exist()
Ejemplo n.º 9
0
def check_login(request):
    if Control.check_session(request):
        return PageResponse.jump_to_index()
    if (request.method == "POST"):
        try:
            from Download9.getmd5 import getmd5
            pwd = getmd5(request.POST["password"])
            x = Database.find_single("account",
                                     {"username": request.POST["username"]})
            assert x[Database.id("account", "password")] == pwd
            request.session["MemberName"] = request.POST["username"]
            request.session.set_expiry(Const.LoginTime)
            return PageResponse.login_success(request)
        except:
            return PageResponse.login_failed(request, request.POST["username"],
                                             request.POST["password"])
    else:
        return PageResponse.jump_to_not_exist()
Ejemplo n.º 10
0
def get_overall_state(request):
    if request.is_ajax():
        import json
        if Control.check_session(request):
            usr = Control.get_username_by_session(request)

            x = Database.find_single("account", {"username": usr})
            old = x[Database.id("account", "memoryused")]

            memory = Control.check_memoryuse(request)
            if (memory >= MemoryLimit) and (old < MemoryLimit):
                return JsonResponse.memory_limit_exceeded()

            y = Database.get_all("task", {"username": usr})
            overall_cnt = len(y)
            return JsonResponse.get_overall_state(overall_cnt, memory)

        else:
            return JsonResponse.session_failed()
    else:
        return PageResponse.jump_to_not_exist()