diff options
author | RaNaN <Mast3rRaNaN@hotmail.de> | 2011-02-10 17:53:25 +0100 |
---|---|---|
committer | RaNaN <Mast3rRaNaN@hotmail.de> | 2011-02-10 17:53:25 +0100 |
commit | 6750a9481f44c55252d72b3c791f5efbcaeae71c (patch) | |
tree | 90011b409c2e1f2103c7b505a013600a2ddd9840 /module/web | |
parent | captcha trader fix (diff) | |
download | pyload-6750a9481f44c55252d72b3c791f5efbcaeae71c.tar.xz |
cleanup
Diffstat (limited to 'module/web')
-rw-r--r-- | module/web/ajax/__init__.py | 0 | ||||
-rw-r--r-- | module/web/ajax/models.py | 2 | ||||
-rw-r--r-- | module/web/ajax/tests.py | 23 | ||||
-rw-r--r-- | module/web/ajax/urls.py | 36 | ||||
-rw-r--r-- | module/web/ajax/views.py | 321 | ||||
-rw-r--r-- | module/web/cnl/__init__.py | 0 | ||||
-rw-r--r-- | module/web/cnl/models.py | 3 | ||||
-rw-r--r-- | module/web/cnl/tests.py | 23 | ||||
-rw-r--r-- | module/web/cnl/urls.py | 21 | ||||
-rw-r--r-- | module/web/cnl/views.py | 166 | ||||
-rw-r--r-- | module/web/pyload/__init__.py | 0 | ||||
-rw-r--r-- | module/web/pyload/admin.py | 15 | ||||
-rw-r--r-- | module/web/pyload/models.py | 31 | ||||
-rw-r--r-- | module/web/pyload/templatetags/__init__.py | 0 | ||||
-rw-r--r-- | module/web/pyload/templatetags/contains.py | 14 | ||||
-rw-r--r-- | module/web/pyload/templatetags/quotepath.py | 68 | ||||
-rw-r--r-- | module/web/pyload/templatetags/token.py | 17 | ||||
-rw-r--r-- | module/web/pyload/templatetags/truncate.py | 13 | ||||
-rw-r--r-- | module/web/pyload/tests.py | 23 | ||||
-rw-r--r-- | module/web/pyload/urls.py | 31 | ||||
-rw-r--r-- | module/web/pyload/views.py | 492 | ||||
-rw-r--r-- | module/web/pyload_app.py | 47 |
22 files changed, 32 insertions, 1314 deletions
diff --git a/module/web/ajax/__init__.py b/module/web/ajax/__init__.py deleted file mode 100644 index e69de29bb..000000000 --- a/module/web/ajax/__init__.py +++ /dev/null diff --git a/module/web/ajax/models.py b/module/web/ajax/models.py deleted file mode 100644 index 35e0d6486..000000000 --- a/module/web/ajax/models.py +++ /dev/null @@ -1,2 +0,0 @@ - -# Create your models here. diff --git a/module/web/ajax/tests.py b/module/web/ajax/tests.py deleted file mode 100644 index 2247054b3..000000000 --- a/module/web/ajax/tests.py +++ /dev/null @@ -1,23 +0,0 @@ -""" -This file demonstrates two different styles of tests (one doctest and one -unittest). These will both pass when you run "manage.py test". - -Replace these with more appropriate tests for your application. -""" - -from django.test import TestCase - -class SimpleTest(TestCase): - def test_basic_addition(self): - """ - Tests that 1 + 1 always equals 2. - """ - self.failUnlessEqual(1 + 1, 2) - -__test__ = {"doctest": """ -Another way to test that 1 + 1 is equal to 2. - ->>> 1 + 1 == 2 -True -"""} - diff --git a/module/web/ajax/urls.py b/module/web/ajax/urls.py deleted file mode 100644 index ebbf401af..000000000 --- a/module/web/ajax/urls.py +++ /dev/null @@ -1,36 +0,0 @@ -# -*- coding: utf-8 -*- -from django.conf.urls.defaults import * - - -urlpatterns = patterns('ajax', - # Example: - # (r'^pyload/', include('pyload.foo.urls')), - - # Uncomment the admin/doc line below and add 'django.contrib.admindocs' - # to INSTALLED_APPS to enable admin documentation: - # (r'^admin/doc/', include('django.contrib.admindocs.urls')), - - # Uncomment the next line to enable the admin: - (r'^add_package$', 'views.add_package'), - (r'^abort_link/(\d+)$', 'views.abort_link'), - (r'^status$', 'views.status'), - (r'^links$', 'views.links'), #currently active links - (r'^queue$', 'views.queue'), - (r'^pause$', 'views.pause'), - (r'^unpause$', 'views.unpause'), - (r'^cancel$', 'views.cancel'), - (r'^packages$', 'views.packages'), - (r'^package/(\d+)$', 'views.package'), - (r'^link/(\d+)$', 'views.link'), - (r'^remove_package/(\d+)$', 'views.remove_package'), - (r'^restart_package/(\d+)$', 'views.restart_package'), - (r'^remove_link/(\d+)$', 'views.remove_link'), - (r'^restart_link/(\d+)$', 'views.restart_link'), - (r'^move_package/(\d+)/(\d+)$', 'views.move_package'), - (r'^set_captcha$', 'views.set_captcha'), - (r'^package_order/([0-9|]+)$', 'views.package_order'), - (r'^link_order/([0-9|]+)$', 'views.link_order'), - (r'edit_package$', 'views.edit_package'), - (r'restart_failed$', 'views.restart_failed'), - (r'delete_finished$', 'views.delete_finished'), - )
\ No newline at end of file diff --git a/module/web/ajax/views.py b/module/web/ajax/views.py deleted file mode 100644 index acceac585..000000000 --- a/module/web/ajax/views.py +++ /dev/null @@ -1,321 +0,0 @@ -# Create your views here. -from os.path import join -import time - -from django.conf import settings -from django.core.serializers import json -from django.http import HttpResponse -from django.http import HttpResponseForbidden -from django.http import HttpResponseServerError -from django.utils import simplejson -from django.utils.translation import ugettext as _ -import base64 - -from traceback import print_exc - -def format_time(seconds): - seconds = int(seconds) - - hours, seconds = divmod(seconds, 3600) - minutes, seconds = divmod(seconds, 60) - return "%.2i:%.2i:%.2i" % (hours, minutes, seconds) - -def get_sort_key(item): - return item["order"] - -def permission(perm): - def _dec(view_func): - def _view(request, * args, ** kwargs): - if request.user.has_perm(perm) and request.user.is_authenticated(): - return view_func(request, * args, ** kwargs) - else: - return HttpResponseForbidden() - - _view.__name__ = view_func.__name__ - _view.__dict__ = view_func.__dict__ - _view.__doc__ = view_func.__doc__ - - return _view - - return _dec - -class JsonResponse(HttpResponse): - def __init__(self, object): - content = simplejson.dumps( - object, indent=2, cls=json.DjangoJSONEncoder, - ensure_ascii=False) - super(JsonResponse, self).__init__( - content)#, content_type='application/json') #@TODO uncomment - self['Cache-Control'] = 'no-cache, must-revalidate' - - -@permission('pyload.can_add') -def add_package(request): - - name = request.POST['add_name'] - queue = int(request.POST['add_dest']) - links = request.POST['add_links'].split("\n") - pw = request.POST.get("add_password", "").strip("\n\r") - - try: - f = request.FILES['add_file'] - - if name is None or name == "": - name = f.name - - fpath = join(settings.PYLOAD.get_conf_val("general","download_folder"), "tmp_"+ f.name) - destination = open(fpath, 'wb') - for chunk in f.chunks(): - destination.write(chunk) - destination.close() - links.insert(0, fpath) - except: - pass - - if name is None or name == "": - return HttpResponseServerError() - - links = map(lambda x: x.strip(), links) - links = filter(lambda x: x != "", links) - - pack = settings.PYLOAD.add_package(name, links, queue) - if pw: - data = {"password": pw} - settings.PYLOAD.set_package_data(pack, data) - - return JsonResponse("success") - -@permission('pyload.can_delete') -def remove_link(request, id): - try: - settings.PYLOAD.del_links([int(id)]) - return JsonResponse("sucess") - except Exception, e: - return HttpResponseServerError() - -@permission('pyload.can_see_dl') -def status(request): - try: - status = settings.PYLOAD.status_server() - status['captcha'] = settings.PYLOAD.is_captcha_waiting() - return JsonResponse(status) - except: - return HttpResponseServerError() - -@permission('pyload.can_see_dl') -def links(request): - try: - links = settings.PYLOAD.status_downloads() - ids = [] - for link in links: - ids.append(link['id']) - - if link['status'] == 12: - link['info'] = "%s @ %s kb/s" % (link['format_eta'], round(link['speed'], 2)) - elif link['status'] == 5: - link['percent'] = 0 - link['size'] = 0 - link['kbleft'] = 0 - link['info'] = _("waiting %s") % link['format_wait'] - else: - link['info'] = "" - - - data = {} - data['links'] = links - data['ids'] = ids - return JsonResponse(data) - except Exception, e: - return HttpResponseServerError() - -@permission('pyload.can_see_dl') -def queue(request): - try: - return JsonResponse(settings.PYLOAD.get_queue()) - - except: - return HttpResponseServerError() - - -@permission('pyload.can_change_satus') -def pause(request): - try: - return JsonResponse(settings.PYLOAD.pause_server()) - - except: - return HttpResponseServerError() - - -@permission('pyload.can_change_status') -def unpause(request): - try: - return JsonResponse(settings.PYLOAD.unpause_server()) - - except: - return HttpResponseServerError() - - -@permission('pyload.can_change_status') -def cancel(request): - try: - return JsonResponse(settings.PYLOAD.stop_downloads()) - except: - return HttpResponseServerError() - -@permission('pyload.can_see_dl') -def packages(request): - try: - data = settings.PYLOAD.get_queue() - - for package in data: - package['links'] = [] - for file in settings.PYLOAD.get_package_files(package['id']): - package['links'].append(settings.PYLOAD.get_file_info(file)) - - return JsonResponse(data) - - except: - return HttpResponseServerError() - -@permission('pyload.can_see_dl') -def package(request, id): - try: - data = settings.PYLOAD.get_package_data(int(id)) - - for pyfile in data["links"].itervalues(): - if pyfile["status"] == 0: - pyfile["icon"] = "status_finished.png" - elif pyfile["status"] in (2,3): - pyfile["icon"] = "status_queue.png" - elif pyfile["status"] in (9,1): - pyfile["icon"] = "status_offline.png" - elif pyfile["status"] == 5: - pyfile["icon"] = "status_waiting.png" - elif pyfile["status"] == 8: - pyfile["icon"] = "status_failed.png" - elif pyfile["status"] in (11,13): - pyfile["icon"] = "status_proc.png" - else: - pyfile["icon"] = "status_downloading.png" - - tmp = data["links"].values() - tmp.sort(key=get_sort_key) - data["links"] = tmp - - return JsonResponse(data) - - except: - print_exc() - return HttpResponseServerError() - -@permission('pyload.can_add') -def package_order(request, ids): - try: - pid, pos = ids.split("|") - settings.PYLOAD.order_package(int(pid), int(pos)) - return JsonResponse("success") - except: - print_exc() - return HttpResponseServerError() - -@permission('pyload.can_add') -def link_order(request, ids): - try: - pid, pos = ids.split("|") - settings.PYLOAD.order_file(int(pid), int(pos)) - return JsonResponse("success") - except: - print_exc() - return HttpResponseServerError() - -@permission('pyload.can_see_dl') -def link(request, id): - try: - data = settings.PYLOAD.get_file_info(int(id)) - return JsonResponse(data) - - except: - return HttpResponseServerError() - -@permission('pyload.can_delete') -def remove_package(request, id): - try: - settings.PYLOAD.del_packages([int(id)]) - return JsonResponse("success") - except Exception, e: - print_exc() - return HttpResponseServerError() - -@permission('pyload.can_add') -def restart_package(request, id): - try: - settings.PYLOAD.restart_package(int(id)) - return JsonResponse("success") - except Exception: - return HttpResponseServerError() - -@permission('pyload.can_add') -def restart_link(request, id): - try: - settings.PYLOAD.restart_file(int(id)) - return JsonResponse("success") - except Exception: - return HttpResponseServerError() - -@permission('pyload.can_delete') -def abort_link(request, id): - try: - settings.PYLOAD.stop_download("link", int(id)) - return JsonResponse("success") - except: - return HttpResponseServerError() - -@permission('pyload.can_add') -def move_package(request, dest, id): - try: - settings.PYLOAD.move_package(int(dest), int(id)) - return JsonResponse("success") - except: - return HttpResponseServerError() - -@permission('pyload.can_add') -def edit_package(request): - try: - id = int(request.POST.get("pack_id")) - data = {"name": request.POST.get("pack_name"), - "folder": request.POST.get("pack_folder"), - "priority": request.POST.get("pack_prio"), - "password": request.POST.get("pack_pws")} - - settings.PYLOAD.set_package_data(id, data) - return JsonResponse("success") - - except: - return HttpResponseServerError() - -@permission('pyload.can_add') -def set_captcha(request): - if request.META['REQUEST_METHOD'] == "POST": - try: - settings.PYLOAD.set_captcha_result(request.POST["cap_id"], request.POST["cap_text"]) - except: - pass - - id, binary, typ = settings.PYLOAD.get_captcha_task() - - if id: - binary = base64.standard_b64encode(str(binary)) - src = "data:image/%s;base64,%s" % (typ, binary) - - return JsonResponse({'captcha': True, 'src': src, 'id': id}) - else: - return JsonResponse({'captcha': False}) - - -@permission('pyload.can_delete') -def delete_finished(request): - return JsonResponse({"del":settings.PYLOAD.delete_finished()}) - -@permission('pyload.can_delete') -def restart_failed(request): - return JsonResponse(settings.PYLOAD.restart_failed())
\ No newline at end of file diff --git a/module/web/cnl/__init__.py b/module/web/cnl/__init__.py deleted file mode 100644 index e69de29bb..000000000 --- a/module/web/cnl/__init__.py +++ /dev/null diff --git a/module/web/cnl/models.py b/module/web/cnl/models.py deleted file mode 100644 index 71a836239..000000000 --- a/module/web/cnl/models.py +++ /dev/null @@ -1,3 +0,0 @@ -from django.db import models - -# Create your models here. diff --git a/module/web/cnl/tests.py b/module/web/cnl/tests.py deleted file mode 100644 index 2247054b3..000000000 --- a/module/web/cnl/tests.py +++ /dev/null @@ -1,23 +0,0 @@ -""" -This file demonstrates two different styles of tests (one doctest and one -unittest). These will both pass when you run "manage.py test". - -Replace these with more appropriate tests for your application. -""" - -from django.test import TestCase - -class SimpleTest(TestCase): - def test_basic_addition(self): - """ - Tests that 1 + 1 always equals 2. - """ - self.failUnlessEqual(1 + 1, 2) - -__test__ = {"doctest": """ -Another way to test that 1 + 1 is equal to 2. - ->>> 1 + 1 == 2 -True -"""} - diff --git a/module/web/cnl/urls.py b/module/web/cnl/urls.py deleted file mode 100644 index 635e751ca..000000000 --- a/module/web/cnl/urls.py +++ /dev/null @@ -1,21 +0,0 @@ -# -*- coding: utf-8 -*- -from django.conf.urls.defaults import * - - -urlpatterns = patterns('cnl', - # Example: - # (r'^pyload/', include('pyload.foo.urls')), - - # Uncomment the admin/doc line below and add 'django.contrib.admindocs' - # to INSTALLED_APPS to enable admin documentation: - # (r'^admin/doc/', include('django.contrib.admindocs.urls')), - - # Uncomment the next line to enable the admin: - (r'^add$', 'views.add'), - (r'^addcrypted$', 'views.addcrypted'), - (r'^addcrypted2$', 'views.addcrypted2'), - (r'^crossdomain\.xml', 'views.crossdomain'), - (r'^jdcheck\.js', 'views.jdcheck'), - (r'^checkSupportForUrl', 'views.checksupport'), - (r'', 'views.flash') - ) diff --git a/module/web/cnl/views.py b/module/web/cnl/views.py deleted file mode 100644 index 8b43bdccc..000000000 --- a/module/web/cnl/views.py +++ /dev/null @@ -1,166 +0,0 @@ -# Create your views here. - - -from os.path import join -import re -from urllib import unquote -from base64 import standard_b64decode -from binascii import unhexlify - -from django.conf import settings -from django.http import HttpResponse -from django.http import HttpResponseServerError - -from django.core.serializers import json -from django.utils import simplejson - -try: - from Crypto.Cipher import AES -except: - pass - -def local_check(function): - def _dec(view_func): - def _view(request, * args, ** kwargs): - if request.META.get('REMOTE_ADDR', "0") in ('127.0.0.1','localhost') or request.META.get('HTTP_HOST','0') == '127.0.0.1:9666': - return view_func(request, * args, ** kwargs) - else: - return HttpResponseServerError() - - _view.__name__ = view_func.__name__ - _view.__dict__ = view_func.__dict__ - _view.__doc__ = view_func.__doc__ - - return _view - - if function is None: - return _dec - else: - return _dec(function) - -class JsonResponse(HttpResponse): - def __init__(self, obj, request): - cb = request.GET.get("callback") - if cb: - obj = {"content": obj} - content = simplejson.dumps(obj, indent=2, cls=json.DjangoJSONEncoder, ensure_ascii=False) - content = "%s(%s)\r\n" % (cb, content) - HttpResponse.__init__(self, content, content_type="application/json") - else: - content = "%s\r\n" % obj - HttpResponse.__init__(self, content, content_type="text/html") - self["Cache-Control"] = "no-cache, must-revalidate" - -@local_check -def flash(request): - return HttpResponse("JDownloader") - -@local_check -def add(request): - package = request.POST.get('referer', 'ClickAndLoad Package') - urls = filter(lambda x: x != "", request.POST['urls'].split("\n")) - - settings.PYLOAD.add_package(package, urls, False) - - return HttpResponse() - -@local_check -def addcrypted(request): - - package = request.POST.get('referer', 'ClickAndLoad Package') - dlc = request.POST['crypted'].replace(" ", "+") - - dlc_path = join(settings.DL_ROOT, package.replace("/", "").replace("\\", "").replace(":", "") + ".dlc") - dlc_file = file(dlc_path, "wb") - dlc_file.write(dlc) - dlc_file.close() - - try: - settings.PYLOAD.add_package(package, [dlc_path], False) - except: - return JsonResponse("", request) - else: - return JsonResponse("success", request) - -@local_check -def addcrypted2(request): - - package = request.POST.get("source", "ClickAndLoad Package") - crypted = request.POST["crypted"] - jk = request.POST["jk"] - - crypted = standard_b64decode(unquote(crypted.replace(" ", "+"))) - if settings.JS: - jk = "%s f()" % jk - jk = settings.JS.eval(jk) - - else: - try: - jk = re.findall(r"return ('|\")(.+)('|\")", jk)[0][1] - except: - ## 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 = unhexlify(jk) - except: - print "Could not decrypt key, please install py-spidermonkey or ossp-js" - return JsonResponse("failed", request) - - IV = Key - - obj = AES.new(Key, AES.MODE_CBC, IV) - result = obj.decrypt(crypted).replace("\x00", "").replace("\r","").split("\n") - - result = filter(lambda x: x != "", result) - - try: - settings.PYLOAD.add_package(package, result, False) - except: - return JsonResponse("failed can't add", request) - else: - return JsonResponse("success", request) - -@local_check -def flashgot(request): - if request.META['HTTP_REFERER'] != "http://localhost:9666/flashgot" and request.META['HTTP_REFERER'] != "http://127.0.0.1:9666/flashgot": - return HttpResponseServerError() - - autostart = int(request.POST.get('autostart', 0)) - package = request.POST.get('package', "FlashGot") - urls = filter(lambda x: x != "", request.POST['urls'].split("\n")) - folder = request.POST.get('dir', None) - - settings.PYLOAD.add_package(package, urls, autostart) - - return HttpResponse("") - -@local_check -def crossdomain(request): - rep = "<?xml version=\"1.0\"?>\n" - rep += "<!DOCTYPE cross-domain-policy SYSTEM \"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd\">\n" - rep += "<cross-domain-policy>\n" - rep += "<allow-access-from domain=\"*\" />\n" - rep += "</cross-domain-policy>" - return HttpResponse(rep) - -@local_check -def checksupport(request): - - url = request.GET.get("url") - res = settings.PYLOAD.checkURLs([url]) - supported = (not res[0][1] is None) - - return JsonResponse(str(supported).lower(), request) - -@local_check -def jdcheck(request): - rep = "jdownloader=true;\n" - rep += "var version='10629';\n" - return HttpResponse(rep) diff --git a/module/web/pyload/__init__.py b/module/web/pyload/__init__.py deleted file mode 100644 index e69de29bb..000000000 --- a/module/web/pyload/__init__.py +++ /dev/null diff --git a/module/web/pyload/admin.py b/module/web/pyload/admin.py deleted file mode 100644 index 99cb28836..000000000 --- a/module/web/pyload/admin.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -from django.contrib import admin -from models import Prefs -from django.contrib.auth.models import User -from django.contrib.auth.admin import UserAdmin as RealUserAdmin - - -class UserProfileInline(admin.StackedInline): - model = Prefs - -class UserAdmin(RealUserAdmin): - inlines = [ UserProfileInline ] - -admin.site.unregister(User) -admin.site.register(User, UserAdmin)
\ No newline at end of file diff --git a/module/web/pyload/models.py b/module/web/pyload/models.py deleted file mode 100644 index 86962f23c..000000000 --- a/module/web/pyload/models.py +++ /dev/null @@ -1,31 +0,0 @@ -# -*- coding: utf-8 -*- -from django.db import models -from django.contrib.auth.models import User -# Create your models here. - -class Prefs(models.Model): - """ Permissions setting """ - - user = models.ForeignKey(User, unique=True) - template = models.CharField(max_length=30, default='default', null=False, blank=False) #@TODO: currently unused - - class Meta: - permissions = ( - ('can_see_dl', 'User can see Downloads'), - ('can_change_status', 'User can change Status'), - ('can_download', 'User can download'), - ('can_add', 'User can add Links'), - ('can_delete', 'User can delete Links'), - ('can_see_logs', 'User can see Logs'), - ) - verbose_name = "Preferences" - verbose_name_plural = "Preferences" - - def __unicode__(self): - return "Preferences for %s" % self.user - - -def user_post_save(sender, instance, **kwargs): - profile, new = Prefs.objects.get_or_create(user=instance) - -models.signals.post_save.connect(user_post_save, User)
\ No newline at end of file diff --git a/module/web/pyload/templatetags/__init__.py b/module/web/pyload/templatetags/__init__.py deleted file mode 100644 index e69de29bb..000000000 --- a/module/web/pyload/templatetags/__init__.py +++ /dev/null diff --git a/module/web/pyload/templatetags/contains.py b/module/web/pyload/templatetags/contains.py deleted file mode 100644 index ed6225a95..000000000 --- a/module/web/pyload/templatetags/contains.py +++ /dev/null @@ -1,14 +0,0 @@ -from django import template -register = template.Library() - -@register.filter() -def contains(value, arg): - """ - Usage: - {% if text|contains:" http://" %} - This is a link. - {% else %} - Not a link. - {% endif %} - """ - return arg in value diff --git a/module/web/pyload/templatetags/quotepath.py b/module/web/pyload/templatetags/quotepath.py deleted file mode 100644 index 8483a1553..000000000 --- a/module/web/pyload/templatetags/quotepath.py +++ /dev/null @@ -1,68 +0,0 @@ -import os - -from django.template.defaultfilters import stringfilter -from django import template - -try: - from os.path import relpath -except: - from posixpath import curdir, sep, pardir, join - def relpath(path, start=curdir): - """Return a relative version of a path""" - if not path: - raise ValueError("no path specified") - start_list = os.path.abspath(start).split(sep) - path_list = os.path.abspath(path).split(sep) - # Work out how much of the filepath is shared by start and path. - i = len(os.path.commonprefix([start_list, path_list])) - rel_list = [pardir] * (len(start_list)-i) + path_list[i:] - if not rel_list: - return curdir - return join(*rel_list) - -register = template.Library() - -quotechar = "::/" - -@stringfilter -def quotepath(path): - try: - return path.replace("../", quotechar) - except AttributeError: - return path - except: - return "" - - -register.filter(quotepath) - -@stringfilter -def unquotepath(path): - try: - return path.replace(quotechar, "../") - except AttributeError: - return path - except: - return "" - -register.filter(unquotepath) - -def path_make_absolute(path): - p = os.path.abspath(path) - if p[-1] == os.path.sep: - return p - else: - return p + os.path.sep - - -register.filter(path_make_absolute) - -def path_make_relative(path): - p = relpath(path) - if p[-1] == os.path.sep: - return p - else: - return p + os.path.sep - -register.filter(path_make_relative) - diff --git a/module/web/pyload/templatetags/token.py b/module/web/pyload/templatetags/token.py deleted file mode 100644 index e6117b839..000000000 --- a/module/web/pyload/templatetags/token.py +++ /dev/null @@ -1,17 +0,0 @@ - -from django import VERSION -from django import template -register = template.Library() - -if VERSION[:3] < (1,1,2): - - class TokenNode(template.Node): - def render(self, content): - return "" - - @register.tag() - def csrf_token(parser, token): - """ - Return nothing, since csrf is deactivated in django 1.1 - """ - return TokenNode() diff --git a/module/web/pyload/templatetags/truncate.py b/module/web/pyload/templatetags/truncate.py deleted file mode 100644 index ed35ea998..000000000 --- a/module/web/pyload/templatetags/truncate.py +++ /dev/null @@ -1,13 +0,0 @@ -from django.template.defaultfilters import stringfilter -from django import template - -register = template.Library() - - -@stringfilter -def truncate(value, n): - if (n - len(value)) < 3: - return value[:n]+"..." - return value - -register.filter(truncate) diff --git a/module/web/pyload/tests.py b/module/web/pyload/tests.py deleted file mode 100644 index 2247054b3..000000000 --- a/module/web/pyload/tests.py +++ /dev/null @@ -1,23 +0,0 @@ -""" -This file demonstrates two different styles of tests (one doctest and one -unittest). These will both pass when you run "manage.py test". - -Replace these with more appropriate tests for your application. -""" - -from django.test import TestCase - -class SimpleTest(TestCase): - def test_basic_addition(self): - """ - Tests that 1 + 1 always equals 2. - """ - self.failUnlessEqual(1 + 1, 2) - -__test__ = {"doctest": """ -Another way to test that 1 + 1 is equal to 2. - ->>> 1 + 1 == 2 -True -"""} - diff --git a/module/web/pyload/urls.py b/module/web/pyload/urls.py deleted file mode 100644 index fe85c1096..000000000 --- a/module/web/pyload/urls.py +++ /dev/null @@ -1,31 +0,0 @@ -# -*- coding: utf-8 -*- - -from os.path import join - -from django.conf import settings -from django.conf.urls.defaults import * - - -urlpatterns = patterns('pyload', - (r'^home/$', 'views.home'), - (r'^downloads/$', 'views.downloads',{},'downloads'), - (r'^download/(?P<path>[a-zA-z\.0-9\-/_% "\\]+)$', 'views.download',{},'download'), - (r'^queue/$', 'views.queue',{}, 'queue'), - (r'^collector/$', 'views.collector',{}, 'collector'), - (r'^settings/$', 'views.config',{}, 'config'), - (r'^logs/$', 'views.logs',{}, 'logs'), - (r'^logs/(?P<item>\d+)$', 'views.logs',{}, 'logs'), - (r'^package_ui.js$', 'views.package_ui', {}, 'package_ui'), - (r'^$', 'views.home',{}, 'home'), - url(r'^pathchooser/(?P<path>.*)', 'views.path', {'type':'folder'}, name='path'), - url(r'^pathchooser/$', 'views.root', {'type':'folder'}, name='pathroot'), - url(r'^filechooser/(?P<path>.*)', 'views.path', {'type':'file'}, name='file'), - url(r'^filechooser/$', 'views.root', {'type':'file'}, name='fileroot'), - ) - -urlpatterns += patterns('django.contrib.auth', - (r'^login/$', 'views.login', {'template_name': join(settings.TEMPLATE, 'login.html')}), - (r'^logout/$', 'views.logout', {'template_name': join(settings.TEMPLATE, 'logout.html')}, 'logout'), -) - - diff --git a/module/web/pyload/views.py b/module/web/pyload/views.py deleted file mode 100644 index 8e72402a4..000000000 --- a/module/web/pyload/views.py +++ /dev/null @@ -1,492 +0,0 @@ -# -*- coding: utf-8 -*- - -# Create your views here. -import mimetypes -import os -from os import listdir -from os import stat -from os.path import isdir -from os.path import isfile -from os.path import join -from sys import getfilesystemencoding -from urllib import unquote -from itertools import chain -from datetime import datetime -from time import localtime, strftime -from copy import deepcopy -from operator import itemgetter -from pyload.templatetags import quotepath - -try: - from os.path import relpath -except: - from posixpath import curdir, sep, pardir - def relpath(path, start=curdir): - """Return a relative version of a path""" - if not path: - raise ValueError("no path specified") - start_list = os.path.abspath(start).split(sep) - path_list = os.path.abspath(path).split(sep) - # Work out how much of the filepath is shared by start and path. - i = len(os.path.commonprefix([start_list, path_list])) - rel_list = [pardir] * (len(start_list)-i) + path_list[i:] - if not rel_list: - return curdir - return join(*rel_list) - -from django.conf import settings -from django.contrib.auth.decorators import login_required -from django.http import HttpResponse -from django.http import HttpResponseNotFound -from django.http import HttpResponseRedirect -from django.shortcuts import render_to_response -from django.template import RequestContext -from django.utils.translation import ugettext as _ -from django.core.urlresolvers import reverse - - -def get_sort_key(item): - return item[1]["order"] - -def formatSize(size): - """formats size of bytes""" - size = int(size) - steps = 0 - sizes = ["KB", "MB", "GB", "TB"] - - while size > 1000: - size /= 1024.0 - steps += 1 - - return "%.2f %s" % (size, sizes[steps]) - -def check_server(function): - def _dec(view_func): - def _view(request, * args, ** kwargs): - try: - version = settings.PYLOAD.get_server_version() - except Exception, e: - return base(request, messages=[_('Can\'t connect to pyLoad. Please check your configuration and make sure pyLoad is running.'), str(e)]) - return view_func(request, * args, ** kwargs) - - _view.__name__ = view_func.__name__ - _view.__dict__ = view_func.__dict__ - _view.__doc__ = view_func.__doc__ - - return _view - - if function is None: - return _dec - else: - return _dec(function) - - -def permission(perm): - def _dec(view_func): - def _view(request, * args, ** kwargs): - if request.user.has_perm(perm) and request.user.is_authenticated(): - return view_func(request, * args, ** kwargs) - else: - return base(request, messages=[_('You don\'t have permission to view this page.')]) - - _view.__name__ = view_func.__name__ - _view.__dict__ = view_func.__dict__ - _view.__doc__ = view_func.__doc__ - - return _view - - return _dec - - - -def status_proc(request): - return {'status': settings.PYLOAD.status_server(), 'captcha': settings.PYLOAD.is_captcha_waiting()} - - -def base(request, messages): - return render_to_response(join(settings.TEMPLATE, 'base.html'), {'messages': messages}, RequestContext(request)) - -@login_required -@permission('pyload.can_see_dl') -@check_server -def home(request): - res = settings.PYLOAD.status_downloads() - - for link in res: - if link["status"] == 12: - link["information"] = "%s kB @ %s kB/s" % (link["size"] - link["kbleft"], link["speed"]) - - return render_to_response(join(settings.TEMPLATE, 'home.html'), RequestContext(request, {'content': res}, [status_proc])) - - -@login_required -@permission('pyload.can_see_dl') -@check_server -def queue(request): - queue = settings.PYLOAD.get_queue_info() - - data = zip(queue.keys(), queue.values()) - data.sort(key=get_sort_key) - - return render_to_response(join(settings.TEMPLATE, 'queue.html'), RequestContext(request, {'content': data}, [status_proc])) - - -@login_required -@permission('pyload.can_download') -@check_server -def downloads(request): - - root = settings.PYLOAD.get_conf_val("general", "download_folder") - - if not isdir(root): - return base(request, [_('Download directory not found.')]) - data = { - 'folder': [], - 'files': [] - } - - for item in sorted(listdir(root)): - if isdir(join(root, item)): - folder = { - 'name': item, - 'path': item, - 'files': [] - } - for file in sorted(listdir(join(root, item))): - try: - if isfile(join(root, item, file)): - folder['files'].append(file) - except: - pass - - data['folder'].append(folder) - elif isfile(join(root, item)): - data['files'].append(item) - - - return render_to_response(join(settings.TEMPLATE, 'downloads.html'), RequestContext(request, {'files': data}, [status_proc])) - -@login_required -@permission('pyload.can_download') -@check_server -def download(request, path): - path = unquote(path) - path = path.split("/") - - root = settings.PYLOAD.get_conf_val("general", "download_folder") - - dir = join(root, path[1].replace('..', '')) - if isdir(dir) or isfile(dir): - if isdir(dir): filepath = join(dir, path[2]) - elif isfile(dir): filepath = dir - - if isfile(filepath): - try: - type, encoding = mimetypes.guess_type(filepath) - if type is None: - type = 'application/octet-stream' - - response = HttpResponse(mimetype=type) - response['Content-Length'] = str(stat(filepath).st_size) - - if encoding is not None: - response['Content-Encoding'] = encoding - - response.write(file(filepath, "rb").read()) - return response - - except Exception, e: - return HttpResponseNotFound("File not Found. %s" % str(e)) - - return HttpResponseNotFound("File not Found.") - -@login_required -@permission('pyload.can_see_logs') -@check_server -def logs(request, item=-1): - - perpage = request.session.get('perpage', 34) - reversed = request.session.get('reversed', False) - - warning = "" - conf = settings.PYLOAD.get_config() - if not conf['log']['file_log']['value']: - warning = "Warning: File log is disabled, see settings page." - - perpage_p = ((20,20), (34, 34), (40, 40), (100, 100), (0,'all')) - fro = None - - if request.method == 'POST': - try: - fro = datetime.strptime(request.POST['from'], '%d.%m.%Y %H:%M:%S') - except: - pass - try: - perpage = int(request.POST['perpage']) - request.session['perpage'] = perpage - - reversed = bool(request.POST.get('reversed', False)) - request.session['reversed'] = reversed - except: - pass - - try: - item = int(item) - except: - pass - - log = settings.PYLOAD.get_log() - if perpage == 0: - item = 0 - - 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: # we will search for datetime - item = -1 - - data = [] - counter = 0 - perpagecheck = 0 - for l in log: - counter = counter+1 - - if counter >= item: - try: - date,time,level,message = l.split(" ", 3) - dtime = datetime.strptime(date+' '+time, '%d.%m.%Y %H:%M:%S') - except: - dtime = None - date = '?' - time = ' ' - level = '?' - message = l - if item == -1 and dtime is not None and fro <= dtime: - item = counter #found our 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.now() - if reversed: - data.reverse() - return render_to_response(join(settings.TEMPLATE, 'logs.html'), RequestContext(request, {'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}, [status_proc])) - -@login_required -@permission('pyload.can_add_dl') -@check_server -def collector(request): - queue = settings.PYLOAD.get_collector_info() - - data = zip(queue.keys(), queue.values()) - data.sort(key=get_sort_key) - - return render_to_response(join(settings.TEMPLATE, 'collector.html'), RequestContext(request, {'content': data}, [status_proc])) - - -@login_required -@permission('pyload.can_change_status') -@check_server -def config(request): - conf = settings.PYLOAD.get_config() - plugin = settings.PYLOAD.get_plugin_config() - accs = settings.PYLOAD.get_accounts(False, False) - messages = [] - - for section in chain(conf.itervalues(), plugin.itervalues()): - for key, option in section.iteritems(): - if key == "desc": continue - - if ";" in option["type"]: - option["list"] = option["type"].split(";") - - if request.META.get('REQUEST_METHOD', "GET") == "POST": - - errors = [] - - for key, value in request.POST.iteritems(): - if not "|" in key: continue - sec, skey, okey = key.split("|")[:] - - if sec == "General": - - if conf.has_key(skey): - if conf[skey].has_key(okey): - try: - if str(conf[skey][okey]['value']) != value: - settings.PYLOAD.set_conf_val(skey, okey, value) - except Exception, e: - errors.append("%s | %s : %s" % (skey, okey, e)) - else: - continue - else: - continue - - elif sec == "Plugin": - if plugin.has_key(skey): - if plugin[skey].has_key(okey): - try: - if str(plugin[skey][okey]['value']) != value: - settings.PYLOAD.set_conf_val(skey, okey, value, "plugin") - except Exception, e: - errors.append("%s | %s : %s" % (skey, okey, e)) - else: - continue - else: - continue - elif sec == "Accounts": - if ";" in okey: - action, name = okey.split(";") - if action == "delete": - settings.PYLOAD.remove_account(skey, name) - - if okey == "newacc" and value: - # add account - - pw = request.POST.get("Accounts|%s|newpw" % skey) - - settings.PYLOAD.update_account(skey, value, pw) - - for pluginname, accdata in accs.iteritems(): - for data in accdata: - newpw = request.POST.get("Accounts|%s|password;%s" % (pluginname, data["login"]), "").strip() - time = request.POST.get("Accounts|%s|time;%s" % (pluginname, data["login"]), "").strip() - - if newpw or (time and (not data["options"].has_key("time") or [time] != data["options"]["time"])): - settings.PYLOAD.update_account(pluginname, data["login"], newpw, {"time": [time]}) - - - if errors: - messages.append(_("Error occured when setting the following options:")) - messages.append("") - messages += errors - else: - messages.append(_("All options were set correctly.")) - - accs = deepcopy(settings.PYLOAD.get_accounts(False, False)) - for accounts in accs.itervalues(): - for data in accounts: - if data["trafficleft"] == -1: - data["trafficleft"] = _("unlimited") - elif not data["trafficleft"]: - data["trafficleft"] = _("not available") - else: - data["trafficleft"] = formatSize(data["trafficleft"]) - - if data["validuntil"] == -1: - data["validuntil"] = _("unlimited") - elif not data["validuntil"]: - data["validuntil"] = _("not available") - else: - t = localtime(data["validuntil"]) - data["validuntil"] = strftime("%d.%m.%Y",t) - - if data["options"].has_key("time"): - try: - data["time"] = data["options"]["time"][0] - except: - data["time"] = "invalid" - - return render_to_response(join(settings.TEMPLATE, 'settings.html'), RequestContext(request, {'conf': {'Plugin':plugin, 'General':conf, 'Accounts': accs}, 'errors': messages}, [status_proc])) - -@login_required -@permission('pyload.can_change_status') -@check_server -def package_ui(request): - return render_to_response(join(settings.TEMPLATE, 'package_ui.js'), RequestContext(request, {}, )) - - -@login_required -@permission('pyload.can_change_status') -@check_server -def root(request, type): - cwd = os.getcwd() - return HttpResponseRedirect(reverse('path', args=[cwd[1:], type])) - -@login_required -@permission('pyload.can_change_status') -@check_server -def path(request, path, type): - - path = os.path.normpath(quotepath.unquotepath(path)) - - if os.path.isfile(path): - oldfile = path - path = os.path.dirname(path) - else: - oldfile = '' - - abs = False - - if os.path.isdir(path): - if os.path.isabs(path): - cwd = os.path.abspath(path) - abs = True - else: - cwd = relpath(path) - else: - cwd = os.getcwd() - - try: - cwd = cwd.encode("utf8") - except: - pass - - cwd = os.path.normpath(os.path.abspath(cwd)) - parentdir = os.path.dirname(cwd) - if not abs: - if os.path.abspath(cwd) == "/": - cwd = relpath(cwd) - else: - cwd = relpath(cwd) + os.path.sep - parentdir = relpath(parentdir) + os.path.sep - - if os.path.abspath(cwd) == "/": - parentdir = "" - - try: - folders = os.listdir(cwd) - except: - folders = [] - - files = [] - - for f in folders: - try: - f = f.decode(getfilesystemencoding()) - data = {} - data['name'] = f - data['fullpath'] = os.path.join(cwd, f) - data['sort'] = data['fullpath'].lower() - data['modified'] = datetime.fromtimestamp(int(os.path.getmtime(os.path.join(cwd, f)))) - data['ext'] = os.path.splitext(f)[1] - except: - continue - - if os.path.isdir(os.path.join(cwd, f)): - data['type'] = 'dir' - else: - data['type'] = 'file' - - if os.path.isfile(os.path.join(cwd, f)): - data['size'] = os.path.getsize(os.path.join(cwd, f)) - - power = 0 - while (data['size']/1024) > 0.3: - power += 1 - data['size'] = data['size'] / 1024. - units = ('', 'K','M','G','T') - data['unit'] = units[power]+'Byte' - else: - data['size'] = '' - - files.append(data) - - files = sorted(files, key=itemgetter('type', 'sort')) - - return render_to_response(join(settings.TEMPLATE, 'pathchooser.html'), {'cwd': cwd, 'files': files, 'parentdir': parentdir, 'type': type, 'oldfile': oldfile, 'absolute': abs}, RequestContext(request))
\ No newline at end of file diff --git a/module/web/pyload_app.py b/module/web/pyload_app.py index 0f8dd859c..d240564ab 100644 --- a/module/web/pyload_app.py +++ b/module/web/pyload_app.py @@ -31,7 +31,7 @@ from sys import getfilesystemencoding from hashlib import sha1 from urllib import unquote -from bottle import route, static_file, request, response, redirect, HTTPError +from bottle import route, static_file, request, response, redirect, HTTPError, error from webinterface import PYLOAD, PROJECT_DIR @@ -65,10 +65,16 @@ def base(messages): ## Views +@error(500) +def error500(error): + return base(["An Error occured, please enable debug mode to get more details.", error, + error.traceback.replace("\n", "<br>")]) + @route('/media/:path#.+#') def server_static(path): - response.headers['Expires'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(time.time() + 60 * 60 * 24 * 7)) + response.headers['Expires'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", + time.gmtime(time.time() + 60 * 60 * 24 * 7)) response.headers['Cache-control'] = "public" return static_file(path, root=join(PROJECT_DIR, "media")) @@ -258,7 +264,8 @@ def config(): newpw = request.POST.get("Accounts|%s|password;%s" % (pluginname, data["login"]), "").strip() new_time = request.POST.get("Accounts|%s|time;%s" % (pluginname, data["login"]), "").strip() - if newpw or (new_time and (not data["options"].has_key("time") or [new_time] != data["options"]["time"])): + if newpw or ( + new_time and (not data["options"].has_key("time") or [new_time] != data["options"]["time"])): PYLOAD.update_account(pluginname, data["login"], newpw, {"time": [new_time]}) if errors: @@ -292,7 +299,6 @@ def config(): except: data["time"] = "invalid" - return render_to_response('settings.html', {'conf': {'Plugin': plugin, 'General': conf, 'Accounts': accs}, 'errors': messages}, [pre_processor]) @@ -300,7 +306,8 @@ def config(): @route("/package_ui.js") @login_required('can_see_dl') def package_ui(): - response.headers['Expires'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(time.time() + 60 * 60 * 24 * 7)) + response.headers['Expires'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", + time.gmtime(time.time() + 60 * 60 * 24 * 7)) response.headers['Cache-control'] = "public" return render_to_response('package_ui.js') @@ -380,11 +387,11 @@ def path(file="", path=""): data['size'] = os.path.getsize(join(cwd, f)) power = 0 - while (data['size']/1024) > 0.3: + while (data['size'] / 1024) > 0.3: power += 1 data['size'] /= 1024. - units = ('', 'K','M','G','T') - data['unit'] = units[power]+'Byte' + units = ('', 'K', 'M', 'G', 'T') + data['unit'] = units[power] + 'Byte' else: data['size'] = '' @@ -392,7 +399,9 @@ def path(file="", path=""): files = sorted(files, key=itemgetter('type', 'sort')) - return render_to_response('pathchooser.html', {'cwd': cwd, 'files': files, 'parentdir': parentdir, 'type': type, 'oldfile': oldfile, 'absolute': abs}, []) + return render_to_response('pathchooser.html', + {'cwd': cwd, 'files': files, 'parentdir': parentdir, 'type': type, 'oldfile': oldfile, + 'absolute': abs}, []) @route("/logs") @route("/logs", method="POST") @@ -410,7 +419,7 @@ def logs(item=-1): if not conf['log']['file_log']['value']: warning = "Warning: File log is disabled, see settings page." - perpage_p = ((20,20), (34, 34), (40, 40), (100, 100), (0,'all')) + perpage_p = ((20, 20), (34, 34), (40, 40), (100, 100), (0, 'all')) fro = None if request.environ.get('REQUEST_METHOD', "GET") == "POST": @@ -439,7 +448,7 @@ def logs(item=-1): item = 0 if item < 1 or type(item) is not int: - item = 1 if len(log) - perpage + 1 < 1 else len(log) - perpage + 1 + item = 1 if len(log) - perpage + 1 < 1 else len(log) - perpage + 1 if type(fro) is datetime: # we will search for datetime item = -1 @@ -452,8 +461,8 @@ def logs(item=-1): if counter >= item: try: - date,time,level,message = l.split(" ", 3) - dtime = datetime.strptime(date+' '+time, '%d.%m.%Y %H:%M:%S') + date, time, level, message = l.split(" ", 3) + dtime = datetime.strptime(date + ' ' + time, '%d.%m.%Y %H:%M:%S') except: dtime = None date = '?' @@ -463,7 +472,7 @@ def logs(item=-1): if item == -1 and dtime is not None and fro <= dtime: item = counter #found our datetime if item >= 0: - data.append({'line': counter, 'date': date+" "+time, 'level':level, 'message': message}) + 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 @@ -474,4 +483,12 @@ def logs(item=-1): fro = 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}, [pre_processor]) + 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}, + [pre_processor]) + +@route("/admin") +def admin(): + return base([])
\ No newline at end of file |