예제 #1
0
def admin():
    # convert to dict
    user = dict((name, convert.to_dict(y)) for name, y in API.get_all_user_data().iteritems())
    perms = permlist()

    for data in user.itervalues():
        data['perms'] = {}
        get_permission(data['perms'], data['permission'])
        data['perms']['admin'] = data['role'] is 0

    s = bottle.request.environ.get('beaker.session')
    if bottle.request.environ.get('REQUEST_METHOD', "GET") == "POST":
        for name in user:
            if bottle.request.POST.get("%s|admin" % name, False):
                user[name]['role'] = 0
                user[name]['perms']['admin'] = True
            elif name != s['name']:
                user[name]['role'] = 1
                user[name]['perms']['admin'] = False

            # set all perms to false
            for perm in perms:
                user[name]['perms'][perm] = False

            for perm in bottle.request.POST.getall("%s|perms" % name):
                user[name]['perms'][perm] = True

            user[name]['permission'] = set_permission(user[name]['perms'])

            API.set_user_permission(name, user[name]['permission'], user[name]['role'])

    return render_to_response("admin.html", {"users": user, "permlist": perms}, [pre_processor])
예제 #2
0
def pre_processor():
    s = bottle.request.environ.get('beaker.session')
    user = parse_userdata(s)
    perms = parse_permissions(s)
    status = {}
    captcha = False
    update = False
    plugins = False
    if user['is_authenticated']:
        status = API.status_server()
        info = API.get_info_by_plugin("UpdateManager")
        captcha = API.is_captcha_waiting()

        # check if update check is available
        if info:
            if info['pyload'] == "True":
                update = info['version']
            if info['plugins'] == "True":
                plugins = True

    return {"user": user,
            'status': status,
            'captcha': captcha,
            'perms': perms,
            'url': bottle.request.url,
            'update': update,
            'plugins': plugins}
예제 #3
0
def add(request):
    package = bottle.request.POST.get('referer', None)
    urls = filter(lambda x: x != "", bottle.request.POST['urls'].split("\n"))

    if package:
        API.add_package(package, urls, 0)
    else:
        API.generate_and_add_packages(urls, 0)

    return ""
예제 #4
0
def config():
    conf = API.get_config()
    plugin = API.get_plugin_config()
    conf_menu = []
    plugin_menu = []

    for entry in sorted(conf.keys()):
        conf_menu.append((entry, conf[entry].description))

    last_name = None
    for entry in sorted(plugin.keys()):
        desc = plugin[entry].description
        name, none, type = desc.partition("_")

        if type in API.pyload.pluginManager.TYPES:
            if name == last_name or len([a for a, b in plugin.iteritems() if b.description.startswith(name + "_")]) > 1:
                desc = name + " (" + type.title() + ")"
            else:
                desc = name
            last_name = name
        plugin_menu.append((entry, desc))

    accs = API.get_accounts(False)

    for data in accs:
        if data.trafficleft == -1:
            data.trafficleft = _("unlimited")
        elif not data.trafficleft:
            data.trafficleft = _("not available")
        else:
            data.trafficleft = format_size(data.trafficleft)

        if data.validuntil == -1:
            data.validuntil = _("unlimited")
        elif not data.validuntil:
            data.validuntil = _("not available")
        else:
            t = time.localtime(data.validuntil)
            data.validuntil = time.strftime("%d.%m.%Y - %H:%M:%S", t)

        try:
            data.options['time'] = data.options['time'][0]
        except Exception:
            data.options['time'] = "0:00-0:00"

        if "limitDL" in data.options:
            data.options['limitdl'] = data.options['limitDL'][0]
        else:
            data.options['limitdl'] = "0"

    return render_to_response('settings.html',
                              {'conf': {'plugin': plugin_menu, 'general': conf_menu, 'accs': accs},
                               'types': API.get_account_types()},
                              [pre_processor])
예제 #5
0
def addcrypted():
    package = bottle.request.forms.get('referer', 'ClickNLoad Package')
    dlc = bottle.request.forms['crypted'].replace(" ", "+")

    dlc_path = os.path.join(API.get_config_value('general', 'download_folder'),
                            package.replace("/", "").replace("\\", "").replace(":", "") + ".dlc")
    with open(dlc_path, "wb") as dlc_file:
        dlc_file.write(dlc)

    try:
        API.add_package(package, [dlc_path], 0)
    except Exception:
        return bottle.HTTPError()
    else:
        return "success\r\n"
예제 #6
0
def info():
    conf = API.get_config_dict()
    extra = os.uname() if hasattr(os, "uname") else tuple()

    data = {"python"   : sys.version,
            "os"       : " ".join((os.name, sys.platform) + extra),
            "version"  : API.get_server_version(),
            "folder"   : os.path.abspath(PYLOAD_DIR), "config": os.path.abspath(""),
            "download" : os.path.abspath(conf['general']['download_folder']['value']),
            "freespace": format_size(API.free_space()),
            "remote"   : conf['remote']['port']['value'],
            "webif"    : conf['webui']['port']['value'],
            "language" : conf['general']['language']['value']}

    return render_to_response("info.html", data, [pre_processor])
예제 #7
0
def flashgot():
    if bottle.request.environ['HTTP_REFERER'] not in ("http://localhost:9666/flashgot", "http://127.0.0.1:9666/flashgot"):
        return bottle.HTTPError()

    autostart = int(bottle.request.forms.get('autostart', 0))
    package = bottle.request.forms.get('package', None)
    urls = filter(lambda x: x != "", bottle.request.forms['urls'].split("\n"))
    folder = bottle.request.forms.get('dir', None)

    if package:
        API.add_package(package, urls, autostart)
    else:
        API.generate_and_add_packages(urls, autostart)

    return ""
예제 #8
0
def call_API(func, args=""):
    bottle.response.headers.replace("Content-type", "application/json")
    bottle.response.headers.append("Cache-Control", "no-cache, must-revalidate")

    s = bottle.request.environ.get('beaker.session')
    if 'session' in bottle.request.POST:
        s = s.get_by_id(bottle.request.POST['session'])

    if not s or not s.get("authenticated", False):
        return bottle.HTTPError(403, json_dumps("Forbidden"))

    if not API.is_authorized(func, {"role": s['role'], "permission": s['perms']}):
        return bottle.HTTPError(401, json_dumps("Unauthorized"))

    args = args.split("/")[1:]
    kwargs = {}

    for x, y in itertools.chain(bottle.request.GET.iteritems(), bottle.request.POST.iteritems()):
        if x == "session":
            continue
        kwargs[x] = urllib.unquote(y)

    try:
        return call_API(func, *args, **kwargs)
    except Exception, e:
        traceback.print_exc()
        return bottle.HTTPError(500, json_dumps({"error": e.message, "traceback": traceback.format_exc()}))
예제 #9
0
def login():
    bottle.response.headers.replace("Content-type", "application/json")
    bottle.response.headers.append("Cache-Control", "no-cache, must-revalidate")

    user = bottle.request.forms.get("username")
    password = bottle.request.forms.get("password")

    remote_addr = bottle.request.environ.get("REMOTE_ADDR", "0")

    info = API.check_auth(user, password)

    if info:
        API.pyload.log.debug(_("API login from IP address: %s") % remote_addr)
    else:
        API.pyload.log.warning(_("Failed API login from IP address: %s") % remote_addr)
        return json_dumps(False)

    s = set_session(request, info)

    # get the session id by dirty way, documentations seems wrong
    try:
        sid = s._headers['cookie_out'].split("=")[1].split(";")[0]
        return json_dumps(sid)
    except Exception:
        return json_dumps(True)
예제 #10
0
def downloads():
    root = API.get_config_value("general", "download_folder")

    if not os.path.isdir(root):
        return base([_('Download directory not found.')])
    data = {
        'folder': [],
        'files': []
    }

    items = os.listdir(fs_encode(root))

    for item in sorted([fs_decode(x) for x in items]):
        if os.path.isdir(fs_join(root, item)):
            folder = {
                'name': item,
                'path': item,
                'files': []
            }
            files = os.listdir(fs_join(root, item))
            for file in sorted([fs_decode(x) for x in files]):
                try:
                    if os.path.isfile(fs_join(root, item, file)):
                        folder['files'].append(file)
                except Exception:
                    pass

            data['folder'].append(folder)
        elif os.path.isfile(os.path.join(root, item)):
            data['files'].append(item)

    return render_to_response('downloads.html', {'files': data}, [pre_processor])
예제 #11
0
def login():
    if API.get_config_value("webui", "nolocalauth") \
       and bottle.request.environ.get("REMOTE_ADDR", "0") in ("127.0.0.1", "localhost"):
        set_session(request, "local")
        return bottle.redirect("/")
    else:
        return render_to_response("login.html", proc=[pre_processor])
예제 #12
0
def get_download(path):
    path = urllib.unquote(decode(path))
    #@TODO some files can not be downloaded

    root = API.get_config_value("general", "download_folder")

    path = path.replace("..", "")
    return bottle.static_file(fs_encode(path), fs_encode(root))
예제 #13
0
def addcrypted2():
    package = bottle.request.forms.get("source", None)
    crypted = bottle.request.forms['crypted']
    jk = bottle.request.forms['jk']

    crypted = base64.standard_b64decode(urllib.unquote(crypted.replace(" ", "+")))
    if JS:
        jk = "%s f()" % jk
        jk = JS.eval(jk)

    else:
        try:
            jk = re.findall(r"return ('|\")(.+)('|\")", jk)[0][1]
        except Exception:
            # Test for some known js functions to decode
            if jk.find("dec") > -1 and jk.find("org") > -1:
                org = re.findall(r"var org = ('|\")([^\"']+)", jk)[0][1]
                jk = list(org)
                jk.reverse()
                jk = "".join(jk)
            else:
                print "Could not decrypt key, please install py-spidermonkey or ossp-js"

    try:
        Key = binascii.unhexlify(jk)
    except Exception:
        print "Could not decrypt key, please install py-spidermonkey or ossp-js"
        return "failed"

    IV = Key

    obj = Crypto.Cipher.AES.new(Key, Crypto.Cipher.AES.MODE_CBC, IV)
    result = obj.decrypt(crypted).replace("\x00", "").replace("\r", "").split("\n")

    result = filter(lambda x: x != "", result)

    try:
        if package:
            API.add_package(package, result, 0)
        else:
            API.generate_and_add_packages(result, 0)
    except Exception:
        return "failed can't add"
    else:
        return "success\r\n"
예제 #14
0
def home():
    try:
        res = [convert.to_dict(x) for x in API.status_downloads()]
    except Exception:
        s = bottle.request.environ.get('beaker.session')
        s.delete()
        return bottle.redirect("/login")

    for link in res:
        if link['status'] == 12:
            link['information'] = "%s kB @ %s kB/s" % (link['size'] - link['bleft'], link['speed'])

    return render_to_response("home.html", {"res": res}, [pre_processor])
예제 #15
0
def login_post():
    user = bottle.request.forms.get("username")
    password = bottle.request.forms.get("password")

    remote_addr = bottle.request.environ.get("REMOTE_ADDR", "0")

    info = API.check_auth(user, password)

    if info:
        API.pyload.log.debug(_("WebUI login from IP address: %s") % remote_addr)
    else:
        API.pyload.log.warning(_("Failed WebUI login from IP address: %s") % remote_addr)
        return render_to_response("login.html", {"errors": True}, [pre_processor])

    set_session(info)
    return bottle.redirect("/")
예제 #16
0
def logs(item=-1):
    s = bottle.request.environ.get('beaker.session')

    perpage = s.get('perpage', 34)
    reversed = s.get('reversed', False)

    warning = ""
    conf = API.get_config_value("log", "file_log")
    if not conf:
        warning = "Warning: File log is disabled, see settings page."

    perpage_p = ((20, 20), (50, 50), (100, 100), (250, 250), (0, 'all'))
    fro = None

    if bottle.request.environ.get('REQUEST_METHOD', "GET") == "POST":
        try:
            fro = datetime.datetime.strptime(bottle.request.forms['from'], '%d.%m.%Y %H:%M:%S')
        except Exception:
            pass
        try:
            perpage = int(bottle.request.forms['perpage'])
            s['perpage'] = perpage

            reversed = bool(bottle.request.forms.get('reversed', False))
            s['reversed'] = reversed
        except Exception:
            pass

        s.save()

    try:
        item = int(item)
    except Exception:
        pass

    log = API.get_log()
    if not perpage:
        item = 1

    if item < 1 or type(item) is not int:
        item = 1 if len(log) - perpage + 1 < 1 else len(log) - perpage + 1

    if type(fro) is datetime.datetime:  #: we will search for datetime.datetime
        item = -1

    data = []
    counter = 0
    perpagecheck = 0
    for l in log:
        counter += 1

        if counter >= item:
            try:
                date, time, level, message = decode(l).split(" ", 3)
                dtime = datetime.datetime.strptime(date + ' ' + time, '%Y-%m-%d %H:%M:%S')
            except Exception:
                dtime = None
                date = '?'
                time = ' '
                level = '?'
                message = l

            if item == -1 and dtime is not None and fro <= dtime:
                item = counter  #: found our datetime.datetime

            if item >= 0:
                data.append({'line': counter, 'date': date + " " + time, 'level': level, 'message': message})
                perpagecheck += 1
                if fro is None and dtime is not None:  #: if fro not set set it to first showed line
                    fro = dtime

            if perpagecheck >= perpage > 0:
                break

    if fro is None:  #: still not set, empty log?
        fro = datetime.datetime.now()
    if reversed:
        data.reverse()
    return render_to_response('logs.html', {'warning': warning, 'log': data, 'from': fro.strftime('%d.%m.%Y %H:%M:%S'),
                                            'reversed': reversed, 'perpage': perpage, 'perpage_p': sorted(perpage_p),
                                            'iprev': 1 if item - perpage < 1 else item - perpage,
                                            'inext': (item + perpage) if item + perpage < len(log) else item,
                                            'color_console': API.get_config_value("log", "color_console")},
                              [pre_processor])
예제 #17
0
def collector():
    queue = API.get_collector()

    queue.sort(key=operator.attrgetter("order"))

    return render_to_response('queue.html', {'content': queue, 'target': 0}, [pre_processor])
예제 #18
0
def checksupport():
    url = bottle.request.GET.get("url")
    res = API.checkURLs([url])
    supported = (not res[0][1] is None)

    return str(supported).lower()