diff options
-rw-r--r-- | .hgignore | 14 | ||||
-rw-r--r-- | config | 43 | ||||
-rw-r--r-- | icons/gui/clipboard.png | bin | 0 -> 1344 bytes | |||
-rw-r--r-- | icons/gui/edit_small.png | bin | 0 -> 570 bytes | |||
-rw-r--r-- | icons/gui/pull_small.png | bin | 0 -> 614 bytes | |||
-rw-r--r-- | icons/gui/push_small.png | bin | 0 -> 618 bytes | |||
-rw-r--r-- | icons/gui/refresh_small.png | bin | 0 -> 821 bytes | |||
-rw-r--r-- | icons/gui/remove_small.png | bin | 0 -> 287 bytes | |||
-rw-r--r-- | icons/gui/toolbar_add.png | bin | 0 -> 932 bytes | |||
-rw-r--r-- | icons/gui/toolbar_pause.png | bin | 0 -> 943 bytes | |||
-rw-r--r-- | icons/gui/toolbar_remove.png | bin | 0 -> 496 bytes | |||
-rw-r--r-- | icons/gui/toolbar_start.png | bin | 0 -> 1504 bytes | |||
-rw-r--r-- | icons/gui/toolbar_stop.png | bin | 0 -> 523 bytes | |||
-rw-r--r-- | icons/logo.png | bin | 0 -> 8172 bytes | |||
-rw-r--r-- | module/BeautifulSoup.py | 2000 | ||||
-rw-r--r-- | module/CaptchaManager.py | 112 | ||||
-rw-r--r-- | module/HookManager.py | 93 | ||||
-rw-r--r-- | module/Plugin.py | 103 | ||||
-rw-r--r-- | module/Unzip.py | 50 | ||||
-rw-r--r-- | module/XMLConfigParser.py | 166 | ||||
-rw-r--r-- | module/config/core_default.xml | 61 | ||||
-rw-r--r-- | module/config/gui_default.xml | 12 | ||||
-rw-r--r-- | module/config/plugin_default.xml | 35 | ||||
-rw-r--r-- | module/download_thread.py | 80 | ||||
-rw-r--r-- | module/file_list.py | 579 | ||||
-rw-r--r-- | module/gui/CaptchaDock.py | 85 | ||||
-rw-r--r-- | module/gui/Collector.py | 312 | ||||
-rw-r--r-- | module/gui/ConnectionManager.py | 249 | ||||
-rw-r--r-- | module/gui/LinkDock.py | 54 | ||||
-rw-r--r-- | module/gui/MainWindow.py | 421 | ||||
-rw-r--r-- | module/gui/PWInputWindow.py | 47 | ||||
-rw-r--r-- | module/gui/PackageDock.py | 76 | ||||
-rw-r--r-- | module/gui/Queue.py | 373 | ||||
-rw-r--r-- | module/gui/XMLParser.py | 71 | ||||
-rw-r--r-- | module/gui/__init__.py | 1 | ||||
-rw-r--r-- | module/gui/connector.py | 424 | ||||
-rw-r--r-- | module/network/Keepalive.py | 1 | ||||
-rwxr-xr-x | module/network/Request.py | 234 | ||||
-rw-r--r-- | module/plugins/BluehostTo.py | 71 | ||||
-rw-r--r-- | module/plugins/DLC.pyc | bin | 2231 -> 0 bytes | |||
-rw-r--r-- | module/plugins/Hook.py | 69 | ||||
-rw-r--r-- | module/plugins/MyvideoDe.py | 65 | ||||
-rw-r--r-- | module/plugins/RSDF.py | 59 | ||||
-rw-r--r-- | module/plugins/__init__.py | 1 | ||||
-rw-r--r-- | module/plugins/captcha/GigasizeCom.py (renamed from module/captcha/GigasizeCom.py) | 0 | ||||
-rw-r--r-- | module/plugins/captcha/LinksaveIn.py | 161 | ||||
-rw-r--r-- | module/plugins/captcha/MegauploadCom.py (renamed from module/captcha/MegauploadCom.py) | 1 | ||||
-rw-r--r-- | module/plugins/captcha/NetloadIn.py (renamed from module/captcha/NetloadIn.py) | 0 | ||||
-rw-r--r-- | module/plugins/captcha/ShareonlineBiz.py (renamed from module/captcha/ShareonlineBiz.py) | 0 | ||||
-rw-r--r-- | module/plugins/captcha/__init__.py (renamed from module/captcha/__init__.py) | 0 | ||||
-rw-r--r-- | module/plugins/captcha/captcha.py (renamed from module/captcha/captcha.py) | 0 | ||||
-rw-r--r-- | module/plugins/container/CCF.py (renamed from module/plugins/CCF.py) | 7 | ||||
-rw-r--r-- | module/plugins/container/DLC.pyc | bin | 0 -> 5923 bytes | |||
-rw-r--r-- | module/plugins/container/LinkList.py | 39 | ||||
-rw-r--r-- | module/plugins/container/RSDF.py | 50 | ||||
-rw-r--r-- | module/plugins/container/__init__.py | 0 | ||||
-rw-r--r-- | module/plugins/decrypter/DDLMusicOrg.py (renamed from module/plugins/DDLMusicOrg.py) | 6 | ||||
-rw-r--r-- | module/plugins/decrypter/FourChanOrg.py (renamed from module/plugins/FourChanOrg.py) | 0 | ||||
-rw-r--r-- | module/plugins/decrypter/HoerbuchIn.py (renamed from module/plugins/HoerbuchIn.py) | 4 | ||||
-rw-r--r-- | module/plugins/decrypter/LixIn.py (renamed from module/plugins/LixIn.py) | 0 | ||||
-rw-r--r-- | module/plugins/decrypter/OneKhDe.py (renamed from module/plugins/OneKhDe.py) | 0 | ||||
-rw-r--r-- | module/plugins/decrypter/RSLayerCom.py (renamed from module/plugins/RSLayerCom.py) | 0 | ||||
-rw-r--r-- | module/plugins/decrypter/RelinkUs.py (renamed from module/plugins/RelinkUs.py) | 9 | ||||
-rw-r--r-- | module/plugins/decrypter/SecuredIn.py | 335 | ||||
-rw-r--r-- | module/plugins/decrypter/SerienjunkiesOrg.py | 216 | ||||
-rw-r--r-- | module/plugins/decrypter/StealthTo.py (renamed from module/plugins/StealthTo.py) | 0 | ||||
-rw-r--r-- | module/plugins/decrypter/YoutubeChannel.py (renamed from module/plugins/YoutubeChannel.py) | 37 | ||||
-rw-r--r-- | module/plugins/decrypter/__init__.py | 0 | ||||
-rw-r--r-- | module/plugins/hooks/ContainerDownload.py | 44 | ||||
-rw-r--r-- | module/plugins/hooks/ExternalScripts.py | 100 | ||||
-rw-r--r-- | module/plugins/hooks/__init__.py | 0 | ||||
-rw-r--r-- | module/plugins/hoster/DepositfilesCom.py (renamed from module/plugins/DepositfilesCom.py) | 0 | ||||
-rw-r--r-- | module/plugins/hoster/FilefactoryCom.py (renamed from module/plugins/FilefactoryCom.py) | 1 | ||||
-rw-r--r-- | module/plugins/hoster/FilesmonsterCom.py (renamed from module/plugins/FilesmonsterCom.py) | 0 | ||||
-rw-r--r-- | module/plugins/hoster/FreakshareNet.py (renamed from module/plugins/FreakshareNet.py) | 0 | ||||
-rw-r--r-- | module/plugins/hoster/GigasizeCom.py (renamed from module/plugins/GigasizeCom.py) | 0 | ||||
-rw-r--r-- | module/plugins/hoster/HotfileCom.py (renamed from module/plugins/HotfileCom.py) | 57 | ||||
-rw-r--r-- | module/plugins/hoster/MegauploadCom.py (renamed from module/plugins/MegauploadCom.py) | 14 | ||||
-rw-r--r-- | module/plugins/hoster/MyvideoDe.py | 40 | ||||
-rw-r--r-- | module/plugins/hoster/NetloadIn.py (renamed from module/plugins/NetloadIn.py) | 131 | ||||
-rw-r--r-- | module/plugins/hoster/RapidshareCom.py (renamed from module/plugins/RapidshareCom.py) | 141 | ||||
-rw-r--r-- | module/plugins/hoster/ShareonlineBiz.py (renamed from module/plugins/ShareonlineBiz.py) | 71 | ||||
-rw-r--r-- | module/plugins/hoster/ShragleCom.py (renamed from module/plugins/ShragleCom.py) | 0 | ||||
-rw-r--r-- | module/plugins/hoster/StorageTo.py (renamed from module/plugins/StorageTo.py) | 0 | ||||
-rw-r--r-- | module/plugins/hoster/UploadedTo.py (renamed from module/plugins/UploadedTo.py) | 34 | ||||
-rw-r--r-- | module/plugins/hoster/XupIn.py (renamed from module/plugins/XupIn.py) | 0 | ||||
-rw-r--r-- | module/plugins/hoster/YoupornCom.py (renamed from module/plugins/YoupornCom.py) | 0 | ||||
-rw-r--r-- | module/plugins/hoster/YoutubeCom.py (renamed from module/plugins/YoutubeCom.py) | 0 | ||||
-rw-r--r-- | module/plugins/hoster/ZippyshareCom.py (renamed from module/plugins/ZippyshareCom.py) | 13 | ||||
-rw-r--r-- | module/plugins/hoster/ZshareNet.py (renamed from module/plugins/ZshareNet.py) | 0 | ||||
-rw-r--r-- | module/plugins/hoster/__init__.py | 0 | ||||
-rw-r--r-- | module/remote/ClientHandler.py | 24 | ||||
-rw-r--r-- | module/remote/ClientSocket.py | 63 | ||||
-rw-r--r-- | module/remote/RequestHandler.py | 64 | ||||
-rw-r--r-- | module/remote/RequestObject.py | 18 | ||||
-rw-r--r-- | module/remote/SecureXMLRPCServer.py | 130 | ||||
-rw-r--r-- | module/remote/SocketServer.py | 84 | ||||
-rw-r--r-- | module/thread_list.py | 175 | ||||
-rw-r--r-- | module/unescape.py | 28 | ||||
-rw-r--r-- | module/web/ServerThread.py | 58 | ||||
-rw-r--r-- | module/web/WebServer.py | 290 | ||||
-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 | 29 | ||||
-rw-r--r-- | module/web/ajax/views.py | 196 | ||||
-rw-r--r-- | module/web/bottle.py | 886 | ||||
-rwxr-xr-x | module/web/manage.py | 13 | ||||
-rw-r--r-- | module/web/media/default/css/default.css | 1510 | ||||
-rw-r--r-- | module/web/media/default/css/jquery-ui-1.7.2.custom.css | 406 | ||||
-rw-r--r-- | module/web/media/default/css/window.css | 75 | ||||
-rw-r--r-- | module/web/media/default/img/Button-Add-grey.png (renamed from module/web/static/default/Button-Add-grey.png) | bin | 2112 -> 2112 bytes | |||
-rw-r--r-- | module/web/media/default/img/Button-Add.png (renamed from module/web/static/default/Button-Add.png) | bin | 2110 -> 2110 bytes | |||
-rw-r--r-- | module/web/media/default/img/Button-Pause-grey.png (renamed from module/web/static/default/Button-Pause-grey.png) | bin | 1932 -> 1932 bytes | |||
-rw-r--r-- | module/web/media/default/img/Button-Pause.png (renamed from module/web/static/default/Button-Pause.png) | bin | 2146 -> 2146 bytes | |||
-rw-r--r-- | module/web/media/default/img/Button-Play-grey.png (renamed from module/web/static/default/Button-Play-grey.png) | bin | 1938 -> 1938 bytes | |||
-rw-r--r-- | module/web/media/default/img/Button-Play.png (renamed from module/web/static/default/Button-Play.png) | bin | 2023 -> 2023 bytes | |||
-rw-r--r-- | module/web/media/default/img/arrow_refresh.png | bin | 0 -> 685 bytes | |||
-rw-r--r-- | module/web/media/default/img/big_button.gif (renamed from module/web/static/window/big_button.gif) | bin | 1905 -> 1905 bytes | |||
-rw-r--r-- | module/web/media/default/img/big_button_over.gif (renamed from module/web/static/window/big_button_over.gif) | bin | 728 -> 728 bytes | |||
-rw-r--r-- | module/web/media/default/img/body.png (renamed from module/web/static/window/body.png) | bin | 402 -> 402 bytes | |||
-rw-r--r-- | module/web/media/default/img/button.png | bin | 0 -> 452 bytes | |||
-rw-r--r-- | module/web/media/default/img/closebtn.gif (renamed from module/web/static/window/closebtn.gif) | bin | 254 -> 254 bytes | |||
-rw-r--r-- | module/web/media/default/img/cog.png | bin | 0 -> 512 bytes | |||
-rw-r--r-- | module/web/media/default/img/control_cancel.png | bin | 0 -> 3349 bytes | |||
-rw-r--r-- | module/web/media/default/img/control_cancel_blue.png | bin | 0 -> 787 bytes | |||
-rw-r--r-- | module/web/media/default/img/control_pause.png | bin | 0 -> 598 bytes | |||
-rw-r--r-- | module/web/media/default/img/control_pause_blue.png | bin | 0 -> 721 bytes | |||
-rw-r--r-- | module/web/media/default/img/control_play.png | bin | 0 -> 592 bytes | |||
-rw-r--r-- | module/web/media/default/img/control_play_blue.png | bin | 0 -> 717 bytes | |||
-rw-r--r-- | module/web/media/default/img/control_stop.png | bin | 0 -> 403 bytes | |||
-rw-r--r-- | module/web/media/default/img/control_stop_blue.png | bin | 0 -> 695 bytes | |||
-rw-r--r-- | module/web/media/default/img/delete.png | bin | 0 -> 715 bytes | |||
-rw-r--r-- | module/web/media/default/img/drag_corner.gif (renamed from module/web/static/window/drag_corner.gif) | bin | 76 -> 76 bytes | |||
-rw-r--r-- | module/web/media/default/img/folder.png | bin | 0 -> 537 bytes | |||
-rw-r--r-- | module/web/media/default/img/full.png (renamed from module/web/static/window/full.png) | bin | 3543 -> 3543 bytes | |||
-rw-r--r-- | module/web/media/default/img/head-login.png (renamed from module/web/static/default/head-login.png) | bin | 1288 -> 1288 bytes | |||
-rw-r--r-- | module/web/media/default/img/head-menu-development.png (renamed from module/web/static/default/head-menu-development.png) | bin | 1324 -> 1324 bytes | |||
-rw-r--r-- | module/web/media/default/img/head-menu-download.png (renamed from module/web/static/default/head-menu-download.png) | bin | 721 -> 721 bytes | |||
-rw-r--r-- | module/web/media/default/img/head-menu-home.png (renamed from module/web/static/default/head-menu-home.png) | bin | 920 -> 920 bytes | |||
-rw-r--r-- | module/web/media/default/img/head-menu-index.png (renamed from module/web/static/default/head-menu-index.png) | bin | 482 -> 482 bytes | |||
-rw-r--r-- | module/web/media/default/img/head-menu-news.png (renamed from module/web/static/default/head-menu-news.png) | bin | 628 -> 628 bytes | |||
-rw-r--r-- | module/web/media/default/img/head-menu-recent.png (renamed from module/web/static/default/head-menu-recent.png) | bin | 932 -> 932 bytes | |||
-rw-r--r-- | module/web/media/default/img/head-menu-wiki.png (renamed from module/web/static/default/head-menu-wiki.png) | bin | 1204 -> 1204 bytes | |||
-rw-r--r-- | module/web/media/default/img/head-search-noshadow.png (renamed from module/web/static/default/head-search-noshadow.png) | bin | 1187 -> 1187 bytes | |||
-rw-r--r-- | module/web/media/default/img/head_bg1.png (renamed from module/web/static/default/head_bg1.png) | bin | 125 -> 125 bytes | |||
-rw-r--r-- | module/web/media/default/img/page-tools-backlinks.png (renamed from module/web/static/default/page-tools-backlinks.png) | bin | 540 -> 540 bytes | |||
-rw-r--r-- | module/web/media/default/img/page-tools-edit.png (renamed from module/web/static/default/page-tools-edit.png) | bin | 574 -> 574 bytes | |||
-rw-r--r-- | module/web/media/default/img/page-tools-revisions.png (renamed from module/web/static/default/page-tools-revisions.png) | bin | 603 -> 603 bytes | |||
-rw-r--r-- | module/web/media/default/img/pyload-logo-edited3.5-new-font-small.png (renamed from module/web/static/default/pyload-logo-edited3.5-new-font-small.png) | bin | 8457 -> 8457 bytes | |||
-rw-r--r-- | module/web/media/default/img/status_None.png | bin | 0 -> 7613 bytes | |||
-rw-r--r-- | module/web/media/default/img/status_aborted.png | bin | 0 -> 700 bytes | |||
-rw-r--r-- | module/web/media/default/img/status_downloading.png | bin | 0 -> 943 bytes | |||
-rw-r--r-- | module/web/media/default/img/status_failed.png | bin | 0 -> 700 bytes | |||
-rw-r--r-- | module/web/media/default/img/status_finished.png | bin | 0 -> 781 bytes | |||
-rw-r--r-- | module/web/media/default/img/status_waiting.png | bin | 0 -> 889 bytes | |||
-rw-r--r-- | module/web/media/default/img/tab-background.png (renamed from module/web/static/default/tab-background.png) | bin | 179 -> 179 bytes | |||
-rw-r--r-- | module/web/media/default/img/tabs-border-bottom.png (renamed from module/web/static/default/tabs-border-bottom.png) | bin | 163 -> 163 bytes | |||
-rw-r--r-- | module/web/media/default/img/user-actions-logout.png (renamed from module/web/static/default/user-actions-logout.png) | bin | 799 -> 799 bytes | |||
-rw-r--r-- | module/web/media/default/img/user-actions-profile.png (renamed from module/web/static/default/user-actions-profile.png) | bin | 628 -> 628 bytes | |||
-rw-r--r-- | module/web/media/default/js/funktions.js | 23 | ||||
-rw-r--r-- | module/web/media/default/js/jquery.timers-1.2.js | 138 | ||||
-rw-r--r-- | module/web/media/default/js/mootools-1.2.3-core.js (renamed from module/web/static/mootools-1.2.3-core.js) | 0 | ||||
-rw-r--r-- | module/web/media/default/js/mootools-1.2.3.1-more.js (renamed from module/web/static/mootools-1.2.3.1-more.js) | 0 | ||||
-rw-r--r-- | module/web/media/default/js/mootools-1.2.4-core.js | 337 | ||||
-rw-r--r-- | module/web/media/default/js/mootools-1.2.4.2-more.js | 134 | ||||
-rw-r--r-- | module/web/media/default/js/sprintf.js | 123 | ||||
-rw-r--r-- | module/web/media/default/js/status.js (renamed from module/web/static/default/status.js) | 4 | ||||
-rw-r--r-- | module/web/media/img/favicon.ico (renamed from module/web/static/favicon.ico) | bin | 7206 -> 7206 bytes | |||
-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/tests.py | 23 | ||||
-rw-r--r-- | module/web/pyload/urls.py | 22 | ||||
-rw-r--r-- | module/web/pyload/views.py | 153 | ||||
-rwxr-xr-x | module/web/run_unix.py | 21 | ||||
-rw-r--r-- | module/web/settings.py | 135 | ||||
-rw-r--r-- | module/web/static/default.css | 189 | ||||
-rw-r--r-- | module/web/static/default/home.js | 212 | ||||
-rw-r--r-- | module/web/static/default/progress-bar-back.gif | bin | 10819 -> 0 bytes | |||
-rw-r--r-- | module/web/static/default/progress-bar.gif | bin | 10819 -> 0 bytes | |||
-rw-r--r-- | module/web/static/window.css | 17 | ||||
-rw-r--r-- | module/web/templates/default.tpl | 230 | ||||
-rw-r--r-- | module/web/templates/default/add.html | 12 | ||||
-rw-r--r-- | module/web/templates/default/base.html | 213 | ||||
-rw-r--r-- | module/web/templates/default/downloads.html | 44 | ||||
-rw-r--r-- | module/web/templates/default/home.html | 233 | ||||
-rw-r--r-- | module/web/templates/default/login.html | 35 | ||||
-rw-r--r-- | module/web/templates/default/logout.html | 9 | ||||
-rw-r--r-- | module/web/templates/default/logs.html | 25 | ||||
-rw-r--r-- | module/web/templates/default/queue.html | 125 | ||||
-rw-r--r-- | module/web/templates/default/window.html | 33 | ||||
-rw-r--r-- | module/web/templates/footer.tpl | 6 | ||||
-rw-r--r-- | module/web/templates/header.tpl | 24 | ||||
-rw-r--r-- | module/web/templates/window.tpl | 28 | ||||
-rw-r--r-- | module/web/urls.py | 22 | ||||
-rw-r--r-- | pluginconfig | 29 | ||||
-rwxr-xr-x | pyLoadCli.py | 324 | ||||
-rwxr-xr-x | pyLoadCore.py | 1014 | ||||
-rwxr-xr-x | pyLoadGui.py | 914 | ||||
-rwxr-xr-x | pyLoadUpdater.py | 106 | ||||
-rw-r--r-- | scripts/Readme.txt | 25 |
202 files changed, 12638 insertions, 3936 deletions
@@ -10,4 +10,16 @@ syntax: glob *.pydevproject Downloads/* Logs/* -Plugins/DLC.py
\ No newline at end of file +Plugins/DLC.py +failed_links.txt +module/config/gui.xml +module/config/core.xml +module/config/plugin.xml +links.txt +module/links.pkl +module/cookies.txt +ssl.crt +ssl.key +cert.pem +module/web/pyload.db +webserver.pid diff --git a/config b/config deleted file mode 100644 index 58df443a2..000000000 --- a/config +++ /dev/null @@ -1,43 +0,0 @@ -[remote] -port = 7272 -password = pwhere - -[webinterface] -activated = False -listenaddr = 0.0.0.0 -port = 8080 -username = User -password = webpw - -[log] -file_log = True -log_folder = Logs -log_count = 5 - -[general] -language = de -download_folder = Downloads -max_downloads = 3 -use_reconnect = False -link_file = links.txt -failed_file = failed_links.txt -reconnect_method = reconnect_method -debug_mode = False -max_download_time = 18000 - -[updates] -search_updates = True -install_updates = False - -[reconnectTime] -start = 0:00 -end = 0:00 - -[downloadTime] -start = 0:00 -end = 0:00 - -[proxy] -activated = False -adress = http://localhost:8080 -protocol = http diff --git a/icons/gui/clipboard.png b/icons/gui/clipboard.png Binary files differnew file mode 100644 index 000000000..9ba608eba --- /dev/null +++ b/icons/gui/clipboard.png diff --git a/icons/gui/edit_small.png b/icons/gui/edit_small.png Binary files differnew file mode 100644 index 000000000..eb76e21b4 --- /dev/null +++ b/icons/gui/edit_small.png diff --git a/icons/gui/pull_small.png b/icons/gui/pull_small.png Binary files differnew file mode 100644 index 000000000..432ad321f --- /dev/null +++ b/icons/gui/pull_small.png diff --git a/icons/gui/push_small.png b/icons/gui/push_small.png Binary files differnew file mode 100644 index 000000000..701fc69e3 --- /dev/null +++ b/icons/gui/push_small.png diff --git a/icons/gui/refresh_small.png b/icons/gui/refresh_small.png Binary files differnew file mode 100644 index 000000000..1ffd18d97 --- /dev/null +++ b/icons/gui/refresh_small.png diff --git a/icons/gui/remove_small.png b/icons/gui/remove_small.png Binary files differnew file mode 100644 index 000000000..bf99763e8 --- /dev/null +++ b/icons/gui/remove_small.png diff --git a/icons/gui/toolbar_add.png b/icons/gui/toolbar_add.png Binary files differnew file mode 100644 index 000000000..17003e9f0 --- /dev/null +++ b/icons/gui/toolbar_add.png diff --git a/icons/gui/toolbar_pause.png b/icons/gui/toolbar_pause.png Binary files differnew file mode 100644 index 000000000..b7a727b71 --- /dev/null +++ b/icons/gui/toolbar_pause.png diff --git a/icons/gui/toolbar_remove.png b/icons/gui/toolbar_remove.png Binary files differnew file mode 100644 index 000000000..1e9c00e16 --- /dev/null +++ b/icons/gui/toolbar_remove.png diff --git a/icons/gui/toolbar_start.png b/icons/gui/toolbar_start.png Binary files differnew file mode 100644 index 000000000..1123266e6 --- /dev/null +++ b/icons/gui/toolbar_start.png diff --git a/icons/gui/toolbar_stop.png b/icons/gui/toolbar_stop.png Binary files differnew file mode 100644 index 000000000..b388e3d72 --- /dev/null +++ b/icons/gui/toolbar_stop.png diff --git a/icons/logo.png b/icons/logo.png Binary files differnew file mode 100644 index 000000000..72a95b740 --- /dev/null +++ b/icons/logo.png diff --git a/module/BeautifulSoup.py b/module/BeautifulSoup.py new file mode 100644 index 000000000..34204e740 --- /dev/null +++ b/module/BeautifulSoup.py @@ -0,0 +1,2000 @@ +"""Beautiful Soup +Elixir and Tonic +"The Screen-Scraper's Friend" +http://www.crummy.com/software/BeautifulSoup/ + +Beautiful Soup parses a (possibly invalid) XML or HTML document into a +tree representation. It provides methods and Pythonic idioms that make +it easy to navigate, search, and modify the tree. + +A well-formed XML/HTML document yields a well-formed data +structure. An ill-formed XML/HTML document yields a correspondingly +ill-formed data structure. If your document is only locally +well-formed, you can use this library to find and process the +well-formed part of it. + +Beautiful Soup works with Python 2.2 and up. It has no external +dependencies, but you'll have more success at converting data to UTF-8 +if you also install these three packages: + +* chardet, for auto-detecting character encodings + http://chardet.feedparser.org/ +* cjkcodecs and iconv_codec, which add more encodings to the ones supported + by stock Python. + http://cjkpython.i18n.org/ + +Beautiful Soup defines classes for two main parsing strategies: + + * BeautifulStoneSoup, for parsing XML, SGML, or your domain-specific + language that kind of looks like XML. + + * BeautifulSoup, for parsing run-of-the-mill HTML code, be it valid + or invalid. This class has web browser-like heuristics for + obtaining a sensible parse tree in the face of common HTML errors. + +Beautiful Soup also defines a class (UnicodeDammit) for autodetecting +the encoding of an HTML or XML document, and converting it to +Unicode. Much of this code is taken from Mark Pilgrim's Universal Feed Parser. + +For more than you ever wanted to know about Beautiful Soup, see the +documentation: +http://www.crummy.com/software/BeautifulSoup/documentation.html + +Here, have some legalese: + +Copyright (c) 2004-2009, Leonard Richardson + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + * Neither the name of the the Beautiful Soup Consortium and All + Night Kosher Bakery nor the names of its contributors may be + used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE, DAMMIT. + +""" +from __future__ import generators + +__author__ = "Leonard Richardson (leonardr@segfault.org)" +__version__ = "3.1.0.1" +__copyright__ = "Copyright (c) 2004-2009 Leonard Richardson" +__license__ = "New-style BSD" + +import codecs +import markupbase +import types +import re +from HTMLParser import HTMLParser, HTMLParseError +try: + from htmlentitydefs import name2codepoint +except ImportError: + name2codepoint = {} +try: + set +except NameError: + from sets import Set as set + +#These hacks make Beautiful Soup able to parse XML with namespaces +markupbase._declname_match = re.compile(r'[a-zA-Z][-_.:a-zA-Z0-9]*\s*').match + +DEFAULT_OUTPUT_ENCODING = "utf-8" + +# First, the classes that represent markup elements. + +def sob(unicode, encoding): + """Returns either the given Unicode string or its encoding.""" + if encoding is None: + return unicode + else: + return unicode.encode(encoding) + +class PageElement: + """Contains the navigational information for some part of the page + (either a tag or a piece of text)""" + + def setup(self, parent=None, previous=None): + """Sets up the initial relations between this element and + other elements.""" + self.parent = parent + self.previous = previous + self.next = None + self.previousSibling = None + self.nextSibling = None + if self.parent and self.parent.contents: + self.previousSibling = self.parent.contents[-1] + self.previousSibling.nextSibling = self + + def replaceWith(self, replaceWith): + oldParent = self.parent + myIndex = self.parent.contents.index(self) + if hasattr(replaceWith, 'parent') and replaceWith.parent == self.parent: + # We're replacing this element with one of its siblings. + index = self.parent.contents.index(replaceWith) + if index and index < myIndex: + # Furthermore, it comes before this element. That + # means that when we extract it, the index of this + # element will change. + myIndex = myIndex - 1 + self.extract() + oldParent.insert(myIndex, replaceWith) + + def extract(self): + """Destructively rips this element out of the tree.""" + if self.parent: + try: + self.parent.contents.remove(self) + except ValueError: + pass + + #Find the two elements that would be next to each other if + #this element (and any children) hadn't been parsed. Connect + #the two. + lastChild = self._lastRecursiveChild() + nextElement = lastChild.next + + if self.previous: + self.previous.next = nextElement + if nextElement: + nextElement.previous = self.previous + self.previous = None + lastChild.next = None + + self.parent = None + if self.previousSibling: + self.previousSibling.nextSibling = self.nextSibling + if self.nextSibling: + self.nextSibling.previousSibling = self.previousSibling + self.previousSibling = self.nextSibling = None + return self + + def _lastRecursiveChild(self): + "Finds the last element beneath this object to be parsed." + lastChild = self + while hasattr(lastChild, 'contents') and lastChild.contents: + lastChild = lastChild.contents[-1] + return lastChild + + def insert(self, position, newChild): + if (isinstance(newChild, basestring) + or isinstance(newChild, unicode)) \ + and not isinstance(newChild, NavigableString): + newChild = NavigableString(newChild) + + position = min(position, len(self.contents)) + if hasattr(newChild, 'parent') and newChild.parent != None: + # We're 'inserting' an element that's already one + # of this object's children. + if newChild.parent == self: + index = self.find(newChild) + if index and index < position: + # Furthermore we're moving it further down the + # list of this object's children. That means that + # when we extract this element, our target index + # will jump down one. + position = position - 1 + newChild.extract() + + newChild.parent = self + previousChild = None + if position == 0: + newChild.previousSibling = None + newChild.previous = self + else: + previousChild = self.contents[position-1] + newChild.previousSibling = previousChild + newChild.previousSibling.nextSibling = newChild + newChild.previous = previousChild._lastRecursiveChild() + if newChild.previous: + newChild.previous.next = newChild + + newChildsLastElement = newChild._lastRecursiveChild() + + if position >= len(self.contents): + newChild.nextSibling = None + + parent = self + parentsNextSibling = None + while not parentsNextSibling: + parentsNextSibling = parent.nextSibling + parent = parent.parent + if not parent: # This is the last element in the document. + break + if parentsNextSibling: + newChildsLastElement.next = parentsNextSibling + else: + newChildsLastElement.next = None + else: + nextChild = self.contents[position] + newChild.nextSibling = nextChild + if newChild.nextSibling: + newChild.nextSibling.previousSibling = newChild + newChildsLastElement.next = nextChild + + if newChildsLastElement.next: + newChildsLastElement.next.previous = newChildsLastElement + self.contents.insert(position, newChild) + + def append(self, tag): + """Appends the given tag to the contents of this tag.""" + self.insert(len(self.contents), tag) + + def findNext(self, name=None, attrs={}, text=None, **kwargs): + """Returns the first item that matches the given criteria and + appears after this Tag in the document.""" + return self._findOne(self.findAllNext, name, attrs, text, **kwargs) + + def findAllNext(self, name=None, attrs={}, text=None, limit=None, + **kwargs): + """Returns all items that match the given criteria and appear + after this Tag in the document.""" + return self._findAll(name, attrs, text, limit, self.nextGenerator, + **kwargs) + + def findNextSibling(self, name=None, attrs={}, text=None, **kwargs): + """Returns the closest sibling to this Tag that matches the + given criteria and appears after this Tag in the document.""" + return self._findOne(self.findNextSiblings, name, attrs, text, + **kwargs) + + def findNextSiblings(self, name=None, attrs={}, text=None, limit=None, + **kwargs): + """Returns the siblings of this Tag that match the given + criteria and appear after this Tag in the document.""" + return self._findAll(name, attrs, text, limit, + self.nextSiblingGenerator, **kwargs) + fetchNextSiblings = findNextSiblings # Compatibility with pre-3.x + + def findPrevious(self, name=None, attrs={}, text=None, **kwargs): + """Returns the first item that matches the given criteria and + appears before this Tag in the document.""" + return self._findOne(self.findAllPrevious, name, attrs, text, **kwargs) + + def findAllPrevious(self, name=None, attrs={}, text=None, limit=None, + **kwargs): + """Returns all items that match the given criteria and appear + before this Tag in the document.""" + return self._findAll(name, attrs, text, limit, self.previousGenerator, + **kwargs) + fetchPrevious = findAllPrevious # Compatibility with pre-3.x + + def findPreviousSibling(self, name=None, attrs={}, text=None, **kwargs): + """Returns the closest sibling to this Tag that matches the + given criteria and appears before this Tag in the document.""" + return self._findOne(self.findPreviousSiblings, name, attrs, text, + **kwargs) + + def findPreviousSiblings(self, name=None, attrs={}, text=None, + limit=None, **kwargs): + """Returns the siblings of this Tag that match the given + criteria and appear before this Tag in the document.""" + return self._findAll(name, attrs, text, limit, + self.previousSiblingGenerator, **kwargs) + fetchPreviousSiblings = findPreviousSiblings # Compatibility with pre-3.x + + def findParent(self, name=None, attrs={}, **kwargs): + """Returns the closest parent of this Tag that matches the given + criteria.""" + # NOTE: We can't use _findOne because findParents takes a different + # set of arguments. + r = None + l = self.findParents(name, attrs, 1) + if l: + r = l[0] + return r + + def findParents(self, name=None, attrs={}, limit=None, **kwargs): + """Returns the parents of this Tag that match the given + criteria.""" + + return self._findAll(name, attrs, None, limit, self.parentGenerator, + **kwargs) + fetchParents = findParents # Compatibility with pre-3.x + + #These methods do the real heavy lifting. + + def _findOne(self, method, name, attrs, text, **kwargs): + r = None + l = method(name, attrs, text, 1, **kwargs) + if l: + r = l[0] + return r + + def _findAll(self, name, attrs, text, limit, generator, **kwargs): + "Iterates over a generator looking for things that match." + + if isinstance(name, SoupStrainer): + strainer = name + else: + # Build a SoupStrainer + strainer = SoupStrainer(name, attrs, text, **kwargs) + results = ResultSet(strainer) + g = generator() + while True: + try: + i = g.next() + except StopIteration: + break + if i: + found = strainer.search(i) + if found: + results.append(found) + if limit and len(results) >= limit: + break + return results + + #These Generators can be used to navigate starting from both + #NavigableStrings and Tags. + def nextGenerator(self): + i = self + while i: + i = i.next + yield i + + def nextSiblingGenerator(self): + i = self + while i: + i = i.nextSibling + yield i + + def previousGenerator(self): + i = self + while i: + i = i.previous + yield i + + def previousSiblingGenerator(self): + i = self + while i: + i = i.previousSibling + yield i + + def parentGenerator(self): + i = self + while i: + i = i.parent + yield i + + # Utility methods + def substituteEncoding(self, str, encoding=None): + encoding = encoding or "utf-8" + return str.replace("%SOUP-ENCODING%", encoding) + + def toEncoding(self, s, encoding=None): + """Encodes an object to a string in some encoding, or to Unicode. + .""" + if isinstance(s, unicode): + if encoding: + s = s.encode(encoding) + elif isinstance(s, str): + if encoding: + s = s.encode(encoding) + else: + s = unicode(s) + else: + if encoding: + s = self.toEncoding(str(s), encoding) + else: + s = unicode(s) + return s + +class NavigableString(unicode, PageElement): + + def __new__(cls, value): + """Create a new NavigableString. + + When unpickling a NavigableString, this method is called with + the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be + passed in to the superclass's __new__ or the superclass won't know + how to handle non-ASCII characters. + """ + if isinstance(value, unicode): + return unicode.__new__(cls, value) + return unicode.__new__(cls, value, DEFAULT_OUTPUT_ENCODING) + + def __getnewargs__(self): + return (unicode(self),) + + def __getattr__(self, attr): + """text.string gives you text. This is for backwards + compatibility for Navigable*String, but for CData* it lets you + get the string without the CData wrapper.""" + if attr == 'string': + return self + else: + raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__.__name__, attr) + + def encode(self, encoding=DEFAULT_OUTPUT_ENCODING): + return self.decode().encode(encoding) + + def decodeGivenEventualEncoding(self, eventualEncoding): + return self + +class CData(NavigableString): + + def decodeGivenEventualEncoding(self, eventualEncoding): + return u'<![CDATA[' + self + u']]>' + +class ProcessingInstruction(NavigableString): + + def decodeGivenEventualEncoding(self, eventualEncoding): + output = self + if u'%SOUP-ENCODING%' in output: + output = self.substituteEncoding(output, eventualEncoding) + return u'<?' + output + u'?>' + +class Comment(NavigableString): + def decodeGivenEventualEncoding(self, eventualEncoding): + return u'<!--' + self + u'-->' + +class Declaration(NavigableString): + def decodeGivenEventualEncoding(self, eventualEncoding): + return u'<!' + self + u'>' + +class Tag(PageElement): + + """Represents a found HTML tag with its attributes and contents.""" + + def _invert(h): + "Cheap function to invert a hash." + i = {} + for k,v in h.items(): + i[v] = k + return i + + XML_ENTITIES_TO_SPECIAL_CHARS = { "apos" : "'", + "quot" : '"', + "amp" : "&", + "lt" : "<", + "gt" : ">" } + + XML_SPECIAL_CHARS_TO_ENTITIES = _invert(XML_ENTITIES_TO_SPECIAL_CHARS) + + def _convertEntities(self, match): + """Used in a call to re.sub to replace HTML, XML, and numeric + entities with the appropriate Unicode characters. If HTML + entities are being converted, any unrecognized entities are + escaped.""" + x = match.group(1) + if self.convertHTMLEntities and x in name2codepoint: + return unichr(name2codepoint[x]) + elif x in self.XML_ENTITIES_TO_SPECIAL_CHARS: + if self.convertXMLEntities: + return self.XML_ENTITIES_TO_SPECIAL_CHARS[x] + else: + return u'&%s;' % x + elif len(x) > 0 and x[0] == '#': + # Handle numeric entities + if len(x) > 1 and x[1] == 'x': + return unichr(int(x[2:], 16)) + else: + return unichr(int(x[1:])) + + elif self.escapeUnrecognizedEntities: + return u'&%s;' % x + else: + return u'&%s;' % x + + def __init__(self, parser, name, attrs=None, parent=None, + previous=None): + "Basic constructor." + + # We don't actually store the parser object: that lets extracted + # chunks be garbage-collected + self.parserClass = parser.__class__ + self.isSelfClosing = parser.isSelfClosingTag(name) + self.name = name + if attrs == None: + attrs = [] + self.attrs = attrs + self.contents = [] + self.setup(parent, previous) + self.hidden = False + self.containsSubstitutions = False + self.convertHTMLEntities = parser.convertHTMLEntities + self.convertXMLEntities = parser.convertXMLEntities + self.escapeUnrecognizedEntities = parser.escapeUnrecognizedEntities + + def convert(kval): + "Converts HTML, XML and numeric entities in the attribute value." + k, val = kval + if val is None: + return kval + return (k, re.sub("&(#\d+|#x[0-9a-fA-F]+|\w+);", + self._convertEntities, val)) + self.attrs = map(convert, self.attrs) + + def get(self, key, default=None): + """Returns the value of the 'key' attribute for the tag, or + the value given for 'default' if it doesn't have that + attribute.""" + return self._getAttrMap().get(key, default) + + def has_key(self, key): + return self._getAttrMap().has_key(key) + + def __getitem__(self, key): + """tag[key] returns the value of the 'key' attribute for the tag, + and throws an exception if it's not there.""" + return self._getAttrMap()[key] + + def __iter__(self): + "Iterating over a tag iterates over its contents." + return iter(self.contents) + + def __len__(self): + "The length of a tag is the length of its list of contents." + return len(self.contents) + + def __contains__(self, x): + return x in self.contents + + def __nonzero__(self): + "A tag is non-None even if it has no contents." + return True + + def __setitem__(self, key, value): + """Setting tag[key] sets the value of the 'key' attribute for the + tag.""" + self._getAttrMap() + self.attrMap[key] = value + found = False + for i in range(0, len(self.attrs)): + if self.attrs[i][0] == key: + self.attrs[i] = (key, value) + found = True + if not found: + self.attrs.append((key, value)) + self._getAttrMap()[key] = value + + def __delitem__(self, key): + "Deleting tag[key] deletes all 'key' attributes for the tag." + for item in self.attrs: + if item[0] == key: + self.attrs.remove(item) + #We don't break because bad HTML can define the same + #attribute multiple times. + self._getAttrMap() + if self.attrMap.has_key(key): + del self.attrMap[key] + + def __call__(self, *args, **kwargs): + """Calling a tag like a function is the same as calling its + findAll() method. Eg. tag('a') returns a list of all the A tags + found within this tag.""" + return apply(self.findAll, args, kwargs) + + def __getattr__(self, tag): + #print "Getattr %s.%s" % (self.__class__, tag) + if len(tag) > 3 and tag.rfind('Tag') == len(tag)-3: + return self.find(tag[:-3]) + elif tag.find('__') != 0: + return self.find(tag) + raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__, tag) + + def __eq__(self, other): + """Returns true iff this tag has the same name, the same attributes, + and the same contents (recursively) as the given tag. + + NOTE: right now this will return false if two tags have the + same attributes in a different order. Should this be fixed?""" + if not hasattr(other, 'name') or not hasattr(other, 'attrs') or not hasattr(other, 'contents') or self.name != other.name or self.attrs != other.attrs or len(self) != len(other): + return False + for i in range(0, len(self.contents)): + if self.contents[i] != other.contents[i]: + return False + return True + + def __ne__(self, other): + """Returns true iff this tag is not identical to the other tag, + as defined in __eq__.""" + return not self == other + + def __repr__(self, encoding=DEFAULT_OUTPUT_ENCODING): + """Renders this tag as a string.""" + return self.decode(eventualEncoding=encoding) + + BARE_AMPERSAND_OR_BRACKET = re.compile("([<>]|" + + "&(?!#\d+;|#x[0-9a-fA-F]+;|\w+;)" + + ")") + + def _sub_entity(self, x): + """Used with a regular expression to substitute the + appropriate XML entity for an XML special character.""" + return "&" + self.XML_SPECIAL_CHARS_TO_ENTITIES[x.group(0)[0]] + ";" + + def __unicode__(self): + return self.decode() + + def __str__(self): + return self.encode() + + def encode(self, encoding=DEFAULT_OUTPUT_ENCODING, + prettyPrint=False, indentLevel=0): + return self.decode(prettyPrint, indentLevel, encoding).encode(encoding) + + def decode(self, prettyPrint=False, indentLevel=0, + eventualEncoding=DEFAULT_OUTPUT_ENCODING): + """Returns a string or Unicode representation of this tag and + its contents. To get Unicode, pass None for encoding.""" + + attrs = [] + if self.attrs: + for key, val in self.attrs: + fmt = '%s="%s"' + if isString(val): + if (self.containsSubstitutions + and eventualEncoding is not None + and '%SOUP-ENCODING%' in val): + val = self.substituteEncoding(val, eventualEncoding) + + # The attribute value either: + # + # * Contains no embedded double quotes or single quotes. + # No problem: we enclose it in double quotes. + # * Contains embedded single quotes. No problem: + # double quotes work here too. + # * Contains embedded double quotes. No problem: + # we enclose it in single quotes. + # * Embeds both single _and_ double quotes. This + # can't happen naturally, but it can happen if + # you modify an attribute value after parsing + # the document. Now we have a bit of a + # problem. We solve it by enclosing the + # attribute in single quotes, and escaping any + # embedded single quotes to XML entities. + if '"' in val: + fmt = "%s='%s'" + if "'" in val: + # TODO: replace with apos when + # appropriate. + val = val.replace("'", "&squot;") + + # Now we're okay w/r/t quotes. But the attribute + # value might also contain angle brackets, or + # ampersands that aren't part of entities. We need + # to escape those to XML entities too. + val = self.BARE_AMPERSAND_OR_BRACKET.sub(self._sub_entity, val) + if val is None: + # Handle boolean attributes. + decoded = key + else: + decoded = fmt % (key, val) + attrs.append(decoded) + close = '' + closeTag = '' + if self.isSelfClosing: + close = ' /' + else: + closeTag = '</%s>' % self.name + + indentTag, indentContents = 0, 0 + if prettyPrint: + indentTag = indentLevel + space = (' ' * (indentTag-1)) + indentContents = indentTag + 1 + contents = self.decodeContents(prettyPrint, indentContents, + eventualEncoding) + if self.hidden: + s = contents + else: + s = [] + attributeString = '' + if attrs: + attributeString = ' ' + ' '.join(attrs) + if prettyPrint: + s.append(space) + s.append('<%s%s%s>' % (self.name, attributeString, close)) + if prettyPrint: + s.append("\n") + s.append(contents) + if prettyPrint and contents and contents[-1] != "\n": + s.append("\n") + if prettyPrint and closeTag: + s.append(space) + s.append(closeTag) + if prettyPrint and closeTag and self.nextSibling: + s.append("\n") + s = ''.join(s) + return s + + def decompose(self): + """Recursively destroys the contents of this tree.""" + contents = [i for i in self.contents] + for i in contents: + if isinstance(i, Tag): + i.decompose() + else: + i.extract() + self.extract() + + def prettify(self, encoding=DEFAULT_OUTPUT_ENCODING): + return self.encode(encoding, True) + + def encodeContents(self, encoding=DEFAULT_OUTPUT_ENCODING, + prettyPrint=False, indentLevel=0): + return self.decodeContents(prettyPrint, indentLevel).encode(encoding) + + def decodeContents(self, prettyPrint=False, indentLevel=0, + eventualEncoding=DEFAULT_OUTPUT_ENCODING): + """Renders the contents of this tag as a string in the given + encoding. If encoding is None, returns a Unicode string..""" + s=[] + for c in self: + text = None + if isinstance(c, NavigableString): + text = c.decodeGivenEventualEncoding(eventualEncoding) + elif isinstance(c, Tag): + s.append(c.decode(prettyPrint, indentLevel, eventualEncoding)) + if text and prettyPrint: + text = text.strip() + if text: + if prettyPrint: + s.append(" " * (indentLevel-1)) + s.append(text) + if prettyPrint: + s.append("\n") + return ''.join(s) + + #Soup methods + + def find(self, name=None, attrs={}, recursive=True, text=None, + **kwargs): + """Return only the first child of this Tag matching the given + criteria.""" + r = None + l = self.findAll(name, attrs, recursive, text, 1, **kwargs) + if l: + r = l[0] + return r + findChild = find + + def findAll(self, name=None, attrs={}, recursive=True, text=None, + limit=None, **kwargs): + """Extracts a list of Tag objects that match the given + criteria. You can specify the name of the Tag and any + attributes you want the Tag to have. + + The value of a key-value pair in the 'attrs' map can be a + string, a list of strings, a regular expression object, or a + callable that takes a string and returns whether or not the + string matches for some custom definition of 'matches'. The + same is true of the tag name.""" + generator = self.recursiveChildGenerator + if not recursive: + generator = self.childGenerator + return self._findAll(name, attrs, text, limit, generator, **kwargs) + findChildren = findAll + + # Pre-3.x compatibility methods. Will go away in 4.0. + first = find + fetch = findAll + + def fetchText(self, text=None, recursive=True, limit=None): + return self.findAll(text=text, recursive=recursive, limit=limit) + + def firstText(self, text=None, recursive=True): + return self.find(text=text, recursive=recursive) + + # 3.x compatibility methods. Will go away in 4.0. + def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING, + prettyPrint=False, indentLevel=0): + if encoding is None: + return self.decodeContents(prettyPrint, indentLevel, encoding) + else: + return self.encodeContents(encoding, prettyPrint, indentLevel) + + + #Private methods + + def _getAttrMap(self): + """Initializes a map representation of this tag's attributes, + if not already initialized.""" + if not getattr(self, 'attrMap'): + self.attrMap = {} + for (key, value) in self.attrs: + self.attrMap[key] = value + return self.attrMap + + #Generator methods + def recursiveChildGenerator(self): + if not len(self.contents): + raise StopIteration + stopNode = self._lastRecursiveChild().next + current = self.contents[0] + while current is not stopNode: + yield current + current = current.next + + def childGenerator(self): + if not len(self.contents): + raise StopIteration + current = self.contents[0] + while current: + yield current + current = current.nextSibling + raise StopIteration + +# Next, a couple classes to represent queries and their results. +class SoupStrainer: + """Encapsulates a number of ways of matching a markup element (tag or + text).""" + + def __init__(self, name=None, attrs={}, text=None, **kwargs): + self.name = name + if isString(attrs): + kwargs['class'] = attrs + attrs = None + if kwargs: + if attrs: + attrs = attrs.copy() + attrs.update(kwargs) + else: + attrs = kwargs + self.attrs = attrs + self.text = text + + def __str__(self): + if self.text: + return self.text + else: + return "%s|%s" % (self.name, self.attrs) + + def searchTag(self, markupName=None, markupAttrs={}): + found = None + markup = None + if isinstance(markupName, Tag): + markup = markupName + markupAttrs = markup + callFunctionWithTagData = callable(self.name) \ + and not isinstance(markupName, Tag) + + if (not self.name) \ + or callFunctionWithTagData \ + or (markup and self._matches(markup, self.name)) \ + or (not markup and self._matches(markupName, self.name)): + if callFunctionWithTagData: + match = self.name(markupName, markupAttrs) + else: + match = True + markupAttrMap = None + for attr, matchAgainst in self.attrs.items(): + if not markupAttrMap: + if hasattr(markupAttrs, 'get'): + markupAttrMap = markupAttrs + else: + markupAttrMap = {} + for k,v in markupAttrs: + markupAttrMap[k] = v + attrValue = markupAttrMap.get(attr) + if not self._matches(attrValue, matchAgainst): + match = False + break + if match: + if markup: + found = markup + else: + found = markupName + return found + + def search(self, markup): + #print 'looking for %s in %s' % (self, markup) + found = None + # If given a list of items, scan it for a text element that + # matches. + if isList(markup) and not isinstance(markup, Tag): + for element in markup: + if isinstance(element, NavigableString) \ + and self.search(element): + found = element + break + # If it's a Tag, make sure its name or attributes match. + # Don't bother with Tags if we're searching for text. + elif isinstance(markup, Tag): + if not self.text: + found = self.searchTag(markup) + # If it's text, make sure the text matches. + elif isinstance(markup, NavigableString) or \ + isString(markup): + if self._matches(markup, self.text): + found = markup + else: + raise Exception, "I don't know how to match against a %s" \ + % markup.__class__ + return found + + def _matches(self, markup, matchAgainst): + #print "Matching %s against %s" % (markup, matchAgainst) + result = False + if matchAgainst == True and type(matchAgainst) == types.BooleanType: + result = markup != None + elif callable(matchAgainst): + result = matchAgainst(markup) + else: + #Custom match methods take the tag as an argument, but all + #other ways of matching match the tag name as a string. + if isinstance(markup, Tag): + markup = markup.name + if markup is not None and not isString(markup): + markup = unicode(markup) + #Now we know that chunk is either a string, or None. + if hasattr(matchAgainst, 'match'): + # It's a regexp object. + result = markup and matchAgainst.search(markup) + elif (isList(matchAgainst) + and (markup is not None or not isString(matchAgainst))): + result = markup in matchAgainst + elif hasattr(matchAgainst, 'items'): + result = markup.has_key(matchAgainst) + elif matchAgainst and isString(markup): + if isinstance(markup, unicode): + matchAgainst = unicode(matchAgainst) + else: + matchAgainst = str(matchAgainst) + + if not result: + result = matchAgainst == markup + return result + +class ResultSet(list): + """A ResultSet is just a list that keeps track of the SoupStrainer + that created it.""" + def __init__(self, source): + list.__init__([]) + self.source = source + +# Now, some helper functions. + +def isList(l): + """Convenience method that works with all 2.x versions of Python + to determine whether or not something is listlike.""" + return ((hasattr(l, '__iter__') and not isString(l)) + or (type(l) in (types.ListType, types.TupleType))) + +def isString(s): + """Convenience method that works with all 2.x versions of Python + to determine whether or not something is stringlike.""" + try: + return isinstance(s, unicode) or isinstance(s, basestring) + except NameError: + return isinstance(s, str) + +def buildTagMap(default, *args): + """Turns a list of maps, lists, or scalars into a single map. + Used to build the SELF_CLOSING_TAGS, NESTABLE_TAGS, and + NESTING_RESET_TAGS maps out of lists and partial maps.""" + built = {} + for portion in args: + if hasattr(portion, 'items'): + #It's a map. Merge it. + for k,v in portion.items(): + built[k] = v + elif isList(portion) and not isString(portion): + #It's a list. Map each item to the default. + for k in portion: + built[k] = default + else: + #It's a scalar. Map it to the default. + built[portion] = default + return built + +# Now, the parser classes. + +class HTMLParserBuilder(HTMLParser): + + def __init__(self, soup): + HTMLParser.__init__(self) + self.soup = soup + + # We inherit feed() and reset(). + + def handle_starttag(self, name, attrs): + if name == 'meta': + self.soup.extractCharsetFromMeta(attrs) + else: + self.soup.unknown_starttag(name, attrs) + + def handle_endtag(self, name): + self.soup.unknown_endtag(name) + + def handle_data(self, content): + self.soup.handle_data(content) + + def _toStringSubclass(self, text, subclass): + """Adds a certain piece of text to the tree as a NavigableString + subclass.""" + self.soup.endData() + self.handle_data(text) + self.soup.endData(subclass) + + def handle_pi(self, text): + """Handle a processing instruction as a ProcessingInstruction + object, possibly one with a %SOUP-ENCODING% slot into which an + encoding will be plugged later.""" + if text[:3] == "xml": + text = u"xml version='1.0' encoding='%SOUP-ENCODING%'" + self._toStringSubclass(text, ProcessingInstruction) + + def handle_comment(self, text): + "Handle comments as Comment objects." + self._toStringSubclass(text, Comment) + + def handle_charref(self, ref): + "Handle character references as data." + if self.soup.convertEntities: + data = unichr(int(ref)) + else: + data = '&#%s;' % ref + self.handle_data(data) + + def handle_entityref(self, ref): + """Handle entity references as data, possibly converting known + HTML and/or XML entity references to the corresponding Unicode + characters.""" + data = None + if self.soup.convertHTMLEntities: + try: + data = unichr(name2codepoint[ref]) + except KeyError: + pass + + if not data and self.soup.convertXMLEntities: + data = self.soup.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref) + + if not data and self.soup.convertHTMLEntities and \ + not self.soup.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref): + # TODO: We've got a problem here. We're told this is + # an entity reference, but it's not an XML entity + # reference or an HTML entity reference. Nonetheless, + # the logical thing to do is to pass it through as an + # unrecognized entity reference. + # + # Except: when the input is "&carol;" this function + # will be called with input "carol". When the input is + # "AT&T", this function will be called with input + # "T". We have no way of knowing whether a semicolon + # was present originally, so we don't know whether + # this is an unknown entity or just a misplaced + # ampersand. + # + # The more common case is a misplaced ampersand, so I + # escape the ampersand and omit the trailing semicolon. + data = "&%s" % ref + if not data: + # This case is different from the one above, because we + # haven't already gone through a supposedly comprehensive + # mapping of entities to Unicode characters. We might not + # have gone through any mapping at all. So the chances are + # very high that this is a real entity, and not a + # misplaced ampersand. + data = "&%s;" % ref + self.handle_data(data) + + def handle_decl(self, data): + "Handle DOCTYPEs and the like as Declaration objects." + self._toStringSubclass(data, Declaration) + + def parse_declaration(self, i): + """Treat a bogus SGML declaration as raw data. Treat a CDATA + declaration as a CData object.""" + j = None + if self.rawdata[i:i+9] == '<![CDATA[': + k = self.rawdata.find(']]>', i) + if k == -1: + k = len(self.rawdata) + data = self.rawdata[i+9:k] + j = k+3 + self._toStringSubclass(data, CData) + else: + try: + j = HTMLParser.parse_declaration(self, i) + except HTMLParseError: + toHandle = self.rawdata[i:] + self.handle_data(toHandle) + j = i + len(toHandle) + return j + + +class BeautifulStoneSoup(Tag): + + """This class contains the basic parser and search code. It defines + a parser that knows nothing about tag behavior except for the + following: + + You can't close a tag without closing all the tags it encloses. + That is, "<foo><bar></foo>" actually means + "<foo><bar></bar></foo>". + + [Another possible explanation is "<foo><bar /></foo>", but since + this class defines no SELF_CLOSING_TAGS, it will never use that + explanation.] + + This class is useful for parsing XML or made-up markup languages, + or when BeautifulSoup makes an assumption counter to what you were + expecting.""" + + SELF_CLOSING_TAGS = {} + NESTABLE_TAGS = {} + RESET_NESTING_TAGS = {} + QUOTE_TAGS = {} + PRESERVE_WHITESPACE_TAGS = [] + + MARKUP_MASSAGE = [(re.compile('(<[^<>]*)/>'), + lambda x: x.group(1) + ' />'), + (re.compile('<!\s+([^<>]*)>'), + lambda x: '<!' + x.group(1) + '>') + ] + + ROOT_TAG_NAME = u'[document]' + + HTML_ENTITIES = "html" + XML_ENTITIES = "xml" + XHTML_ENTITIES = "xhtml" + # TODO: This only exists for backwards-compatibility + ALL_ENTITIES = XHTML_ENTITIES + + # Used when determining whether a text node is all whitespace and + # can be replaced with a single space. A text node that contains + # fancy Unicode spaces (usually non-breaking) should be left + # alone. + STRIP_ASCII_SPACES = { 9: None, 10: None, 12: None, 13: None, 32: None, } + + def __init__(self, markup="", parseOnlyThese=None, fromEncoding=None, + markupMassage=True, smartQuotesTo=XML_ENTITIES, + convertEntities=None, selfClosingTags=None, isHTML=False, + builder=HTMLParserBuilder): + """The Soup object is initialized as the 'root tag', and the + provided markup (which can be a string or a file-like object) + is fed into the underlying parser. + + HTMLParser will process most bad HTML, and the BeautifulSoup + class has some tricks for dealing with some HTML that kills + HTMLParser, but Beautiful Soup can nonetheless choke or lose data + if your data uses self-closing tags or declarations + incorrectly. + + By default, Beautiful Soup uses regexes to sanitize input, + avoiding the vast majority of these problems. If the problems + don't apply to you, pass in False for markupMassage, and + you'll get better performance. + + The default parser massage techniques fix the two most common + instances of invalid HTML that choke HTMLParser: + + <br/> (No space between name of closing tag and tag close) + <! --Comment--> (Extraneous whitespace in declaration) + + You can pass in a custom list of (RE object, replace method) + tuples to get Beautiful Soup to scrub your input the way you + want.""" + + self.parseOnlyThese = parseOnlyThese + self.fromEncoding = fromEncoding + self.smartQuotesTo = smartQuotesTo + self.convertEntities = convertEntities + # Set the rules for how we'll deal with the entities we + # encounter + if self.convertEntities: + # It doesn't make sense to convert encoded characters to + # entities even while you're converting entities to Unicode. + # Just convert it all to Unicode. + self.smartQuotesTo = None + if convertEntities == self.HTML_ENTITIES: + self.convertXMLEntities = False + self.convertHTMLEntities = True + self.escapeUnrecognizedEntities = True + elif convertEntities == self.XHTML_ENTITIES: + self.convertXMLEntities = True + self.convertHTMLEntities = True + self.escapeUnrecognizedEntities = False + elif convertEntities == self.XML_ENTITIES: + self.convertXMLEntities = True + self.convertHTMLEntities = False + self.escapeUnrecognizedEntities = False + else: + self.convertXMLEntities = False + self.convertHTMLEntities = False + self.escapeUnrecognizedEntities = False + + self.instanceSelfClosingTags = buildTagMap(None, selfClosingTags) + self.builder = builder(self) + self.reset() + + if hasattr(markup, 'read'): # It's a file-type object. + markup = markup.read() + self.markup = markup + self.markupMassage = markupMassage + try: + self._feed(isHTML=isHTML) + except StopParsing: + pass + self.markup = None # The markup can now be GCed. + self.builder = None # So can the builder. + + def _feed(self, inDocumentEncoding=None, isHTML=False): + # Convert the document to Unicode. + markup = self.markup + if isinstance(markup, unicode): + if not hasattr(self, 'originalEncoding'): + self.originalEncoding = None + else: + dammit = UnicodeDammit\ + (markup, [self.fromEncoding, inDocumentEncoding], + smartQuotesTo=self.smartQuotesTo, isHTML=isHTML) + markup = dammit.unicode + self.originalEncoding = dammit.originalEncoding + self.declaredHTMLEncoding = dammit.declaredHTMLEncoding + if markup: + if self.markupMassage: + if not isList(self.markupMassage): + self.markupMassage = self.MARKUP_MASSAGE + for fix, m in self.markupMassage: + markup = fix.sub(m, markup) + # TODO: We get rid of markupMassage so that the + # soup object can be deepcopied later on. Some + # Python installations can't copy regexes. If anyone + # was relying on the existence of markupMassage, this + # might cause problems. + del(self.markupMassage) + self.builder.reset() + + self.builder.feed(markup) + # Close out any unfinished strings and close all the open tags. + self.endData() + while self.currentTag.name != self.ROOT_TAG_NAME: + self.popTag() + + def isSelfClosingTag(self, name): + """Returns true iff the given string is the name of a + self-closing tag according to this parser.""" + return self.SELF_CLOSING_TAGS.has_key(name) \ + or self.instanceSelfClosingTags.has_key(name) + + def reset(self): + Tag.__init__(self, self, self.ROOT_TAG_NAME) + self.hidden = 1 + self.builder.reset() + self.currentData = [] + self.currentTag = None + self.tagStack = [] + self.quoteStack = [] + self.pushTag(self) + + def popTag(self): + tag = self.tagStack.pop() + # Tags with just one string-owning child get the child as a + # 'string' property, so that soup.tag.string is shorthand for + # soup.tag.contents[0] + if len(self.currentTag.contents) == 1 and \ + isinstance(self.currentTag.contents[0], NavigableString): + self.currentTag.string = self.currentTag.contents[0] + + #print "Pop", tag.name + if self.tagStack: + self.currentTag = self.tagStack[-1] + return self.currentTag + + def pushTag(self, tag): + #print "Push", tag.name + if self.currentTag: + self.currentTag.contents.append(tag) + self.tagStack.append(tag) + self.currentTag = self.tagStack[-1] + + def endData(self, containerClass=NavigableString): + if self.currentData: + currentData = u''.join(self.currentData) + if (currentData.translate(self.STRIP_ASCII_SPACES) == '' and + not set([tag.name for tag in self.tagStack]).intersection( + self.PRESERVE_WHITESPACE_TAGS)): + if '\n' in currentData: + currentData = '\n' + else: + currentData = ' ' + self.currentData = [] + if self.parseOnlyThese and len(self.tagStack) <= 1 and \ + (not self.parseOnlyThese.text or \ + not self.parseOnlyThese.search(currentData)): + return + o = containerClass(currentData) + o.setup(self.currentTag, self.previous) + if self.previous: + self.previous.next = o + self.previous = o + self.currentTag.contents.append(o) + + + def _popToTag(self, name, inclusivePop=True): + """Pops the tag stack up to and including the most recent + instance of the given tag. If inclusivePop is false, pops the tag + stack up to but *not* including the most recent instqance of + the given tag.""" + #print "Popping to %s" % name + if name == self.ROOT_TAG_NAME: + return + + numPops = 0 + mostRecentTag = None + for i in range(len(self.tagStack)-1, 0, -1): + if name == self.tagStack[i].name: + numPops = len(self.tagStack)-i + break + if not inclusivePop: + numPops = numPops - 1 + + for i in range(0, numPops): + mostRecentTag = self.popTag() + return mostRecentTag + + def _smartPop(self, name): + + """We need to pop up to the previous tag of this type, unless + one of this tag's nesting reset triggers comes between this + tag and the previous tag of this type, OR unless this tag is a + generic nesting trigger and another generic nesting trigger + comes between this tag and the previous tag of this type. + + Examples: + <p>Foo<b>Bar *<p>* should pop to 'p', not 'b'. + <p>Foo<table>Bar *<p>* should pop to 'table', not 'p'. + <p>Foo<table><tr>Bar *<p>* should pop to 'tr', not 'p'. + + <li><ul><li> *<li>* should pop to 'ul', not the first 'li'. + <tr><table><tr> *<tr>* should pop to 'table', not the first 'tr' + <td><tr><td> *<td>* should pop to 'tr', not the first 'td' + """ + + nestingResetTriggers = self.NESTABLE_TAGS.get(name) + isNestable = nestingResetTriggers != None + isResetNesting = self.RESET_NESTING_TAGS.has_key(name) + popTo = None + inclusive = True + for i in range(len(self.tagStack)-1, 0, -1): + p = self.tagStack[i] + if (not p or p.name == name) and not isNestable: + #Non-nestable tags get popped to the top or to their + #last occurance. + popTo = name + break + if (nestingResetTriggers != None + and p.name in nestingResetTriggers) \ + or (nestingResetTriggers == None and isResetNesting + and self.RESET_NESTING_TAGS.has_key(p.name)): + + #If we encounter one of the nesting reset triggers + #peculiar to this tag, or we encounter another tag + #that causes nesting to reset, pop up to but not + #including that tag. + popTo = p.name + inclusive = False + break + p = p.parent + if popTo: + self._popToTag(popTo, inclusive) + + def unknown_starttag(self, name, attrs, selfClosing=0): + #print "Start tag %s: %s" % (name, attrs) + if self.quoteStack: + #This is not a real tag. + #print "<%s> is not real!" % name + attrs = ''.join(map(lambda(x, y): ' %s="%s"' % (x, y), attrs)) + self.handle_data('<%s%s>' % (name, attrs)) + return + self.endData() + + if not self.isSelfClosingTag(name) and not selfClosing: + self._smartPop(name) + + if self.parseOnlyThese and len(self.tagStack) <= 1 \ + and (self.parseOnlyThese.text or not self.parseOnlyThese.searchTag(name, attrs)): + return + + tag = Tag(self, name, attrs, self.currentTag, self.previous) + if self.previous: + self.previous.next = tag + self.previous = tag + self.pushTag(tag) + if selfClosing or self.isSelfClosingTag(name): + self.popTag() + if name in self.QUOTE_TAGS: + #print "Beginning quote (%s)" % name + self.quoteStack.append(name) + self.literal = 1 + return tag + + def unknown_endtag(self, name): + #print "End tag %s" % name + if self.quoteStack and self.quoteStack[-1] != name: + #This is not a real end tag. + #print "</%s> is not real!" % name + self.handle_data('</%s>' % name) + return + self.endData() + self._popToTag(name) + if self.quoteStack and self.quoteStack[-1] == name: + self.quoteStack.pop() + self.literal = (len(self.quoteStack) > 0) + + def handle_data(self, data): + self.currentData.append(data) + + def extractCharsetFromMeta(self, attrs): + self.unknown_starttag('meta', attrs) + + +class BeautifulSoup(BeautifulStoneSoup): + + """This parser knows the following facts about HTML: + + * Some tags have no closing tag and should be interpreted as being + closed as soon as they are encountered. + + * The text inside some tags (ie. 'script') may contain tags which + are not really part of the document and which should be parsed + as text, not tags. If you want to parse the text as tags, you can + always fetch it and parse it explicitly. + + * Tag nesting rules: + + Most tags can't be nested at all. For instance, the occurance of + a <p> tag should implicitly close the previous <p> tag. + + <p>Para1<p>Para2 + should be transformed into: + <p>Para1</p><p>Para2 + + Some tags can be nested arbitrarily. For instance, the occurance + of a <blockquote> tag should _not_ implicitly close the previous + <blockquote> tag. + + Alice said: <blockquote>Bob said: <blockquote>Blah + should NOT be transformed into: + Alice said: <blockquote>Bob said: </blockquote><blockquote>Blah + + Some tags can be nested, but the nesting is reset by the + interposition of other tags. For instance, a <tr> tag should + implicitly close the previous <tr> tag within the same <table>, + but not close a <tr> tag in another table. + + <table><tr>Blah<tr>Blah + should be transformed into: + <table><tr>Blah</tr><tr>Blah + but, + <tr>Blah<table><tr>Blah + should NOT be transformed into + <tr>Blah<table></tr><tr>Blah + + Differing assumptions about tag nesting rules are a major source + of problems with the BeautifulSoup class. If BeautifulSoup is not + treating as nestable a tag your page author treats as nestable, + try ICantBelieveItsBeautifulSoup, MinimalSoup, or + BeautifulStoneSoup before writing your own subclass.""" + + def __init__(self, *args, **kwargs): + if not kwargs.has_key('smartQuotesTo'): + kwargs['smartQuotesTo'] = self.HTML_ENTITIES + kwargs['isHTML'] = True + BeautifulStoneSoup.__init__(self, *args, **kwargs) + + SELF_CLOSING_TAGS = buildTagMap(None, + ['br' , 'hr', 'input', 'img', 'meta', + 'spacer', 'link', 'frame', 'base']) + + PRESERVE_WHITESPACE_TAGS = set(['pre', 'textarea']) + + QUOTE_TAGS = {'script' : None, 'textarea' : None} + + #According to the HTML standard, each of these inline tags can + #contain another tag of the same type. Furthermore, it's common + #to actually use these tags this way. + NESTABLE_INLINE_TAGS = ['span', 'font', 'q', 'object', 'bdo', 'sub', 'sup', + 'center'] + + #According to the HTML standard, these block tags can contain + #another tag of the same type. Furthermore, it's common + #to actually use these tags this way. + NESTABLE_BLOCK_TAGS = ['blockquote', 'div', 'fieldset', 'ins', 'del'] + + #Lists can contain other lists, but there are restrictions. + NESTABLE_LIST_TAGS = { 'ol' : [], + 'ul' : [], + 'li' : ['ul', 'ol'], + 'dl' : [], + 'dd' : ['dl'], + 'dt' : ['dl'] } + + #Tables can contain other tables, but there are restrictions. + NESTABLE_TABLE_TAGS = {'table' : [], + 'tr' : ['table', 'tbody', 'tfoot', 'thead'], + 'td' : ['tr'], + 'th' : ['tr'], + 'thead' : ['table'], + 'tbody' : ['table'], + 'tfoot' : ['table'], + } + + NON_NESTABLE_BLOCK_TAGS = ['address', 'form', 'p', 'pre'] + + #If one of these tags is encountered, all tags up to the next tag of + #this type are popped. + RESET_NESTING_TAGS = buildTagMap(None, NESTABLE_BLOCK_TAGS, 'noscript', + NON_NESTABLE_BLOCK_TAGS, + NESTABLE_LIST_TAGS, + NESTABLE_TABLE_TAGS) + + NESTABLE_TAGS = buildTagMap([], NESTABLE_INLINE_TAGS, NESTABLE_BLOCK_TAGS, + NESTABLE_LIST_TAGS, NESTABLE_TABLE_TAGS) + + # Used to detect the charset in a META tag; see start_meta + CHARSET_RE = re.compile("((^|;)\s*charset=)([^;]*)", re.M) + + def extractCharsetFromMeta(self, attrs): + """Beautiful Soup can detect a charset included in a META tag, + try to convert the document to that charset, and re-parse the + document from the beginning.""" + httpEquiv = None + contentType = None + contentTypeIndex = None + tagNeedsEncodingSubstitution = False + + for i in range(0, len(attrs)): + key, value = attrs[i] + key = key.lower() + if key == 'http-equiv': + httpEquiv = value + elif key == 'content': + contentType = value + contentTypeIndex = i + + if httpEquiv and contentType: # It's an interesting meta tag. + match = self.CHARSET_RE.search(contentType) + if match: + if (self.declaredHTMLEncoding is not None or + self.originalEncoding == self.fromEncoding): + # An HTML encoding was sniffed while converting + # the document to Unicode, or an HTML encoding was + # sniffed during a previous pass through the + # document, or an encoding was specified + # explicitly and it worked. Rewrite the meta tag. + def rewrite(match): + return match.group(1) + "%SOUP-ENCODING%" + newAttr = self.CHARSET_RE.sub(rewrite, contentType) + attrs[contentTypeIndex] = (attrs[contentTypeIndex][0], + newAttr) + tagNeedsEncodingSubstitution = True + else: + # This is our first pass through the document. + # Go through it again with the encoding information. + newCharset = match.group(3) + if newCharset and newCharset != self.originalEncoding: + self.declaredHTMLEncoding = newCharset + self._feed(self.declaredHTMLEncoding) + raise StopParsing + pass + tag = self.unknown_starttag("meta", attrs) + if tag and tagNeedsEncodingSubstitution: + tag.containsSubstitutions = True + + +class StopParsing(Exception): + pass + +class ICantBelieveItsBeautifulSoup(BeautifulSoup): + + """The BeautifulSoup class is oriented towards skipping over + common HTML errors like unclosed tags. However, sometimes it makes + errors of its own. For instance, consider this fragment: + + <b>Foo<b>Bar</b></b> + + This is perfectly valid (if bizarre) HTML. However, the + BeautifulSoup class will implicitly close the first b tag when it + encounters the second 'b'. It will think the author wrote + "<b>Foo<b>Bar", and didn't close the first 'b' tag, because + there's no real-world reason to bold something that's already + bold. When it encounters '</b></b>' it will close two more 'b' + tags, for a grand total of three tags closed instead of two. This + can throw off the rest of your document structure. The same is + true of a number of other tags, listed below. + + It's much more common for someone to forget to close a 'b' tag + than to actually use nested 'b' tags, and the BeautifulSoup class + handles the common case. This class handles the not-co-common + case: where you can't believe someone wrote what they did, but + it's valid HTML and BeautifulSoup screwed up by assuming it + wouldn't be.""" + + I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS = \ + ['em', 'big', 'i', 'small', 'tt', 'abbr', 'acronym', 'strong', + 'cite', 'code', 'dfn', 'kbd', 'samp', 'strong', 'var', 'b', + 'big'] + + I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS = ['noscript'] + + NESTABLE_TAGS = buildTagMap([], BeautifulSoup.NESTABLE_TAGS, + I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS, + I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS) + +class MinimalSoup(BeautifulSoup): + """The MinimalSoup class is for parsing HTML that contains + pathologically bad markup. It makes no assumptions about tag + nesting, but it does know which tags are self-closing, that + <script> tags contain Javascript and should not be parsed, that + META tags may contain encoding information, and so on. + + This also makes it better for subclassing than BeautifulStoneSoup + or BeautifulSoup.""" + + RESET_NESTING_TAGS = buildTagMap('noscript') + NESTABLE_TAGS = {} + +class BeautifulSOAP(BeautifulStoneSoup): + """This class will push a tag with only a single string child into + the tag's parent as an attribute. The attribute's name is the tag + name, and the value is the string child. An example should give + the flavor of the change: + + <foo><bar>baz</bar></foo> + => + <foo bar="baz"><bar>baz</bar></foo> + + You can then access fooTag['bar'] instead of fooTag.barTag.string. + + This is, of course, useful for scraping structures that tend to + use subelements instead of attributes, such as SOAP messages. Note + that it modifies its input, so don't print the modified version + out. + + I'm not sure how many people really want to use this class; let me + know if you do. Mainly I like the name.""" + + def popTag(self): + if len(self.tagStack) > 1: + tag = self.tagStack[-1] + parent = self.tagStack[-2] + parent._getAttrMap() + if (isinstance(tag, Tag) and len(tag.contents) == 1 and + isinstance(tag.contents[0], NavigableString) and + not parent.attrMap.has_key(tag.name)): + parent[tag.name] = tag.contents[0] + BeautifulStoneSoup.popTag(self) + +#Enterprise class names! It has come to our attention that some people +#think the names of the Beautiful Soup parser classes are too silly +#and "unprofessional" for use in enterprise screen-scraping. We feel +#your pain! For such-minded folk, the Beautiful Soup Consortium And +#All-Night Kosher Bakery recommends renaming this file to +#"RobustParser.py" (or, in cases of extreme enterprisiness, +#"RobustParserBeanInterface.class") and using the following +#enterprise-friendly class aliases: +class RobustXMLParser(BeautifulStoneSoup): + pass +class RobustHTMLParser(BeautifulSoup): + pass +class RobustWackAssHTMLParser(ICantBelieveItsBeautifulSoup): + pass +class RobustInsanelyWackAssHTMLParser(MinimalSoup): + pass +class SimplifyingSOAPParser(BeautifulSOAP): + pass + +###################################################### +# +# Bonus library: Unicode, Dammit +# +# This class forces XML data into a standard format (usually to UTF-8 +# or Unicode). It is heavily based on code from Mark Pilgrim's +# Universal Feed Parser. It does not rewrite the XML or HTML to +# reflect a new encoding: that happens in BeautifulStoneSoup.handle_pi +# (XML) and BeautifulSoup.start_meta (HTML). + +# Autodetects character encodings. +# Download from http://chardet.feedparser.org/ +try: + import chardet +# import chardet.constants +# chardet.constants._debug = 1 +except ImportError: + chardet = None + +# cjkcodecs and iconv_codec make Python know about more character encodings. +# Both are available from http://cjkpython.i18n.org/ +# They're built in if you use Python 2.4. +try: + import cjkcodecs.aliases +except ImportError: + pass +try: + import iconv_codec +except ImportError: + pass + +class UnicodeDammit: + """A class for detecting the encoding of a *ML document and + converting it to a Unicode string. If the source encoding is + windows-1252, can replace MS smart quotes with their HTML or XML + equivalents.""" + + # This dictionary maps commonly seen values for "charset" in HTML + # meta tags to the corresponding Python codec names. It only covers + # values that aren't in Python's aliases and can't be determined + # by the heuristics in find_codec. + CHARSET_ALIASES = { "macintosh" : "mac-roman", + "x-sjis" : "shift-jis" } + + def __init__(self, markup, overrideEncodings=[], + smartQuotesTo='xml', isHTML=False): + self.declaredHTMLEncoding = None + self.markup, documentEncoding, sniffedEncoding = \ + self._detectEncoding(markup, isHTML) + self.smartQuotesTo = smartQuotesTo + self.triedEncodings = [] + if markup == '' or isinstance(markup, unicode): + self.originalEncoding = None + self.unicode = unicode(markup) + return + + u = None + for proposedEncoding in overrideEncodings: + u = self._convertFrom(proposedEncoding) + if u: break + if not u: + for proposedEncoding in (documentEncoding, sniffedEncoding): + u = self._convertFrom(proposedEncoding) + if u: break + + # If no luck and we have auto-detection library, try that: + if not u and chardet and not isinstance(self.markup, unicode): + u = self._convertFrom(chardet.detect(self.markup)['encoding']) + + # As a last resort, try utf-8 and windows-1252: + if not u: + for proposed_encoding in ("utf-8", "windows-1252"): + u = self._convertFrom(proposed_encoding) + if u: break + + self.unicode = u + if not u: self.originalEncoding = None + + def _subMSChar(self, match): + """Changes a MS smart quote character to an XML or HTML + entity.""" + orig = match.group(1) + sub = self.MS_CHARS.get(orig) + if type(sub) == types.TupleType: + if self.smartQuotesTo == 'xml': + sub = '&#x'.encode() + sub[1].encode() + ';'.encode() + else: + sub = '&'.encode() + sub[0].encode() + ';'.encode() + else: + sub = sub.encode() + return sub + + def _convertFrom(self, proposed): + proposed = self.find_codec(proposed) + if not proposed or proposed in self.triedEncodings: + return None + self.triedEncodings.append(proposed) + markup = self.markup + + # Convert smart quotes to HTML if coming from an encoding + # that might have them. + if self.smartQuotesTo and proposed.lower() in("windows-1252", + "iso-8859-1", + "iso-8859-2"): + smart_quotes_re = "([\x80-\x9f])" + smart_quotes_compiled = re.compile(smart_quotes_re) + markup = smart_quotes_compiled.sub(self._subMSChar, markup) + + try: + # print "Trying to convert document to %s" % proposed + u = self._toUnicode(markup, proposed) + self.markup = u + self.originalEncoding = proposed + except Exception, e: + # print "That didn't work!" + # print e + return None + #print "Correct encoding: %s" % proposed + return self.markup + + def _toUnicode(self, data, encoding): + '''Given a string and its encoding, decodes the string into Unicode. + %encoding is a string recognized by encodings.aliases''' + + # strip Byte Order Mark (if present) + if (len(data) >= 4) and (data[:2] == '\xfe\xff') \ + and (data[2:4] != '\x00\x00'): + encoding = 'utf-16be' + data = data[2:] + elif (len(data) >= 4) and (data[:2] == '\xff\xfe') \ + and (data[2:4] != '\x00\x00'): + encoding = 'utf-16le' + data = data[2:] + elif data[:3] == '\xef\xbb\xbf': + encoding = 'utf-8' + data = data[3:] + elif data[:4] == '\x00\x00\xfe\xff': + encoding = 'utf-32be' + data = data[4:] + elif data[:4] == '\xff\xfe\x00\x00': + encoding = 'utf-32le' + data = data[4:] + newdata = unicode(data, encoding) + return newdata + + def _detectEncoding(self, xml_data, isHTML=False): + """Given a document, tries to detect its XML encoding.""" + xml_encoding = sniffed_xml_encoding = None + try: + if xml_data[:4] == '\x4c\x6f\xa7\x94': + # EBCDIC + xml_data = self._ebcdic_to_ascii(xml_data) + elif xml_data[:4] == '\x00\x3c\x00\x3f': + # UTF-16BE + sniffed_xml_encoding = 'utf-16be' + xml_data = unicode(xml_data, 'utf-16be').encode('utf-8') + elif (len(xml_data) >= 4) and (xml_data[:2] == '\xfe\xff') \ + and (xml_data[2:4] != '\x00\x00'): + # UTF-16BE with BOM + sniffed_xml_encoding = 'utf-16be' + xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8') + elif xml_data[:4] == '\x3c\x00\x3f\x00': + # UTF-16LE + sniffed_xml_encoding = 'utf-16le' + xml_data = unicode(xml_data, 'utf-16le').encode('utf-8') + elif (len(xml_data) >= 4) and (xml_data[:2] == '\xff\xfe') and \ + (xml_data[2:4] != '\x00\x00'): + # UTF-16LE with BOM + sniffed_xml_encoding = 'utf-16le' + xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8') + elif xml_data[:4] == '\x00\x00\x00\x3c': + # UTF-32BE + sniffed_xml_encoding = 'utf-32be' + xml_data = unicode(xml_data, 'utf-32be').encode('utf-8') + elif xml_data[:4] == '\x3c\x00\x00\x00': + # UTF-32LE + sniffed_xml_encoding = 'utf-32le' + xml_data = unicode(xml_data, 'utf-32le').encode('utf-8') + elif xml_data[:4] == '\x00\x00\xfe\xff': + # UTF-32BE with BOM + sniffed_xml_encoding = 'utf-32be' + xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8') + elif xml_data[:4] == '\xff\xfe\x00\x00': + # UTF-32LE with BOM + sniffed_xml_encoding = 'utf-32le' + xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8') + elif xml_data[:3] == '\xef\xbb\xbf': + # UTF-8 with BOM + sniffed_xml_encoding = 'utf-8' + xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8') + else: + sniffed_xml_encoding = 'ascii' + pass + except: + xml_encoding_match = None + xml_encoding_re = '^<\?.*encoding=[\'"](.*?)[\'"].*\?>'.encode() + xml_encoding_match = re.compile(xml_encoding_re).match(xml_data) + if not xml_encoding_match and isHTML: + meta_re = '<\s*meta[^>]+charset=([^>]*?)[;\'">]'.encode() + regexp = re.compile(meta_re, re.I) + xml_encoding_match = regexp.search(xml_data) + if xml_encoding_match is not None: + xml_encoding = xml_encoding_match.groups()[0].decode( + 'ascii').lower() + if isHTML: + self.declaredHTMLEncoding = xml_encoding + if sniffed_xml_encoding and \ + (xml_encoding in ('iso-10646-ucs-2', 'ucs-2', 'csunicode', + 'iso-10646-ucs-4', 'ucs-4', 'csucs4', + 'utf-16', 'utf-32', 'utf_16', 'utf_32', + 'utf16', 'u16')): + xml_encoding = sniffed_xml_encoding + return xml_data, xml_encoding, sniffed_xml_encoding + + + def find_codec(self, charset): + return self._codec(self.CHARSET_ALIASES.get(charset, charset)) \ + or (charset and self._codec(charset.replace("-", ""))) \ + or (charset and self._codec(charset.replace("-", "_"))) \ + or charset + + def _codec(self, charset): + if not charset: return charset + codec = None + try: + codecs.lookup(charset) + codec = charset + except (LookupError, ValueError): + pass + return codec + + EBCDIC_TO_ASCII_MAP = None + def _ebcdic_to_ascii(self, s): + c = self.__class__ + if not c.EBCDIC_TO_ASCII_MAP: + emap = (0,1,2,3,156,9,134,127,151,141,142,11,12,13,14,15, + 16,17,18,19,157,133,8,135,24,25,146,143,28,29,30,31, + 128,129,130,131,132,10,23,27,136,137,138,139,140,5,6,7, + 144,145,22,147,148,149,150,4,152,153,154,155,20,21,158,26, + 32,160,161,162,163,164,165,166,167,168,91,46,60,40,43,33, + 38,169,170,171,172,173,174,175,176,177,93,36,42,41,59,94, + 45,47,178,179,180,181,182,183,184,185,124,44,37,95,62,63, + 186,187,188,189,190,191,192,193,194,96,58,35,64,39,61,34, + 195,97,98,99,100,101,102,103,104,105,196,197,198,199,200, + 201,202,106,107,108,109,110,111,112,113,114,203,204,205, + 206,207,208,209,126,115,116,117,118,119,120,121,122,210, + 211,212,213,214,215,216,217,218,219,220,221,222,223,224, + 225,226,227,228,229,230,231,123,65,66,67,68,69,70,71,72, + 73,232,233,234,235,236,237,125,74,75,76,77,78,79,80,81, + 82,238,239,240,241,242,243,92,159,83,84,85,86,87,88,89, + 90,244,245,246,247,248,249,48,49,50,51,52,53,54,55,56,57, + 250,251,252,253,254,255) + import string + c.EBCDIC_TO_ASCII_MAP = string.maketrans( \ + ''.join(map(chr, range(256))), ''.join(map(chr, emap))) + return s.translate(c.EBCDIC_TO_ASCII_MAP) + + MS_CHARS = { '\x80' : ('euro', '20AC'), + '\x81' : ' ', + '\x82' : ('sbquo', '201A'), + '\x83' : ('fnof', '192'), + '\x84' : ('bdquo', '201E'), + '\x85' : ('hellip', '2026'), + '\x86' : ('dagger', '2020'), + '\x87' : ('Dagger', '2021'), + '\x88' : ('circ', '2C6'), + '\x89' : ('permil', '2030'), + '\x8A' : ('Scaron', '160'), + '\x8B' : ('lsaquo', '2039'), + '\x8C' : ('OElig', '152'), + '\x8D' : '?', + '\x8E' : ('#x17D', '17D'), + '\x8F' : '?', + '\x90' : '?', + '\x91' : ('lsquo', '2018'), + '\x92' : ('rsquo', '2019'), + '\x93' : ('ldquo', '201C'), + '\x94' : ('rdquo', '201D'), + '\x95' : ('bull', '2022'), + '\x96' : ('ndash', '2013'), + '\x97' : ('mdash', '2014'), + '\x98' : ('tilde', '2DC'), + '\x99' : ('trade', '2122'), + '\x9a' : ('scaron', '161'), + '\x9b' : ('rsaquo', '203A'), + '\x9c' : ('oelig', '153'), + '\x9d' : '?', + '\x9e' : ('#x17E', '17E'), + '\x9f' : ('Yuml', ''),} + +####################################################################### + + +#By default, act as an HTML pretty-printer. +if __name__ == '__main__': + import sys + soup = BeautifulSoup(sys.stdin) + print soup.prettify() diff --git a/module/CaptchaManager.py b/module/CaptchaManager.py new file mode 100644 index 000000000..9fbff92a1 --- /dev/null +++ b/module/CaptchaManager.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- + +""" + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, + or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, see <http://www.gnu.org/licenses/>. + + @author: mkaay +""" + +from uuid import uuid4 as uuid +from threading import Lock + +class CaptchaManager(): + def __init__(self, core): + self.lock = Lock() + self.core = core + self.tasks = [] + + def newTask(self, plugin): + task = CaptchaTask(plugin, self) + self.lock.acquire() + self.tasks.append(task) + self.lock.release() + return task + + def removeTask(self, task): + self.lock.acquire() + self.tasks.remove(task) + self.lock.release() + + def getTask(self): + self.lock.acquire() + for task in self.tasks: + if task.getStatus() == "waiting": + self.lock.release() + return task + self.lock.release() + return None + + def getTaskFromID(self, tid): + self.lock.acquire() + for task in self.tasks: + if task.getID() == tid: + self.lock.release() + return task + self.lock.release() + return None + +class CaptchaTask(): + def __init__(self, plugin, manager): + self.lock = Lock() + self.plugin = plugin + self.manager = manager + self.captchaImg = None + self.captchaType = None + self.result = None + self.status = "preparing" + self.id = uuid().hex + + def setCaptcha(self, img, imgType): + self.lock.acquire() + self.captchaImg = img + self.captchaType = imgType + self.lock.release() + + def getCaptcha(self): + return self.captchaImg, self.captchaType + + def setResult(self, result): + self.lock.acquire() + self.result = result + self.lock.release() + + def getResult(self): + return self.result + + def getID(self): + return self.id + + def getStatus(self): + return self.status + + def setDone(self): + self.lock.acquire() + self.status = "done" + self.lock.release() + + def setWaiting(self): + self.lock.acquire() + self.status = "waiting" + self.lock.release() + + def setWatingForUser(self): + self.lock.acquire() + self.status = "user" + self.lock.release() + + def removeTask(self): + self.manager.removeTask(self) + + def __str__(self): + return "<CaptchaTask '%s'>" % (self.getID(),) diff --git a/module/HookManager.py b/module/HookManager.py new file mode 100644 index 000000000..a283a7349 --- /dev/null +++ b/module/HookManager.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- + +""" + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, + or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, see <http://www.gnu.org/licenses/>. + + @author: mkaay + @interface-version: 0.1 +""" +from glob import glob +import logging +from os.path import basename +from os.path import join +from threading import Lock + +from module.XMLConfigParser import XMLConfigParser + +class HookManager(): + def __init__(self, core): + self.core = core + self.configParser = XMLConfigParser(join("module", "config", "plugin.xml")) + self.configParser.loadData() + self.config = self.configParser.getConfig() + self.logger = logging.getLogger("log") + self.plugins = [] + self.lock = Lock() + self.createIndex() + + def createIndex(self): + self.lock.acquire() + + pluginFiles = glob(join(self.core.plugin_folder, "hooks", "*.py")) + plugins = [] + for pluginFile in pluginFiles: + pluginName = basename(pluginFile).replace(".py", "") + if pluginName == "__init__": + continue + if pluginName in self.config.keys(): + if not self.config[pluginName]["activated"]: + self.logger.info("Deactivated %s" % pluginName) + continue + else: + self.configParser.set(pluginName, {"option": "activated", "type": "bool", "name": "Activated"}, True) + module = __import__("module.plugins.hooks." + pluginName, globals(), locals(), [pluginName], -1) + pluginClass = getattr(module, pluginName) + plugin = pluginClass(self.core) + plugin.readConfig() + plugins.append(plugin) + self.logger.info("Activated %s" % pluginName) + + self.plugins = plugins + self.lock.release() + + def downloadStarts(self, pyfile): + self.lock.acquire() + + for plugin in self.plugins: + plugin.downloadStarts(pyfile) + self.lock.release() + + def downloadFinished(self, pyfile): + self.lock.acquire() + + for plugin in self.plugins: + plugin.downloadFinished(pyfile) + self.lock.release() + + def packageFinished(self, pyfile, package): + raise NotImplementedError + + def beforeReconnecting(self, ip): + self.lock.acquire() + + for plugin in self.plugins: + plugin.beforeReconnecting(ip) + self.lock.release() + + def afterReconnecting(self, ip): + self.lock.acquire() + + for plugin in self.plugins: + plugin.afterReconnecting(ip) + self.lock.release() diff --git a/module/Plugin.py b/module/Plugin.py index 7b726c3ac..5006da8dd 100644 --- a/module/Plugin.py +++ b/module/Plugin.py @@ -1,36 +1,40 @@ -#!/usr/bin/env python # -*- coding: utf-8 -*- -# -#Copyright (C) 2009 kingzero, RaNaN -# -#This program is free software; you can redistribute it and/or modify -#it under the terms of the GNU General Public License as published by -#the Free Software Foundation; either version 3 of the License, -#or (at your option) any later version. -# -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#See the GNU General Public License for more details. -# -#You should have received a copy of the GNU General Public License -# along with this program; if not, see <http://www.gnu.org/licenses/>. -# -### -import ConfigParser + +""" + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, + or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, see <http://www.gnu.org/licenses/>. + + @author: RaNaN, spoob, mkaay +""" + import logging import re +from os.path import exists + +from time import sleep from module.network.Request import Request +from module.download_thread import CaptchaError + class Plugin(): def __init__(self, parent): - self.parser = ConfigParser.SafeConfigParser() + self.configparser = parent.core.parser_plugins self.config = {} props = {} props['name'] = "BasePlugin" - props['version'] = "0.2" + props['version'] = "0.3" props['pattern'] = None props['type'] = "hoster" props['description'] = """Base Plugin""" @@ -45,6 +49,7 @@ class Plugin(): self.multi_dl = True self.ocr = None #captcha reader instance self.logger = logging.getLogger("log") + self.decryptNow = True def prepare(self, thread): pyfile = self.parent @@ -54,7 +59,7 @@ class Plugin(): pyfile.status.exists = self.file_exists() if not pyfile.status.exists: - raise Exception, "The file was not found on the server." + raise Exception, "File not found" return False pyfile.status.filename = self.get_file_name() @@ -75,12 +80,19 @@ class Plugin(): def download_html(self): """ gets the url from self.parent.url saves html in self.html and parses """ - html = "" - self.html = html + self.html = "" def file_exists(self): """ returns True or False """ + if re.search(r"(?!http://).*\.(dlc|ccf|rsdf|txt)", self.parent.url): + return exists(self.parent.url) + header = self.req.load(self.parent.url, just_header=True) + try: + if re.search(r"HTTP/1.1 404 Not Found", header): + return False + except: + pass return True def get_file_url(self): @@ -89,33 +101,36 @@ class Plugin(): return self.parent.url def get_file_name(self): - return re.findall("([^\/=]+)", self.parent.url)[-1] + try: + return re.findall("([^\/=]+)", self.parent.url)[-1] + except: + return self.parent.url[:20] def wait_until(self): if self.html != None: self.download_html() return self.time_plus_wait - def proceed(self, url, location, folder=""): - self.req.download(url, location, folder) + def proceed(self, url, location): + self.req.download(url, location) def set_config(self): - pass + for k, v in self.config: + self.configparser.set(self.props['name'], k, v) def get_config(self, value): - self.parser.read("pluginconfig") - return self.parser.get(self.props['name'], value) + self.configparser.loadData() + return self.configparser.get(self.props['name'], value) def read_config(self): - self.parser.read("pluginconfig") - - if self.parser.has_section(self.props['name']): - for option in self.parser.options(self.props['name']): - self.config[option] = self.parser.get(self.props['name'], option, raw=True) - self.config[option] = False if self.config[option].lower() == 'false' else self.config[option] + self.configparser.loadData() + try: + self.config = self.configparser.getConfig()[self.props['name']] + except: + pass def init_ocr(self): - modul = __import__("module.captcha." + self.props['name'], fromlist=['captcha']) + modul = __import__("module.plugins.captcha." + self.props['name'], fromlist=['captcha']) captchaClass = getattr(modul, self.props['name']) self.ocr = captchaClass() @@ -132,3 +147,17 @@ class Plugin(): 20 - unknown error """ return (True, 10) + + def waitForCaptcha(self, captchaData, imgType): + captchaManager = self.parent.core.captchaManager + task = captchaManager.newTask(self) + task.setCaptcha(captchaData, imgType) + task.setWaiting() + while not task.getStatus() == "done": + if not self.parent.core.isGUIConnected(): + task.removeTask() + raise CaptchaError + sleep(1) + result = task.getResult() + task.removeTask() + return result diff --git a/module/Unzip.py b/module/Unzip.py new file mode 100644 index 000000000..f56fbe751 --- /dev/null +++ b/module/Unzip.py @@ -0,0 +1,50 @@ +import zipfile +import os + +class Unzip: + def __init__(self): + pass + + def extract(self, file, dir): + if not dir.endswith(':') and not os.path.exists(dir): + os.mkdir(dir) + + zf = zipfile.ZipFile(file) + + # create directory structure to house files + self._createstructure(file, dir) + + # extract files to directory structure + for i, name in enumerate(zf.namelist()): + + if not name.endswith('/') and not name.endswith("config"): + print "extracting", name.replace("pyload/","") + outfile = open(os.path.join(dir, name.replace("pyload/","")), 'wb') + outfile.write(zf.read(name)) + outfile.flush() + outfile.close() + + def _createstructure(self, file, dir): + self._makedirs(self._listdirs(file), dir) + + def _makedirs(self, directories, basedir): + """ Create any directories that don't currently exist """ + for dir in directories: + curdir = os.path.join(basedir, dir) + if not os.path.exists(curdir): + os.mkdir(curdir) + + def _listdirs(self, file): + """ Grabs all the directories in the zip structure + This is necessary to create the structure before trying + to extract the file to it. """ + zf = zipfile.ZipFile(file) + + dirs = [] + + for name in zf.namelist(): + if name.endswith('/'): + dirs.append(name.replace("pyload/","")) + + dirs.sort() + return dirs diff --git a/module/XMLConfigParser.py b/module/XMLConfigParser.py new file mode 100644 index 000000000..678338b41 --- /dev/null +++ b/module/XMLConfigParser.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +""" + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, + or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, see <http://www.gnu.org/licenses/>. + + @author: mkaay, spoob +""" +from __future__ import with_statement + +from os.path import exists + +from xml.dom.minidom import parse + +from shutil import copy + +class XMLConfigParser(): + def __init__(self, data): + self.xml = None + self.version = "0.1" + self.file = data + self.file_default = self.file.replace(".xml", "_default.xml") + self.config = {} + self.data = {} + self.types = {} + self.loadData() + self.root = None + + def loadData(self): + file = self.file + if not exists(self.file): + self._copyConfig() + with open(file, 'r') as fh: + self.xml = parse(fh) + if not self.xml.documentElement.getAttribute("version") == self.version: + self._copyConfig() + with open(file, 'r') as fh: + self.xml = parse(fh) + if not self.xml.documentElement.getAttribute("version") == self.version: + print "Cant Update %s" % self.file + exit() #ok? + self.root = self.xml.documentElement + self._read_config() + + def _copyConfig(self): + try: + copy(self.file_default, self.file) + except: + print "%s not found" % self.file_default + exit() #ok? + + def saveData(self): + with open(self.file, 'w') as fh: + self.xml.writexml(fh) + + def _read_config(self): + def format(val): + if val.lower() == "true": + return True + elif val.lower() == "false": + return False + else: + return val + root = self.xml.documentElement + self.root = root + config = {} + data = {} + for node in root.childNodes: + if node.nodeType == node.ELEMENT_NODE: + section = node.tagName + config[section] = {} + data[section] = {} + data[section]["options"] = {} + data[section]["name"] = node.getAttribute("name") + for opt in node.childNodes: + if opt.nodeType == opt.ELEMENT_NODE: + data[section]["options"][opt.tagName] = {} + try: + config[section][opt.tagName] = format(opt.firstChild.data) + data[section]["options"][opt.tagName]["value"] = format(opt.firstChild.data) + except: + config[section][opt.tagName] = "" + data[section]["options"][opt.tagName]["name"] = opt.getAttribute("name") + data[section]["options"][opt.tagName]["type"] = opt.getAttribute("type") + data[section]["options"][opt.tagName]["input"] = opt.getAttribute("input") + self.config = config + self.data = data + + def get(self, section, option, default=None): + try: + return self.config[section][option] + except: + return default + + def getConfig(self): + return self.config + + def set(self, section, data, value): + root = self.root + replace = False + sectionNode = False + for node in root.childNodes: + if node.nodeType == node.ELEMENT_NODE: + if section == node.tagName: + sectionNode = node + for opt in node.childNodes: + if opt.nodeType == opt.ELEMENT_NODE: + if data["option"] == opt.tagName: + replace = opt + text = self.xml.createTextNode(str(value)) + if replace: + replace.replaceChild(text, replace.firstChild) + else: + newNode = self.xml.createElement(data["option"]) + newNode.appendChild(text) + if sectionNode: + sectionNode.appendChild(newNode) + else: + newSection = self.xml.createElement(section) + newSection.appendChild(newNode) + root.appendChild(newSection) + self._setAttributes(section, data) + self.saveData() + self.loadData() + + def _setAttributes(self, node, data): + option = self.root.getElementsByTagName(node)[0].getElementsByTagName(data["option"])[0] + option.setAttribute("name", data["name"]) + option.setAttribute("type", data["type"]) + try: + option.setAttribute("input", data["input"]) + except: + pass + + def getType(self, section, option): + try: + return self.data[section]["options"][option]["type"] + except: + return "str" + + def getInputValues(self, section, option): + try: + return self.data[section]["options"][option]["input"].split(";") + except: + return [] + + def getDisplayName(self, section, option=None): + try: + if option: + return self.data[section]["options"][option]["name"] + else: + return self.data[section]["name"] + except: + if option: + return option + else: + return section diff --git a/module/config/core_default.xml b/module/config/core_default.xml new file mode 100644 index 000000000..0d684890a --- /dev/null +++ b/module/config/core_default.xml @@ -0,0 +1,61 @@ +<?xml version="1.0" ?> +<config name="Configuration" version="0.1"> + <remote name="Remote"> + <port type="int" name="Port">7227</port> + <listenaddr type="ip" name="Adress">0.0.0.0</listenaddr> + <username type="str" name="Username">admin</username> + <password type="str" name="Password">pwhere</password> + </remote> + <ssl name="SSL"> + <activated type="bool" name="Activated">False</activated> + <cert type="str" name="Remote Port">ssl.srt</cert> + <key type="str" name="Remote Port">ssl.key</key> + </ssl> + <webinterface name="Webinterface"> + <activated type="bool" name="Activated">True</activated> + <host type="ip" name="IP">0.0.0.0</host> + <port type="int" name="Port">8001</port> + <template type="str" name="Template">default</template> + <local type="bool" name="Local">True</local> + <ssl type="bool" name="SSL">False</ssl> + <username type="str" name="Username">None</username> + <adress type="ip" name="Adress">None</adress> + <extport type="int" name="Extern Port">None</extport> + <pw type="str" name="Password">None</pw> + </webinterface> + <log name="Log"> + <file_log type="bool" name="File Log">True</file_log> + <log_folder type="str" name="Folder">Logs</log_folder> + <log_count type="int" name="Count">5</log_count> + </log> + <general name="General"> + <language type="str" input="en;de;fr" name="Language">de</language> + <download_folder type="str" name="Download Folder">Downloads</download_folder> + <max_downloads type="int" name="Max Parallel Downloads">3</max_downloads> + <link_file type="str" name="File For Links">links.txt</link_file> + <failed_file type="str" name="File For Failed Links">failed_links.txt</failed_file> + <debug_mode type="bool" name="Debug Mode">False</debug_mode> + <max_download_time type="int" name="Max Download Time">5</max_download_time> + <download_speed_limit type="int" name="Download Speed Limit">0</download_speed_limit> + <checksum type="bool" name="Use Checksum">True</checksum> + </general> + <updates name="Updates"> + <search_updates type="bool" name="Search">True</search_updates> + <install_updates type="bool" name="Install">False</install_updates> + </updates> + <reconnect name="Reconnect"> + <activated type="bool" name="Use Reconnect">False</activated> + <method type="str" name="Method">None</method> + <startTime type="time" name="Start">0:00</startTime> + <endTime type="time" name="End">0:00</endTime> + </reconnect> + <downloadTime name="Download Time"> + <start type="time" name="Start">0:00</start> + <end type="time" name="End">0:00</end> + </downloadTime> + <proxy name="Proxy"> + <activated type="bool" name="Activated">False</activated> + <adress type="str" name="Adress">http://localhost:8080</adress> + <protocol type="str" name="Protocol">http</protocol> + </proxy> +</config> diff --git a/module/config/gui_default.xml b/module/config/gui_default.xml new file mode 100644 index 000000000..490af199e --- /dev/null +++ b/module/config/gui_default.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" ?> +<root> + <connections> + <connection default="True" type="local" id="33965310e19b4a869112c43b39a16440"> + <name>Local</name> + </connection> + </connections> + <mainWindow> + <state></state> + <geometry></geometry> + </mainWindow> +</root> diff --git a/module/config/plugin_default.xml b/module/config/plugin_default.xml new file mode 100644 index 000000000..43c220516 --- /dev/null +++ b/module/config/plugin_default.xml @@ -0,0 +1,35 @@ +<?xml version="1.0" ?> +<config name="Configuration" version="0.1"> + <RapidshareCom> + <server input=";Cogent;Deutsche Telekom;Level(3);Level(3) #2;GlobalCrossing;Level(3) #3;Teleglobe;GlobalCrossing #2;TeliaSonera #2;Teleglobe #2;TeliaSonera #3;TeliaSonera"></server> + <premium>False</premium> + <username></username> + <password></password> + </RapidshareCom> + <NetloadIn> + <premium>False</premium> + <username></username> + <password></password> + </NetloadIn> + <UploadedTo> + <premium>False</premium> + <username></username> + <password></password> + </UploadedTo> + <ShareonlineBiz> + <premium>False</premium> + <username></username> + <password></password> + </ShareonlineBiz> + <YoutubeCom> + <high_quality>True</high_quality> + </YoutubeCom> + <YoutubeChannel> + <!-- False for no limitation --> + <max_videos>False</max_videos> + <video_groups name="Video Groups" type="str" input="uploads;favorites">uploads,favorites</video_groups> + </YoutubeChannel> + <SerienjunkiesOrg> + <preferredHoster>RapidshareCom,UploadedTo,NetloadIn,FilefactoryCom</preferredHoster> + </SerienjunkiesOrg> +</config> diff --git a/module/download_thread.py b/module/download_thread.py index 539f3e62f..4a031a04c 100644 --- a/module/download_thread.py +++ b/module/download_thread.py @@ -19,6 +19,7 @@ ### import threading import traceback +from os.path import join from time import sleep, time from module.network.Request import AbortDownload @@ -48,7 +49,8 @@ class Status(object): return self.pyfile.plugin.req.dl_size / 1024 def percent(self): if not self.kB_left() == 0 and not self.size() == 0: - return ((self.size()-self.kB_left()) * 100) / self.size() + percent = ((self.size()-self.kB_left()) * 100) / self.size() + return percent if percent < 101 else 0 return 0 class Reconnect(Exception): @@ -65,6 +67,9 @@ class Checksum(Exception): def getFile(self): return self.file +class CaptchaError(Exception): + pass + class Download_Thread(threading.Thread): def __init__(self, parent): threading.Thread.__init__(self) @@ -76,7 +81,7 @@ class Download_Thread(threading.Thread): self.start() def run(self): - while (not self.shutdown): + while not self.shutdown: self.loadedPyFile = self.parent.get_job() if self.loadedPyFile: try: @@ -92,8 +97,10 @@ class Download_Thread(threading.Thread): f = open("%s.info" % e.getFile(), "w") f.write("Checksum not matched!") f.close() + except CaptchaError: + self.loadedPyFile.status.type = "failed" + self.loadedPyFile.status.error = "Can't solve captcha" except Exception, e: - try: if self.parent.parent.config['general']['debug_mode']: traceback.print_exc() @@ -109,55 +116,53 @@ class Download_Thread(threading.Thread): self.loadedPyFile.status.error = str(e) finally: self.parent.job_finished(self.loadedPyFile) - sleep(0.5) + else: + sleep(3) + sleep(0.8) if self.shutdown: sleep(1) self.parent.remove_thread(self) def download(self, pyfile): status = pyfile.status + status.type = "starting" pyfile.init_download() pyfile.plugin.prepare(self) pyfile.plugin.req.set_timeout(self.parent.parent.config['general']['max_download_time']) - - if status.url == "": - status.url = pyfile.plugin.get_file_url() - - status.type = "downloading" - local_file = pyfile.download_folder + "/" + status.filename - pyfile.plugin.proceed(status.url, local_file) - - status.type = "checking" + if pyfile.plugin.props["type"] == "container": + status.type = "decrypting" + else: + status.type = "downloading" - check, code = pyfile.plugin.check_file(local_file) - """ - return codes: - 0 - checksum ok - 1 - checksum wrong - 5 - can't get checksum - 10 - not implemented - 20 - unknown error - """ - if code == 0: - self.parent.parent.logger.info("Checksum ok ('%s')" % status.filename) - elif code == 1: - self.parent.parent.logger.info("Checksum not matched! ('%s')" % status.filename) - elif code == 5: - self.parent.parent.logger.debug("Can't get checksum for %s" % status.filename) - elif code == 10: - self.parent.parent.logger.debug("Checksum not implemented for %s" % status.filename) - if not check: - raise Checksum(code, local_file) - #print "checksum check returned: %s, %s" % (check, code) + location = join(pyfile.folder, status.filename) + pyfile.plugin.proceed(status.url, location) - status.type = "finished" + if self.parent.parent.xmlconfig.get("general", "checksum", True): + status.type = "checking" + check, code = pyfile.plugin.check_file(location) + """ + return codes: + 0 - checksum ok + 1 - checksum wrong + 5 - can't get checksum + 10 - not implemented + 20 - unknown error + """ + if code == 0: + self.parent.parent.logger.info("Checksum ok ('%s')" % status.filename) + elif code == 1: + self.parent.parent.logger.info("Checksum not matched! ('%s')" % status.filename) + elif code == 5: + self.parent.parent.logger.debug("Can't get checksum for %s" % status.filename) + elif code == 10: + self.parent.parent.logger.debug("Checksum not implemented for %s" % status.filename) + if not check: + raise Checksum(code, location) - #startet downloader - #urllib.urlretrieve(status.url, pyfile.download_folder + "/" + status.filename, status) - #self.shutdown = True + status.type = "finished" def wait(self, pyfile): pyfile.status.type = "waiting" @@ -171,4 +176,3 @@ class Download_Thread(threading.Thread): sleep(1) pyfile.status.want_reconnect = False return True - diff --git a/module/file_list.py b/module/file_list.py index c55ce5bc6..7c68a7427 100644 --- a/module/file_list.py +++ b/module/file_list.py @@ -1,180 +1,483 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -# -#Copyright (C) 2009 RaNaN -# -#This program is free software; you can redistribute it and/or modify -#it under the terms of the GNU General Public License as published by -#the Free Software Foundation; either version 3 of the License, -#or (at your option) any later version. -# -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#See the GNU General Public License for more details. -# -#You should have received a copy of the GNU General Public License -# along with this program; if not, see <http://www.gnu.org/licenses/>. -# -### - -LIST_VERSION = 3 + +""" + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, + or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, see <http://www.gnu.org/licenses/>. + + @author: mkaay + @author: RaNaN + @version: v0.3 + @list-version: v4 +""" + +LIST_VERSION = 4 from threading import RLock from download_thread import Status import cPickle import re -from module.remote.RequestObject import RequestObject import module.Plugin +from operator import concat +from operator import attrgetter +from os import sep +from time import sleep + +class NoSuchElementException(Exception): + pass class File_List(object): def __init__(self, core): self.core = core - self.files = [] - self.data = {'version': LIST_VERSION, 'order': []} self.lock = RLock() + self.download_folder = self.core.config['general']['download_folder'] + self.collector = self.pyLoadCollector(self) + self.packager = self.pyLoadPackager(self) + + self.data = { + "version": LIST_VERSION, + "queue": [], + "packages": [], + "collector": [] + } self.load() - - def new_pyfile(self, url, folder): - url = url.replace("\n", "") - pyfile = PyLoadFile(self.core, url) - pyfile.download_folder = self.core.config['general']['download_folder'] - pyfile.id = self.get_id() - pyfile.folder = folder - - return pyfile - - def append(self, url, folder=""): - if not url: - return False - #@TODO: filter non existence and invalid links - #re.compile("https?://[-a-z0-9\.]{4,}(?::\d+)?/[^#?]+(?:#\S+)?",re.IGNORECASE) - new_file = self.new_pyfile(url, folder) - self.files.append(new_file) - self.data[new_file.id] = Data(url, folder) - self.data['order'].append(int(new_file.id)) - - def extend(self, urls): - for url in urls: - self.append(url) - - def remove(self, pyfile): - if not self.core.config['general']['debug_mode']: - if pyfile in self.files: - self.files.remove(pyfile) - - self.data['order'].remove(pyfile.id) - del self.data[pyfile.id] - - def remove_id(self, pyid): - #also abort download - pyid = int(pyid) - found = False - for pyfile in self.files: - if pyfile.id == pyid: - self.files.remove(pyfile) - found = True - break - - if not found: - for pyfile in self.core.thread_list.py_downloading: - if pyfile.id == pyid: - pyfile.plugin.req.abort = True - break - return False - - self.data['order'].remove(pyid) - del self.data[pyid] - - def get_id(self): - """return a free id""" - id = 1 - while id in self.data.keys(): - id += 1 - - return id - - def move(self, id, offset=-1): - for pyfile in self.files: - if pyfile.id == id: - index = self.files.index(pyfile) - pyfile = self.files.pop(index) - self.files.insert(index + offset, pyfile) - break - - index = self.data['order'].index(id) - pyfile = self.data['order'].pop(index) - self.data['order'].insert(index + offset, pyfile) - + def load(self): + self.lock.acquire() + try: + pkl_file = open('module' + sep + 'links.pkl', 'rb') + obj = cPickle.load(pkl_file) + except: + obj = False + if obj != False and obj['version'] == LIST_VERSION: + packages = [] + queue = [] + collector = [] + for n, pd in enumerate(obj["packages"]): + p = PyLoadPackage() + pd.get(p, self) + packages.append(p) + for pd in obj["queue"]: + p = PyLoadPackage() + pd.get(p, self) + queue.append(p) + for fd in obj["collector"]: + f = PyLoadFile("", self) + fd.get(f) + collector.append(f) + obj["packages"] = packages + obj["queue"] = queue + obj["collector"] = collector + self.data = obj + self.lock.release() + + if len(self.data["collector"]) > 0: + self.core.logger.info("Found %s links in linkcollector" % len(self.data["collector"])) + if len(self.data["packages"]) > 0: + self.core.logger.info("Found %s unqueued packages" % len(self.data["packages"])) + if len(self.data["queue"]) > 0: + self.core.logger.info("Added %s packages to queue" % len(self.data["queue"])) + def save(self): self.lock.acquire() + + pdata = { + "version": LIST_VERSION, + "queue": [], + "packages": [], + "collector": [] + } - output = open('links.pkl', 'wb') - cPickle.dump(self.data, output, -1) - - self.inform_client() + pdata["packages"] = [PyLoadPackageData().set(x) for x in self.data["packages"]] + pdata["queue"] = [PyLoadPackageData().set(x) for x in self.data["queue"]] + pdata["collector"] = [PyLoadFileData().set(x) for x in self.data["collector"]] + + output = open('module' + sep + 'links.pkl', 'wb') + cPickle.dump(pdata, output, -1) self.lock.release() + + def queueEmpty(self): + return (self.data["queue"] == []) + + def getDownloadList(self, occ): + """ + for thread_list only, returns all elements that are suitable for downloadthread + """ + files = [] + files += [[x for x in p.files if x.status.type == None and x.plugin.props['type'] == "container" and not x.active] for p in self.data["queue"] + self.data["packages"]] + files += [[x for x in p.files if (x.status.type == None or x.status.type == "reconnected") and not x.active and not x.modul.__name__ in occ] for p in self.data["queue"]] - def load(self): + return reduce(concat, files, []) + + def getAllFiles(self): + + files = [] + for pypack in self.data["queue"] + self.data["packages"]: + files += pypack.files + return files + + def countDownloads(self): + """ simply return len of all files in all packages(which have no type) in queue and collector""" + return len(reduce(concat, [[x for x in p.files if x.status.type == None] for p in self.data["queue"] + self.data["packages"]], [])) + + def getFileInfo(self, id): try: - pkl_file = open('links.pkl', 'rb') - obj = cPickle.load(pkl_file) - except: - obj = {'version': LIST_VERSION, 'order': []} - - if obj['version'] < LIST_VERSION: - obj = {'version': LIST_VERSION, 'order': []} - - for i in obj['order']: - self.append(obj[i].url, obj[i].folder) - - self.core.logger.info("Links loaded: " + str(int(len(obj) - 2))) - - def inform_client(self): - obj = RequestObject() - obj.command = "file_list" - obj.data = self.data + n, pyfile = self.collector._getFileFromID(id) + except NoSuchElementException: + key, n, pyfile, pypack, pid = self.packager._getFileFromID(id) + info = {} + info["id"] = pyfile.id + info["url"] = pyfile.url + info["folder"] = pyfile.folder + info["filename"] = pyfile.status.filename + info["status_type"] = pyfile.status.type + info["status_url"] = pyfile.status.url + info["status_filename"] = pyfile.status.filename + info["status_error"] = pyfile.status.error + info["size"] = pyfile.status.size() + info["active"] = pyfile.active + info["plugin"] = pyfile.plugin.props['name'] + return info - self.core.server.push_all(obj) + def continueAborted(self): + [[self.packager.resetFileStatus(x.id) for x in p.files if x.status.type == "aborted"] for p in self.data["queue"]] + + class pyLoadCollector(): + def __init__(collector, file_list): + collector.file_list = file_list + + def _getFileFromID(collector, id): + """ + returns PyLoadFile instance and position in collector with given id + """ + for n, pyfile in enumerate(collector.file_list.data["collector"]): + if pyfile.id == id: + return (n, pyfile) + raise NoSuchElementException() + + def _getFreeID(collector): + """ + returns a free id + """ + ids = [] + for pypack in (collector.file_list.data["packages"] + collector.file_list.data["queue"]): + for pyf in pypack.files: + ids.append(pyf.id) + ids += map(attrgetter("id"), collector.file_list.data["collector"]) + id = 1 + while id in ids: + id += 1 + return id + + def getFile(collector, id): + """ + returns PyLoadFile instance from given id + """ + return collector._getFileFromID(id)[1] + + def popFile(collector, id): + """ + returns PyLoadFile instance given id and remove it from the collector + """ + collector.file_list.lock.acquire() + try: + n, pyfile = collector._getFileFromID(id) + del collector.file_list.data["collector"][n] + except Exception, e: + raise Exception, e + else: + return pyfile + finally: + collector.file_list.lock.release() + + def addLink(collector, url): + """ + appends a new PyLoadFile instance to the end of the collector + """ + pyfile = PyLoadFile(url, collector.file_list) + pyfile.id = collector._getFreeID() + pyfile.folder = collector.file_list.download_folder + collector.file_list.lock.acquire() + collector.file_list.data["collector"].append(pyfile) + collector.file_list.lock.release() + return pyfile.id + + def removeFile(collector, id): + """ + removes PyLoadFile instance with the given id from collector + """ + collector.popFile(id) + + def replaceFile(collector, newpyfile): + """ + replaces PyLoadFile instance with the given PyLoadFile instance at the given id + """ + collector.file_list.lock.acquire() + try: + n, pyfile = collector._getFileFromID(newpyfile.id) + collector.file_list.data["collector"][n] = newpyfile + finally: + collector.file_list.lock.release() + + class pyLoadPackager(): + def __init__(packager, file_list): + packager.file_list = file_list + + def _getFreeID(packager): + """ + returns a free id + """ + ids = [ pypack.data["id"] for pypack in packager.file_list.data["packages"] + packager.file_list.data["queue"]] + + id = 1 + while id in ids: + id += 1 + return id + + def _getPackageFromID(packager, id): + """ + returns PyLoadPackage instance and position with given id + """ + for n, pypack in enumerate(packager.file_list.data["packages"]): + if pypack.data["id"] == id: + return ("packages", n, pypack) + for n, pypack in enumerate(packager.file_list.data["queue"]): + if pypack.data["id"] == id: + return ("queue", n, pypack) + raise NoSuchElementException() + + def _getFileFromID(packager, id): + """ + returns PyLoadFile instance and position with given id + """ + for n, pypack in enumerate(packager.file_list.data["packages"]): + for pyfile in pypack.files: + if pyfile.id == id: + return ("packages", n, pyfile, pypack, pypack.data["id"]) + for n, pypack in enumerate(packager.file_list.data["queue"]): + for pyfile in pypack.files: + if pyfile.id == id: + return ("queue", n, pyfile, pypack, pypack.data["id"]) + raise NoSuchElementException() + + def addNewPackage(packager, package_name=None): + pypack = PyLoadPackage() + pypack.data["id"] = packager._getFreeID() + if package_name is not None: + pypack.data["package_name"] = package_name + packager.file_list.data["packages"].append(pypack) + return pypack.data["id"] + + def removePackage(packager, id): + packager.file_list.lock.acquire() + try: + key, n, pypack = packager._getPackageFromID(id) + for pyfile in pypack.files: + pyfile.plugin.req.abort = True + sleep(0.1) + del packager.file_list.data[key][n] + finally: + packager.file_list.lock.release() + + def removeFile(packager, id): + """ + removes PyLoadFile instance with the given id from package + """ + packager.file_list.lock.acquire() + try: + key, n, pyfile, pypack, pid = packager._getFileFromID(id) + pyfile.plugin.req.abort = True + sleep(0.1) + packager.removeFileFromPackage(id, pid) + if not pypack.files: + packager.removePackage(pid) + finally: + packager.file_list.lock.release() + + def pushPackage2Queue(packager, id): + packager.file_list.lock.acquire() + try: + key, n, pypack = packager._getPackageFromID(id) + if key == "packages": + del packager.file_list.data["packages"][n] + packager.file_list.data["queue"].append(pypack) + finally: + packager.file_list.lock.release() + + def pullOutPackage(packager, id): + packager.file_list.lock.acquire() + try: + key, n, pypack = packager._getPackageFromID(id) + if key == "queue": + del packager.file_list.data["queue"][n] + packager.file_list.data["packages"].append(pypack) + finally: + packager.file_list.lock.release() + + def setPackageData(packager, id, package_name=None, folder=None): + packager.file_list.lock.acquire() + try: + key, n, pypack = packager._getPackageFromID(id) + if package_name is not None: + pypack.data["package_name"] = package_name + if folder is not None: + pypack.data["folder"] = folder + packager.file_list.data[key][n] = pypack + finally: + packager.file_list.lock.release() + + def getPackageData(packager, id): + key, n, pypack = packager._getPackageFromID(id) + return pypack.data + + def getPackageFiles(packager, id): + key, n, pypack = packager._getPackageFromID(id) + ids = map(attrgetter("id"), pypack.files) + + return ids + + def addFileToPackage(packager, id, pyfile): + key, n, pypack = packager._getPackageFromID(id) + pyfile.package = pypack + pypack.files.append(pyfile) + packager.file_list.data[key][n] = pypack + + def resetFileStatus(packager, fileid): + packager.file_list.lock.acquire() + try: + key, n, pyfile, pypack, pid = packager._getFileFromID(fileid) + pyfile.init() + pyfile.status.type = None + finally: + packager.file_list.lock.release() + + def abortFile(packager, fileid): + packager.file_list.lock.acquire() + try: + key, n, pyfile, pypack, pid = packager._getFileFromID(fileid) + pyfile.plugin.req.abort = True + finally: + packager.file_list.lock.release() + + #oooops, duplicate? + def removeFileFromPackage(packager, id, pid): + key, n, pypack = packager._getPackageFromID(pid) + for k, pyfile in enumerate(pypack.files): + if id == pyfile.id: + del pypack.files[k] + if not pypack.files: + packager.removePackage(pid) + return True + raise NoSuchElementException() -class Data(): - def __init__(self, url, folder=""): - self.url = url - self.folder = folder +class PyLoadPackage(): + def __init__(self): + self.files = [] + self.data = { + "id": None, + "package_name": "new_package", + "folder": "" + } -class PyLoadFile: - """ represents the url or file - """ - def __init__(self, parent, url): - self.parent = parent +class PyLoadFile(): + def __init__(self, url, file_list): self.id = None self.url = url - self.folder = None - self.filename = "filename" - self.download_folder = "" + self.folder = "" + self.file_list = file_list + self.core = file_list.core + self.package = None + self.filename = "n/a" + self.init() + + def init(self): + self.active = False pluginName = self._get_my_plugin() if pluginName: - self.modul = __import__(pluginName) - pluginClass = getattr(self.modul, self.modul.__name__) + for dir in ["hoster", "decrypter", "container"]: + try: + self.modul = __import__("%s.%s" % (dir, pluginName), globals(), locals(), [pluginName], -1) + except ImportError: + pass + pluginClass = getattr(self.modul, pluginName) else: self.modul = module.Plugin pluginClass = module.Plugin.Plugin self.plugin = pluginClass(self) self.status = Status(self) + self.status.filename = self.url + def _get_my_plugin(self): - - """ searches the right plugin for an url - """ - for plugin, plugin_pattern in self.parent.plugins_avaible.items(): + for plugin, plugin_pattern in self.core.plugins_avaible.items(): if re.match(plugin_pattern, self.url) != None: return plugin def init_download(self): + if self.core.config['proxy']['activated']: + self.plugin.req.add_proxy(self.core.config['proxy']['protocol'], self.core.config['proxy']['adress']) + +class PyLoadFileData(): + def __init__(self): + self.id = None + self.url = None + self.folder = None + self.pack_id = None + self.filename = None + self.status_type = None + self.status_url = None - if self.parent.config['proxy']['activated']: - self.plugin.req.add_proxy(self.parent.config['proxy']['protocol'], self.parent.config['proxy']['adress']) + def set(self, pyfile): + self.id = pyfile.id + self.url = pyfile.url + self.folder = pyfile.folder + self.parsePackage(pyfile.package) + self.filename = pyfile.filename + self.status_type = pyfile.status.type + self.status_url = pyfile.status.url + self.status_filename = pyfile.status.filename + self.status_error = pyfile.status.error - #@TODO: check dependicies, ocr etc + return self + def get(self, pyfile): + pyfile.id = self.id + pyfile.url = self.url + pyfile.folder = self.folder + pyfile.filename = self.filename + pyfile.status.type = self.status_type + pyfile.status.url = self.status_url + pyfile.status.filename = self.status_filename + pyfile.status.error = self.status_error + + def parsePackage(self, pack): + if pack: + self.pack_id = pack.data["id"] + +class PyLoadPackageData(): + def __init__(self): + self.data = None + self.files = [] + + def set(self, pypack): + self.data = pypack.data + self.files = [PyLoadFileData().set(x) for x in pypack.files] + return self + + def get(self, pypack, fl): + pypack.data = self.data + for fdata in self.files: + pyfile = PyLoadFile(fdata.url, fl) + fdata.get(pyfile) + pyfile.package = pypack + pypack.files.append(pyfile) diff --git a/module/gui/CaptchaDock.py b/module/gui/CaptchaDock.py new file mode 100644 index 000000000..8a7e8010e --- /dev/null +++ b/module/gui/CaptchaDock.py @@ -0,0 +1,85 @@ +# -*- coding: utf-8 -*- + +""" + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, + or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, see <http://www.gnu.org/licenses/>. + + @author: mkaay +""" + +from PyQt4.QtCore import * +from PyQt4.QtGui import * + +class CaptchaDock(QDockWidget): + def __init__(self): + QDockWidget.__init__(self, "Captcha") + self.setObjectName("Captcha Dock") + self.widget = CaptchaDockWidget(self) + self.setWidget(self.widget) + self.setAllowedAreas(Qt.BottomDockWidgetArea) + self.setFeatures(QDockWidget.NoDockWidgetFeatures) + self.hide() + self.processing = False + self.currentID = None + self.connect(self, SIGNAL("setTask"), self.setTask) + + def isFree(self): + return not self.processing + + def setTask(self, tid, img, imgType): + self.processing = True + data = QByteArray(img) + self.currentID = tid + self.widget.emit(SIGNAL("setImage"), data) + self.widget.input.setText("") + self.show() + +class CaptchaDockWidget(QWidget): + def __init__(self, dock): + QWidget.__init__(self) + self.dock = dock + self.setLayout(QHBoxLayout()) + layout = self.layout() + + imgLabel = QLabel() + captchaInput = QLineEdit() + okayButton = QPushButton("OK") + cancelButton = QPushButton("Cancel") + + layout.addStretch() + layout.addWidget(imgLabel) + layout.addWidget(captchaInput) + layout.addWidget(okayButton) + layout.addWidget(cancelButton) + layout.addStretch() + + self.input = captchaInput + + self.connect(okayButton, SIGNAL("clicked()"), self.slotSubmit) + self.connect(captchaInput, SIGNAL("returnPressed()"), self.slotSubmit) + self.connect(self, SIGNAL("setImage"), self.setImg) + self.connect(self, SIGNAL("setPixmap(const QPixmap &)"), imgLabel, SLOT("setPixmap(const QPixmap &)")) + + def setImg(self, data): + pixmap = QPixmap() + pixmap.loadFromData(data) + self.emit(SIGNAL("setPixmap(const QPixmap &)"), pixmap) + + def slotSubmit(self): + text = self.input.text() + tid = self.dock.currentID + self.dock.currentID = None + self.dock.emit(SIGNAL("done"), tid, str(text)) + self.dock.hide() + self.dock.processing = False + diff --git a/module/gui/Collector.py b/module/gui/Collector.py new file mode 100644 index 000000000..0aad5d1ba --- /dev/null +++ b/module/gui/Collector.py @@ -0,0 +1,312 @@ +# -*- coding: utf-8 -*- +""" + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, + or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, see <http://www.gnu.org/licenses/>. + + @author: mkaay +""" + +from PyQt4.QtCore import * +from PyQt4.QtGui import * + +from module.gui.Queue import ItemIterator + +class PackageCollector(QObject): + def __init__(self, view, connector): + QObject.__init__(self) + self.view = view + self.connector = connector + self.collector = [] + self.interval = 2 + self.rootItem = self.view.invisibleRootItem() + self.mutex = QMutex() + item = self.PackageCollectorPack(self) + item.setPackData({"id":"fixed"}) + item.setData(0, Qt.DisplayRole, QVariant("Single Links")) + item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) + self.rootItem.addChild(item) + self.linkCollector = item + self.pauseIDs = [] + self.updater = self.CollectorUpdater(self.interval) + self.connect(self.updater, SIGNAL("update()"), self.update) + + class CollectorUpdater(QThread): + def __init__(self, interval): + QThread.__init__(self) + self.interval = interval + self.running = True + + def run(self): + while self.running: + self.emit(SIGNAL("update()")) + self.sleep(self.interval) + + def start(self): + self.updater.start() + + def wait(self): + self.updater.wait() + + def stop(self): + self.updater.running = False + + def update(self): + locker = QMutexLocker(self.mutex) + packs = self.connector.getPackageCollector() + ids = [] + for data in packs: + ids.append(data["id"]) + self.clear(ids) + for data in packs: + if data["id"] in self.pauseIDs: + continue + ids.append(data["id"]) + pack = self.getPack(data["id"]) + if not pack: + pack = self.PackageCollectorPack(self) + pack.setPackData(data) + self.addPack(data["id"], pack) + files = self.connector.getPackageFiles(data["id"]) + pack.clear(files) + for fid in files: + info = self.connector.getLinkInfo(fid) + child = pack.getChild(fid) + if not child: + child = self.PackageCollectorFile(self, pack) + child.setFileData(info) + pack.addPackChild(fid, child) + + def addPack(self, pid, newPack): + pos = None + try: + for pack in ItemIterator(self.rootItem): + if pack.getPackData()["id"] == pid: + pos = self.rootItem.indexOfChild(pack) + break + if pos == None: + raise Exception() + item = self.rootItem.child(pos) + item.setPackData(newPack.getPackData()) + except: + self.rootItem.insertChild(self.rootItem.childCount()-1, newPack) + item = newPack + item.setData(0, Qt.DisplayRole, QVariant(item.getPackData()["package_name"])) + item.setData(0, Qt.UserRole, QVariant(pid)) + item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsDropEnabled | Qt.ItemIsEditable) + + def getPack(self, pid): + for k, pack in enumerate(ItemIterator(self.rootItem)): + if pack.getPackData()["id"] == pid: + return pack + return None + + def clear(self, ids): + clear = False + remove = [] + for k, pack in enumerate(ItemIterator(self.rootItem)): + if not pack.getPackData()["id"] in ids and not pack.getPackData()["id"] == "fixed": + clear = True + remove.append(k) + if not clear: + return + remove.sort() + remove.reverse() + for k in remove: + self.rootItem.takeChild(k) + for pack in ItemIterator(self.rootItem): + if pack.getPackData()["id"] == "fixed": + return + item = self.PackageCollectorPack(self) + item.setPackData({"id":"fixed"}) + item.setData(0, Qt.DisplayRole, QVariant("Single Links")) + item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) + self.rootItem.addChild(item) + self.linkCollector = item + + def pauseItemUpdate(self, pid, pause=True): + locker = QMutexLocker(self.mutex) + if pause and not pid in self.pauseIDs: + self.pauseIDs.append(int(pid)) + else: + try: + self.pauseIDs.remove(int(pid)) + except: + pass + + class PackageCollectorPack(QTreeWidgetItem): + def __init__(self, collector): + QTreeWidgetItem.__init__(self) + self.collector = collector + self._data = {} + + def addPackChild(self, cid, newChild): + pos = None + try: + for child in ItemIterator(self): + if child.getData()["id"] == cid: + pos = self.indexOfChild(child) + break + if pos == None: + raise Exception() + item = self.child(pos) + item.setFileData(newChild.getFileData()) + except: + self.addChild(newChild) + item = newChild + item.setData(0, Qt.DisplayRole, QVariant(item.getFileData()["filename"])) + item.setData(0, Qt.UserRole, QVariant(cid)) + item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) + + def setPackData(self, data): + self._data = data + + def getPackData(self): + return self._data + + def getChildren(self): + ret = [] + for item in ItemIterator(self): + ret.append(item) + return ret + + def getChild(self, cid): + for item in ItemIterator(self): + if item.getFileData()["id"] == cid: + return item + return None + + def clear(self, ids): + clear = False + remove = [] + children = [] + for k, file in enumerate(self.getChildren()): + if not file.getFileData()["id"] in ids: + remove.append(file.getFileData()["id"]) + if file.getFileData()["id"] in children and not file.getFileData()["id"] in remove: + remove.append(file.getFileData()["id"]) + continue + children.append(file.getFileData()["id"]) + if not remove: + return + remove.sort() + remove.reverse() + parent = self + for k in remove: + parent.takeChild(k) + + class PackageCollectorFile(QTreeWidgetItem): + def __init__(self, collector, pack): + QTreeWidgetItem.__init__(self) + self.collector = collector + self.pack = pack + self._data = {} + self.wait_since = None + + def getFileData(self): + return self._data + + def setFileData(self, data): + self._data = data + + def getPack(self): + return self.pack + +class LinkCollector(QObject): + def __init__(self, view, root, connector): + QObject.__init__(self) + self.view = view + self.connector = connector + self.interval = 2 + self.rootItem = root + self.mutex = QMutex() + self.updater = self.CollectorUpdater(self.interval) + self.connect(self.updater, SIGNAL("update()"), self.update) + + class CollectorUpdater(QThread): + def __init__(self, interval): + QThread.__init__(self) + self.interval = interval + self.running = True + + def run(self): + while self.running: + self.emit(SIGNAL("update()")) + self.sleep(self.interval) + + def start(self): + self.updater.start() + + def wait(self): + self.updater.wait() + + def stop(self): + self.updater.running = False + + def update(self): + locker = QMutexLocker(self.mutex) + ids = self.connector.getLinkCollector() + self.clear(ids) + for fid in ids: + data = self.connector.getLinkInfo(fid) + file = self.getFile(fid) + if not file: + file = self.LinkCollectorFile(self) + file.setFileData(data) + self.addFile(fid, file) + + def addFile(self, pid, newFile): + pos = None + try: + for pack in ItemIterator(self.rootItem): + if file.getFileData()["id"] == pid: + pos = self.rootItem.indexOfChild(file) + break + if pos == None: + raise Exception() + item = self.rootItem.child(pos) + item.setFileData(newFile.getPackData()) + except: + self.rootItem.addChild(newFile) + item = newFile + item.setData(0, Qt.DisplayRole, QVariant(newFile.getFileData()["filename"])) + item.setData(0, Qt.UserRole, QVariant(pid)) + flags = Qt.ItemIsSelectable | Qt.ItemIsDragEnabled | Qt.ItemIsEnabled + item.setFlags(flags) + + def getFile(self, pid): + for file in ItemIterator(self.rootItem): + if file.getFileData()["id"] == pid: + return file + return None + + def clear(self, ids): + clear = False + for file in ItemIterator(self.rootItem): + if not file.getFileData()["id"] in ids: + clear = True + break + if not clear: + return + self.rootItem.takeChildren() + + class LinkCollectorFile(QTreeWidgetItem): + def __init__(self, collector): + QTreeWidgetItem.__init__(self) + self.collector = collector + self._data = {} + + def getFileData(self): + return self._data + + def setFileData(self, data): + self._data = data diff --git a/module/gui/ConnectionManager.py b/module/gui/ConnectionManager.py new file mode 100644 index 000000000..57aed3a18 --- /dev/null +++ b/module/gui/ConnectionManager.py @@ -0,0 +1,249 @@ +# -*- coding: utf-8 -*- +""" + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, + or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, see <http://www.gnu.org/licenses/>. + + @author: mkaay +""" + +from PyQt4.QtCore import * +from PyQt4.QtGui import * + +from uuid import uuid4 as uuid + +class ConnectionManager(QWidget): + def __init__(self): + QWidget.__init__(self) + + mainLayout = QHBoxLayout() + buttonLayout = QVBoxLayout() + + connList = QListWidget() + + new = QPushButton("New") + edit = QPushButton("Edit") + remove = QPushButton("Remove") + connect = QPushButton("Connect") + + mainLayout.addWidget(connList) + mainLayout.addLayout(buttonLayout) + + buttonLayout.addWidget(new) + buttonLayout.addWidget(edit) + buttonLayout.addWidget(remove) + buttonLayout.addStretch() + buttonLayout.addWidget(connect) + + self.setLayout(mainLayout) + + self.new = new + self.connectb = connect + self.remove = remove + self.editb = edit + self.connList = connList + self.edit = self.EditWindow() + self.connectSignals() + + self.defaultStates = {} + + def connectSignals(self): + self.connect(self, SIGNAL("setConnections(connections)"), self.setConnections) + self.connect(self.new, SIGNAL("clicked()"), self.slotNew) + self.connect(self.editb, SIGNAL("clicked()"), self.slotEdit) + self.connect(self.remove, SIGNAL("clicked()"), self.slotRemove) + self.connect(self.connectb, SIGNAL("clicked()"), self.slotConnect) + self.connect(self.edit, SIGNAL("save"), self.slotSave) + self.connect(self.connList, SIGNAL("itemDoubleClicked(QListWidgetItem *)"), self.slotItemDoubleClicked) + + def setConnections(self, connections): + self.connList.clear() + for conn in connections: + item = QListWidgetItem() + item.setData(Qt.DisplayRole, QVariant(conn["name"])) + item.setData(Qt.UserRole, QVariant(conn)) + self.connList.addItem(item) + if conn["default"]: + item.setData(Qt.DisplayRole, QVariant("%s (Default)" % conn["name"])) + self.connList.setCurrentItem(item) + + def slotNew(self): + data = {"id":uuid().hex, "type":"remote", "default":False, "name":"", "host":"", "ssl":False, "port":"7227", "user":"admin"} + self.edit.setData(data) + self.edit.show() + + def slotEdit(self): + item = self.connList.currentItem() + data = item.data(Qt.UserRole).toPyObject() + data = self.cleanDict(data) + self.edit.setData(data) + self.edit.show() + + def slotRemove(self): + item = self.connList.currentItem() + data = item.data(Qt.UserRole).toPyObject() + data = self.cleanDict(data) + self.emit(SIGNAL("removeConnection"), data) + + def slotConnect(self): + item = self.connList.currentItem() + data = item.data(Qt.UserRole).toPyObject() + data = self.cleanDict(data) + self.emit(SIGNAL("connect"), data) + + def cleanDict(self, data): + tmp = {} + for k, d in data.items(): + tmp[str(k)] = d + return tmp + + def slotSave(self, data): + self.emit(SIGNAL("saveConnection"), data) + + def slotItemDoubleClicked(self, defaultItem): + data = defaultItem.data(Qt.UserRole).toPyObject() + self.setDefault(data, True) + did = self.cleanDict(data)["id"] + allItems = self.connList.findItems("*", Qt.MatchWildcard) + count = self.connList.count() + for i in range(count): + item = self.connList.item(i) + data = item.data(Qt.UserRole).toPyObject() + if self.cleanDict(data)["id"] == did: + continue + self.setDefault(data, False) + + def setDefault(self, data, state): + data = self.cleanDict(data) + self.edit.setData(data) + data = self.edit.getData() + data["default"] = state + self.edit.emit(SIGNAL("save"), data) + + class EditWindow(QWidget): + def __init__(self): + QWidget.__init__(self) + + grid = QGridLayout() + + nameLabel = QLabel("Name:") + hostLabel = QLabel("Host:") + sslLabel = QLabel("SSL:") + localLabel = QLabel("Local:") + userLabel = QLabel("User:") + portLabel = QLabel("Port:") + + name = QLineEdit() + host = QLineEdit() + ssl = QCheckBox() + local = QCheckBox() + user = QLineEdit() + port = QSpinBox() + port.setRange(1,10000) + + save = QPushButton("Save") + cancel = QPushButton("Cancel") + + grid.addWidget(nameLabel, 0, 0) + grid.addWidget(name, 0, 1) + grid.addWidget(localLabel, 1, 0) + grid.addWidget(local, 1, 1) + grid.addWidget(hostLabel, 2, 0) + grid.addWidget(host, 2, 1) + grid.addWidget(sslLabel, 4, 0) + grid.addWidget(ssl, 4, 1) + grid.addWidget(userLabel, 5, 0) + grid.addWidget(user, 5, 1) + grid.addWidget(portLabel, 3, 0) + grid.addWidget(port, 3, 1) + grid.addWidget(cancel, 6, 0) + grid.addWidget(save, 6, 1) + + self.setLayout(grid) + self.controls = {} + self.controls["name"] = name + self.controls["host"] = host + self.controls["ssl"] = ssl + self.controls["local"] = local + self.controls["user"] = user + self.controls["port"] = port + self.controls["save"] = save + self.controls["cancel"] = cancel + + self.connect(cancel, SIGNAL("clicked()"), self.hide) + self.connect(save, SIGNAL("clicked()"), self.slotDone) + self.connect(local, SIGNAL("stateChanged(int)"), self.slotLocalChanged) + + self.id = None + self.default = None + + def setData(self, data): + self.id = data["id"] + self.default = data["default"] + self.controls["name"].setText(data["name"]) + if data["type"] == "local": + data["local"] = True + else: + data["local"] = False + self.controls["local"].setChecked(data["local"]) + if not data["local"]: + self.controls["ssl"].setChecked(data["ssl"]) + self.controls["user"].setText(data["user"]) + self.controls["port"].setValue(int(data["port"])) + self.controls["host"].setText(data["host"]) + self.controls["ssl"].setDisabled(False) + self.controls["user"].setDisabled(False) + self.controls["port"].setDisabled(False) + self.controls["host"].setDisabled(False) + else: + self.controls["ssl"].setChecked(False) + self.controls["user"].setText("") + self.controls["port"].setValue(1) + self.controls["host"].setText("") + self.controls["ssl"].setDisabled(True) + self.controls["user"].setDisabled(True) + self.controls["port"].setDisabled(True) + self.controls["host"].setDisabled(True) + + def slotLocalChanged(self, val): + if val == 2: + self.controls["ssl"].setDisabled(True) + self.controls["user"].setDisabled(True) + self.controls["port"].setDisabled(True) + self.controls["host"].setDisabled(True) + elif val == 0: + self.controls["ssl"].setDisabled(False) + self.controls["user"].setDisabled(False) + self.controls["port"].setDisabled(False) + self.controls["host"].setDisabled(False) + + def getData(self): + d = {} + d["id"] = self.id + d["default"] = self.default + d["name"] = self.controls["name"].text() + d["local"] = self.controls["local"].isChecked() + d["ssl"] = str(self.controls["ssl"].isChecked()) + d["user"] = self.controls["user"].text() + d["host"] = self.controls["host"].text() + d["port"] = self.controls["port"].value() + if d["local"]: + d["type"] = "local" + else: + d["type"] = "remote" + return d + + def slotDone(self): + data = self.getData() + self.hide() + self.emit(SIGNAL("save"), data) + diff --git a/module/gui/LinkDock.py b/module/gui/LinkDock.py new file mode 100644 index 000000000..99429d04b --- /dev/null +++ b/module/gui/LinkDock.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +""" + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, + or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, see <http://www.gnu.org/licenses/>. + + @author: mkaay +""" + +from PyQt4.QtCore import * +from PyQt4.QtGui import * + +class NewLinkDock(QDockWidget): + def __init__(self): + QDockWidget.__init__(self, "New Links") + self.setObjectName("New Links Dock") + self.widget = NewLinkWindow(self) + self.setWidget(self.widget) + self.setAllowedAreas(Qt.RightDockWidgetArea|Qt.LeftDockWidgetArea) + self.hide() + + def slotDone(self): + text = str(self.widget.box.toPlainText()) + lines = text.splitlines() + self.emit(SIGNAL("done"), lines) + self.widget.box.clear() + self.hide() + +class NewLinkWindow(QWidget): + def __init__(self, dock): + QWidget.__init__(self) + self.dock = dock + self.setLayout(QVBoxLayout()) + layout = self.layout() + + boxLabel = QLabel("Paste URLs here:") + self.box = QTextEdit() + + save = QPushButton("Add") + + layout.addWidget(boxLabel) + layout.addWidget(self.box) + layout.addWidget(save) + + self.connect(save, SIGNAL("clicked()"), self.dock.slotDone) diff --git a/module/gui/MainWindow.py b/module/gui/MainWindow.py new file mode 100644 index 000000000..250b701e4 --- /dev/null +++ b/module/gui/MainWindow.py @@ -0,0 +1,421 @@ +# -*- coding: utf-8 -*- +""" + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, + or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, see <http://www.gnu.org/licenses/>. + + @author: mkaay +""" + +from PyQt4.QtCore import * +from PyQt4.QtGui import * + +from module.gui.PackageDock import * +from module.gui.LinkDock import * +from module.gui.CaptchaDock import CaptchaDock + +class MainWindow(QMainWindow): + def __init__(self): + """ + set up main window + """ + QMainWindow.__init__(self) + #window stuff + self.setWindowTitle("pyLoad Client") + self.setWindowIcon(QIcon("icons/logo.png")) + self.resize(850,500) + + #layout version + self.version = 2 + + #init docks + self.newPackDock = NewPackageDock() + self.addDockWidget(Qt.RightDockWidgetArea, self.newPackDock) + self.newLinkDock = NewLinkDock() + self.addDockWidget(Qt.RightDockWidgetArea, self.newLinkDock) + self.connect(self.newLinkDock, SIGNAL("done"), self.slotAddLinks) + self.connect(self.newPackDock, SIGNAL("done"), self.slotAddPackage) + self.captchaDock = CaptchaDock() + self.addDockWidget(Qt.BottomDockWidgetArea, self.captchaDock) + + #central widget, layout + self.masterlayout = QVBoxLayout() + lw = QWidget() + lw.setLayout(self.masterlayout) + self.setCentralWidget(lw) + + #set menubar and statusbar + self.menubar = self.menuBar() + self.statusbar = self.statusBar() + self.connect(self.statusbar, SIGNAL("showMsg"), self.statusbar.showMessage) + self.serverStatus = QLabel("Status: Not Connected") + self.statusbar.addPermanentWidget(self.serverStatus) + + #menu + self.menus = {} + self.menus["file"] = self.menubar.addMenu("&File") + self.menus["connections"] = self.menubar.addMenu("&Connections") + + #menu actions + self.mactions = {} + self.mactions["exit"] = QAction("Exit", self.menus["file"]) + self.mactions["manager"] = QAction("Connection manager", self.menus["connections"]) + + #add menu actions + self.menus["file"].addAction(self.mactions["exit"]) + self.menus["connections"].addAction(self.mactions["manager"]) + + #toolbar + self.actions = {} + self.init_toolbar() + + #tabs + self.tabw = QTabWidget() + self.tabs = {} + self.tabs["queue"] = {"w":QWidget()} + self.tabs["collector"] = {"w":QWidget()} + self.tabs["settings"] = {"w":QWidget()} + self.tabs["log"] = {"w":QWidget()} + self.tabw.addTab(self.tabs["queue"]["w"], "Queue") + self.tabw.addTab(self.tabs["collector"]["w"], "Collector") + self.tabw.addTab(self.tabs["settings"]["w"], "Settings") + self.tabw.addTab(self.tabs["log"]["w"], "Log") + self.tabw.setTabEnabled(2, False) + + #init tabs + self.init_tabs() + + #context menus + self.init_context() + + #layout + self.masterlayout.addWidget(self.tabw) + + #signals.. + self.connect(self.mactions["manager"], SIGNAL("triggered()"), self.slotShowConnector) + self.connect(self.mactions["exit"], SIGNAL("triggered()"), self.close) + + self.connect(self.tabs["queue"]["view"], SIGNAL('customContextMenuRequested(const QPoint &)'), self.slotQueueContextMenu) + self.connect(self.tabs["collector"]["package_view"], SIGNAL('customContextMenuRequested(const QPoint &)'), self.slotCollectorContextMenu) + self.connect(self.tabs["collector"]["package_view"].itemDelegate(), SIGNAL("closeEditor(QWidget *, QAbstractItemDelegate::EndEditHint)"), self.slotCloseItemEditor) + + self.lastAddedID = None + + def init_toolbar(self): + """ + create toolbar + """ + self.toolbar = self.addToolBar("Main Toolbar") + self.toolbar.setObjectName("Main Toolbar") + self.toolbar.setIconSize(QSize(40,40)) + self.actions["toggle_status"] = self.toolbar.addAction("Toggle Pause/Resume") + pricon = QIcon() + pricon.addFile("icons/gui/toolbar_start.png", QSize(), QIcon.Normal, QIcon.Off) + pricon.addFile("icons/gui/toolbar_pause.png", QSize(), QIcon.Normal, QIcon.On) + self.actions["toggle_status"].setIcon(pricon) + self.actions["toggle_status"].setCheckable(True) + self.actions["status_stop"] = self.toolbar.addAction(QIcon("icons/gui/toolbar_stop.png"), "Stop") + self.toolbar.addSeparator() + self.actions["add"] = self.toolbar.addAction(QIcon("icons/gui/toolbar_add.png"), "Add") + self.toolbar.addSeparator() + self.actions["clipboard"] = self.toolbar.addAction(QIcon("icons/gui/clipboard.png"), "Check Clipboard") + self.actions["clipboard"].setCheckable(True) + + self.connect(self.actions["toggle_status"], SIGNAL("toggled(bool)"), self.slotToggleStatus) + self.connect(self.actions["clipboard"], SIGNAL("toggled(bool)"), self.slotToggleClipboard) + self.connect(self.actions["status_stop"], SIGNAL("triggered()"), self.slotStatusStop) + self.addMenu = QMenu() + packageAction = self.addMenu.addAction("Package") + linkAction = self.addMenu.addAction("Links") + containerAction = self.addMenu.addAction("Container") + self.connect(self.actions["add"], SIGNAL("triggered()"), self.slotAdd) + self.connect(packageAction, SIGNAL("triggered()"), self.slotShowAddPackage) + self.connect(linkAction, SIGNAL("triggered()"), self.slotShowAddLinks) + self.connect(containerAction, SIGNAL("triggered()"), self.slotShowAddContainer) + + def init_tabs(self): + """ + create tabs + """ + #queue + self.tabs["queue"]["l"] = QGridLayout() + self.tabs["queue"]["w"].setLayout(self.tabs["queue"]["l"]) + self.tabs["queue"]["view"] = QTreeWidget() + self.tabs["queue"]["l"].addWidget(self.tabs["queue"]["view"]) + + #collector + groupPackage = QGroupBox("Packages") + groupPackage.setLayout(QVBoxLayout()) + toQueue = QPushButton("Push selected packages to queue") + self.tabs["collector"]["l"] = QGridLayout() + self.tabs["collector"]["w"].setLayout(self.tabs["collector"]["l"]) + self.tabs["collector"]["package_view"] = QTreeWidget() + groupPackage.layout().addWidget(self.tabs["collector"]["package_view"]) + groupPackage.layout().addWidget(toQueue) + self.tabs["collector"]["l"].addWidget(groupPackage, 0, 0) + self.connect(toQueue, SIGNAL("clicked()"), self.slotPushPackageToQueue) + self.tabs["collector"]["package_view"].setContextMenuPolicy(Qt.CustomContextMenu) + self.tabs["queue"]["view"].setContextMenuPolicy(Qt.CustomContextMenu) + + #settings + self.tabs["settings"]["l"] = QGridLayout() + self.tabs["settings"]["w"].setLayout(self.tabs["settings"]["l"]) + + #log + self.tabs["log"]["l"] = QGridLayout() + self.tabs["log"]["w"].setLayout(self.tabs["log"]["l"]) + self.tabs["log"]["text"] = QTextEdit() + self.tabs["log"]["text"].logOffset = 0 + self.tabs["log"]["text"].setReadOnly(True) + self.connect(self.tabs["log"]["text"], SIGNAL("append(QString)"), self.tabs["log"]["text"].append) + self.tabs["log"]["l"].addWidget(self.tabs["log"]["text"]) + + def init_context(self): + """ + create context menus + """ + self.activeMenu = None + #queue + self.queueContext = QMenu() + self.queueContext.buttons = {} + self.queueContext.item = (None, None) + self.queueContext.buttons["remove"] = QAction(QIcon("icons/gui/remove_small.png"), "Remove", self.queueContext) + self.queueContext.buttons["restart"] = QAction(QIcon("icons/gui/refresh_small.png"), "Restart", self.queueContext) + self.queueContext.buttons["pull"] = QAction(QIcon("icons/gui/pull_small.png"), "Pull out", self.queueContext) + self.queueContext.addAction(self.queueContext.buttons["pull"]) + self.queueContext.addAction(self.queueContext.buttons["remove"]) + self.queueContext.addAction(self.queueContext.buttons["restart"]) + self.connect(self.queueContext.buttons["remove"], SIGNAL("triggered()"), self.slotRemoveDownload) + self.connect(self.queueContext.buttons["restart"], SIGNAL("triggered()"), self.slotRestartDownload) + self.connect(self.queueContext.buttons["pull"], SIGNAL("triggered()"), self.slotPullOutPackage) + + #collector + self.collectorContext = QMenu() + self.collectorContext.buttons = {} + self.collectorContext.item = (None, None) + self.collectorContext.buttons["remove"] = QAction(QIcon("icons/gui/remove_small.png"), "Remove", self.collectorContext) + self.collectorContext.buttons["push"] = QAction(QIcon("icons/gui/push_small.png"), "Push to queue", self.collectorContext) + self.collectorContext.buttons["edit"] = QAction(QIcon("icons/gui/edit_small.png"), "Edit Name", self.collectorContext) + self.collectorContext.addAction(self.collectorContext.buttons["push"]) + self.collectorContext.addAction(self.collectorContext.buttons["edit"]) + self.collectorContext.addAction(self.collectorContext.buttons["remove"]) + self.connect(self.collectorContext.buttons["remove"], SIGNAL("triggered()"), self.slotRemoveDownload) + self.connect(self.collectorContext.buttons["push"], SIGNAL("triggered()"), self.slotPushPackageToQueue) + self.connect(self.collectorContext.buttons["edit"], SIGNAL("triggered()"), self.slotEditPackage) + + def slotToggleStatus(self, status): + """ + pause/start toggle (toolbar) + """ + self.emit(SIGNAL("setDownloadStatus"), status) + + def slotStatusStop(self): + """ + stop button (toolbar) + """ + self.emit(SIGNAL("stopAllDownloads")) + + def slotAdd(self): + """ + add button (toolbar) + show context menu (choice: links/package) + """ + self.addMenu.exec_(QCursor.pos()) + + def slotShowAddPackage(self): + """ + action from add-menu + show new-package dock + """ + self.tabw.setCurrentIndex(1) + self.newPackDock.show() + + def slotShowAddLinks(self): + """ + action from add-menu + show new-links dock + """ + self.tabw.setCurrentIndex(1) + self.newLinkDock.show() + + def slotShowConnector(self): + """ + connectionmanager action triggered + let main to the stuff + """ + self.emit(SIGNAL("connector")) + + def slotAddLinks(self, links): + """ + new links + let main to the stuff + """ + self.emit(SIGNAL("addLinks"), links) + + def slotAddPackage(self, name, ids): + """ + new package + let main to the stuff + """ + self.emit(SIGNAL("addPackage"), name, ids) + + def slotShowAddContainer(self): + """ + action from add-menu + show file selector, emit upload + """ + fileNames = QFileDialog.getOpenFileNames(self, "Container Öffnen", "", "All Container Types (*.dlc *.ccf *.rsdf *.txt);;DLC (*.dlc);;CCF (*.ccf);;RSDF (*.rsdf);;Text Files (*.txt)") + for name in fileNames: + self.emit(SIGNAL("addContainer"), str(name)) + + def slotPushPackageToQueue(self): + """ + push collector pack to queue + get child ids + let main to the rest + """ + items = self.tabs["collector"]["package_view"].selectedItems() + for item in items: + try: + item.getFileData() + id = item.parent().getPackData()["id"] + pack = item.parent() + except: + id = item.getPackData()["id"] + pack = item + if id == "fixed": + ids = [] + for child in pack.getChildren(): + ids.append(child.getFileData()["id"]) + self.emit(SIGNAL("addPackage"), "Single Links", ids) + id = self.lastAddedID + self.emit(SIGNAL("pushPackageToQueue"), id) + + def saveWindow(self): + """ + get window state/geometry + pass data to main + """ + state_raw = self.saveState(self.version) + geo_raw = self.saveGeometry() + + state = str(state_raw.toBase64()) + geo = str(geo_raw.toBase64()) + + self.emit(SIGNAL("saveMainWindow"), state, geo) + + def closeEvent(self, event): + """ + somebody wants to close me! + let me first save my state + """ + self.saveWindow() + event.accept() + + def restoreWindow(self, state, geo): + """ + restore window state/geometry + """ + state = QByteArray(state) + geo = QByteArray(geo) + + state_raw = QByteArray.fromBase64(state) + geo_raw = QByteArray.fromBase64(geo) + + self.restoreState(state_raw, self.version) + self.restoreGeometry(geo_raw) + + def slotQueueContextMenu(self, pos): + """ + custom context menu in queue view requested + """ + globalPos = self.tabs["queue"]["view"].mapToGlobal(pos) + i = self.tabs["queue"]["view"].itemAt(pos) + if not i: + return + i.setSelected(True) + self.queueContext.item = (i.data(0, Qt.UserRole).toPyObject(), i.parent() == None) + menuPos = QCursor.pos() + menuPos.setX(menuPos.x()+2) + self.activeMenu = self.queueContext + if hasattr(i, "getPackData"): + self.queueContext.buttons["pull"].setVisible(True) + else: + self.queueContext.buttons["pull"].setVisible(False) + self.queueContext.exec_(menuPos) + + def slotCollectorContextMenu(self, pos): + """ + custom context menu in package collector view requested + """ + globalPos = self.tabs["collector"]["package_view"].mapToGlobal(pos) + i = self.tabs["collector"]["package_view"].itemAt(pos) + if not i: + return + i.setSelected(True) + self.collectorContext.item = (i.data(0, Qt.UserRole).toPyObject(), i.parent() == None) + menuPos = QCursor.pos() + menuPos.setX(menuPos.x()+2) + self.activeMenu = self.collectorContext + if hasattr(i, "getPackData"): + self.collectorContext.buttons["edit"].setVisible(True) + else: + self.collectorContext.buttons["edit"].setVisible(False) + self.collectorContext.exec_(menuPos) + + def slotLinkCollectorContextMenu(self, pos): + """ + custom context menu in link collector view requested + """ + pass + + def slotRestartDownload(self): + """ + restart download action is triggered + """ + id, isTopLevel = self.queueContext.item + if not id == None: + self.emit(SIGNAL("restartDownload"), id, isTopLevel) + + def slotRemoveDownload(self): + """ + remove download action is triggered + """ + id, isTopLevel = self.activeMenu.item + if not id == None: + self.emit(SIGNAL("removeDownload"), id, isTopLevel) + + def slotToggleClipboard(self, status): + """ + check clipboard (toolbar) + """ + self.emit(SIGNAL("setClipboardStatus"), status) + + def slotEditPackage(self): + item = self.tabs["collector"]["package_view"].currentItem() + pid = self.tabs["collector"]["package_view"].currentItem().data(0, Qt.UserRole).toPyObject() + self.emit(SIGNAL("pauseItemUpdate"), pid, True) + self.tabs["collector"]["package_view"].editItem(item, 0) + + def slotCloseItemEditor(self, editor, hint): + pid = self.tabs["collector"]["package_view"].currentItem().data(0, Qt.UserRole).toPyObject() + self.emit(SIGNAL("changePackageName"), pid, editor.text()) + self.emit(SIGNAL("pauseItemUpdate"), pid, False) + + def slotPullOutPackage(self): + """ + pull package out of the queue + """ + id, isTopLevel = self.activeMenu.item + if not id == None: + self.emit(SIGNAL("pullOutPackage"), id, isTopLevel) + diff --git a/module/gui/PWInputWindow.py b/module/gui/PWInputWindow.py new file mode 100644 index 000000000..4fc834c4f --- /dev/null +++ b/module/gui/PWInputWindow.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +""" + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, + or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, see <http://www.gnu.org/licenses/>. + + @author: mkaay +""" + +from PyQt4.QtCore import * +from PyQt4.QtGui import * + +class PWInputWindow(QWidget): + def __init__(self): + QWidget.__init__(self) + self.input = QLineEdit() + self.input.setEchoMode(QLineEdit.Password) + label = QLabel("Password:") + ok = QPushButton("OK") + cancel = QPushButton("Cancel") + grid = QGridLayout() + grid.addWidget(label, 0, 0, 1, 2) + grid.addWidget(self.input, 1, 0, 1, 2) + grid.addWidget(cancel, 2, 0) + grid.addWidget(ok, 2, 1) + self.setLayout(grid) + + self.connect(ok, SIGNAL("clicked()"), self.slotOK) + self.connect(cancel, SIGNAL("clicked()"), self.slotCancel) + self.connect(self.input, SIGNAL("returnPressed()"), self.slotOK) + + def slotOK(self): + self.hide() + self.emit(SIGNAL("ok"), self.input.text()) + + def slotCancel(self): + self.hide() + self.emit(SIGNAL("cancel")) diff --git a/module/gui/PackageDock.py b/module/gui/PackageDock.py new file mode 100644 index 000000000..c81798935 --- /dev/null +++ b/module/gui/PackageDock.py @@ -0,0 +1,76 @@ +# -*- coding: utf-8 -*- +""" + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, + or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, see <http://www.gnu.org/licenses/>. + + @author: mkaay +""" + +from PyQt4.QtCore import * +from PyQt4.QtGui import * + +class NewPackageDock(QDockWidget): + def __init__(self): + QDockWidget.__init__(self, "New Package") + self.setObjectName("New Package Dock") + self.widget = NewPackageWindow(self) + self.setWidget(self.widget) + self.setAllowedAreas(Qt.RightDockWidgetArea|Qt.LeftDockWidgetArea) + self.hide() + + def slotDone(self): + view = self.widget.view + count = view.topLevelItemCount() + ids = [] + for i in range(count): + item = view.topLevelItem(i) + if item: + ids.append(item.data(0, Qt.UserRole).toInt()[0]) + self.emit(SIGNAL("done"), self.widget.nameInput.text(), ids) + view.clear() + self.hide() + +class NewPackageWindow(QWidget): + def __init__(self, dock): + QWidget.__init__(self) + self.dock = dock + self.setLayout(QGridLayout()) + layout = self.layout() + + nameLabel = QLabel("Name") + nameInput = QLineEdit() + + linksLabel = QLabel("Links in this Package") + linkView = QTreeWidget() + linkView.setSelectionBehavior(QAbstractItemView.SelectRows) + linkView.setSelectionMode(QAbstractItemView.ExtendedSelection) + linkView.setColumnCount(1) + linkView.setHeaderLabels(["Name"]) + linkView.setDragEnabled(True) + linkView.setDragDropMode(QAbstractItemView.DragDrop) + linkView.setDropIndicatorShown(True) + linkView.setAcceptDrops(True) + linkView.setDragDropOverwriteMode(True) + + self.view = linkView + self.nameInput = nameInput + + save = QPushButton("Create") + + layout.addWidget(nameLabel, 0, 0) + layout.addWidget(nameInput, 0, 1) + layout.addWidget(linksLabel, 1, 0, 1, 2) + layout.addWidget(linkView, 2, 0, 1, 2) + layout.addWidget(save, 3, 0, 1, 2) + + self.connect(save, SIGNAL("clicked()"), self.dock.slotDone) diff --git a/module/gui/Queue.py b/module/gui/Queue.py new file mode 100644 index 000000000..8681d3bb1 --- /dev/null +++ b/module/gui/Queue.py @@ -0,0 +1,373 @@ +# -*- coding: utf-8 -*- +""" + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, + or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, see <http://www.gnu.org/licenses/>. + + @author: mkaay +""" + +from PyQt4.QtCore import * +from PyQt4.QtGui import * + +from time import sleep, time + +class Queue(QObject): + def __init__(self, view, connector): + QObject.__init__(self) + self.view = view + self.connector = connector + self.statusMap = { + "finished": 0, + "queued": 1, + "checking": 2, + "waiting": 3, + "reconnected": 4, + "starting": 5, + "failed": 6, + "aborted": 7, + "decrypting": 8, + "downloading": 9 + } + self.statusMapReverse = dict((v,k) for k, v in self.statusMap.iteritems()) + self.interval = 1 + self.wait_dict = {} + self.rootItem = self.view.invisibleRootItem() + self.mutex = QMutex() + self.updater = self.QueueUpdater(self.interval) + self.connect(self.updater, SIGNAL("update()"), self.update) + + class QueueUpdater(QThread): + def __init__(self, interval): + QThread.__init__(self) + self.interval = interval + self.running = True + + def run(self): + while self.running: + self.emit(SIGNAL("update()")) + self.sleep(self.interval) + + def start(self): + self.updater.start() + + def wait(self): + self.updater.wait() + + def stop(self): + self.updater.running = False + + def update(self): + locker = QMutexLocker(self.mutex) + packs = self.connector.getPackageQueue() + downloading_raw = self.connector.getDownloadQueue() + downloading = {} + for d in downloading_raw: + did = d["id"] + del d["id"] + del d["name"] + del d["status"] + downloading[did] = d + ids = [] + for data in packs: + ids.append(data["id"]) + self.clear(ids) + for data in packs: + pack = self.getPack(data["id"]) + if not pack: + pack = self.QueuePack(self) + pack.setPackData(data) + files = self.connector.getPackageFiles(data["id"]) + pack.clear(files) + self.addPack(data["id"], pack) + for fid in files: + info = self.connector.getLinkInfo(fid) + child = pack.getChild(fid) + if not child: + child = self.QueueFile(self, pack) + info["downloading"] = None + try: + info["downloading"] = downloading[info["id"]] + except: + pass + if not info["status_type"]: + info["status_type"] = "queued" + child.setFileData(info) + pack.addPackChild(fid, child) + self.addPack(data["id"], pack) + + def addPack(self, pid, newPack): + pos = None + try: + for pack in QueueIterator(self.rootItem): + if pack.getPackData()["id"] == pid: + pos = self.rootItem.indexOfChild(pack) + break + if pos == None: + raise Exception() + item = self.rootItem.child(pos) + item.setPackData(newPack.getPackData()) + except: + self.rootItem.addChild(newPack) + item = newPack + item.setData(0, Qt.DisplayRole, QVariant(item.getPackData()["package_name"])) + status = -1 + speed = self.getSpeed(item) + plugins = [] + for child in item.getChildren(): + data = child.getFileData() + if self.statusMap.has_key(data["status_type"]) and self.statusMap[data["status_type"]] > status: + status = self.statusMap[data["status_type"]] + if not data["plugin"] in plugins: + plugins.append(data["plugin"]) + if status >= 0: + if speed == None or self.statusMapReverse[status] == "starting" or self.statusMapReverse[status] == "decrypting": + statustxt = self.statusMapReverse[status] + else: + statustxt = "%s (%s KB/s)" % (self.statusMapReverse[status], speed) + item.setData(2, Qt.DisplayRole, QVariant(statustxt)) + item.setData(1, Qt.DisplayRole, QVariant(", ".join(plugins))) + item.setData(0, Qt.UserRole, QVariant(pid)) + item.setData(3, Qt.UserRole, QVariant(item)) + + def getPack(self, pid): + for k, pack in enumerate(ItemIterator(self.rootItem)): + if pack.getPackData()["id"] == pid: + return pack + return None + + def clear(self, ids): + clear = False + remove = [] + for k, pack in enumerate(ItemIterator(self.rootItem)): + if not pack.getPackData()["id"] in ids: + clear = True + remove.append(k) + if not clear: + return + remove.sort() + remove.reverse() + for k in remove: + self.rootItem.takeChild(k) + + def getWaitingProgress(self, q): + locker = QMutexLocker(self.mutex) + if isinstance(q, self.QueueFile): + data = q.getFileData() + if data["status_type"] == "waiting" and data["downloading"]: + until = float(data["downloading"]["wait_until"]) + try: + since, until_old = self.wait_dict[data["id"]] + if not until == until_old: + raise Exception + except: + since = time() + self.wait_dict[data["id"]] = since, until + since = float(since) + max_wait = float(until-since) + rest = int(until-time()) + res = 100/max_wait + perc = rest*res + return perc, rest + return None + + def getProgress(self, q): + locker = QMutexLocker(self.mutex) + if isinstance(q, self.QueueFile): + data = q.getFileData() + if data["downloading"]: + return int(data["downloading"]["percent"]) + if data["status_type"] == "finished" or \ + data["status_type"] == "failed" or \ + data["status_type"] == "aborted": + return 100 + elif isinstance(q, self.QueuePack): + children = q.getChildren() + count = len(children) + perc_sum = 0 + for child in children: + val = 0 + data = child.getFileData() + if data["downloading"]: + val = int(data["downloading"]["percent"]) + elif data["status_type"] == "finished" or \ + data["status_type"] == "failed" or \ + data["status_type"] == "aborted": + val = 100 + perc_sum += val + if count == 0: + return 0 + return perc_sum/count + return 0 + + def getSpeed(self, q): + if isinstance(q, self.QueueFile): + data = q.getFileData() + if data["downloading"]: + return int(data["downloading"]["speed"]) + elif isinstance(q, self.QueuePack): + children = q.getChildren() + count = len(children) + speed_sum = 0 + all_waiting = True + running = False + for child in children: + val = 0 + data = child.getFileData() + if data["downloading"]: + if not data["status_type"] == "waiting": + all_waiting = False + val = int(data["downloading"]["speed"]) + running = True + speed_sum += val + if count == 0 or not running or all_waiting: + return None + return speed_sum + return None + + class QueuePack(QTreeWidgetItem): + def __init__(self, queue): + QTreeWidgetItem.__init__(self) + self.queue = queue + self._data = {} + + def addPackChild(self, cid, newChild): + pos = None + try: + for child in ItemIterator(self): + if child.getData()["id"] == cid: + pos = self.indexOfChild(child) + break + if pos == None: + raise Exception() + item = self.child(pos) + item.setFileData(newChild.getFileData()) + except: + self.addChild(newChild) + item = newChild + speed = self.queue.getSpeed(item) + if speed == None or item.getFileData()["status_type"] == "starting" or item.getFileData()["status_type"] == "decrypting": + status = item.getFileData()["status_type"] + else: + status = "%s (%s KB/s)" % (item.getFileData()["status_type"], speed) + item.setData(0, Qt.DisplayRole, QVariant(item.getFileData()["filename"])) + item.setData(2, Qt.DisplayRole, QVariant(status)) + item.setData(1, Qt.DisplayRole, QVariant(item.getFileData()["plugin"])) + item.setData(0, Qt.UserRole, QVariant(cid)) + item.setData(3, Qt.UserRole, QVariant(item)) + + def setPackData(self, data): + self._data = data + + def getPackData(self): + return self._data + + def getChildren(self): + ret = [] + for item in ItemIterator(self): + ret.append(item) + return ret + + def getChild(self, cid): + for item in ItemIterator(self): + if item.getFileData()["id"] == cid: + return item + return None + + def clear(self, ids): + clear = False + remove = [] + children = [] + for k, file in enumerate(self.getChildren()): + if not file.getFileData()["id"] in ids: + remove.append(file.getFileData()["id"]) + if file.getFileData()["id"] in children and not file.getFileData()["id"] in remove: + remove.append(file.getFileData()["id"]) + continue + children.append(file.getFileData()["id"]) + if not remove: + return + remove.sort() + remove.reverse() + for k in remove: + self.takeChild(k) + + class QueueFile(QTreeWidgetItem): + def __init__(self, queue, pack): + QTreeWidgetItem.__init__(self) + self.queue = queue + self.pack = pack + self._data = {} + self.wait_since = None + + def getFileData(self): + return self._data + + def setFileData(self, data): + self._data = data + + def getPack(self): + return self.pack + +class QueueProgressBarDelegate(QItemDelegate): + def __init__(self, parent, queue): + QItemDelegate.__init__(self, parent) + self.queue = queue + + def paint(self, painter, option, index): + if index.column() == 3: + qe = index.data(Qt.UserRole).toPyObject() + w = self.queue.getWaitingProgress(qe) + wait = None + if w: + progress = w[0] + wait = w[1] + else: + progress = self.queue.getProgress(qe) + opts = QStyleOptionProgressBarV2() + opts.maximum = 100 + opts.minimum = 0 + opts.progress = progress + opts.rect = option.rect + opts.rect.setRight(option.rect.right()-1) + opts.rect.setHeight(option.rect.height()-1) + opts.textVisible = True + opts.textAlignment = Qt.AlignCenter + if not wait == None: + opts.text = QString("waiting %d seconds" % (wait,)) + else: + opts.text = QString.number(opts.progress) + "%" + QApplication.style().drawControl(QStyle.CE_ProgressBar, opts, painter) + return + QItemDelegate.paint(self, painter, option, index) + +class ItemIterator(): + def __init__(self, item): + self.item = item + self.current = -1 + + def __iadd__(self, val): + self.current += val + + def value(self): + return self.item.child(self.current) + + def next(self): + self.__iadd__(1) + value = self.value() + if value: + return self.value() + else: + raise StopIteration + + def __iter__(self): + return self diff --git a/module/gui/XMLParser.py b/module/gui/XMLParser.py new file mode 100644 index 000000000..5e3b7bf65 --- /dev/null +++ b/module/gui/XMLParser.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +""" + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, + or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, see <http://www.gnu.org/licenses/>. + + @author: mkaay +""" +from __future__ import with_statement + +from PyQt4.QtCore import * +from PyQt4.QtGui import * +from PyQt4.QtXml import * + +import os + +class XMLParser(): + def __init__(self, data, dfile=""): + self.mutex = QMutex() + self.mutex.lock() + self.xml = QDomDocument() + self.file = data + self.dfile = dfile + self.mutex.unlock() + self.loadData() + self.root = self.xml.documentElement() + + def loadData(self): + self.mutex.lock() + f = self.file + if not os.path.exists(f): + f = self.dfile + with open(f, 'r') as fh: + content = fh.read() + self.xml.setContent(content) + self.mutex.unlock() + + def saveData(self): + self.mutex.lock() + content = self.xml.toString() + with open(self.file, 'w') as fh: + fh.write(content) + self.mutex.unlock() + return content + + def parseNode(self, node, ret_type="list"): + if ret_type == "dict": + childNodes = {} + else: + childNodes = [] + child = node.firstChild() + while True: + n = child.toElement() + if n.isNull(): + break + else: + if ret_type == "dict": + childNodes[str(n.tagName())] = n + else: + childNodes.append(n) + child = child.nextSibling() + return childNodes diff --git a/module/gui/__init__.py b/module/gui/__init__.py new file mode 100644 index 000000000..8d1c8b69c --- /dev/null +++ b/module/gui/__init__.py @@ -0,0 +1 @@ + diff --git a/module/gui/connector.py b/module/gui/connector.py new file mode 100644 index 000000000..432999161 --- /dev/null +++ b/module/gui/connector.py @@ -0,0 +1,424 @@ +# -*- coding: utf-8 -*- +""" + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, + or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, see <http://www.gnu.org/licenses/>. + + @author: mkaay +""" + +SERVER_VERSION = "0.3" + +from time import sleep + +from PyQt4.QtCore import * +from PyQt4.QtGui import * + +from xmlrpclib import ServerProxy + +class connector(QThread): + def __init__(self): + """ + init thread + """ + QThread.__init__(self) + self.mutex = QMutex() + self.running = True + self.proxy = None + self.addr = None + self.errorQueue = [] + self.connect(self, SIGNAL("proxy_error"), self._proxyError) + + def setAddr(self, addr): + """ + set new address + """ + self.mutex.lock() + self.addr = addr + self.mutex.unlock() + + def run(self): + """ + start thread + (called from thread.start()) + """ + self.canConnect() + while self.running: + sleep(1) + self.getError() + + def canConnect(self): + return self.connectProxy(self.addr) + + def stop(self): + """ + stop thread + """ + self.running = False + + def connectProxy(self, addr): + """ + connect to remote server + """ + self.proxy = ServerProxy(addr, allow_none=True) + try: + server_version = self.proxy.get_server_version() + except: + return False + if not server_version == SERVER_VERSION: + self.emit(SIGNAL("error_box"), "server is version %s client accepts version %s" % (server_version, SERVER_VERSION)) + return False + return True + + def _proxyError(self, func, e): + """ + formats proxy error msg + """ + msg = "proxy error in '%s':\n%s" % (func, e) + self.errorQueue.append(msg) + + def getError(self): + self.mutex.lock() + if len(self.errorQueue) > 0: + err = self.errorQueue.pop() + print err + self.emit(SIGNAL("error_box"), err) + self.mutex.unlock() + + def getLinkCollector(self): + """ + grab links from collector and return the ids + """ + self.mutex.lock() + try: + return self.proxy.get_collector_files() + except Exception, e: + self.emit(SIGNAL("proxy_error"), "getLinkCollector", e) + finally: + self.mutex.unlock() + + def getPackageCollector(self): + """ + grab packages from collector and return the data + """ + self.mutex.lock() + try: + return self.proxy.get_collector_packages() + except Exception, e: + self.emit(SIGNAL("proxy_error"), "getPackageCollector", e) + finally: + self.mutex.unlock() + + def getLinkInfo(self, id): + """ + grab file info for the given id and return it + """ + self.mutex.lock() + try: + return self.proxy.get_file_info(id) + except Exception, e: + self.emit(SIGNAL("proxy_error"), "getLinkInfo", e) + finally: + self.mutex.unlock() + + def getPackageInfo(self, id): + """ + grab package info for the given id and return it + """ + self.mutex.lock() + try: + return self.proxy.get_package_data(id) + except Exception, e: + self.emit(SIGNAL("proxy_error"), "getPackageInfo", e) + finally: + self.mutex.unlock() + + def getPackageQueue(self): + """ + grab queue return the data + """ + self.mutex.lock() + try: + return self.proxy.get_queue() + except Exception, e: + self.emit(SIGNAL("proxy_error"), "getPackageQueue", e) + finally: + self.mutex.unlock() + + def getPackageFiles(self, id): + """ + grab package files and return ids + """ + self.mutex.lock() + try: + return self.proxy.get_package_files(id) + except Exception, e: + self.emit(SIGNAL("proxy_error"), "getPackageFiles", e) + finally: + self.mutex.unlock() + + def getDownloadQueue(self): + """ + grab files that are currently downloading and return info + """ + self.mutex.lock() + try: + return self.proxy.status_downloads() + except Exception, e: + self.emit(SIGNAL("proxy_error"), "getDownloadQueue", e) + finally: + self.mutex.unlock() + + def getServerStatus(self): + """ + return server status + """ + self.mutex.lock() + try: + return self.proxy.status_server() + except Exception, e: + self.emit(SIGNAL("proxy_error"), "getServerStatus", e) + finally: + self.mutex.unlock() + + def addURLs(self, links): + """ + add links to collector + """ + self.mutex.lock() + try: + self.proxy.add_urls(links) + except Exception, e: + self.emit(SIGNAL("proxy_error"), "addURLs", e) + finally: + self.mutex.unlock() + + def togglePause(self): + """ + toogle pause + """ + self.mutex.lock() + try: + return self.proxy.toggle_pause() + except Exception, e: + self.emit(SIGNAL("proxy_error"), "togglePause", e) + finally: + self.mutex.unlock() + + def setPause(self, pause): + """ + set pause + """ + self.mutex.lock() + try: + if pause: + self.proxy.pause_server() + else: + self.proxy.unpause_server() + except Exception, e: + self.emit(SIGNAL("proxy_error"), "setPause", e) + finally: + self.mutex.unlock() + + def newPackage(self, name): + """ + create a new package and return id + """ + self.mutex.lock() + try: + return self.proxy.new_package(name) + except Exception, e: + self.emit(SIGNAL("proxy_error"), "newPackage", e) + finally: + self.mutex.unlock() + + def addFileToPackage(self, fileid, packid): + """ + add a file from collector to package + """ + self.mutex.lock() + try: + self.proxy.move_file_2_package(fileid, packid) + except Exception, e: + self.emit(SIGNAL("proxy_error"), "addFileToPackage", e) + finally: + self.mutex.unlock() + + def pushPackageToQueue(self, packid): + """ + push a package to queue + """ + self.mutex.lock() + try: + self.proxy.push_package_2_queue(packid) + except Exception, e: + self.emit(SIGNAL("proxy_error"), "pushPackageToQueue", e) + finally: + self.mutex.unlock() + + def restartPackage(self, packid): + """ + restart a package + """ + self.mutex.lock() + try: + self.proxy.restart_package(packid) + except Exception, e: + self.emit(SIGNAL("proxy_error"), "restartPackage", e) + finally: + self.mutex.unlock() + + def restartFile(self, fileid): + """ + restart a file + """ + self.mutex.lock() + try: + self.proxy.restart_file(fileid) + except Exception, e: + self.emit(SIGNAL("proxy_error"), "restartFile", e) + finally: + self.mutex.unlock() + + def removePackage(self, packid): + """ + remove a package + """ + self.mutex.lock() + try: + self.proxy.del_packages([packid,]) + except Exception, e: + self.emit(SIGNAL("proxy_error"), "removePackage", e) + finally: + self.mutex.unlock() + + def removeFile(self, fileid): + """ + remove a file + """ + self.mutex.lock() + try: + self.proxy.del_links([fileid,]) + except Exception, e: + self.emit(SIGNAL("proxy_error"), "removeFile", e) + finally: + self.mutex.unlock() + + def uploadContainer(self, filename, type, content): + """ + upload a container + """ + self.mutex.lock() + try: + self.proxy.upload_container(filename, type, content) + except Exception, e: + self.emit(SIGNAL("proxy_error"), "uploadContainer", e) + finally: + self.mutex.unlock() + + def getLog(self, offset): + """ + get log + """ + self.mutex.lock() + try: + return self.proxy.get_log(offset) + except Exception, e: + self.emit(SIGNAL("proxy_error"), "getLog", e) + finally: + self.mutex.unlock() + + def stopAllDownloads(self): + """ + get log + """ + self.mutex.lock() + try: + self.proxy.pause_server() + self.proxy.stop_downloads() + except Exception, e: + self.emit(SIGNAL("proxy_error"), "stopAllDownloads", e) + finally: + self.mutex.unlock() + + def updateAvailable(self): + """ + update available + """ + self.mutex.lock() + try: + return self.proxy.update_available() + except Exception, e: + self.emit(SIGNAL("proxy_error"), "updateAvailable", e) + finally: + self.mutex.unlock() + + def setPackageName(self, pid, name): + """ + set new package name + """ + self.mutex.lock() + try: + return self.proxy.set_package_name(pid, name) + except Exception, e: + self.emit(SIGNAL("proxy_error"), "setPackageName", e) + finally: + self.mutex.unlock() + + def pullOutPackage(self, pid): + """ + pull out package + """ + self.mutex.lock() + try: + return self.proxy.pull_out_package(pid) + except Exception, e: + self.emit(SIGNAL("proxy_error"), "pullOutPackage", e) + finally: + self.mutex.unlock() + + def captchaWaiting(self): + """ + is the a captcha waiting? + """ + self.mutex.lock() + try: + return self.proxy.is_captcha_waiting() + except Exception, e: + self.emit(SIGNAL("proxy_error"), "captchaWaiting", e) + finally: + self.mutex.unlock() + + def getCaptcha(self): + """ + get captcha + """ + self.mutex.lock() + try: + return self.proxy.get_captcha_task() + except Exception, e: + self.emit(SIGNAL("proxy_error"), "getCaptcha", e) + finally: + self.mutex.unlock() + + def setCaptchaResult(self, cid, result): + """ + get captcha + """ + self.mutex.lock() + try: + return self.proxy.set_captcha_result(cid, result) + except Exception, e: + self.emit(SIGNAL("proxy_error"), "setCaptchaResult", e) + finally: + self.mutex.unlock() + diff --git a/module/network/Keepalive.py b/module/network/Keepalive.py index 2443f5bbf..0ab3431ad 100644 --- a/module/network/Keepalive.py +++ b/module/network/Keepalive.py @@ -609,7 +609,6 @@ def test(url, N=10): test_timeout(url) if __name__ == '__main__': - import time import sys try: N = int(sys.argv[1]) diff --git a/module/network/Request.py b/module/network/Request.py index 9f27af4ec..dfe29e62d 100755 --- a/module/network/Request.py +++ b/module/network/Request.py @@ -5,16 +5,13 @@ """ authored by: RaNaN, Spoob """ -import os import base64 import cookielib from gzip import GzipFile import time -import re from os import sep, rename -from os.path import dirname, exists +from os.path import exists import urllib -from base64 import b64decode from cStringIO import StringIO try: @@ -51,13 +48,28 @@ class Request: self.lastURL = None self.auth = False - self.timeout = 5*3600 - + self.timeout = 5 + + bufferBase = 1024 + bufferMulti = 4 + self.bufferSize = bufferBase*bufferMulti + self.canContinue = False + + self.dl_speed = 0.0 + self.averageSpeed = 0.0 + self.averageSpeeds = [] + self.averageSpeedTime = 0.0 + self.averageSpeedCount = 0.0 + + self.speedLimitActive = False + self.maxSpeed = 0 + self.isSlow = False + try: if pycurl: self.curl = True except: self.curl = False - + if self.curl: self.init_curl() @@ -94,13 +106,14 @@ class Request: self.pycurl = pycurl.Curl() self.pycurl.setopt(pycurl.FOLLOWLOCATION, 1) self.pycurl.setopt(pycurl.MAXREDIRS, 5) - self.pycurl.setopt(pycurl.TIMEOUT, self.timeout) + self.pycurl.setopt(pycurl.TIMEOUT, (self.timeout*3600)) self.pycurl.setopt(pycurl.CONNECTTIMEOUT, 30) self.pycurl.setopt(pycurl.NOSIGNAL, 1) self.pycurl.setopt(pycurl.NOPROGRESS, 0) self.pycurl.setopt(pycurl.PROGRESSFUNCTION, self.progress) self.pycurl.setopt(pycurl.AUTOREFERER, 1) self.pycurl.setopt(pycurl.HEADERFUNCTION, self.write_header) + self.pycurl.setopt(pycurl.BUFFERSIZE, self.bufferSize) self.pycurl.setopt(pycurl.USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.10") @@ -110,7 +123,9 @@ class Request: "Connection: keep-alive", "Keep-Alive: 300"]) - def load(self, url, get={}, post={}, ref=True, cookies=False): + def load(self, url, get={}, post={}, ref=True, cookies=False, just_header=False): + + url = str(url) if post: post = urllib.urlencode(post) @@ -131,22 +146,31 @@ class Request: if cookies: self.curl_enable_cookies() - if post: self.pycurl.setopt(pycurl.POSTFIELDS, post) + if post: + self.pycurl.setopt(pycurl.POSTFIELDS, post) if ref and self.lastURL is not None: self.pycurl.setopt(pycurl.REFERER, self.lastURL) + if just_header: + self.pycurl.setopt(pycurl.NOPROGRESS, 1) + self.pycurl.setopt(pycurl.NOBODY, 1) + self.pycurl.perform() + self.lastEffectiveURL = self.pycurl.getinfo(pycurl.EFFECTIVE_URL) + self.pycurl.setopt(pycurl.NOPROGRESS, 0) + self.pycurl.setopt(pycurl.NOBODY, 0) + return self.header self.pycurl.perform() - + self.lastEffectiveURL = self.pycurl.getinfo(pycurl.EFFECTIVE_URL) self.lastURL = url header = self.get_header() return self.get_rep() - else: + req = urllib2.Request(url, data=post) if ref and self.lastURL is not None: @@ -160,8 +184,9 @@ class Request: for cookie in self.cj.make_cookies(rep, req): self.cookies.append(cookie) - - output = rep.read() + + if not just_header: + output = rep.read() if rep.headers.has_key("content-encoding"): if rep.headers["content-encoding"] == "gzip": @@ -169,6 +194,9 @@ class Request: self.lastEffectiveURL = rep.geturl() self.lastURL = url + + if just_header: + return rep.headers return output @@ -182,13 +210,14 @@ class Request: self.auth = True self.user = user self.pw = pw - + + upwstr = str("%s:%s" % (user,pw)) if self.curl: - self.pycurl.setopt(pycurl.HTTPHEADER, ['Authorization: Basic ' + base64.encodestring(user + ':' + pw)[:-1]]) - self.pycurl.setopt(pycurl.USERPWD, user + ":" + pw) + self.pycurl.setopt(pycurl.HTTPHEADER, ['Authorization: Basic ' + base64.encodestring(upwstr)[:-1]]) + self.pycurl.setopt(pycurl.USERPWD, upwstr) self.pycurl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_ANY) else: - self.downloader.addheaders.append(['Authorization', 'Basic ' + base64.encodestring(user + ':' + pw)[:-1]]) + self.downloader.addheaders.append(['Authorization', 'Basic ' + base64.encodestring(upwstr)[:-1]]) def add_cookies(self, req): cookie_head = "" @@ -215,7 +244,9 @@ class Request: self.opener.add_handler(handler) self.downloader.add_handler(handler) - def download(self, url, file_name, folder="", get={}, post={}, ref=True, cookies=False): + def download(self, url, file_name, get={}, post={}, ref=True, cookies=False): + + url = str(url) if post: post = urllib.urlencode(post) @@ -229,19 +260,21 @@ class Request: get = "" if self.curl: - - file_temp = file_name + ".part" - fp = open(file_temp, 'wb') + file_temp = self.get_free_name(file_name) + ".part" + self.fp = open(file_temp, 'wb') + if not self.canContinue: + self.fp.truncate() + partSize = self.fp.tell() self.init_curl() self.pycurl.setopt(pycurl.URL, url) - self.pycurl.setopt(pycurl.WRITEDATA, fp) if cookies: self.curl_enable_cookies() - if post: self.pycurl.setopt(pycurl.POSTFIELDS, post) + if post: + self.pycurl.setopt(pycurl.POSTFIELDS, post) if self.auth: self.add_auth(self.user, self.pw) @@ -252,37 +285,61 @@ class Request: self.dl_arrived = 0 self.dl_time = time.time() self.dl = True - - self.pycurl.perform() - if "..." in file_name: - download_folder = dirname(file_name) + sep - headers = self.get_header() - file_name_search = re.search('filename=(?P<quote>\")?(.+)(?(quote)\")', headers) - if file_name_search: - file_name = file_name_search.group(2) - if "?=" in file_name[-3:]: - file_name = file_name.replace("=?UTF-8?B?", "").replace("?=", "==") - file_name = b64decode(file_name) - file_name = download_folder + sep + file_name - - file_count = 0 - while exists(file_name): - file_count += 1 - if "." in file_name: - file_split = file_name.split(".") - temp_name = "%s-%i.%s" % (".".join(file_split[:-1]), file_count, file_split[-1]) + + self.chunkSize = 0 + self.chunkRead = 0 + self.subStartTime = 0 + self.maxChunkSize = 0 + + def restLimit(): + subTime = time.time() - self.subStartTime + if subTime <= 1: + if self.speedLimitActive: + return self.maxChunkSize + else: + return -1 else: - temp_name = "%s-%i" % (file_name, file_count) - if not exists(temp_name): - file_name = temp_name + self.updateCurrentSpeed(float(self.chunkRead/1024) / subTime) - rename(file_temp, file_name) - + self.subStartTime = time.time() + self.chunkRead = 0 + if self.maxSpeed > 0: + self.maxChunkSize = self.maxSpeed + else: + self.maxChunkSize = 0 + return 0 + + def writefunc(buf): + if self.abort: + return False + chunkSize = len(buf) + while chunkSize > restLimit() > -1: + time.sleep(0.05) + self.maxChunkSize -= chunkSize + self.fp.write(buf) + self.chunkRead += chunkSize + self.dl_arrived += chunkSize + + + self.pycurl.setopt(pycurl.WRITEFUNCTION, writefunc) + + try: + self.pycurl.perform() + except Exception, e: + code, msg = e + if not code == 23: + raise Exception, e + + self.fp.close() + + if self.abort: + raise AbortDownload + + rename(file_temp, self.get_free_name(file_name)) + self.dl = False self.dl_finished = time.time() - fp.close() - return True else: @@ -299,10 +356,15 @@ class Request: for cookie in self.cj.make_cookies(rep, req): self.cookies.append(cookie) - + + self.dl = False if not self.dl: self.dl = True - file = open(file_name, 'wb') + file_temp = self.get_free_name(file_name) + ".part" + file = open(file_temp, 'wb') + if not self.canContinue: + file.truncate() + partSize = file.tell() conn = self.downloader.open(req, post) if conn.headers.has_key("content-length"): @@ -311,16 +373,56 @@ class Request: self.dl_size = 0 self.dl_arrived = 0 self.dl_time = time.time() - for chunk in conn: - if self.abort: raise AbortDownload - self.dl_arrived += len(chunk) - file.write(chunk) + + chunkSize = 1 + while chunkSize > 0: + if self.abort: + break + chunkRead = 0 + if not self.speedLimitActive: + maxChunkSize = -1 + elif self.maxSpeed > 0: + maxChunkSize = self.maxSpeed + else: + maxChunkSize = 0 + subStartTime = time.time() + while (time.time() - subStartTime) <= 1: + if maxChunkSize == -1 or chunkRead <= maxChunkSize: + chunk = conn.read(self.bufferSize) + chunkSize = len(chunk) + file.write(chunk) + self.dl_arrived += chunkSize + chunkRead += chunkSize + else: + time.sleep(0.05) + subTime = time.time() - subStartTime + self.updateCurrentSpeed(float(chunkRead/1024) / subTime) file.close() + if self.abort: + raise AbortDownload self.dl = False self.dl_finished = time.time() + rename(file_temp, self.get_free_name(file_name)) return True - + + def updateCurrentSpeed(self, speed): + self.dl_speed = speed + if self.averageSpeedTime + 10 < time.time(): + self.averageSpeeds = [] + self.averageSpeeds.append(self.averageSpeed) + self.averageSpeeds.append(speed) + self.averageSpeed = (speed + self.averageSpeed)/2 + self.averageSpeedTime = time.time() + self.averageSpeedCount = 2 + else: + self.averageSpeeds.append(speed) + self.averageSpeedCount += 1 + allspeed = 0.0 + for s in self.averageSpeeds: + allspeed += s + self.averageSpeed = allspeed / self.averageSpeedCount + def write_header(self, string): self.header += string @@ -337,7 +439,7 @@ class Request: def get_speed(self): try: - return (self.dl_arrived / ((time.time() if self.dl else self.dl_finished) - self.dl_time)) / 1024 + return self.dl_speed except: return 0 @@ -351,10 +453,24 @@ class Request: return (self.dl_size - self.dl_arrived) / 1024 def progress(self, dl_t, dl_d, up_t, up_d): - if self.abort: raise AbortDownload + if self.abort: + return False self.dl_arrived = int(dl_d) self.dl_size = int(dl_t) + def get_free_name(self, file_name): + file_count = 0 + while exists(file_name): + file_count += 1 + if "." in file_name: + file_split = file_name.split(".") + temp_name = "%s-%i.%s" % (".".join(file_split[:-1]), file_count, file_split[-1]) + else: + temp_name = "%s-%i" % (file_name, file_count) + if not exists(temp_name): + file_name = temp_name + return file_name + if __name__ == "__main__": import doctest doctest.testmod() diff --git a/module/plugins/BluehostTo.py b/module/plugins/BluehostTo.py deleted file mode 100644 index eff8ebcd8..000000000 --- a/module/plugins/BluehostTo.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -import re -import time - -from module.Plugin import Plugin - -class BluehostTo(Plugin): - - def __init__(self, parent): - Plugin.__init__(self, parent) - props = {} - props['name'] = "BluehostTo" - props['type'] = "hoster" - props['pattern'] = r"http://(?:www.)?bluehost.to/file/" - props['version'] = "0.1" - props['description'] = """Bluehost Download PLugin""" - props['author_name'] = ("RaNaN") - props['author_mail'] = ("RaNaN@pyload.org") - self.props = props - self.parent = parent - self.html = None - self.multi_dl = False - - def download_html(self): - url = self.parent.url - self.html = self.req.load(url) - time.sleep(1.5) - self.html = self.req.load(url, cookies=True) - - def get_file_url(self): - """ returns the absolute downloadable filepath - """ - if self.html == None: - self.download_html() - - inputs = re.findall(r"(<(input|form)[^>]+)", self.html) - for i in inputs: - if re.search(r"name=\"BluehostVers2dl\"",i[0]): - self.BluehostVers2dl = re.search(r"value=\"([^\"]+)", i[0]).group(1) - elif re.search(r"name=\"PHPSESSID\"",i[0]): - self.PHPSESSID = re.search(r"value=\"([^\"]+)", i[0]).group(1) - elif re.search(r"name=\"DownloadV2Hash\"",i[0]): - self.DownloadV2Hash = re.search(r"value=\"([^\"]+)", i[0]).group(1) - elif re.search(r"name=\"access\"",i[0]): - self.access = re.search(r"value=\"([^\"]+)", i[0]).group(1) - elif re.search(r"name=\"download\"",i[0]): - url = re.search(r"action=\"([^\"]+)", i[0]).group(1) - - return url - - def get_file_name(self): - if self.html == None: - self.download_html() - file_name_pattern = r"<center><b>.+: (.+)<\/b><\/center>" - return re.search(file_name_pattern, self.html).group(1) - - def file_exists(self): - """ returns True or False - """ - if self.html == None: - self.download_html() - - if re.search(r"html", self.html) == None: - return False - else: - return True - - def proceed(self, url, location): - self.req.download(url, location, {'BluehostVers2dl': self.BluehostVers2dl, 'DownloadV2Hash': self.DownloadV2Hash, 'PHPSESSID': self.PHPSESSID, 'access': self.access}) diff --git a/module/plugins/DLC.pyc b/module/plugins/DLC.pyc Binary files differdeleted file mode 100644 index 980dd8ace..000000000 --- a/module/plugins/DLC.pyc +++ /dev/null diff --git a/module/plugins/Hook.py b/module/plugins/Hook.py new file mode 100644 index 000000000..541d0c2e9 --- /dev/null +++ b/module/plugins/Hook.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- + +""" + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, + or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, see <http://www.gnu.org/licenses/>. + + @author: mkaay + @interface-version: 0.1 +""" + +import logging + + +class Hook(): + def __init__(self, core): + self.logger = logging.getLogger("log") + self.configParser = core.parser_plugins + self.config = {} + props = {} + props['name'] = "Hook" + props['version'] = "0.1" + props['description'] = """interface for hook""" + props['author_name'] = ("mkaay") + props['author_mail'] = ("mkaay@mkaay.de") + self.props = props + self.core = core + + def readConfig(self): + self.configParser.loadData() + section = self.props['name'] + try: + self.config = self.configParser.getConfig()[section] + except: + self.setup() + + def setup(self): + self.configParser.set(self.props["name"], {"option": "activated", "type": "bool", "name": "Activated"}, True) + self.readConfig() + + def isActivated(self): + return self.config["activated"] + + def downloadStarts(self, pyfile): + pass + + def downloadFinished(self, pyfile): + pass + + def packageFinished(self, pypack): + """ + not implemented! + """ + pass + + def beforeReconnecting(self, ip): + pass + + def afterReconnecting(self, ip): + pass diff --git a/module/plugins/MyvideoDe.py b/module/plugins/MyvideoDe.py deleted file mode 100644 index 5e2eb0b39..000000000 --- a/module/plugins/MyvideoDe.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -import re -from module.Plugin import Plugin - -class MyvideoDe(Plugin): - - def __init__(self, parent): - Plugin.__init__(self, parent) - props = {} - props['name'] = "MyvideoDe" - props['type'] = "hoster" - props['pattern'] = r"http://(www\.)?myvideo.de/watch/" - props['version'] = "0.1" - props['description'] = """Youtube.com Video Download Plugin""" - props['author_name'] = ("spoob") - props['author_mail'] = ("spoob@pyload.org") - self.props = props - self.parent = parent - self.html = None - self.html_old = None #time() where loaded the HTML - self.time_plus_wait = None #time() + wait in seconds - - def set_parent_status(self): - """ sets all available Statusinfos about a File in self.parent.status - """ - if self.html == None: - self.download_html() - self.parent.status.filename = self.get_file_name() - self.parent.status.url = self.get_file_url() - self.parent.status.wait = self.wait_until() - - def download_html(self): - url = self.parent.url - self.html = self.req.load(url) - - def get_file_url(self): - """ returns the absolute downloadable filepath - """ - if self.html == None: - self.download_html() - videoId = re.search(r"addVariable\('_videoid','(.*)'\);p.addParam\('quality'", self.html).group(1) - videoServer = re.search("rel='image_src' href='(.*)thumbs/.*' />", self.html).group(1) - file_url = videoServer + videoId + ".flv" - print videoId - print videoServer - print file_url - return file_url - - def get_file_name(self): - if self.html == None: - self.download_html() - file_name_pattern = r"<h1 class='globalHd'>(.*)</h1>" - return re.search(file_name_pattern, self.html).group(1).replace("/", "") + '.flv' - - def file_exists(self): - """ returns True or False - """ - if self.html == None: - self.download_html() - if re.search(r"(.* Das angeforderte Video ist nicht.*)", self.html) != None: - return False - else: - return True diff --git a/module/plugins/RSDF.py b/module/plugins/RSDF.py deleted file mode 100644 index 50fca9b1f..000000000 --- a/module/plugins/RSDF.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -import base64 -import binascii - -from module.Plugin import Plugin - -class RSDF(Plugin): - - def __init__(self, parent): - Plugin.__init__(self, parent) - props = {} - props['name'] = "RSDF" - props['type'] = "container" - props['pattern'] = r".*\.rsdf" - props['version'] = "0.2" - props['description'] = """RSDF Container Decode Plugin""" - props['author_name'] = ("RaNaN", "spoob") - props['author_mail'] = ("RaNaN@pyload.org", "spoob@pyload.org") - self.props = props - self.parent = parent - self.multi_dl = True - self.links = [] - - def file_exists(self): - """ returns True or False - """ - return True - - def proceed(self, url, location): - try: - from Crypto.Cipher import AES - - infile = url.replace("\n", "") - Key = binascii.unhexlify('8C35192D964DC3182C6F84F3252239EB4A320D2500000000') - - IV = binascii.unhexlify('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF') - IV_Cipher = AES.new(Key, AES.MODE_ECB) - IV = IV_Cipher.encrypt(IV) - - obj = AES.new(Key, AES.MODE_CFB, IV) - - rsdf = open(infile, 'r') - - data = rsdf.read() - data = binascii.unhexlify(''.join(data.split())) - data = data.splitlines() - - for link in data: - link = base64.b64decode(link) - link = obj.decrypt(link) - decryptedUrl = link.replace('CCF: ', '') - self.links.append(decryptedUrl) - - rsdf.close() - - except: - print "Kein Crypto installiert, RSDF Plugin kann nicht genutzt werden" diff --git a/module/plugins/__init__.py b/module/plugins/__init__.py index 8d1c8b69c..e69de29bb 100644 --- a/module/plugins/__init__.py +++ b/module/plugins/__init__.py @@ -1 +0,0 @@ - diff --git a/module/captcha/GigasizeCom.py b/module/plugins/captcha/GigasizeCom.py index 136092181..136092181 100644 --- a/module/captcha/GigasizeCom.py +++ b/module/plugins/captcha/GigasizeCom.py diff --git a/module/plugins/captcha/LinksaveIn.py b/module/plugins/captcha/LinksaveIn.py new file mode 100644 index 000000000..d6f61e362 --- /dev/null +++ b/module/plugins/captcha/LinksaveIn.py @@ -0,0 +1,161 @@ +from captcha import OCR +import Image +from os import sep +from os.path import dirname +from os.path import abspath +from glob import glob +import tempfile + + +class LinksaveIn(OCR): + def __init__(self): + OCR.__init__(self) + self.data_dir = dirname(abspath(__file__)) + sep + "LinksaveIn" + sep + + def load_image(self, image): + im = Image.open(image) + frame_nr = 0 + + lut = im.resize((256, 1)) + lut.putdata(range(256)) + lut = list(lut.convert("RGB").getdata()) + + new = Image.new("RGB", im.size) + npix = new.load() + while True: + try: + im.seek(frame_nr) + except EOFError: + break + frame = im.copy() + pix = frame.load() + for x in range(frame.size[0]): + for y in range(frame.size[1]): + if lut[pix[x, y]] != (0,0,0): + npix[x, y] = lut[pix[x, y]] + frame_nr += 1 + new.save(self.data_dir+"unblacked.png") + self.image = new.copy() + self.pixels = self.image.load() + self.result_captcha = '' + + def get_bg(self): + stat = {} + cstat = {} + img = self.image.convert("P") + for bgpath in glob(self.data_dir+"bg/*.gif"): + stat[bgpath] = 0 + bg = Image.open(bgpath) + + bglut = bg.resize((256, 1)) + bglut.putdata(range(256)) + bglut = list(bglut.convert("RGB").getdata()) + + lut = img.resize((256, 1)) + lut.putdata(range(256)) + lut = list(lut.convert("RGB").getdata()) + + bgpix = bg.load() + pix = img.load() + for x in range(bg.size[0]): + for y in range(bg.size[1]): + rgb_bg = bglut[bgpix[x, y]] + rgb_c = lut[pix[x, y]] + try: + cstat[rgb_c] += 1 + except: + cstat[rgb_c] = 1 + if rgb_bg == rgb_c: + stat[bgpath] += 1 + max_p = 0 + bg = "" + for bgpath, value in stat.items(): + if max_p < value: + bg = bgpath + max_p = value + return bg + + def substract_bg(self, bgpath): + bg = Image.open(bgpath) + img = self.image.convert("P") + + bglut = bg.resize((256, 1)) + bglut.putdata(range(256)) + bglut = list(bglut.convert("RGB").getdata()) + + lut = img.resize((256, 1)) + lut.putdata(range(256)) + lut = list(lut.convert("RGB").getdata()) + + bgpix = bg.load() + pix = img.load() + orgpix = self.image.load() + for x in range(bg.size[0]): + for y in range(bg.size[1]): + rgb_bg = bglut[bgpix[x, y]] + rgb_c = lut[pix[x, y]] + if rgb_c == rgb_bg: + orgpix[x, y] = (255,255,255) + + def eval_black_white(self): + new = Image.new("RGB", (140, 75)) + pix = new.load() + orgpix = self.image.load() + thresh = 4 + for x in range(new.size[0]): + for y in range(new.size[1]): + rgb = orgpix[x, y] + r, g, b = rgb + pix[x, y] = (255,255,255) + if r > max(b, g)+thresh: + pix[x, y] = (0,0,0) + if g < min(r, b): + pix[x, y] = (0,0,0) + if g > max(r, b)+thresh: + pix[x, y] = (0,0,0) + if b > max(r, g)+thresh: + pix[x, y] = (0,0,0) + self.image = new + self.pixels = self.image.load() + + def run_tesser(self): + self.logger.debug("create tmp tif") + tmp = tempfile.NamedTemporaryFile(suffix=".tif") + self.logger.debug("create tmp txt") + tmpTxt = tempfile.NamedTemporaryFile(suffix=".txt") + self.logger.debug("save tiff") + self.image.save(tmp.name, 'TIFF') + self.logger.debug("run tesseract") + self.run(['tesseract', tmp.name, tmpTxt.name.replace(".txt", ""), "nobatch", self.data_dir+"tesser_conf"]) + self.logger.debug("read txt") + + with open(tmpTxt.name, 'r') as f: + self.result_captcha = f.read().replace("\n", "") + + def get_captcha(self, image): + self.load_image(image) + bg = self.get_bg() + self.substract_bg(bg) + self.eval_black_white() + self.to_greyscale() + self.image.save(self.data_dir+"cleaned_pass1.png") + self.clean(4) + self.clean(4) + self.image.save(self.data_dir+"cleaned_pass2.png") + letters = self.split_captcha_letters() + final = "" + for n, letter in enumerate(letters): + self.image = letter + self.image.save(ocr.data_dir+"letter%d.png" % n) + self.run_tesser() + final += self.result_captcha + + return final + +if __name__ == '__main__': + import urllib + ocr = LinksaveIn() + testurl = "http://linksave.in/captcha/cap.php?hsh=2229185&code=ZzHdhl3UffV3lXTH5U4b7nShXj%2Bwma1vyoNBcbc6lcc%3D" + urllib.urlretrieve(testurl, ocr.data_dir+"captcha.gif") + + print ocr.get_captcha(ocr.data_dir+'captcha.gif') diff --git a/module/captcha/MegauploadCom.py b/module/plugins/captcha/MegauploadCom.py index 40939c792..374bcd678 100644 --- a/module/captcha/MegauploadCom.py +++ b/module/plugins/captcha/MegauploadCom.py @@ -6,7 +6,6 @@ class MegauploadCom(OCR): def get_captcha(self, image): self.load_image(image) - self.threshold(2.8) self.run_tesser() return self.result_captcha diff --git a/module/captcha/NetloadIn.py b/module/plugins/captcha/NetloadIn.py index 9799a6a2b..9799a6a2b 100644 --- a/module/captcha/NetloadIn.py +++ b/module/plugins/captcha/NetloadIn.py diff --git a/module/captcha/ShareonlineBiz.py b/module/plugins/captcha/ShareonlineBiz.py index 91124f181..91124f181 100644 --- a/module/captcha/ShareonlineBiz.py +++ b/module/plugins/captcha/ShareonlineBiz.py diff --git a/module/captcha/__init__.py b/module/plugins/captcha/__init__.py index e69de29bb..e69de29bb 100644 --- a/module/captcha/__init__.py +++ b/module/plugins/captcha/__init__.py diff --git a/module/captcha/captcha.py b/module/plugins/captcha/captcha.py index 283b171e0..283b171e0 100644 --- a/module/captcha/captcha.py +++ b/module/plugins/captcha/captcha.py diff --git a/module/plugins/CCF.py b/module/plugins/container/CCF.py index ba5b1c77d..88b567904 100644 --- a/module/plugins/CCF.py +++ b/module/plugins/container/CCF.py @@ -17,7 +17,7 @@ class CCF(Plugin): props = {} props['name'] = "CCF" props['type'] = "container" - props['pattern'] = r".*\.ccf" + props['pattern'] = r"(?!http://).*\.ccf" props['version'] = "0.1" props['description'] = """CCF Container Convert Plugin""" props['author_name'] = ("Willnix") @@ -27,11 +27,6 @@ class CCF(Plugin): self.multi_dl = True self.links = [] - def file_exists(self): - """ returns True or False - """ - return True - def proceed(self, url, location): infile = url.replace("\n", "") diff --git a/module/plugins/container/DLC.pyc b/module/plugins/container/DLC.pyc Binary files differnew file mode 100644 index 000000000..14d5d39a4 --- /dev/null +++ b/module/plugins/container/DLC.pyc diff --git a/module/plugins/container/LinkList.py b/module/plugins/container/LinkList.py new file mode 100644 index 000000000..92508ce29 --- /dev/null +++ b/module/plugins/container/LinkList.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + + +from module.Plugin import Plugin + +class LinkList(Plugin): + + def __init__(self, parent): + Plugin.__init__(self, parent) + props = {} + props['name'] = "LinkList" + props['type'] = "container" + props['pattern'] = r"(?!http://).*\.txt" + props['version'] = "0.1" + props['description'] = """Read Link Lists in txt format""" + props['author_name'] = ("Spoob") + props['author_mail'] = ("spoob@pyload.org") + self.props = props + self.parent = parent + self.html = None + self.read_config() + + def proceed(self, linkList, location): + tmpLinks = [] + txt = open(linkList, 'r') + links = txt.readlines() + for link in links: + if link != "\n": + tmpLinks.append(link.replace("\n", "")) + txt.close() + + if not self.parent.core.config['general']['debug_mode']: + txt = open(linkList, 'w') + txt.write("") + txt.close() + #@TODO: maybe delete read txt file? + + self.links = tmpLinks diff --git a/module/plugins/container/RSDF.py b/module/plugins/container/RSDF.py new file mode 100644 index 000000000..0b6a63722 --- /dev/null +++ b/module/plugins/container/RSDF.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import base64 +import binascii + +from module.Plugin import Plugin + +class RSDF(Plugin): + + def __init__(self, parent): + Plugin.__init__(self, parent) + props = {} + props['name'] = "RSDF" + props['type'] = "container" + props['pattern'] = r"(?!http://).*\.rsdf" + props['version'] = "0.2" + props['description'] = """RSDF Container Decode Plugin""" + props['author_name'] = ("RaNaN", "spoob") + props['author_mail'] = ("RaNaN@pyload.org", "spoob@pyload.org") + self.props = props + self.parent = parent + self.multi_dl = True + self.links = [] + + def proceed(self, url, location): + from Crypto.Cipher import AES + + infile = url.replace("\n", "") + Key = binascii.unhexlify('8C35192D964DC3182C6F84F3252239EB4A320D2500000000') + + IV = binascii.unhexlify('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF') + IV_Cipher = AES.new(Key, AES.MODE_ECB) + IV = IV_Cipher.encrypt(IV) + + obj = AES.new(Key, AES.MODE_CFB, IV) + + rsdf = open(infile, 'r') + + data = rsdf.read() + data = binascii.unhexlify(''.join(data.split())) + data = data.splitlines() + + for link in data: + link = base64.b64decode(link) + link = obj.decrypt(link) + decryptedUrl = link.replace('CCF: ', '') + self.links.append(decryptedUrl) + + rsdf.close() diff --git a/module/plugins/container/__init__.py b/module/plugins/container/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/module/plugins/container/__init__.py diff --git a/module/plugins/DDLMusicOrg.py b/module/plugins/decrypter/DDLMusicOrg.py index e34e6fbde..c927d261c 100644 --- a/module/plugins/DDLMusicOrg.py +++ b/module/plugins/decrypter/DDLMusicOrg.py @@ -21,6 +21,7 @@ class DDLMusicOrg(Plugin): self.props = props self.parent = parent self.html = None + self.multi_dl = False def download_html(self): url = self.parent.url @@ -29,7 +30,8 @@ class DDLMusicOrg(Plugin): def file_exists(self): """ returns True or False """ - self.download_html() + if not self.html: + self.download_html() if re.search(r"Wer dies nicht rechnen kann", self.html) != None: return True return False @@ -48,7 +50,7 @@ class DDLMusicOrg(Plugin): else: solve = int(math.group(1)) - int(math.group(3)) sleep(3) - htmlwithlink = self.req.load("http://ddl-music.org%s" % posturl, cookies=True, post={"calc0":solve, "send0":"Send", "id":id, "linknr":linknr}) + htmlwithlink = self.req.load("http://ddl-music.org%s" % posturl, cookies=True, post={"calc%s" % linknr:solve, "send%s" % linknr:"Send", "id":id, "linknr":linknr}) m = re.search(r"<form id=\"ff\" action=\"(.*?)\" method=\"post\">", htmlwithlink) if m: self.links = [m.group(1)] diff --git a/module/plugins/FourChanOrg.py b/module/plugins/decrypter/FourChanOrg.py index e3b00c1f7..e3b00c1f7 100644 --- a/module/plugins/FourChanOrg.py +++ b/module/plugins/decrypter/FourChanOrg.py diff --git a/module/plugins/HoerbuchIn.py b/module/plugins/decrypter/HoerbuchIn.py index ae7ae9774..2c3fd4123 100644 --- a/module/plugins/HoerbuchIn.py +++ b/module/plugins/decrypter/HoerbuchIn.py @@ -12,8 +12,8 @@ class HoerbuchIn(Plugin): props = {} props['name'] = "HoerbuchIn" props['type'] = "container" - props['pattern'] = r"http://(www\.)?hoerbuch\.in/blog\.php\?id=" - props['version'] = "0.3" + props['pattern'] = r"http://(www\.)?hoerbuch\.in/(blog\.php\?id=|download_(.*)\.html)" + props['version'] = "0.4" props['description'] = """Hoerbuch.in Container Plugin""" props['author_name'] = ("spoob") props['author_mail'] = ("spoob@pyload.org") diff --git a/module/plugins/LixIn.py b/module/plugins/decrypter/LixIn.py index d7ef6521d..d7ef6521d 100644 --- a/module/plugins/LixIn.py +++ b/module/plugins/decrypter/LixIn.py diff --git a/module/plugins/OneKhDe.py b/module/plugins/decrypter/OneKhDe.py index 5f24b543a..5f24b543a 100644 --- a/module/plugins/OneKhDe.py +++ b/module/plugins/decrypter/OneKhDe.py diff --git a/module/plugins/RSLayerCom.py b/module/plugins/decrypter/RSLayerCom.py index 20cadbe18..20cadbe18 100644 --- a/module/plugins/RSLayerCom.py +++ b/module/plugins/decrypter/RSLayerCom.py diff --git a/module/plugins/RelinkUs.py b/module/plugins/decrypter/RelinkUs.py index 786733558..71b441116 100644 --- a/module/plugins/RelinkUs.py +++ b/module/plugins/decrypter/RelinkUs.py @@ -4,7 +4,7 @@ import re import time -from Plugin import Plugin +from module.Plugin import Plugin class RelinkUs(Plugin): @@ -14,10 +14,10 @@ class RelinkUs(Plugin): props['name'] = "RelinkUs" props['type'] = "container" props['pattern'] = r"http://(www\.)?relink.us/(f|((view|go).php))" - props['version'] = "0.2" + props['version'] = "1" props['description'] = """Relink.us Container Plugin""" - props['author_name'] = ("Sleeper-") - props['author_mail'] = ("@nonymous") + props['author_name'] = ("Sleeper-", "spoob") + props['author_mail'] = ("@nonymous", "spoob@pyload.org") self.props = props self.parent = parent self.html = None @@ -55,7 +55,6 @@ class RelinkUs(Plugin): # Wait some secs for relink.us server... time.sleep(5) - print new_link temp_links.append(new_link) self.links = temp_links diff --git a/module/plugins/decrypter/SecuredIn.py b/module/plugins/decrypter/SecuredIn.py new file mode 100644 index 000000000..510d48b28 --- /dev/null +++ b/module/plugins/decrypter/SecuredIn.py @@ -0,0 +1,335 @@ +# -*- coding: utf-8 -*- + +import re + +from module.Plugin import Plugin +from module.BeautifulSoup import BeautifulSoup + +from math import ceil + +class SecuredIn(Plugin): + def __init__(self, parent): + Plugin.__init__(self, parent) + props = {} + props['name'] = "SecuredIn" + props['type'] = "container" + props['pattern'] = r"http://[\w\.]*?secured\.in/download-[\d]+-[\w]{8}\.html" + props['version'] = "0.1" + props['description'] = """secured.in Container Plugin""" + props['author_name'] = ("mkaay") + props['author_mail'] = ("mkaay@mkaay.de") + self.props = props + self.parent = parent + self.html = None + self.multi_dl = False + + def file_exists(self): + return True + + def proceed(self, url, location): + links = [] + ajaxUrl = "http://secured.in/ajax-handler.php" + src = self.req.load(url, cookies=True) + soup = BeautifulSoup(src) + img = soup.find("img", attrs={"id":"captcha_img"}) + for i in range(3): + form = soup.find("form", attrs={"id":"frm_captcha"}) + captchaHash = form.find("input", attrs={"id":"captcha_hash"})["value"] + captchaUrl = "http://secured.in/%s" % img["src"] + captchaData = self.req.load(str(captchaUrl), cookies=True) + result = self.waitForCaptcha(captchaData, "jpg") + src = self.req.load(url, cookies=True, post={"captcha_key":result, "captcha_hash":captchaHash}) + soup = BeautifulSoup(src) + img = soup.find("img", attrs={"id":"captcha_img"}) + if not img: + files = soup.findAll("tr", attrs={"id":re.compile("file-\d+")}) + dlIDPattern = re.compile("accessDownload\(\d, \d+, '(.*?)', \d\)") + cypher = self.Cypher() + for cfile in files: + m = dlIDPattern.search(cfile["onclick"]) + if m: + crypted = self.req.load(ajaxUrl, cookies=True, post={"cmd":"download", "download_id":m.group(1)}) + cypher.reset() + link = cypher.cypher(crypted) + links.append(link) + break + self.links = links + + class Cypher(): + def __init__(self): + self.reset() + + def reset(self): + self.iatwbfrd = [ + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, + 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, + 0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, + 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, + 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, + 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, + 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, + 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, + 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, + 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, + 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, 0x68fb6faf, + 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, + 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, + 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, + 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, + 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, + 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, + 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, + 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, + 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, + 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, + 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, + 0xa99f8fa1, 0x08ba4799, 0x6e85076a + ]
+
+ self.olkemfjq = [ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, + 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b + ]
+
+ self.oqlaoymh = 0 + self.oqmykrna = 0 + self.pqmyzkid = 0 + self.pldmjnde = 0 + self.ldiwkqly = 0
+
+ self.plkodnyq = [ + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, + 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, + 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, + 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, + 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, + 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, + 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, + 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, + 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, + 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, + 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, + 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, + 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, + 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, + 0xc6913667, 0x8df9317c, 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, + 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, + 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, + 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, + 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, + 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, + 0xcd769c2b, 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, + 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, + 0xce77e25b, 0x578fdfe3, 0x3ac372e6 + ]
+
+ self.pnjzokye = None
+
+ self.thdlpsmy = [ + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, + 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, + 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, + 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, + 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, + 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, + 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, + 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, + 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, 0x3b240b62, + 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, + 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, + 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, + 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, + 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, + 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, + 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, + 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, + 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, + 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, + 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, + 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, + 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, + 0x92638212, 0x670efa8e, 0x406000e0 + ]
+
+ self.ybghjtik = [ + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, + 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, + 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, + 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, + 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, + 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, + 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, + 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, + 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, + 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, + 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba, + 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, + 0x5b6e2f84, 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, + 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, + 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, + 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, 0x8fd948e4, + 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, + 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, + 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, + 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, + 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484, + 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, + 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 + ] + + def cypher(self, code):
+ return self.lskdqpyr(code, "")
+
+ def lskdqpyr(self, alokfmth, yoaksjdh): + if self.pnjzokye == None or self.pnjzokye.lower() == yoaksjdh:
+ self.yoliukev(yoaksjdh)
+ self.pnjzokye = yoaksjdh
+ alokfmth = self.plaomtje(alokfmth)
+ ykaiumgp = ""
+ alokijuh = len(alokfmth)
+ lokimyas = self.ylomiktb(alokfmth[0:8])
+ palsiuzt = lokimyas[0]
+ tzghbndf = lokimyas[1]
+ awsedrft = [None, None]
+ for kiujzhqa in range(8, alokijuh, 8):
+ lokimyas = self.ylomiktb(alokfmth[kiujzhqa:kiujzhqa+8])
+ awsedrft[0] = lokimyas[0]
+ awsedrft[1] = lokimyas[1]
+ lokimyas = self.okaqnhlp(lokimyas[0], lokimyas[1])
+ lokimyas[0] ^= palsiuzt
+ lokimyas[1] ^= tzghbndf
+ palsiuzt = awsedrft[0]
+ tzghbndf = awsedrft[1]
+ ykaiumgp += self.ykijmtkd(lokimyas)
+ return ykaiumgp
+
+ def okaqnhlp(self, lahgrnvp, trenlpys): + ujhaqylw = 0
+ for yalmhopr in range(17, 1, -1):
+ lahgrnvp ^= self.ldiwkqly[yalmhopr]
+ trenlpys ^= (self.oqlaoymh[lahgrnvp >> 24 & 0xff] + self.oqmykrna[lahgrnvp >> 16 & 0xff] ^ self.pqmyzkid[lahgrnvp >> 8 & 0xff]) + self.pldmjnde[lahgrnvp & 0xff]
+ ujhaqylw = lahgrnvp
+ lahgrnvp = trenlpys
+ trenlpys = ujhaqylw
+ ujhaqylw = lahgrnvp
+ lahgrnvp = trenlpys
+ trenlpys = ujhaqylw
+ trenlpys ^= self.ldiwkqly[1]
+ lahgrnvp ^= self.ldiwkqly[0]
+ return [lahgrnvp, trenlpys]
+
+ def plaomtje(self, yoiumqpy): + qkailkzt = ""
+ xoliuzem = 0
+ lyomiujt = 0
+ yploemju = -1
+ for i in range(0, len(yoiumqpy)):
+ yploamzu = ord(yoiumqpy[i])
+ if ord('A') <= yploamzu and yploamzu <= ord('Z'):
+ xoliuzem = ord(yoiumqpy[i]) - 65
+ elif ord('a') <= yploamzu and yploamzu <= ord('z'):
+ xoliuzem = ord(yoiumqpy[i]) - 97 + 26
+ elif ord('0') <= yploamzu and yploamzu <= ord('9'):
+ xoliuzem = ord(yoiumqpy[i]) - 48 + 52
+ elif yploamzu == ord('+'):
+ xoliuzem = 62
+ elif yploamzu == ord('/'):
+ xoliuzem = 63
+ else:
+ continue
+ yploemju += 1
+
+ lxkdmizj = 0
+ switch = yploemju % 4
+ if switch == 0:
+ lyomiujt = xoliuzem
+ continue
+ elif switch == 1:
+ lxkdmizj = lyomiujt << 2 | xoliuzem >> 4
+ lyomiujt = xoliuzem & 0x0F
+ elif switch == 2:
+ lxkdmizj = lyomiujt << 4 | xoliuzem >> 2
+ lyomiujt = xoliuzem & 0x03
+ elif switch == 3:
+ lxkdmizj = lyomiujt << 6 | xoliuzem >> 0
+ lyomiujt = xoliuzem & 0x00
+ qkailkzt += unichr(lxkdmizj)
+ return qkailkzt
+
+ def qmyjuila(self, oqlamykt, yalkionj): + dolizmvw = 0
+ for iumswkya in range(0, 16):
+ oqlamykt ^= self.ldiwkqly[iumswkya]
+ yalkionj ^= (self.oqlaoymh[oqlamykt >> 24 & 0xff] + self.oqmykrna[oqlamykt >> 16 & 0xff] ^ self.pqmyzkid[oqlamykt >> 8 & 0xff]) + self.pldmjnde[oqlamykt & 0xff]
+ dolizmvw = oqlamykt
+ oqlamykt = yalkionj
+ yalkionj = dolizmvw
+ dolizmvw = oqlamykt
+ oqlamykt = yalkionj
+ yalkionj = dolizmvw
+ yalkionj ^= self.ldiwkqly[16]
+ oqlamykt ^= self.ldiwkqly[17]
+ return [oqlamykt, yalkionj]
+
+ def ykijmtkd(self, yoirlkqw): + loipamyu = len(yoirlkqw)
+ yoirlkqwchar = []
+ for ymujtnbq in range(0, loipamyu):
+ yoir = [yoirlkqw[ymujtnbq] >> 24 & 0xff, yoirlkqw[ymujtnbq] >> 16 & 0xff, yoirlkqw[ymujtnbq] >> 8 & 0xff, yoirlkqw[ymujtnbq] & 0xff]
+ for c in yoir:
+ yoirlkqwchar.append(chr(c))
+ return "".join(yoirlkqwchar)
+
+ def ylomiktb(self, lofiuzmq): + plokimqw = int(ceil(len(lofiuzmq) / 4.0))
+ lopkisdq = [] + for ypoqlktz in range(0, plokimqw):
+ lopkisdq.append(ord(lofiuzmq[(ypoqlktz << 2) + 3]) + (ord(lofiuzmq[(ypoqlktz << 2) + 2]) << 8) + (ord(lofiuzmq[(ypoqlktz << 2) + 1]) << 16) + (ord(lofiuzmq[(ypoqlktz << 2)]) << 24)) + return lopkisdq
+
+ def yoliukev(self, kaiumylq): + self.oqlaoymh = self.iatwbfrd
+ self.oqmykrna = self.ybghjtik
+ self.pqmyzkid = self.thdlpsmy
+ self.pldmjnde = self.plkodnyq
+
+ yaqpolft = [0 for i in range(len(kaiumylq))]
+
+ yaqwsedr = 0 + btzqwsay = 0
+ while yaqwsedr < len(kaiumylq):
+ wlqoakmy = 0
+ for lopiuztr in range(0, 4):
+ wlqoakmy = wlqoakmy << 8 | ord(kaiumylq[yaqwsedr % len(kaiumylq)])
+ yaqwsedr += 1
+ yaqpolft[btzqwsay] = wlqoakmy + btzqwsay += 1
+ self.ldiwkqly = []
+ for btzqwsay in range(0, 18):
+ self.ldiwkqly.append(self.olkemfjq[btzqwsay])
+ yalopiuq = [0, 0]
+ for btzqwsay in range(0, 18, 2):
+ yalopiuq = self.qmyjuila(yalopiuq[0], yalopiuq[1])
+ self.ldiwkqly[btzqwsay] = yalopiuq[0]
+ self.ldiwkqly[btzqwsay + 1] = yalopiuq[1]
+ for btzqwsay in range(0, 256, 2):
+ yalopiuq = self.qmyjuila(yalopiuq[0], yalopiuq[1])
+ self.oqlaoymh[btzqwsay] = yalopiuq[0]
+ self.oqlaoymh[btzqwsay + 1] = yalopiuq[1]
+ for btzqwsay in range(0, 256, 2):
+ yalopiuq = self.qmyjuila(yalopiuq[0], yalopiuq[1])
+ self.oqmykrna[btzqwsay] = yalopiuq[0]
+ self.oqmykrna[btzqwsay + 1] = yalopiuq[1]
+ for btzqwsay in range(0, 256, 2):
+ yalopiuq = self.qmyjuila(yalopiuq[0], yalopiuq[1])
+ self.pqmyzkid[btzqwsay] = yalopiuq[0]
+ self.pqmyzkid[btzqwsay + 1] = yalopiuq[1]
+ for btzqwsay in range(0, 256, 2):
+ yalopiuq = self.qmyjuila(yalopiuq[0], yalopiuq[1])
+ self.pldmjnde[btzqwsay] = yalopiuq[0]
+ self.pldmjnde[btzqwsay + 1] = yalopiuq[1] + diff --git a/module/plugins/decrypter/SerienjunkiesOrg.py b/module/plugins/decrypter/SerienjunkiesOrg.py new file mode 100644 index 000000000..af7dc8169 --- /dev/null +++ b/module/plugins/decrypter/SerienjunkiesOrg.py @@ -0,0 +1,216 @@ +# -*- coding: utf-8 -*- + +import re + +from module.Plugin import Plugin +from module.BeautifulSoup import BeautifulSoup +from module.unescape import unescape + +class SerienjunkiesOrg(Plugin): + def __init__(self, parent): + Plugin.__init__(self, parent) + props = {} + props['name'] = "SerienjunkiesOrg" + props['type'] = "container" + props['pattern'] = r"http://.*?serienjunkies.org/.*?" + props['version'] = "0.2" + props['description'] = """serienjunkies.org Container Plugin""" + props['author_name'] = ("mkaay") + props['author_mail'] = ("mkaay@mkaay.de") + self.props = props + self.parent = parent + self.html = None + self.multi_dl = False + + self.hosterMap = { + "rc": "RapidshareCom", + "ff": "FilefactoryCom", + "ut": "UploadedTo", + "ul": "UploadedTo", + "nl": "NetloadIn", + "rs": "RapidshareDe" + } + self.hosterMapReverse = dict((v,k) for k, v in self.hosterMap.iteritems()) + episodePattern = re.compile("^http://download.serienjunkies.org/f-.*?.html$") + oldStyleLink = re.compile("^http://serienjunkies.org/safe/(.*)$") + if episodePattern.match(self.parent.url) or oldStyleLink.match(self.parent.url): + self.decryptNow = False + else: + self.decryptNow = True + + def prepare(self, thread): + pyfile = self.parent + + self.want_reconnect = False + + pyfile.status.exists = self.file_exists() + + if not pyfile.status.exists: + raise Exception, "File not found" + return False + + pyfile.status.filename = self.get_file_name() + + pyfile.status.waituntil = self.time_plus_wait + pyfile.status.url = self.get_file_url() + pyfile.status.want_reconnect = self.want_reconnect + + thread.wait(self.parent) + + return True + + def get_file_name(self): + showPattern = re.compile("^http://serienjunkies.org/serie/(.*)/$") + seasonPattern = re.compile("^http://serienjunkies.org/.*?/(.*)/$") + m = showPattern.match(self.parent.url) + if not m: + m = seasonPattern.match(self.parent.url) + if m: + return m.group(1) + return "n/a" + + def getSJSrc(self, url): + src = self.req.load(str(url)) + if not src.find("Enter Serienjunkies") == -1: + src = self.req.load(str(url)) + return src + + def file_exists(self): + return True + + def handleSeason(self, url): + src = self.getSJSrc(url) + soup = BeautifulSoup(src) + post = soup.find("div", attrs={"class": "post-content"}) + ps = post.findAll("p") + hosterPattern = re.compile("^http://download\.serienjunkies\.org/f-.*?/([rcfultns]{2})_.*?\.html$") + preferredHoster = self.get_config("preferredHoster").split(",") + self.logger.debug("Preferred hoster: %s" % ", ".join(preferredHoster)) + groups = {} + gid = -1 + seasonName = unescape(soup.find("a", attrs={"rel":"bookmark"}).string) + for p in ps: + if re.search("<strong>Dauer|<strong>Sprache|<strong>Format", str(p)): + var = p.findAll("strong") + opts = {"Dauer": "", "Uploader": "", "Sprache": "", "Format": "", u"Größe": ""} + for v in var: + n = unescape(v.string) + val = v.nextSibling + val = val.encode("utf-8") + val = unescape(val) + val = val.replace("|", "").strip() + n = n.strip() + n = re.sub(r"^([:]?)(.*?)([:]?)$", r'\2', n) + val = val.strip() + val = re.sub(r"^([:]?)(.*?)([:]?)$", r'\2', val) + opts[n.strip()] = val.strip() + gid += 1 + groups[gid] = {} + groups[gid]["ep"] = [] + groups[gid]["opts"] = opts + elif re.search("<strong>Download:", str(p)): + links1 = p.findAll("a", attrs={"href": hosterPattern}) + links2 = p.findAll("a", attrs={"href": re.compile("^http://serienjunkies.org/safe/.*$")}) + for link in links1 + links2: + groups[gid]["ep"].append(link["href"]) + packages = {} + for g in groups.values(): + links = [] + linklist = g["ep"] + package = "%s (%s, %s)" % (seasonName, g["opts"]["Format"], g["opts"]["Sprache"]) + linkgroups = {} + for link in linklist: + key = re.sub("^http://download\.serienjunkies\.org/f-.*?/([rcfultns]{2})_", "", link) + if not linkgroups.has_key(key): + linkgroups[key] = [] + linkgroups[key].append(link) + for group in linkgroups.values(): + for pHoster in preferredHoster: + hmatch = False + for link in group: + m = hosterPattern.match(link) + if m: + if pHoster == self.hosterMap[m.group(1)]: + links.append(link) + hmatch = True + break + if hmatch: + break + packages[package] = links + return packages + + def handleEpisode(self, url): + if not self.parent.core.isGUIConnected(): + raise CaptchaError + for i in range(3): + src = self.getSJSrc(url) + if not src.find("Du hast das Download-Limit überschritten! Bitte versuche es später nocheinmal.") == -1: + self.logger.info("Downloadlimit reached") + return False + else: + soup = BeautifulSoup(src) + form = soup.find("form") + captchaTag = soup.find(attrs={"src":re.compile("^/secure/")}) + captchaUrl = "http://download.serienjunkies.org"+captchaTag["src"] + captchaData = self.req.load(str(captchaUrl)) + result = self.waitForCaptcha(captchaData, "png") + url = "http://download.serienjunkies.org"+form["action"] + sinp = form.find(attrs={"name":"s"}) + + sj = self.req.load(str(url), post={'s': sinp["value"], 'c': result, 'action': "Download"}) + + soup = BeautifulSoup(sj) + rawLinks = soup.findAll(attrs={"action": re.compile("^http://download.serienjunkies.org/")}) + + if not len(rawLinks) > 0: + continue + + links = [] + for link in rawLinks: + frameUrl = link["action"].replace("/go-", "/frame/go-") + links.append(self.handleFrame(frameUrl)) + return links + + def handleOldStyleLink(self, url): + if not self.parent.core.isGUIConnected(): + raise CaptchaError + for i in range(3): + sj = self.req.load(str(url)) + soup = BeautifulSoup(sj) + form = soup.find("form", attrs={"action":re.compile("^http://serienjunkies.org")}) + captchaTag = form.find(attrs={"src":re.compile("^/safe/secure/")}) + captchaUrl = "http://serienjunkies.org"+captchaTag["src"] + captchaData = self.req.load(str(captchaUrl)) + result = self.waitForCaptcha(captchaData, "png") + url = form["action"] + sinp = form.find(attrs={"name":"s"}) + + self.req.load(str(url), post={'s': sinp["value"], 'c': result, 'dl.start': "Download"}, cookies=False, just_header=True) + decrypted = self.req.lastEffectiveURL + if decrypted == str(url): + continue + return [decrypted] + return False + + def handleFrame(self, url): + self.req.load(str(url), cookies=False, just_header=True) + return self.req.lastEffectiveURL + + def proceed(self, url, location): + links = False + episodePattern = re.compile("^http://download.serienjunkies.org/f-.*?.html$") + oldStyleLink = re.compile("^http://serienjunkies.org/safe/(.*)$") + framePattern = re.compile("^http://download.serienjunkies.org/frame/go-.*?/$") + showPattern = re.compile("^http://serienjunkies.org/serie/.*/$") + seasonPattern = re.compile("^http://serienjunkies.org/.*?/.*/$") + if framePattern.match(url): + links = [self.handleFrame(url)] + elif episodePattern.match(url): + links = self.handleEpisode(url) + elif oldStyleLink.match(url): + links = self.handleOldStyleLink(url) + elif showPattern.match(url): + pass + elif seasonPattern.match(url): + links = self.handleSeason(url) + self.links = links diff --git a/module/plugins/StealthTo.py b/module/plugins/decrypter/StealthTo.py index 855aae001..855aae001 100644 --- a/module/plugins/StealthTo.py +++ b/module/plugins/decrypter/StealthTo.py diff --git a/module/plugins/YoutubeChannel.py b/module/plugins/decrypter/YoutubeChannel.py index 27a4ff8a7..ba2ca1472 100644 --- a/module/plugins/YoutubeChannel.py +++ b/module/plugins/decrypter/YoutubeChannel.py @@ -13,7 +13,7 @@ class YoutubeChannel(Plugin): props['name'] = "YoutubeChannel" props['type'] = "container" props['pattern'] = r"http://(www\.)?(de\.)?\youtube\.com/user/*" - props['version'] = "0.3" + props['version'] = "0.9" props['description'] = """Youtube.com Channel Download Plugin""" props['author_name'] = ("RaNaN", "Spoob") props['author_mail'] = ("RaNaN@pyload.org", "spoob@pyload.org") @@ -21,29 +21,34 @@ class YoutubeChannel(Plugin): self.parent = parent self.html = None self.read_config() + self.user = re.search(r"/user/(.+)", self.parent.url).group(1) def file_exists(self): - """ returns True or False - """ + if "User not found" in self.req.load("http://gdata.youtube.com/feeds/api/users/%s" % self.user): + return False return True def proceed(self, url, location): - self.user = re.search(r"/user/(.+)", self.parent.url).group(1) max_videos = self.config['max_videos'] if not max_videos: max_videos = 1000 #max video a user can upload page = 0 temp_links = [] - for start_index in range(1, int(max_videos), 50): - max_results = max_videos - page * 50 - if max_results > 50: - max_results = 50 - url = "http://gdata.youtube.com/feeds/api/users/" + self.user + "/uploads?max-results=" + str(max_results) + "&start-index=" + str(start_index) - rep = self.req.load(url) - new_links = re.findall(r"href\='(http:\/\/www.youtube.com\/watch\?v\=[^']+)", rep) - if new_links != []: - temp_links.extend(new_links) - else: - break - page += 1 + if "," in self.config['video_groups']: + video_groups = self.config['video_groups'].split(",") + else: + video_groups = [self.config['video_groups']] + for group in video_groups: + for start_index in range(1, int(max_videos), 50): + max_results = max_videos - page * 50 + if max_results > 50: + max_results = 50 + url = "http://gdata.youtube.com/feeds/api/users/%s/%s?max-results=%i&start-index=%i" % (self.user, group, max_results, start_index) + rep = self.req.load(url) + new_links = re.findall(r"href\='(http:\/\/www.youtube.com\/watch\?v\=[^']+)", rep) + if new_links != []: + temp_links.extend(new_links) + else: + break + page += 1 self.links = temp_links diff --git a/module/plugins/decrypter/__init__.py b/module/plugins/decrypter/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/module/plugins/decrypter/__init__.py diff --git a/module/plugins/hooks/ContainerDownload.py b/module/plugins/hooks/ContainerDownload.py new file mode 100644 index 000000000..f520b705c --- /dev/null +++ b/module/plugins/hooks/ContainerDownload.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- + +""" + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, + or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, see <http://www.gnu.org/licenses/>. + + @author: mkaay + @interface-version: 0.1 +""" + +from module.plugins.Hook import Hook + +from os.path import join, abspath + +class ContainerDownload(Hook): + def __init__(self, core): + Hook.__init__(self, core) + props = {} + props['name'] = "ContainerDownload" + props['version'] = "0.1" + props['description'] = """add the downloaded container to current package""" + props['author_name'] = ("mkaay") + props['author_mail'] = ("mkaay@mkaay.de") + self.props = props + + def downloadFinished(self, pyfile): + filename = pyfile.status.filename + if not pyfile.url.startswith("http"): + return + if filename.endswith(".dlc") or filename.endswith(".ccf") or filename.endswith(".rsdf"): + self.logger.info("ContainerDownload: adding container file") + location = abspath(join(pyfile.folder, filename)) + newFile = self.core.file_list.collector.addLink(location) + self.core.file_list.packager.addFileToPackage(pyfile.package.data["id"], self.core.file_list.collector.popFile(newFile)) diff --git a/module/plugins/hooks/ExternalScripts.py b/module/plugins/hooks/ExternalScripts.py new file mode 100644 index 000000000..30bd43770 --- /dev/null +++ b/module/plugins/hooks/ExternalScripts.py @@ -0,0 +1,100 @@ +# -*- coding: utf-8 -*- + +""" + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, + or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, see <http://www.gnu.org/licenses/>. + + @author: mkaay + @interface-version: 0.1 +""" + +from module.plugins.Hook import Hook +import subprocess +from os import listdir, sep +from os.path import join + +class ExternalScripts(Hook): + def __init__(self, core): + Hook.__init__(self, core) + props = {} + props['name'] = "ExternalScripts" + props['version'] = "0.1" + props['description'] = """run external scripts""" + props['author_name'] = ("mkaay", "RaNaN", "spoob") + props['author_mail'] = ("mkaay@mkaay.de", "ranan@pyload.org", "spoob@pyload.org") + self.props = props + self.core = core + self.scripts = {} + + script_folders = ['scripts'+sep+'download_preparing'+sep, + 'scripts'+sep+'download_finished'+sep, + 'scripts'+sep+'package_finished'+sep, + 'scripts'+sep+'before_reconnect'+sep, + 'scripts'+sep+'after_reconnect'+sep]
+ self.core.check_file(script_folders, _("folders for scripts"), True) + + f = lambda x: False if x.startswith("#") or x.endswith("~") else True + self.scripts = {} + + folder = join(self.core.path, "scripts") + + self.scripts['download_preparing'] = filter(f, listdir(join(folder, 'download_preparing'))) + self.scripts['download_finished'] = filter(f, listdir(join(folder, 'download_finished'))) + self.scripts['package_finished'] = filter(f, listdir(join(folder, 'package_finished'))) + self.scripts['before_reconnect'] = filter(f, listdir(join(folder, 'before_reconnect'))) + self.scripts['after_reconnect'] = filter(f, listdir(join(folder, 'after_reconnect'))) + + for script_type, script_name in self.scripts.iteritems(): + if script_name != []: + self.logger.info("Installed %s Scripts: %s" % (script_type, ", ".join(script_name))) + + #~ self.core.logger.info("Installed Scripts: %s" % str(self.scripts)) + + self.folder = folder + + def downloadStarts(self, pyfile): + for script in self.scripts['download_preparing']: + try: + out = subprocess.Popen([join(self.folder, 'download_preparing', script), pyfile.plugin.props['name'], pyfile.url], stdout=subprocess.PIPE) + out.wait() + except: + pass + + def downloadFinished(self, pyfile): + for script in self.scripts['download_finished']: + try: + out = subprocess.Popen([join(self.folder, 'download_finished', script), pyfile.plugin.props['name'], pyfile.url, pyfile.status.name, \ + join(self.core.path,self.core.config['general']['download_folder'], pyfile.folder, pyfile.status.name)], stdout=subprocess.PIPE) + except: + pass + + def packageFinished(self, pypack): + """ + not implemented! + """ + pass + + def beforeReconnecting(self, ip): + for script in self.scripts['before_reconnect']: + try: + out = subprocess.Popen([join(self.folder, 'before_reconnect', script), ip], stdout=subprocess.PIPE) + out.wait() + except: + pass + + def afterReconnecting(self, ip): + for script in self.scripts['after_reconnect']: + try: + out = subprocess.Popen([join(self.folder, 'download_preparing', script), ip], stdout=subprocess.PIPE) + except: + pass diff --git a/module/plugins/hooks/__init__.py b/module/plugins/hooks/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/module/plugins/hooks/__init__.py diff --git a/module/plugins/DepositfilesCom.py b/module/plugins/hoster/DepositfilesCom.py index 6c5748096..6c5748096 100644 --- a/module/plugins/DepositfilesCom.py +++ b/module/plugins/hoster/DepositfilesCom.py diff --git a/module/plugins/FilefactoryCom.py b/module/plugins/hoster/FilefactoryCom.py index ff069b20f..5b7db301d 100644 --- a/module/plugins/FilefactoryCom.py +++ b/module/plugins/hoster/FilefactoryCom.py @@ -2,7 +2,6 @@ # -*- coding: utf-8 -*- import re -import urllib from module.Plugin import Plugin from time import time diff --git a/module/plugins/FilesmonsterCom.py b/module/plugins/hoster/FilesmonsterCom.py index 27c687363..27c687363 100644 --- a/module/plugins/FilesmonsterCom.py +++ b/module/plugins/hoster/FilesmonsterCom.py diff --git a/module/plugins/FreakshareNet.py b/module/plugins/hoster/FreakshareNet.py index 0768b5476..0768b5476 100644 --- a/module/plugins/FreakshareNet.py +++ b/module/plugins/hoster/FreakshareNet.py diff --git a/module/plugins/GigasizeCom.py b/module/plugins/hoster/GigasizeCom.py index e22fe8593..e22fe8593 100644 --- a/module/plugins/GigasizeCom.py +++ b/module/plugins/hoster/GigasizeCom.py diff --git a/module/plugins/HotfileCom.py b/module/plugins/hoster/HotfileCom.py index 7ae432c78..a9853100c 100644 --- a/module/plugins/HotfileCom.py +++ b/module/plugins/hoster/HotfileCom.py @@ -2,7 +2,6 @@ # -*- coding: utf-8 -*- import re -import urllib from time import time from module.Plugin import Plugin @@ -20,17 +19,18 @@ class HotfileCom(Plugin): props['author_mail'] = ("sitacuisses@yhoo.de","spoob@pyload.org","mkaay@mkaay.de") self.props = props self.parent = parent - self.html = None + self.html = [None, None] self.want_reconnect = False self.multi_dl = False self.htmlwithlink = None self.url = None - + def prepare(self, thread): pyfile = self.parent self.want_reconnect = False - + + self.download_html() pyfile.status.exists = self.file_exists() if not pyfile.status.exists: @@ -46,47 +46,31 @@ class HotfileCom(Plugin): thread.wait(self.parent) pyfile.status.url = self.get_file_url() - return True def download_html(self): self.url = self.parent.url - self.html = self.req.load(self.url) + self.html[0] = self.req.load(self.url, cookies=True) def get_file_url(self): - """ returns the absolute downloadable filepath - """ - if self.html == None: - self.download_html() - if not self.want_reconnect: - self.get_download_page() - file_url = re.search("a href=\"(http://hotfile\.com/get/\S*?)\"", self.htmlwithlink).group(1) - return file_url - else: - return False + form_content = re.search(r"<form style=.*(\n<.*>\s*)*?\n<tr>", self.html[0]).group(0) + form_posts = re.findall(r"<input\stype=hidden\sname=(\S*)\svalue=(\S*)>", form_content) + self.html[1] = self.req.load(self.url, post=form_posts, cookies=True) + file_url = re.search("a href=\"(http://hotfile\.com/get/\S*?)\"", self.html[1]).group(1) + return file_url def get_file_name(self): - if self.html == None: - self.download_html() - if not self.want_reconnect: - file_name = re.search('Downloading\s<b>(.*?)</b>', self.html).group(1) - return file_name - else: - return self.parent.url + file_name = re.search('Downloading\s<b>(.*?)</b>', self.html[0]).group(1) + return file_name def file_exists(self): - """ returns True or False - """ - if self.html == None: - self.download_html() - if re.search(r"Such file does not exist or it has been removed for infringement of copyrights.", self.html) != None: + if re.search(r"Such file does not exist or it has been removed for infringement of copyrights.", self.html[0]) != None: return False - else: - return True + return True def get_wait_time(self): free_limit_pattern = re.compile(r"timerend=d\.getTime\(\)\+(\d+);") - matches = free_limit_pattern.findall(self.html) + matches = free_limit_pattern.findall(self.html[0]) if matches: for match in matches: if int(match) == 60000: @@ -98,14 +82,3 @@ class HotfileCom(Plugin): self.want_reconnect = True return True self.time_plus_wait = time() + 65 - - def get_download_page(self): - herewego = re.search(r"<form style=.*(\n<.*>\s*)*?\n<tr>", self.html).group(0) - all_the_tuples = re.findall(r"<input\stype=hidden\sname=(\S*)\svalue=(\S*)>", herewego) - - self.htmlwithlink = self.req.load(self.url, None, all_the_tuples) - - def proceed(self, url, location): - - self.req.download(url, location) - diff --git a/module/plugins/MegauploadCom.py b/module/plugins/hoster/MegauploadCom.py index 3736503c0..3eb21a591 100644 --- a/module/plugins/MegauploadCom.py +++ b/module/plugins/hoster/MegauploadCom.py @@ -4,6 +4,7 @@ import os import re import tempfile +from time import time from module.Plugin import Plugin @@ -21,6 +22,8 @@ class MegauploadCom(Plugin): props['author_mail'] = ("spoob@pyload.org") self.props = props self.parent = parent + self.time_plus_wait = None #time() + wait in seconds + self.html = [None, None] self.want_reconnect = False self.init_ocr() @@ -30,19 +33,19 @@ class MegauploadCom(Plugin): url = self.parent.url captcha_image = tempfile.NamedTemporaryFile(suffix=".gif").name - + for i in range(5): self.html[0] = self.req.load(url, cookies=True) url_captcha_html = re.search('(http://www.{,3}\.megaupload\.com/gencap.php\?.*\.gif)', self.html[0]).group(1) self.req.download(url_captcha_html, captcha_image, cookies=True) captcha = self.ocr.get_captcha(captcha_image) + os.remove(captcha_image) captchacode = re.search('name="captchacode" value="(.*)"', self.html[0]).group(1) megavar = re.search('name="megavar" value="(.*)">', self.html[0]).group(1) self.html[1] = self.req.load(url, post={"captcha": captcha, "captchacode": captchacode, "megavar": megavar}, cookies=True) if re.search(r"Waiting time before each download begins", self.html[1]) != None: break - - os.remove(captcha_image) + self.time_plus_wait = time() + 45 def get_file_url(self): """ returns the absolute downloadable filepath @@ -52,7 +55,7 @@ class MegauploadCom(Plugin): if not self.want_reconnect: file_url_pattern = 'id="downloadlink"><a href="(.*)" onclick="' search = re.search(file_url_pattern, self.html[1]) - return search.group(1) + return search.group(1).replace(" ", "%20") else: return False @@ -75,3 +78,6 @@ class MegauploadCom(Plugin): return False else: return True + + def proceed(self, url, location): + self.req.download(url, location, cookies=True) diff --git a/module/plugins/hoster/MyvideoDe.py b/module/plugins/hoster/MyvideoDe.py new file mode 100644 index 000000000..0fe315547 --- /dev/null +++ b/module/plugins/hoster/MyvideoDe.py @@ -0,0 +1,40 @@ +# -*- coding: utf-8 -*- + +import re +from module.Plugin import Plugin + +class MyvideoDe(Plugin): + def __init__(self, parent): + Plugin.__init__(self, parent) + props = {} + props['name'] = "MyvideoDe" + props['type'] = "hoster" + props['pattern'] = r"http://(www\.)?myvideo.de/watch/" + props['version'] = "0.9" + props['description'] = """Myvideo.de Video Download Plugin""" + props['author_name'] = ("spoob") + props['author_mail'] = ("spoob@pyload.org") + self.props = props + self.parent = parent + self.html = None + self.url = self.parent.url + + def download_html(self): + self.html = self.req.load(self.url) + + def get_file_url(self): + videoId = re.search(r"addVariable\('_videoid','(.*)'\);p.addParam\('quality'", self.html).group(1) + videoServer = re.search("rel='image_src' href='(.*)thumbs/.*' />", self.html).group(1) + file_url = videoServer + videoId + ".flv" + return file_url + + def get_file_name(self): + file_name_pattern = r"<h1 class='globalHd'>(.*)</h1>" + return re.search(file_name_pattern, self.html).group(1).replace("/", "") + '.flv' + + def file_exists(self): + self.download_html() + self.req.load(str(self.url), cookies=False, just_header=True) + if self.req.lastEffectiveURL == "http://www.myvideo.de/": + return False + return True diff --git a/module/plugins/NetloadIn.py b/module/plugins/hoster/NetloadIn.py index b9fb4cfed..46afc4080 100644 --- a/module/plugins/NetloadIn.py +++ b/module/plugins/hoster/NetloadIn.py @@ -37,103 +37,75 @@ class NetloadIn(Plugin): def prepare(self, thread): pyfile = self.parent - + self.req.clear_cookies() self.want_reconnect = False - tries = 0 - - while not pyfile.status.url: - - self.req.clear_cookies() - self.download_html() - - pyfile.status.exists = self.file_exists() - - if not pyfile.status.exists: - raise Exception, "The file was not found on the server." - - self.download_api_data() - + self.download_api_data() + if self.file_exists(): pyfile.status.filename = self.get_file_name() - + if self.config['premium']: + self.req.load("http://netload.in/index.php", None, { "txtuser" : self.config['username'], "txtpass" : self.config['password'], "txtcheck" : "login", "txtlogin" : ""}, cookies=True) + self.logger.info("Netload: Use Premium Account") pyfile.status.url = self.parent.url return True - - self.download_html2() - self.get_wait_time() - - pyfile.status.waituntil = self.time_plus_wait - pyfile.status.want_reconnect = self.want_reconnect - - thread.wait(self.parent) - - pyfile.status.url = self.get_file_url() - - tries += 1 - if tries > 3: - raise Exception, "Error while preparing DL, HTML dump: %s %s" % (self.html[0], self.html[1]) + while not pyfile.status.url: + self.download_html() + self.get_wait_time() + pyfile.status.waituntil = self.time_plus_wait + pyfile.status.want_reconnect = self.want_reconnect + thread.wait(self.parent) + + pyfile.status.url = self.get_file_url() - return True - + else: + raise Exception, "The file was not found on the server." + def download_api_data(self): url = self.parent.url - id_regex = re.compile("http://netload.in/datei(.*?)(?:\.htm|/)") + id_regex = re.compile("http://.*netload.in/datei(.*?)(?:\.htm|/)") match = id_regex.search(url) if match: apiurl = "http://netload.in/share/fileinfos2.php" src = self.req.load(apiurl, cookies=False, get={"file_id": match.group(1)}) self.api_data = {} - lines = src.split(";") - self.api_data["fileid"] = lines[0] - self.api_data["filename"] = lines[1] - self.api_data["size"] = lines[2] #@TODO formatting? (ex: '2.07 KB') - self.api_data["status"] = lines[3] - self.api_data["checksum"] = lines[4] - + if not src == "unknown file_data": + lines = src.split(";") + self.api_data["exists"] = True + self.api_data["fileid"] = lines[0] + self.api_data["filename"] = lines[1] + self.api_data["size"] = lines[2] #@TODO formatting? (ex: '2.07 KB') + self.api_data["status"] = lines[3] + self.api_data["checksum"] = lines[4].strip() + else: + self.api_data["exists"] = False def download_html(self): - if self.config['premium']: - self.config['username'], self.config['password'] - self.req.load("http://netload.in/index.php", None, { "txtuser" : self.config['username'], "txtpass" : self.config['password'], "txtcheck" : "login", "txtlogin" : ""}) - url = self.parent.url - self.html[0] = self.req.load(url, cookies=True) - - def download_html2(self): - + self.html[0] = self.req.load(self.parent.url, cookies=True) url_captcha_html = "http://netload.in/" + re.search('(index.php\?id=10&.*&captcha=1)', self.html[0]).group(1).replace("amp;", "") - for i in range(6): self.html[1] = self.req.load(url_captcha_html, cookies=True) - try: captcha_url = "http://netload.in/" + re.search('(share/includes/captcha.php\?t=\d*)', self.html[1]).group(1) except: url_captcha_html = "http://netload.in/" + re.search('(index.php\?id=10&.*&captcha=1)', self.html[1]).group(1).replace("amp;", "") self.html[1] = self.req.load(url_captcha_html, cookies=True) captcha_url = "http://netload.in/" + re.search('(share/includes/captcha.php\?t=\d*)', self.html[1]).group(1) - - file_id = re.search('<input name="file_id" type="hidden" value="(.*)" />', self.html[1]).group(1) + file_id = re.search('<input name="file_id" type="hidden" value="(.*)" />', self.html[1]).group(1) captcha_image = tempfile.NamedTemporaryFile(suffix=".png").name - self.req.download(captcha_url, captcha_image, cookies=True) captcha = self.ocr.get_captcha(captcha_image) + os.remove(captcha_image) self.logger.debug("Captcha %s: %s" % (i, captcha)) sleep(5) self.html[2] = self.req.load("http://netload.in/index.php?id=10", post={"file_id": file_id, "captcha_check": captcha}, cookies=True) - os.remove(captcha_image) - if re.search(r"(We will prepare your download..|We had a reqeust with the IP)", self.html[2]) != None: - return True - - raise Exception, "Captcha reading failed" + break def get_file_url(self): - """ returns the absolute downloadable filepath - """ try: file_url_pattern = r"<a class=\"Orange_Link\" href=\"(http://.+)\" >Click here" return re.search(file_url_pattern, self.html[2]).group(1) @@ -141,42 +113,45 @@ class NetloadIn(Plugin): return None def get_wait_time(self): - wait = int(re.search(r"countdown\((.+),'change\(\)'\)", self.html[2]).group(1)) - self.time_plus_wait = time() + wait / 100 - if re.search(r"We had a reqeust with the IP", self.html[2]): + wait_minutes = int(re.search(r"countdown\((.+),'change\(\)'\)", self.html[2]).group(1)) / 6000 self.want_reconnect = True + self.time_plus_wait = time() + wait_minutes * 60 + return + + wait_seconds = int(re.search(r"countdown\((.+),'change\(\)'\)", self.html[2]).group(1)) / 100 + self.time_plus_wait = time() + wait_seconds def get_file_name(self): - try: - if self.api_data and self.api_data["filename"]: - return self.api_data["filename"] + if self.api_data["filename"]: + return self.api_data["filename"] + elif self.html[0]: file_name_pattern = '\t\t\t(.+)<span style="color: #8d8d8d;">' - return re.search(file_name_pattern, self.html[0]).group(1) - except: - return self.parent.url + file_name_search = re.search(file_name_pattern, self.html[0]) + if file_name_search: + return file_name_search.group(1) + return self.parent.url def file_exists(self): - """ returns True or False - """ - if re.search(r"The file has been deleted", self.html[0]) != None: - return False - else: + if self.api_data["exists"]: + return self.api_data["exists"] + elif self.html[0] and re.search(r"The file has been deleted", self.html[0]) == None: return True + return False def proceed(self, url, location): - self.req.download(url, location, cookies=True) def check_file(self, local_file): if self.api_data and self.api_data["checksum"]: h = hashlib.md5() - with open(local_file, "rb") as f: - h.update(f.read()) + f = open(local_file, "rb") + h.update(f.read()) + f.close() hexd = h.hexdigest() if hexd == self.api_data["checksum"]: return (True, 0) else: return (False, 1) else: - return (True, 5) + return (True, 5) diff --git a/module/plugins/RapidshareCom.py b/module/plugins/hoster/RapidshareCom.py index 275fa761c..10654e5c8 100644 --- a/module/plugins/RapidshareCom.py +++ b/module/plugins/hoster/RapidshareCom.py @@ -15,7 +15,7 @@ class RapidshareCom(Plugin): props['name'] = "RapidshareCom" props['type'] = "hoster" props['pattern'] = r"http://[\w\.]*?rapidshare.com/files/(\d*?)/(.*)" - props['version'] = "0.5" + props['version'] = "1.0" props['description'] = """Rapidshare.com Download Plugin""" props['author_name'] = ("spoob", "RaNaN", "mkaay") props['author_mail'] = ("spoob@pyload.org", "ranan@pyload.org", "mkaay@mkaay.de") @@ -26,6 +26,8 @@ class RapidshareCom(Plugin): self.time_plus_wait = None #time() + wait in seconds self.want_reconnect = False self.no_slots = True + self.api_data = None + self.url = self.parent.url self.read_config() if self.config['premium']: self.multi_dl = True @@ -36,60 +38,47 @@ class RapidshareCom(Plugin): def prepare(self, thread): pyfile = self.parent - + self.req.clear_cookies() self.want_reconnect = False - tries = 0 - - while not self.start_dl or not pyfile.status.url: - - self.req.clear_cookies() - - self.download_html() - - pyfile.status.exists = self.file_exists() - - if not pyfile.status.exists: - raise Exception, "The file was not found on the server." - - self.download_api_data() - + self.download_api_data() + if self.api_data["status"] == "1": pyfile.status.filename = self.get_file_name() - if self.config['premium']: + if self.config["premium"]: + self.logger.info("Rapidshare: Use Premium Account (%sGB left)" % (self.props["premkbleft"]/1000000)) pyfile.status.url = self.parent.url return True + self.download_html() while self.no_slots: - self.download_serverhtml() + self.get_wait_time() pyfile.status.waituntil = self.time_plus_wait pyfile.status.want_reconnect = self.want_reconnect - thread.wait(pyfile) pyfile.status.url = self.get_file_url() - - if self.no_slots: - raise Exception, "No free slots!" - - tries += 1 - if tries > 5: - raise Exception, "Error while preparing, HTML dump:"+ str(self.html[0]) + str(self.html[1]) - return True + return True + elif self.api_data["status"] == "2": + self.logger.info("Rapidshare: Traffic Share (direct download)") + pyfile.status.filename = self.get_file_name() + pyfile.status.url = self.parent.url + return True + else: + raise Exception, "The file was not found on the server." def download_api_data(self): """ http://images.rapidshare.com/apidoc.txt """ - url = self.parent.url api_url_base = "http://api.rapidshare.com/cgi-bin/rsapi.cgi" - api_param = {"sub": "checkfiles_v1", "files": "", "filenames": "", "incmd5": "1"} - m = re.compile(self.props['pattern']).search(url) + api_param_file = {"sub": "checkfiles_v1", "files": "", "filenames": "", "incmd5": "1"} + m = re.compile(self.props['pattern']).search(self.url) if m: - api_param["files"] = m.group(1) - api_param["filenames"] = m.group(2) - src = self.req.load(api_url_base, cookies=False, get=api_param) + api_param_file["files"] = m.group(1) + api_param_file["filenames"] = m.group(2) + src = self.req.load(api_url_base, cookies=False, get=api_param_file) if src.startswith("ERROR"): return fields = src.split(",") @@ -114,84 +103,74 @@ class RapidshareCom(Plugin): self.api_data["mirror"] = "http://rs%(serverid)s%(shorthost)s.rapidshare.com/files/%(fileid)s/%(filename)s" % self.api_data + if self.config["premium"]: + api_param_prem = {"sub": "getaccountdetails_v1", "type": "prem", \ + "login": self.config['username'], "password": self.config['password']} + src = self.req.load(api_url_base, cookies=False, get=api_param_prem) + if src.startswith("ERROR"): + self.config["premium"] = False + self.logger.info("Rapidshare: Login failed") + return + fields = src.split("\n") + premkbleft = int(fields[19].split("=")[1]) + if premkbleft < int(self.api_data["size"][0:-3]): + self.logger.info("Rapidshare: Not enough traffic left") + self.config["premium"] = False + else: + self.props["premkbleft"] = premkbleft + def download_html(self): """ gets the url from self.parent.url saves html in self.html and parses """ - url = self.parent.url - self.html[0] = self.req.load(url, cookies=True) + self.html[0] = self.req.load(self.url, cookies=True) self.html_old = time() - def download_serverhtml(self): + def get_wait_time(self): """downloads html with the important informations """ file_server_url = re.search(r"<form action=\"(.*?)\"", self.html[0]).group(1) self.html[1] = self.req.load(file_server_url, cookies=True, post={"dl.start": "Free"}) self.html_old = time() - self.get_wait_time() - def get_wait_time(self): - if re.search(r"is already downloading", self.html[1]) != None: - self.time_plus_wait = time() + 10 * 60 + if re.search(r"is already downloading", self.html[1]): + self.logger.info("Rapidshare: Already downloading, wait 30 minutes") + self.time_plus_wait = time() + 10 * 30 + return self.no_slots = False try: wait_minutes = re.search(r"Or try again in about (\d+) minute", self.html[1]).group(1) self.time_plus_wait = time() + 60 * int(wait_minutes) self.want_reconnect = True except: - if re.search(r"(Currently a lot of users|There are no more download slots)", self.html[1], re.I) != None: + if re.search(r"(Currently a lot of users|no more download slots|servers are overloaded)", self.html[1], re.I) != None: self.time_plus_wait = time() + 130 - self.parent.parent.logger.info("Rapidshare: No free slots!") + self.logger.info("Rapidshare: No free slots!") self.no_slots = True return True self.no_slots = False wait_seconds = re.search(r"var c=(.*);.*", self.html[1]).group(1) self.time_plus_wait = time() + int(wait_seconds) + 5 - def file_exists(self): - """ returns True or False - """ - if re.search("The file could not be found|This limit is reached| \ - is momentarily not available|removed this file| \ - contain illegal content", self.html[0], re.I) != None: - return False - else: - return True - def get_file_url(self): """ returns the absolute downloadable filepath """ - if self.config['premium']: - self.start_dl = True - if self.api_data and self.api_data["mirror"]: - return self.api_data["mirror"] - return self.parent.url - - #if (self.html_old + 5 * 60) < time(): # nach einiger zeit ist die file_url nicht mehr aktuell - # self.download_serverhtml() - - try: - if self.no_slots: - self.start_dl = False - return False - if self.config['server'] == "": - file_url_pattern = r".*name=\"dlf\" action=\"(.*)\" method=.*" - else: - file_url_pattern = '(http://rs.*)\';" /> %s<br />' % self.config['server'] + if self.config['server'] == "": + file_url_pattern = r".*name=\"dlf\" action=\"(.*)\" method=.*" + else: + file_url_pattern = '(http://rs.*)\';" /> %s<br />' % self.config['server'] - self.start_dl = True - return re.search(file_url_pattern, self.html[1]).group(1) - except Exception, e: - self.start_dl = False - return False - #print self.html[1] #test print - #raise Exception, "Error when retrieving download url" + return re.search(file_url_pattern, self.html[1]).group(1) def get_file_name(self): - if self.api_data and self.api_data["filename"]: + if self.api_data["filename"]: return self.api_data["filename"] - file_name_pattern = r"<p class=\"downloadlink\">.+/(.+) <font" - return re.findall(file_name_pattern, self.html[0])[0] + elif self.html[0]: + file_name_pattern = r"<p class=\"downloadlink\">.+/(.+) <font" + file_name_search = re.search(file_name_pattern, self.html[0]) + if file_name_search: + return file_name_search.group(1) + return self.url.split("/")[-1] def proceed(self, url, location): if self.config['premium']: @@ -210,4 +189,4 @@ class RapidshareCom(Plugin): else: return (False, 1) else: - return (True, 5) + return (True, 5) diff --git a/module/plugins/ShareonlineBiz.py b/module/plugins/hoster/ShareonlineBiz.py index a798ccefa..63d05c47a 100644 --- a/module/plugins/ShareonlineBiz.py +++ b/module/plugins/hoster/ShareonlineBiz.py @@ -6,6 +6,7 @@ import re import tempfile from time import time from base64 import b64decode +import hashlib from module.Plugin import Plugin @@ -26,11 +27,45 @@ class ShareonlineBiz(Plugin): self.html = [None, None] self.want_reconnect = False self.init_ocr() + self.url = self.parent.url + self.read_config() if self.config['premium']: self.multi_dl = True else: self.multi_dl = False + def prepare(self, thread): + pyfile = self.parent + + self.download_api_data() + if self.api_data["status"]: + self.download_html() + pyfile.status.filename = self.api_data["filename"] + pyfile.status.waituntil = self.time_plus_wait + pyfile.status.url = self.get_file_url() + pyfile.status.want_reconnect = self.want_reconnect + else: + raise Exception, "File not found" + return False + + def download_api_data(self): + """ + http://images.rapidshare.com/apidoc.txt + """ + api_url_base = "http://www.share-online.biz/linkcheck/linkcheck.php?md5=1" + api_param_file = {"links": self.url} + src = self.req.load(api_url_base, cookies=False, post=api_param_file) + + fields = src.split(";") + self.api_data = {} + self.api_data["fileid"] = fields[0] + self.api_data["status"] = fields[1] + if self.api_data["status"] == "NOTFOUND": + return + self.api_data["filename"] = fields[2] + self.api_data["size"] = fields[3] # in bytes + self.api_data["checksum"] = fields[4].strip().lower().replace("\n\n", "") # md5 + def download_html(self): if self.config['premium']: post_vars = {"act": "login", @@ -47,11 +82,12 @@ class ShareonlineBiz(Plugin): if not self.config['premium']: captcha_image = tempfile.NamedTemporaryFile(suffix=".jpg").name - for i in range(5): + for i in range(10): self.req.download("http://www.share-online.biz/captcha.php", captcha_image, cookies=True) captcha = self.ocr.get_captcha(captcha_image) + self.logger.debug("Captcha %s: %s" % (i, captcha)) self.html[1] = self.req.load(url, post={"captchacode": captcha}, cookies=True) - if re.search(r"Der Download ist Ihnen zu langsam?", self.html[1]) != None: + if re.search(r"Der Download ist Ihnen zu langsam", self.html[1]) != None: self.time_plus_wait = time() + 15 break @@ -60,29 +96,22 @@ class ShareonlineBiz(Plugin): def get_file_url(self): """ returns the absolute downloadable filepath """ - if self.html[0] == None: - self.download_html() if not self.want_reconnect: file_url_pattern = 'loadfilelink\.decode\("(.*)\); document' return b64decode(re.search(file_url_pattern, self.html[1]).group(1)) else: return False - def get_file_name(self): - if self.html[0] == None: - self.download_html() - if not self.want_reconnect: - file_name_pattern = 'class="locatedActive">Download (.*)</span>' - return re.search(file_name_pattern, self.html[1]).group(1) - else: - return self.parent.url - - def file_exists(self): - """ returns True or False - """ - if self.html[0] == None: - self.download_html() - if re.search(r"nicht zum Download bereitgestellt werden", self.html[0]) != None: - return False + def check_file(self, local_file): + if self.api_data and self.api_data["checksum"]: + h = hashlib.md5() + f = open(local_file, "rb") + h.update(f.read()) + f.close() + hexd = h.hexdigest() + if hexd == self.api_data["checksum"]: + return (True, 0) + else: + return (False, 1) else: - return True + return (True, 5) diff --git a/module/plugins/ShragleCom.py b/module/plugins/hoster/ShragleCom.py index c0cc9de72..c0cc9de72 100644 --- a/module/plugins/ShragleCom.py +++ b/module/plugins/hoster/ShragleCom.py diff --git a/module/plugins/StorageTo.py b/module/plugins/hoster/StorageTo.py index dbff844ad..dbff844ad 100644 --- a/module/plugins/StorageTo.py +++ b/module/plugins/hoster/StorageTo.py diff --git a/module/plugins/UploadedTo.py b/module/plugins/hoster/UploadedTo.py index 4bddbd6f1..619c9bba1 100644 --- a/module/plugins/UploadedTo.py +++ b/module/plugins/hoster/UploadedTo.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python # -*- coding: utf-8 -*- import re @@ -13,7 +12,7 @@ class UploadedTo(Plugin): props = {} props['name'] = "UploadedTo" props['type'] = "hoster" - props['pattern'] = r"http://(?:www\.)?u(?:p)?l(?:oaded)?\.to/(?:file/)?(.*)" + props['pattern'] = r"http://(?:www\.)?u(?:p)?l(?:oaded)?\.to/(?:file/|\?id=)?(.+)" props['version'] = "0.3" props['description'] = """Uploaded.to Download Plugin""" props['author_name'] = ("spoob", "mkaay") @@ -21,7 +20,6 @@ class UploadedTo(Plugin): self.props = props self.parent = parent self.html = None - self.html_old = None #time() where loaded the HTML self.time_plus_wait = None #time() + wait in seconds self.api_data = None self.want_reconnect = False @@ -35,12 +33,11 @@ class UploadedTo(Plugin): def prepare(self, thread): pyfile = self.parent - + self.want_reconnect = False tries = 0 while not pyfile.status.url: - self.req.clear_cookies() self.download_html() @@ -84,11 +81,8 @@ class UploadedTo(Plugin): self.api_data["filename"] = lines[0] self.api_data["size"] = lines[1] # in kbytes self.api_data["checksum"] = lines[2] #sha1 - + def download_html(self): - if self.config['premium']: - self.config['username'], self.config['password'] - self.req.load("http://uploaded.to/login", None, { "email" : self.config['username'], "password" : self.config['password']}) url = self.parent.url self.html = self.req.load(url, cookies=False) @@ -102,12 +96,9 @@ class UploadedTo(Plugin): self.time_plus_wait = 0 def get_file_url(self): - """ returns the absolute downloadable filepath - """ if self.config['premium']: self.start_dl = True return self.parent.url - try: file_url_pattern = r".*<form name=\"download_form\" method=\"post\" action=\"(.*)\">" return re.search(file_url_pattern, self.html).group(1) @@ -124,19 +115,28 @@ class UploadedTo(Plugin): return file_name return file_name + file_suffix.group(1) except: - self.parent.status.url = None return self.parent.url def file_exists(self): - """ returns True or False - """ if re.search(r"(File doesn't exist .*)", self.html) != None: return False else: return True - + + def cleanUrl(self, url): + url = url.replace("ul.to/", "uploaded.to/file/") + url = url.replace("/?id=", "/file/") + url = url.replace("?id=", "file/") + url = re.sub("/\?(.*?)&id=", "/file/", url, 1) + return url + def proceed(self, url, location): if self.config['premium']: + self.req.load("http://uploaded.to/login", None, { "email" : self.config['username'], "password" : self.config['password']}, cookies=True) + self.req.load(url, cookies=True, just_header=True) + if self.cleanUrl(self.req.lastEffectiveURL) == self.cleanUrl(url): + self.logger.info("UploadedTo indirect download") + url = self.cleanUrl(url)+"?redirect" self.req.download(url, location, cookies=True) else: self.req.download(url, location, cookies=False, post={"download_submit": "Free Download"}) @@ -153,4 +153,4 @@ class UploadedTo(Plugin): else: return (False, 1) else: - return (True, 5) + return (True, 5) diff --git a/module/plugins/XupIn.py b/module/plugins/hoster/XupIn.py index d044f2389..d044f2389 100644 --- a/module/plugins/XupIn.py +++ b/module/plugins/hoster/XupIn.py diff --git a/module/plugins/YoupornCom.py b/module/plugins/hoster/YoupornCom.py index e501954da..e501954da 100644 --- a/module/plugins/YoupornCom.py +++ b/module/plugins/hoster/YoupornCom.py diff --git a/module/plugins/YoutubeCom.py b/module/plugins/hoster/YoutubeCom.py index 38a4934df..38a4934df 100644 --- a/module/plugins/YoutubeCom.py +++ b/module/plugins/hoster/YoutubeCom.py diff --git a/module/plugins/ZippyshareCom.py b/module/plugins/hoster/ZippyshareCom.py index 0c638087b..bec7f8c65 100644 --- a/module/plugins/ZippyshareCom.py +++ b/module/plugins/hoster/ZippyshareCom.py @@ -30,14 +30,11 @@ class ZippyshareCom(Plugin): def get_file_url(self): """ returns the absolute downloadable filepath """ - if self.html == None: - self.download_html() - if not self.want_reconnect: - file_url = urllib.unquote(re.search("var \w* = 'fck(.*)';", self.html).group(1)) - return file_url - else: - return False - + file_url_pattern = r"var \w* = '(http%.*?)';" + file_url_search = re.search(file_url_pattern, self.html).group(1) + file_url = urllib.unquote(file_url_search.replace("nnn", "aaa").replace("unlg", "v").replace("serwus", "zippyshare")) + return file_url + def get_file_name(self): if self.html == None: self.download_html() diff --git a/module/plugins/ZshareNet.py b/module/plugins/hoster/ZshareNet.py index 08f28a35c..08f28a35c 100644 --- a/module/plugins/ZshareNet.py +++ b/module/plugins/hoster/ZshareNet.py diff --git a/module/plugins/hoster/__init__.py b/module/plugins/hoster/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/module/plugins/hoster/__init__.py diff --git a/module/remote/ClientHandler.py b/module/remote/ClientHandler.py deleted file mode 100644 index 9653db9ae..000000000 --- a/module/remote/ClientHandler.py +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -""" -authored by: RaNaN - -this module handels the incoming requests - -""" -import hashlib - -from Crypto.Cipher import Blowfish -from RequestHandler import RequestHandler - -class ClientHandler(RequestHandler): - def __init__(self, client, pw): - self.client = client - key = hashlib.sha256(pw) - self.bf = Blowfish.new(key.hexdigest(), Blowfish.MODE_ECB) - - def proceed(self, data): - obj = self.decrypt(data) - - self.client.data_arrived(obj)
\ No newline at end of file diff --git a/module/remote/ClientSocket.py b/module/remote/ClientSocket.py deleted file mode 100644 index 0e6a5ed53..000000000 --- a/module/remote/ClientSocket.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -""" -authored by: RaNaN - -socket for connecting to the core's server - -""" -import asynchat -import asyncore -import socket -import threading - -from ClientHandler import ClientHandler -from RequestObject import RequestObject - -class SocketThread(threading.Thread): - def __init__(self, adress, port, pw, client): - threading.Thread.__init__(self) - self.setDaemon(True) - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.connect((adress, port)) - self.socket = ClientSocket(sock, pw, client) - self.start() - - def run(self): - asyncore.loop() - print "loop closed" - - def push_exec(self, function, args=[]): - obj = RequestObject() - obj.command = "exec" - obj.function = function - obj.args = args - self.push(obj) - - def push(self, obj): - self.socket.push_obj(obj) - - -class ClientSocket(asynchat.async_chat): - def __init__(self, sock, pw, client): - asynchat.async_chat.__init__(self, sock) - self.data = "" - self.handler = ClientHandler(client, pw) - self.set_terminator("\n") - #self.create_socket(socket.AF_INET, socket.SOCK_STREAM) - - def handle_close(self): - print "Disconnected from", self.getpeername() - self.close() - - def collect_incoming_data(self, data): - self.data += data - - def found_terminator(self): - self.handler.proceed(self.data) - self.data = "" - - def push_obj(self, obj): - string = self.handler.encrypt(obj) - self.push(string)
\ No newline at end of file diff --git a/module/remote/RequestHandler.py b/module/remote/RequestHandler.py deleted file mode 100644 index a879d2297..000000000 --- a/module/remote/RequestHandler.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -""" -authored by: RaNaN - -this module handels the incoming requests - -""" - -import base64 -import hashlib -import random -import string - -import cPickle -from Crypto.Cipher import Blowfish -from RequestObject import RequestObject - - -class RequestHandler: - def __init__(self, core): - self.core = core - key = hashlib.sha256(core.config['remote']['password']) - self.bf = Blowfish.new(key.hexdigest(), Blowfish.MODE_ECB) - - def proceed(self, data): - obj = self.decrypt(data) - - if obj.command == "exec": - func = getattr(self.core, obj.function) - obj.data = func( * obj.args) - else: - obj.data = "error happend" - - return self.encrypt(obj) - - - def decrypt(self, dec_str): - try: - dec_str = base64.standard_b64decode(dec_str) - dec_str = self.bf.decrypt(dec_str) - - dec_str = dec_str[:-(int(dec_str[-1], 16) + 1)] - obj = cPickle.loads(dec_str) - except: - obj = RequestObject() - - return obj - - def encrypt(self, obj): - enc_str = cPickle.dumps(obj, 1) - padding = len(enc_str) % 16 - padding = 16 - padding - - p_str = "" - for i in range(padding - 1): - p_str += random.choice(string.letters + string.digits + string.punctuation) - p_str += hex(len(p_str)).replace("0x", "") - enc_str += p_str - - enc_str = self.bf.encrypt(enc_str) - enc_str = base64.standard_b64encode(enc_str) - return enc_str + "\n" diff --git a/module/remote/RequestObject.py b/module/remote/RequestObject.py deleted file mode 100644 index 54ea837a6..000000000 --- a/module/remote/RequestObject.py +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -""" -authored by: RaNaN - -represents the object for interaction - -""" -class RequestObject(object): - def __init__(self): - self.version = 0 - self.sender = "ip" - self.status = {} - self.command = None - self.function = "" - self.args = [] - self.data = None diff --git a/module/remote/SecureXMLRPCServer.py b/module/remote/SecureXMLRPCServer.py new file mode 100644 index 000000000..7a60f6c90 --- /dev/null +++ b/module/remote/SecureXMLRPCServer.py @@ -0,0 +1,130 @@ +# Source: http://sources.gentoo.org/viewcvs.py/gimli/server/SecureXMLRPCServer.py?view=markup +# which seems to be based on http://www.sabren.net/code/python/SecureXMLRPCServer.py +# +# Changes: +# 2007-01-06 Christian Hoffmann <ch@hoffie.info> +# * Bugfix: replaced getattr by hasattr in the conditional +# (lead to an error otherwise) +# * SecureXMLRPCServer: added self.instance = None, otherwise a "wrong" +# exception is raised when calling unknown methods via xmlrpc +# * Added HTTP Basic authentication support +# +# Modified for the Sceradon project +# +# This code is in the public domain +# and is provided AS-IS WITH NO WARRANTY WHATSOEVER. +# $Id: SecureXMLRPCServer.py 5 2007-01-06 17:54:13Z hoffie $ + +from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler +import SocketServer +import socket +import base64 + + +class SecureSocketConnection: + def __init__(self, connection): + self.__dict__["connection"] = connection + + def __getattr__(self, name): + return getattr(self.__dict__["connection"], name) + + def __setattr__(self, name, value): + setattr(self.__dict__["connection"], name, value) + + def shutdown(self, how=1): + self.__dict__["connection"].shutdown() + + def accept(self): + connection, address = self.__dict__["connection"].accept() + return (SecureSocketConnection(connection), address) + +class SecureSocketServer(SocketServer.TCPServer, SocketServer.ThreadingMixIn): + def __init__(self, addr, cert, key, requestHandler, verify_cert_func=None): + SSL = __import__("OpenSSL", globals(), locals(), "SSL", -1).SSL + SocketServer.TCPServer.__init__(self, addr, requestHandler) + ctx = SSL.Context(SSL.SSLv23_METHOD) + if not verify_cert_func and hasattr(self, 'verify_client_cert'): + verify_cert_func = getattr(self, 'verify_client_cert') + if verify_cert_func: + ctx.set_verify(SSL.VERIFY_PEER|SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_cert_func) + ctx.use_privatekey_file(key) + ctx.use_certificate_file(cert) + + tmpConnection = SSL.Connection(ctx, socket.socket(socket.AF_INET, socket.SOCK_STREAM)) + self.socket = SecureSocketConnection(tmpConnection) + + self.server_bind() + self.server_activate() + + def finish_request(self, request, client_address): + """Finish one request by instantiating RequestHandlerClass.""" + self.RequestHandlerClass(request, client_address, self) + +####################################### +########### Request Handler ########### +####################################### + +class AuthXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): + def __init__(self, request, client_address, server): + self.authMap = server.getAuthenticationMap() + SimpleXMLRPCRequestHandler.__init__(self, request, client_address, server) + + def setup(self): + self.connection = self.request + self.rfile = socket._fileobject(self.request, "rb", self.rbufsize) + self.wfile = socket._fileobject(self.request, "wb", self.wbufsize) + + def do_POST(self): + # authentication + if self.authMap != None: # explicit None! + if self.headers.has_key('authorization') and self.headers['authorization'].startswith('Basic '): + authenticationString = base64.b64decode(self.headers['authorization'].split(' ')[1]) + if authenticationString.find(':') != -1: + username, password = authenticationString.split(':', 1) + if self.authMap.has_key(username) and self.verifyPassword(username, password): + return SimpleXMLRPCRequestHandler.do_POST(self) + self.send_response(401) + self.end_headers() + return False + return SimpleXMLRPCRequestHandler.do_POST(self) + + def verifyPassword(self, username, givenPassword): + return self.authMap[username] == givenPassword + + +class SecureXMLRPCRequestHandler(AuthXMLRPCRequestHandler): + def __init__(self, request, client_address, server, client_digest=None): + self.authMap = server.getAuthenticationMap() + SimpleXMLRPCRequestHandler.__init__(self, request, client_address, server) + self.client_digest = client_digest + +##################################### +########### XMLRPC Server ########### +##################################### + +class AuthXMLRPCServer(SimpleXMLRPCServer): + def __init__(self, address, authenticationMap = None, handler=AuthXMLRPCRequestHandler): + SimpleXMLRPCServer.__init__(self, address, requestHandler=handler) + self.logRequests = False + self._send_traceback_header = False + self.encoding = "utf-8" + self.allow_none = True + self.authenticationMap = authenticationMap + + def getAuthenticationMap(self): + return self.authenticationMap + +class SecureXMLRPCServer(AuthXMLRPCServer, SecureSocketServer): + def __init__(self, address, cert, key, authenticationMap = None, handler=SecureXMLRPCRequestHandler, verify_cert_func=None): + self.logRequests = False + self._send_traceback_header = False + self.encoding = "utf-8" + self.allow_none = True + SecureSocketServer.__init__(self, address, cert, key, handler, verify_cert_func) + # This comes from SimpleXMLRPCServer.__init__()->SimpleXMLRPCDispatcher.__init__() + self.funcs = {} + self.instance = None + self.authenticationMap = authenticationMap + + def getAuthenticationMap(self): + return self.authenticationMap diff --git a/module/remote/SocketServer.py b/module/remote/SocketServer.py deleted file mode 100644 index 2edd1d9f3..000000000 --- a/module/remote/SocketServer.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -""" -authored by: RaNaN - -This modul class handels all incoming and outgoing data between server and gui - -""" -import asynchat -import asyncore -import socket -import threading -import time - -from RequestHandler import RequestHandler - - -class ServerThread(threading.Thread): - def __init__(self, pycore): - threading.Thread.__init__(self) - self.setDaemon(True) - self.server = MainServerSocket(int(pycore.config['remote']['port']), pycore) - - def run(self): - asyncore.loop() - print "loop closed" - - def sockets(self): - """returns all connected sockets in a list""" - sockets = [] - for value in asyncore.socket_map.values(): - if SecondaryServerSocket == value.__class__: - sockets.append(value) - - return sockets - - def push_all(self, obj): - """push obj to all sockets""" - for socket in self.sockets(): - socket.push_obj(obj) - - -class MainServerSocket(asyncore.dispatcher): - def __init__(self, port, pycore): - asyncore.dispatcher.__init__(self) - pycore.logger.info('initing Remote-Server') - self.pycore = pycore - try: - self.create_socket(socket.AF_INET, socket.SOCK_STREAM) - self.bind(('', port)) - self.listen(5) - except: - raise Exception("Can't create socket") - def handle_accept(self): - newSocket, address = self.accept() - self.pycore.logger.info("Connected from " + str(address)) - SecondaryServerSocket(newSocket, self.pycore) - def handle_close(self): - print "going to close" - self.close() - - -class SecondaryServerSocket(asynchat.async_chat): - def __init__(self, socket, pycore): - asynchat.async_chat.__init__(self, socket) - self.pycore = pycore - self.handler = RequestHandler(pycore) - self.set_terminator('\n') - self.data = "" - def collect_incoming_data(self, data): - self.data += data - def found_terminator(self): - time.sleep(0.2) # if response is received to fast client gets an error O_o ?!?!? - rep = self.handler.proceed(self.data) - self.push(rep) - self.data = "" - #having fun with the data - def handle_close(self): - self.pycore.logger.info("Disconnected from "+ str(self.getpeername())) - self.close() - def push_obj(self, obj): - obj = self.handler.encrypt(obj) - self.push(obj) diff --git a/module/thread_list.py b/module/thread_list.py index d4f2dac97..1a66bf6f5 100644 --- a/module/thread_list.py +++ b/module/thread_list.py @@ -18,12 +18,12 @@ # ### from __future__ import with_statement +from os.path import exists import re import subprocess +from threading import RLock, Thread import time import urllib2 -from os.path import exists -from threading import RLock from download_thread import Download_Thread @@ -40,6 +40,8 @@ class Thread_List(object): self.reconnecting = False self.select_thread() + if self.parent.config['general']['download_speed_limit'] != 0: + self.speedManager = self.SpeedManager(self) def create_thread(self): """ creates thread for Py_Load_File and append thread to self.threads @@ -60,7 +62,7 @@ class Thread_List(object): def get_job(self): """return job if suitable, otherwise send thread idle""" - if not self.parent.is_dltime() or self.pause or self.reconnecting or not self.list.files: #conditions when threads dont download + if not self.parent.server_methods.is_time_download() or self.pause or self.reconnecting or self.list.queueEmpty(): #conditions when threads dont download return None self.init_reconnect() @@ -68,16 +70,19 @@ class Thread_List(object): self.lock.acquire() pyfile = None - for i in range(len(self.list.files)): - if not self.list.files[i].modul.__name__ in self.occ_plugins: - pyfile = self.list.files.pop(i) - break + pyfiles = self.list.getDownloadList(self.occ_plugins) - if pyfile: + if pyfiles: + pyfile = pyfiles[0] self.py_downloading.append(pyfile) + self.parent.hookManager.downloadStarts(pyfile) if not pyfile.plugin.multi_dl: self.occ_plugins.append(pyfile.modul.__name__) - self.parent.logger.info('Download starts: ' + pyfile.url) + pyfile.active = True + if pyfile.plugin.props['type'] == "container": + self.parent.logger.info('Get links from: ' + pyfile.url) + else: + self.parent.logger.info('Download starts: ' + pyfile.url) self.lock.release() return pyfile @@ -89,6 +94,8 @@ class Thread_List(object): if not pyfile.plugin.multi_dl: self.occ_plugins.remove(pyfile.modul.__name__) + + pyfile.active = False if pyfile.plugin.req.curl and not pyfile.status == "reconnected": try: @@ -99,41 +106,65 @@ class Thread_List(object): self.py_downloading.remove(pyfile) if pyfile.status.type == "finished": - self.parent.logger.info('Download finished: ' + pyfile.url + ' @' + str(pyfile.status.get_speed()) + 'kb/s') - - self.list.remove(pyfile) - if pyfile.plugin.props['type'] == "container": - self.list.extend(pyfile.plugin.links) - - - elif pyfile.status.type == "reconnected":#put it back in queque + newLinks = 0 + if pyfile.plugin.links: + if isinstance(pyfile.plugin.links, dict): + packmap = {} + for packname in pyfile.plugin.links.keys(): + packmap[packname] = self.list.packager.addNewPackage(packname) + for packname, links in pyfile.plugin.links.items(): + pid = packmap[packname] + for link in links: + newFile = self.list.collector.addLink(link) + self.list.packager.addFileToPackage(pid, self.list.collector.popFile(newFile)) + newLinks += 1 + else: + for link in pyfile.plugin.links: + newFile = self.list.collector.addLink(link) + self.list.packager.addFileToPackage(pyfile.package.data["id"], self.list.collector.popFile(newFile)) + newLinks += 1 + #self.list.packager.pushPackage2Queue(pyfile.package.data["id"]) + self.list.packager.removeFileFromPackage(pyfile.id, pyfile.package.data["id"]) + + if newLinks: + self.parent.logger.info("Parsed links from %s: %i" % (pyfile.status.filename, newLinks)) + else: + self.parent.logger.info("No links in %s" % pyfile.status.filename) + #~ self.list.packager.removeFileFromPackage(pyfile.id, pyfile.package.id) + #~ for link in pyfile.plugin.links: + #~ id = self.list.collector.addLink(link) + #~ pyfile.packager.pullOutPackage(pyfile.package.id) + #~ pyfile.packager.addFileToPackage(pyfile.package.id, pyfile.collector.popFile(id)) + else: + self.parent.logger.info("Download finished: %s" % pyfile.url) + + elif pyfile.status.type == "reconnected": pyfile.plugin.req.init_curl() - self.list.files.insert(0, pyfile) elif pyfile.status.type == "failed": - self.parent.logger.warning("Download failed: " + pyfile.url+ " | " + pyfile.status.error) + self.parent.logger.warning("Download failed: " + pyfile.url + " | " + pyfile.status.error) with open(self.parent.config['general']['failed_file'], 'a') as f: f.write(pyfile.url + "\n") - self.list.remove(pyfile) elif pyfile.status.type == "aborted": self.parent.logger.info("Download aborted: " + pyfile.url) - self.list.remove(pyfile) self.list.save() + self.parent.hookManager.downloadFinished(pyfile) + self.lock.release() return True def init_reconnect(self): """initialise a reonnect""" - if not self.parent.config['general']['use_reconnect'] or self.reconnecting or not self.parent.is_reconnect_time(): + if not self.parent.config['reconnect']['activated'] or self.reconnecting or not self.parent.server_methods.is_time_reconnect(): return False - if not exists(self.parent.config['general']['reconnect_method']): - self.parent.logger.info(self.parent.config['general']['reconnect_method'] + " not found") - self.parent.config['general']['use_reconnect'] = False + if not exists(self.parent.config['reconnect']['method']): + self.parent.logger.info(self.parent.config['reconnect']['method'] + " not found") + self.parent.config['reconnect']['activated'] = False return False self.lock.acquire() @@ -167,14 +198,104 @@ class Thread_List(object): return False def reconnect(self): - reconn = subprocess.Popen(self.parent.config['general']['reconnect_method']) + self.parent.logger.info("Start reconnect") + ip = re.match(".*Current IP Address: (.*)</body>.*", urllib2.urlopen("http://checkip.dyndns.org/").read()).group(1) + self.parent.hookManager.beforeReconnecting(ip) + reconn = subprocess.Popen(self.parent.config['reconnect']['method'])#, stdout=subprocess.PIPE) reconn.wait() time.sleep(1) ip = "" - while ip == "": #solange versuch bis neue ip ausgelesen + while ip == "": try: ip = re.match(".*Current IP Address: (.*)</body>.*", urllib2.urlopen("http://checkip.dyndns.org/").read()).group(1) #versuchen neue ip aus zu lesen except: ip = "" time.sleep(1) + self.parent.hookManager.afterReconnecting(ip) self.parent.logger.info("Reconnected, new IP: " + ip) + + def stopAllDownloads(self): + self.pause = True + for pyfile in self.py_downloading: + pyfile.plugin.req.abort = True + + class SpeedManager(Thread): + def __init__(self, parent): + Thread.__init__(self) + self.parent = parent + self.running = True + self.lastSlowCheck = 0.0 + + stat = {} + stat["slow_downloads"] = None + stat["each_speed"] = None + stat["each_speed_optimized"] = None + self.stat = stat + + self.slowCheckInterval = 60 + self.slowCheckTestTime = 25 + + self.logger = self.parent.parent.logger + self.start() + + def run(self): + while self.running: + time.sleep(1) + self.manageSpeed() + + def getMaxSpeed(self): + return self.parent.parent.getMaxSpeed() + + def manageSpeed(self): + maxSpeed = self.getMaxSpeed() + if maxSpeed <= 0: + for thread in self.parent.py_downloading: + thread.plugin.req.speedLimitActive = False + return + threads = self.parent.py_downloading + threadCount = len(threads) + if threadCount <= 0: + return + eachSpeed = maxSpeed/threadCount + + currentOverallSpeed = 0 + restSpeed = maxSpeed - currentOverallSpeed + speeds = [] + for thread in threads: + currentOverallSpeed += thread.plugin.req.dl_speed + speeds.append((thread.plugin.req.dl_speed, thread.plugin.req.averageSpeed, thread)) + thread.plugin.req.speedLimitActive = True + + if currentOverallSpeed+50 < maxSpeed: + for thread in self.parent.py_downloading: + thread.plugin.req.speedLimitActive = False + return + + slowCount = 0 + slowSpeed = 0 + if self.lastSlowCheck + self.slowCheckInterval + self.slowCheckTestTime < time.time(): + self.lastSlowCheck = time.time() + if self.lastSlowCheck + self.slowCheckInterval < time.time() < self.lastSlowCheck + self.slowCheckInterval + self.slowCheckTestTime: + for speed in speeds: + speed[2].plugin.req.isSlow = False + else: + for speed in speeds: + if speed[0] <= eachSpeed-7: + if speed[1] < eachSpeed-15: + if speed[2].plugin.req.dl_time > 0 and speed[2].plugin.req.dl_time+30 < time.time(): + speed[2].plugin.req.isSlow = True + if not speed[1]-5 < speed[2].plugin.req.maxSpeed/1024 < speed[1]+5: + speed[2].plugin.req.maxSpeed = (speed[1]+10)*1024 + if speed[2].plugin.req.isSlow: + slowCount += 1 + slowSpeed += speed[2].plugin.req.maxSpeed/1024 + + stat["slow_downloads"] = slowCount + stat["each_speed"] = eachSpeed + eachSpeed = (maxSpeed - slowSpeed) / (threadCount - slowCount) + stat["each_speed_optimized"] = eachSpeed + for speed in speeds: + if speed[2].plugin.req.isSlow: + continue + speed[2].plugin.req.maxSpeed = eachSpeed*1024 + print "max", speed[2].plugin.req.maxSpeed, "current", speed[2].plugin.req.dl_speed diff --git a/module/unescape.py b/module/unescape.py index 462423b03..59f35f36b 100644 --- a/module/unescape.py +++ b/module/unescape.py @@ -1,12 +1,25 @@ +from htmlentitydefs import name2codepoint as n2cp +import re + +def substitute_entity(match): + ent = match.group(2) + if match.group(1) == "#": + return unichr(int(ent)) + else: + cp = n2cp.get(ent) + if cp: + return unichr(cp) + else: + return match.group() + +def unescape(string): + entity_re = re.compile("&(#?)(\d{1,5}|\w{1,8});") + return entity_re.subn(substitute_entity, string)[0] + +""" import re def unescape(text): - """Removes HTML or XML character references - and entities from a text string. - keep &, >, < in the source code. - from Fredrik Lundh - http://effbot.org/zone/re-sub.htm#unescape-html - """ def fixup(m): text = m.group(0) if text[:2] == "&#": @@ -35,4 +48,5 @@ def unescape(text): print "keyerror" pass return text # leave as is - return str(re.sub("&#?\w+;", fixup, text)) + return re.sub("&#?\w+;", fixup, text) +""" diff --git a/module/web/ServerThread.py b/module/web/ServerThread.py new file mode 100644 index 000000000..1276966ef --- /dev/null +++ b/module/web/ServerThread.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +from __future__ import with_statement +import threading +from os.path import join +from os.path import exists +from subprocess import Popen, PIPE, STDOUT +from time import sleep +from signal import SIGINT +import os + +class WebServer(threading.Thread): + def __init__(self, pycore): + threading.Thread.__init__(self) + self.pycore = pycore + self.running = True + self.setDaemon(True) + + def run(self): + host = self.pycore.config['webinterface']['host'] + port = self.pycore.config['webinterface']['port'] + + if not exists(join(self.pycore.path,"module","web","pyload.db")): + print "########## IMPORTANT ###########" + print "### Database for Webinterface doesnt exitst, it will not be available." + print "### Please run: python %s syncdb" % join(self.pycore.path,"module","web","manage.py") + print "### You have to add at least one User, to gain access to webinterface: python %s createsuperuser" % join(self.pycore.path,"module","web","manage.py") + print "### Dont forget to restart pyLoad if you are done." + print "################################" + raise Exception, "Database doesnt exists, please use syncdb" + + self.pycore.logger.info("Starting Webserver: %s:%s" % (host,port) ) + + if os.name == 'posix': + command = ['python',join(self.pycore.path,"module","web","run_unix.py"), "runserver", "%s:%s" % (host,port)] + self.p = Popen(command, close_fds=True, stderr=PIPE, stdin=PIPE, stdout=PIPE) + #os.system("python " + join(self.pycore.path,"module","web","manage.py runserver %s:%s" % (host,port))) + #@TODO: better would be real python code + sleep(1) + with open("webserver.pid", "r") as f: + self.pid = int(f.read().strip()) + while self.running: + sleep(1) + else: + command = ['python',join(self.pycore.path,"module","web","manage.py"), "runserver", "%s:%s" % (host,port)] + self.p = Popen(command, stderr=PIPE, stdin=PIPE, stdout=PIPE) + while self.running: + sleep(1) + + def quit(self): + if os.name == 'posix': + try: + os.kill(self.pid, SIGINT) + except: + pass + else: + self.p.kill() + + self.running = False diff --git a/module/web/WebServer.py b/module/web/WebServer.py deleted file mode 100644 index 8cef0de2f..000000000 --- a/module/web/WebServer.py +++ /dev/null @@ -1,290 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# -#Copyright (C) 2009 RaNaN -# -#This program is free software; you can redistribute it and/or modify -#it under the terms of the GNU General Public License as published by -#the Free Software Foundation; either version 3 of the License, -#or (at your option) any later version. -# -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#See the GNU General Public License for more details. -# -#You should have received a copy of the GNU General Public License -# along with this program; if not, see <http://www.gnu.org/licenses/>. -# -### - -import random -import threading -import time - -import bottle -from bottle import abort -from bottle import redirect -from bottle import request -from bottle import response -from bottle import route -from bottle import run -from bottle import send_file -from bottle import template -from bottle import validate - - -core = None - -PATH = "./module/web/" -TIME = time.strftime("%a, %d %b %Y 00:00:00 +0000", time.localtime()) #set time to current day -USERS = {} - -@route('/login', method='POST') -def do_login(): - #print request.GET - - - username = core.config['webinterface']['username'] - pw = core.config['webinterface']['password'] - - if request.POST['u'] == username and request.POST['p'] == pw: - - id = int(random.getrandbits(16)) - ua = request.HEADER("HTTP_USER_AGENT") - ip = request.HEADER("REMOTE_ADDR") - - auth = {} - - auth['ua'] = ua - auth['ip'] = ip - auth['user'] = username - - USERS[id] = auth - - response.COOKIES['user'] = username - response.COOKIES['id'] = id - - return template('default', page='loggedin', user=username) - else: - return template('default', page='login') - -@route('/login') -def login(): - - if check_auth(request): - redirect("/") - - return template('default', page='login') - -@route('/logout') -def logout(): - try: - del USERS[int(request.COOKIES.get('id'))] - except: - pass - - redirect("/login") - -@route('/') -def home(): - - if not check_auth(request): - redirect("/login") - - username = request.COOKIES.get('user') - - dls = core.get_downloads() - - for dl in dls: - dl['eta'] = str(core.format_time(dl['eta'])) - dl['wait_until'] = str(core.format_time(dl['wait_until'] - time.time())) - - - return template('default', page='home', links=dls, user=username, status=core.server_status()) - -@route('/queue') -def queue(): - - if not check_auth(request): - redirect("/login") - - username = request.COOKIES.get('user') - - return template('default', page='queue', links=core.get_links(), user=username, status=core.server_status()) - -@route('/downloads') -def downloads(): - - if not check_auth(request): - redirect("/login") - - username = request.COOKIES.get('user') - - return template('default', page='downloads', links=core.get_downloads(), user=username, status=core.server_status()) - - -@route('/logs') -def logs(): - - if not check_auth(request): - redirect("/login") - - username = request.COOKIES.get('user') - - return template('default', page='logs', links=core.get_downloads(), user=username, status=core.server_status()) - -@route('/json/links') -def get_links(): - response.header['Cache-Control'] = 'no-cache, must-revalidate' - response.content_type = 'application/json' - - if not check_auth(request): - abort(404, "No Access") - - json = '{ "downloads": [' - - downloads = core.get_downloads() - ids = [] - - for dl in downloads: - ids.append(dl['id']) - json += '{' - json += '"id": %s, "name": "%s", "speed": %s, "eta": "%s", "kbleft": %s, "size": %s, "percent": %s, "wait": "%s", "status": "%s"'\ - % (str(dl['id']), str(dl['name']), str(int(dl['speed'])), str(core.format_time(dl['eta'])), dl['kbleft'], dl['size'], dl['percent'], str(core.format_time(dl['wait_until'] - time.time())), dl['status']) - - json += "}," - - if json.endswith(","): json = json[:-1] - - json += '], "ids": %s }' % str(ids) - - return json - -@route('/json/status') -def get_status(): - response.header['Cache-Control'] = 'no-cache, must-revalidate' - response.content_type = 'application/json' - - if not check_auth(request): - abort(404, "No Access") - - data = core.server_status() - - if data['pause']: - status = "paused" - else: - status = "running" - - json = '{ "status": "%s", "speed": "%s", "queue": "%s" }' % (status, str(int(data['speed'])), str(data['queue'])) - - return json - -@route('/json/addlinks', method='POST') -def add_links(): - response.header['Cache-Control'] = 'no-cache, must-revalidate' - response.content_type = 'application/json' - - if not check_auth(request): - abort(404, "No Access") - - links = request.POST['links'].split('\n') - - core.add_links(links) - - return "{}" - -@route('/json/pause') -def pause(): - response.header['Cache-Control'] = 'no-cache, must-revalidate' - response.content_type = 'application/json' - - if not check_auth(request): - abort(404, "No Access") - - core.thread_list.pause = True - - return "{}" - - -@route('/json/play') -def play(): - response.header['Cache-Control'] = 'no-cache, must-revalidate' - response.content_type = 'application/json' - - if not check_auth(request): - abort(404, "No Access") - - core.thread_list.pause = False - - return "{}" - -@route('/favicon.ico') -def favicon(): - - if request.HEADER("HTTP_IF_MODIFIED_SINCE") == TIME: abort(304, "Not Modified") - - response.header['Last-Modified'] = TIME - - send_file('favicon.ico', root=(PATH + 'static/')) - -@route('static/:section/:filename') -def static_folder(section, filename): - - if request.HEADER("HTTP_IF_MODIFIED_SINCE") == TIME: abort(304, "Not Modified") - - response.header['Last-Modified'] = TIME - send_file(filename, root=(PATH + 'static/' + section)) - -@route('/static/:filename') -def static_file(filename): - - if request.HEADER("HTTP_IF_MODIFIED_SINCE") == TIME: abort(304, "Not Modified") - - response.header['Last-Modified'] = TIME - send_file(filename, root=(PATH + 'static/')) - - -def check_auth(req): - - try: - user = req.COOKIES.get('user') - id = int(req.COOKIES.get('id')) - ua = req.HEADER("HTTP_USER_AGENT") - ip = req.HEADER("REMOTE_ADDR") - - if USERS[id]['user'] == user and USERS[id]['ua'] == ua and USERS[id]['ip'] == ip: - return True - except: - return False - - return False - - -class WebServer(threading.Thread): - def __init__(self, pycore): - threading.Thread.__init__(self) - - global core, TIME - core = pycore - self.core = pycore - self.setDaemon(True) - - if pycore.config['general']['debug_mode']: - bottle.debug(True) - TIME = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime()) - else: - bottle.debug(False) - - #@TODO remove - #TIME = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime()) - - bottle.TEMPLATE_PATH.append('./module/web/templates/%s.tpl') - - def run(self): - self.core.logger.info("Starting Webinterface on %s port %s" % (self.core.config['webinterface']['listenaddr'],self.core.config['webinterface']['port'])) - try: - run(host=self.core.config['webinterface']['listenaddr'], port=int(self.core.config['webinterface']['port']), quiet=True) - except: - self.core.logger.error("Failed starting webserver, no webinterface available: Can't create socket") - exit() diff --git a/module/web/ajax/__init__.py b/module/web/ajax/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/module/web/ajax/__init__.py diff --git a/module/web/ajax/models.py b/module/web/ajax/models.py new file mode 100644 index 000000000..35e0d6486 --- /dev/null +++ b/module/web/ajax/models.py @@ -0,0 +1,2 @@ + +# Create your models here. diff --git a/module/web/ajax/tests.py b/module/web/ajax/tests.py new file mode 100644 index 000000000..2247054b3 --- /dev/null +++ b/module/web/ajax/tests.py @@ -0,0 +1,23 @@ +""" +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 new file mode 100644 index 000000000..d50e7121e --- /dev/null +++ b/module/web/ajax/urls.py @@ -0,0 +1,29 @@ +# -*- 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'), + )
\ No newline at end of file diff --git a/module/web/ajax/views.py b/module/web/ajax/views.py new file mode 100644 index 000000000..4d9762ab4 --- /dev/null +++ b/module/web/ajax/views.py @@ -0,0 +1,196 @@ +# Create your views here. +from os.path import join + +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 + +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'] + + links = request.POST['add_links'].replace(" ","\n").split("\n") + + try: + f = request.FILES['add_file'] + + if name == None or name == "": + name = f.name + + fpath = join(settings.DL_ROOT, f.name) + destination = open(fpath, 'wb') + for chunk in f.chunks(): + destination.write(chunk) + destination.close() + links.insert(0, fpath) + except: + pass + + if name == None or name == "": + return HttpResponseServerError() + + links = filter(lambda x: x != "", links) + + settings.PYLOAD.add_package(name, links) + + return JsonResponse("success") + +@permission('pyload.can_add_dl') +def remove_link(request, id): + try: + settings.PYLOAD.del_links([int(id)]) + return JsonResponse("sucess") + except: + return HttpResponseServerError() + +@permission('pyload.can_see_dl') +def status(request): + try: + return JsonResponse(settings.PYLOAD.status_server()) + except: + return HttpResponseServerError() + +@permission('pyload.can_see_dl') +def links(request): + try: + links = settings.PYLOAD.status_downloads() + ids = map(lambda x: x['id'], links) + data = {} + data['links'] = links + data['ids'] = ids + return JsonResponse(data) + except: + 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)) + data['links'] = [] + for file in settings.PYLOAD.get_package_files(data['id']): + data['links'].append(settings.PYLOAD.get_file_info(file)) + + return JsonResponse(data) + + except: + 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_add_dl') +def remove_package(request, id): + try: + settings.PYLOAD.del_packages([int(id)]) + return JsonResponse("sucess") + except: + return HttpResponseServerError() + +@permission('pyload.can_add_dl') +def restart_package(request, id): + try: + settings.PYLOAD.restart_package(int(id)) + return JsonResponse("sucess") + except: + return HttpResponseServerError() + +@permission('pyload.can_add_dl') +def restart_link(request, id): + try: + settings.PYLOAD.restart_file(int(id)) + return JsonResponse("sucess") + except: + return HttpResponseServerError() + +@permission('pyload.can_add_dl') +def abort_link(request, id): + try: + settings.PYLOAD.stop_download("link", int(id)) + return JsonResponse("sucess") + except: + return HttpResponseServerError()
\ No newline at end of file diff --git a/module/web/bottle.py b/module/web/bottle.py deleted file mode 100644 index 66ceb527f..000000000 --- a/module/web/bottle.py +++ /dev/null @@ -1,886 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Bottle is a fast and simple mirco-framework for small web-applications. It -offers request dispatching (Routes) with url parameter support, Templates, -key/value Databases, a build-in HTTP Server and adapters for many third party -WSGI/HTTP-server and template engines. All in a single file and with no -dependencies other than the Python Standard Library. - -Homepage and documentation: http://wiki.github.com/defnull/bottle - -Special thanks to Stefan Matthias Aust [http://github.com/sma] - for his contribution to SimpelTemplate - -Licence (MIT) -------------- - - Copyright (c) 2009, Marcel Hellkamp. - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - - -Example -------- - - from bottle import route, run, request, response, send_file, abort - - @route('/') - def hello_world(): - return 'Hello World!' - - @route('/hello/:name') - def hello_name(name): - return 'Hello %s!' % name - - @route('/hello', method='POST') - def hello_post(): - name = request.POST['name'] - return 'Hello %s!' % name - - @route('/static/:filename#.*#') - def static_file(filename): - send_file(filename, root='/path/to/static/files/') - - run(host='localhost', port=8080) - -""" - -__author__ = 'Marcel Hellkamp' -__version__ = '0.5.7' -__license__ = 'MIT' - -import sys -import cgi -import mimetypes -import os -import os.path -import traceback -import re -import random -import threading -import time -from wsgiref.headers import Headers as HeaderWrapper -from Cookie import SimpleCookie -import anydbm as dbm - -try: - from urlparse import parse_qs -except ImportError: - from cgi import parse_qs - -try: - import cPickle as pickle -except ImportError: - import pickle as pickle - -try: - try: - from json import dumps as json_dumps - except ImportError: - from simplejson import dumps as json_dumps -except ImportError: - json_dumps = None - - - - - - -# Exceptions and Events - -class BottleException(Exception): - """ A base class for exceptions used by bottle.""" - pass - - -class HTTPError(BottleException): - """ A way to break the execution and instantly jump to an error handler. """ - def __init__(self, status, text): - self.output = text - self.http_status = int(status) - - def __repr__(self): - return "HTTPError(%d,%s)" % (self.http_status, repr(self.output)) - - def __str__(self): - out = [] - status = self.http_status - name = HTTP_CODES.get(status,'Unknown').title() - url = request.path - out.append('<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">') - out.append('<html><head><title>Error %d: %s</title>' % (status, name)) - out.append('</head><body><h1>Error %d: %s</h1>' % (status, name)) - out.append('<p>Sorry, the requested URL "%s" caused an error.</p>' % url) - out.append(''.join(list(self.output))) - out.append('</body></html>') - return "\n".join(out) - - -class BreakTheBottle(BottleException): - """ Not an exception, but a straight jump out of the controller code. - - Causes the Bottle to instantly call start_response() and return the - content of output """ - def __init__(self, output): - self.output = output - - - - - - -# WSGI abstraction: Request and response management - -_default_app = None -def default_app(newapp = None): - ''' Returns the current default app or sets a new one. - Defaults to an instance of Bottle ''' - global _default_app - if newapp: - _default_app = newapp - if not _default_app: - _default_app = Bottle() - return _default_app - - -class Bottle(object): - - def __init__(self, catchall=True, debug=False, optimize=False, autojson=True): - self.simple_routes = {} - self.regexp_routes = {} - self.error_handler = {} - self.optimize = optimize - self.debug = debug - self.autojson = autojson - self.catchall = catchall - - def match_url(self, url, method='GET'): - """Returns the first matching handler and a parameter dict or (None, None) """ - url = url.strip().lstrip("/ ") - # Search for static routes first - route = self.simple_routes.get(method,{}).get(url,None) - if route: - return (route, {}) - - routes = self.regexp_routes.get(method,[]) - for i in range(len(routes)): - match = routes[i][0].match(url) - if match: - handler = routes[i][1] - if i > 0 and self.optimize and random.random() <= 0.001: - routes[i-1], routes[i] = routes[i], routes[i-1] - return (handler, match.groupdict()) - return (None, None) - - def add_route(self, route, handler, method='GET', simple=False): - """ Adds a new route to the route mappings. """ - method = method.strip().upper() - route = route.strip().lstrip('$^/ ').rstrip('$^ ') - if re.match(r'^(\w+/)*\w*$', route) or simple: - self.simple_routes.setdefault(method, {})[route] = handler - else: - route = re.sub(r':([a-zA-Z_]+)(?P<uniq>[^\w/])(?P<re>.+?)(?P=uniq)',r'(?P<\1>\g<re>)',route) - route = re.sub(r':([a-zA-Z_]+)',r'(?P<\1>[^/]+)', route) - route = re.compile('^%s$' % route) - self.regexp_routes.setdefault(method, []).append([route, handler]) - - def route(self, url, **kargs): - """ Decorator for request handler. Same as add_route(url, handler, **kargs).""" - def wrapper(handler): - self.add_route(url, handler, **kargs) - return handler - return wrapper - - def set_error_handler(self, code, handler): - """ Adds a new error handler. """ - code = int(code) - self.error_handler[code] = handler - - def error(self, code=500): - """ Decorator for error handler. Same as set_error_handler(code, handler).""" - def wrapper(handler): - self.set_error_handler(code, handler) - return handler - return wrapper - - def __call__(self, environ, start_response): - """ The bottle WSGI-interface .""" - request.bind(environ) - response.bind() - try: # Unhandled Exceptions - try: # Bottle Error Handling - handler, args = self.match_url(request.path, request.method) - if not handler: raise HTTPError(404, "Not found") - output = handler(**args) - db.close() - except BreakTheBottle, e: - output = e.output - except HTTPError, e: - response.status = e.http_status - output = self.error_handler.get(response.status, str)(e) - # output casting - if hasattr(output, 'read'): - output = environ.get('wsgi.file_wrapper', lambda x: iter(lambda: x.read(8192), ''))(output) - elif self.autojson and json_dumps and isinstance(output, dict): - output = json_dumps(output) - response.content_type = 'application/json' - if isinstance(output, str): - response.header['Content-Length'] = str(len(output)) - output = [output] - except (KeyboardInterrupt, SystemExit, MemoryError): - raise - except Exception, e: - response.status = 500 - if self.catchall: - err = "Unhandled Exception: %s\n" % (repr(e)) - if self.debug: - err += "<h2>Traceback:</h2>\n<pre>\n" - err += traceback.format_exc(10) - err += "\n</pre>" - output = str(HTTPError(500, err)) - request._environ['wsgi.errors'].write(err) - else: - raise - status = '%d %s' % (response.status, HTTP_CODES[response.status]) - start_response(status, response.wsgiheaders()) - return output - - - -class Request(threading.local): - """ Represents a single request using thread-local namespace. """ - - def bind(self, environ): - """ Binds the enviroment of the current request to this request handler """ - self._environ = environ - self._GET = None - self._POST = None - self._GETPOST = None - self._COOKIES = None - self.path = self._environ.get('PATH_INFO', '/').strip() - if not self.path.startswith('/'): - self.path = '/' + self.path - - @property - def method(self): - ''' Returns the request method (GET,POST,PUT,DELETE,...) ''' - return self._environ.get('REQUEST_METHOD', 'GET').upper() - - @property - def query_string(self): - ''' Content of QUERY_STRING ''' - return self._environ.get('QUERY_STRING', '') - - @property - def input_length(self): - ''' Content of CONTENT_LENGTH ''' - try: - return int(self._environ.get('CONTENT_LENGTH', '0')) - except ValueError: - return 0 - - @property - def GET(self): - """Returns a dict with GET parameters.""" - if self._GET is None: - data = parse_qs(self.query_string, keep_blank_values=True) - self._GET = {} - for key, value in data.iteritems(): - if len(value) == 1: - self._GET[key] = value[0] - else: - self._GET[key] = value - return self._GET - - @property - def POST(self): - """Returns a dict with parsed POST or PUT data.""" - if self._POST is None: - data = cgi.FieldStorage(fp=self._environ['wsgi.input'], environ=self._environ, keep_blank_values=True) - self._POST = {} - for item in data.list: - name = item.name - if not item.filename: - item = item.value - self._POST.setdefault(name, []).append(item) - for key in self._POST: - if len(self._POST[key]) == 1: - self._POST[key] = self._POST[key][0] - return self._POST - - @property - def params(self): - ''' Returns a mix of GET and POST data. POST overwrites GET ''' - if self._GETPOST is None: - self._GETPOST = dict(self.GET) - self._GETPOST.update(dict(self.POST)) - return self._GETPOST - - @property - def COOKIES(self): - """Returns a dict with COOKIES.""" - if self._COOKIES is None: - raw_dict = SimpleCookie(self._environ.get('HTTP_COOKIE','')) - self._COOKIES = {} - for cookie in raw_dict.itervalues(): - self._COOKIES[cookie.key] = cookie.value - return self._COOKIES - - def HEADER(self, header): - """Returns HTTP header""" - return self._environ.get(header, '') - -class Response(threading.local): - """ Represents a single response using thread-local namespace. """ - - def bind(self): - """ Clears old data and creates a brand new Response object """ - self._COOKIES = None - self.status = 200 - self.header_list = [] - self.header = HeaderWrapper(self.header_list) - self.content_type = 'text/html' - self.error = None - - def wsgiheaders(self): - ''' Returns a wsgi conform list of header/value pairs ''' - for c in self.COOKIES.itervalues(): - self.header.add_header('Set-Cookie', c.OutputString()) - return [(h.title(), str(v)) for h, v in self.header.items()] - - @property - def COOKIES(self): - if not self._COOKIES: - self._COOKIES = SimpleCookie() - return self._COOKIES - - def set_cookie(self, key, value, **kargs): - """ Sets a Cookie. Optional settings: expires, path, comment, domain, max-age, secure, version, httponly """ - self.COOKIES[key] = value - for k in kargs: - self.COOKIES[key][k] = kargs[k] - - def get_content_type(self): - '''Gives access to the 'Content-Type' header and defaults to 'text/html'.''' - return self.header['Content-Type'] - - def set_content_type(self, value): - self.header['Content-Type'] = value - - content_type = property(get_content_type, set_content_type, None, get_content_type.__doc__) - - -def abort(code=500, text='Unknown Error: Appliction stopped.'): - """ Aborts execution and causes a HTTP error. """ - raise HTTPError(code, text) - - -def redirect(url, code=307): - """ Aborts execution and causes a 307 redirect """ - response.status = code - response.header['Location'] = url - raise BreakTheBottle("") - - -def send_file(filename, root, guessmime = True, mimetype = 'text/plain'): - """ Aborts execution and sends a static files as response. """ - root = os.path.abspath(root) + '/' - filename = os.path.normpath(filename).strip('/') - filename = os.path.join(root, filename) - - if not filename.startswith(root): - abort(401, "Access denied.") - if not os.path.exists(filename) or not os.path.isfile(filename): - abort(404, "File does not exist.") - if not os.access(filename, os.R_OK): - abort(401, "You do not have permission to access this file.") - - if guessmime: - guess = mimetypes.guess_type(filename)[0] - if guess: - response.content_type = guess - elif mimetype: - response.content_type = mimetype - elif mimetype: - response.content_type = mimetype - - stats = os.stat(filename) - # TODO: HTTP_IF_MODIFIED_SINCE -> 304 (Thu, 02 Jul 2009 23:16:31 CEST) - if 'Content-Length' not in response.header: - response.header['Content-Length'] = stats.st_size - if 'Last-Modified' not in response.header: - ts = time.gmtime(stats.st_mtime) - ts = time.strftime("%a, %d %b %Y %H:%M:%S +0000", ts) - response.header['Last-Modified'] = ts - - raise BreakTheBottle(open(filename, 'r')) - - - - - - -# Decorators - -def validate(**vkargs): - ''' Validates and manipulates keyword arguments by user defined callables - and handles ValueError and missing arguments by raising HTTPError(403) ''' - def decorator(func): - def wrapper(**kargs): - for key in vkargs: - if key not in kargs: - abort(403, 'Missing parameter: %s' % key) - try: - kargs[key] = vkargs[key](kargs[key]) - except ValueError, e: - abort(403, 'Wrong parameter format for: %s' % key) - return func(**kargs) - return wrapper - return decorator - - -def route(url, **kargs): - """ Decorator for request handler. Same as add_route(url, handler, **kargs).""" - return default_app().route(url, **kargs) - - -def error(code=500): - """ Decorator for error handler. Same as set_error_handler(code, handler).""" - return default_app().error(code) - - - - - - -# Server adapter - -class ServerAdapter(object): - def __init__(self, host='127.0.0.1', port=8080, **kargs): - self.host = host - self.port = int(port) - self.options = kargs - - def __repr__(self): - return "%s (%s:%d)" % (self.__class__.__name__, self.host, self.port) - - def run(self, handler): - pass - - -class WSGIRefServer(ServerAdapter): - def run(self, handler): - from wsgiref.simple_server import make_server - srv = make_server(self.host, self.port, handler) - srv.serve_forever() - - -class CherryPyServer(ServerAdapter): - def run(self, handler): - from cherrypy import wsgiserver - server = wsgiserver.CherryPyWSGIServer((self.host, self.port), handler) - server.start() - - -class FlupServer(ServerAdapter): - def run(self, handler): - from flup.server.fcgi import WSGIServer - WSGIServer(handler, bindAddress=(self.host, self.port)).run() - - -class PasteServer(ServerAdapter): - def run(self, handler): - from paste import httpserver - from paste.translogger import TransLogger - app = TransLogger(handler) - httpserver.serve(app, host=self.host, port=str(self.port)) - - -class FapwsServer(ServerAdapter): - """ Extreamly fast Webserver using libev (see http://william-os4y.livejournal.com/) - Experimental ... """ - def run(self, handler): - import fapws._evwsgi as evwsgi - from fapws import base - import sys - evwsgi.start(self.host, self.port) - evwsgi.set_base_module(base) - def app(environ, start_response): - environ['wsgi.multiprocess'] = False - return handler(environ, start_response) - evwsgi.wsgi_cb(('',app)) - evwsgi.run() - - -def run(app=None, server=WSGIRefServer, host='127.0.0.1', port=8080, **kargs): - """ Runs bottle as a web server, using Python's built-in wsgiref implementation by default. - - You may choose between WSGIRefServer, CherryPyServer, FlupServer and - PasteServer or write your own server adapter. - """ - if not app: - app = default_app() - - quiet = bool('quiet' in kargs and kargs['quiet']) - - # Instanciate server, if it is a class instead of an instance - if isinstance(server, type) and issubclass(server, ServerAdapter): - server = server(host=host, port=port, **kargs) - - if not isinstance(server, ServerAdapter): - raise RuntimeError("Server must be a subclass of ServerAdapter") - - if not quiet: - print 'Bottle server starting up (using %s)...' % repr(server) - print 'Listening on http://%s:%d/' % (server.host, server.port) - print 'Use Ctrl-C to quit.' - print - - try: - server.run(app) - except KeyboardInterrupt: - print "Shuting down..." - - - - - - -# Templates - -class BaseTemplate(object): - def __init__(self, template='', filename=None): - self.source = filename - if self.source: - fp = open(filename) - template = fp.read() - fp.close() - self.parse(template) - - def parse(self, template): raise NotImplementedError - def render(self, **args): raise NotImplementedError - - @classmethod - def find(cls, name): - for path in TEMPLATE_PATH: - if os.path.isfile(path % name): - return cls(filename = path % name) - return None - - -class MakoTemplate(BaseTemplate): - def parse(self, template): - from mako.template import Template - self.tpl = Template(template) - - def render(self, **args): - return self.tpl.render(**args) - - -class CheetahTemplate(BaseTemplate): - def parse(self, template): - from Cheetah.Template import Template - self.context = threading.local() - self.context.vars = {} - self.tpl = Template(source = template, searchList=[self.context.vars]) - - def render(self, **args): - self.context.vars.update(args) - out = str(self.tpl) - self.context.vars.clear() - return out - - -class SimpleTemplate(BaseTemplate): - re_python = re.compile(r'^\s*%\s*(?:(if|elif|else|try|except|finally|for|while|with|def|class)|(include)|(end)|(.*))') - re_inline = re.compile(r'\{\{(.*?)\}\}') - dedent_keywords = ('elif', 'else', 'except', 'finally') - - def translate(self, template): - indent = 0 - strbuffer = [] - code = [] - self.subtemplates = {} - class PyStmt(str): - def __repr__(self): return 'str(' + self + ')' - def flush(allow_nobreak=False): - if len(strbuffer): - if allow_nobreak and strbuffer[-1].endswith("\\\\\n"): - strbuffer[-1]=strbuffer[-1][:-3] - code.append(" " * indent + "stdout.append(%s)" % repr(''.join(strbuffer))) - code.append((" " * indent + "\n") * len(strbuffer)) # to preserve line numbers - del strbuffer[:] - for line in template.splitlines(True): - m = self.re_python.match(line) - if m: - flush(allow_nobreak=True) - keyword, include, end, statement = m.groups() - if keyword: - if keyword in self.dedent_keywords: - indent -= 1 - code.append(" " * indent + line[m.start(1):]) - indent += 1 - elif include: - tmp = line[m.end(2):].strip().split(None, 1) - name = tmp[0] - args = tmp[1:] and tmp[1] or '' - self.subtemplates[name] = SimpleTemplate.find(name) - code.append(" " * indent + "stdout.append(_subtemplates[%s].render(%s))\n" % (repr(name), args)) - elif end: - indent -= 1 - code.append(" " * indent + '#' + line[m.start(3):]) - elif statement: - code.append(" " * indent + line[m.start(4):]) - else: - splits = self.re_inline.split(line) # text, (expr, text)* - if len(splits) == 1: - strbuffer.append(line) - else: - flush() - for i in range(1, len(splits), 2): - splits[i] = PyStmt(splits[i]) - splits = [x for x in splits if bool(x)] - code.append(" " * indent + "stdout.extend(%s)\n" % repr(splits)) - flush() - return ''.join(code) - - def parse(self, template): - code = self.translate(template) - self.co = compile(code, self.source or '<template>', 'exec') - - def render(self, **args): - ''' Returns the rendered template using keyword arguments as local variables. ''' - args['stdout'] = [] - args['_subtemplates'] = self.subtemplates - eval(self.co, args) - return ''.join(args['stdout']) - - -def template(template, template_adapter=SimpleTemplate, **args): - ''' Returns a string from a template ''' - if template not in TEMPLATES: - if template.find("\n") == template.find("{") == template.find("%") == -1: - TEMPLATES[template] = template_adapter.find(template) - else: - TEMPLATES[template] = template_adapter(template) - if not TEMPLATES[template]: - abort(500, 'Template not found') - args['abort'] = abort - args['request'] = request - args['response'] = response - return TEMPLATES[template].render(**args) - - -def mako_template(template_name, **args): return template(template_name, template_adapter=MakoTemplate, **args) - -def cheetah_template(template_name, **args): return template(template_name, template_adapter=CheetahTemplate, **args) - - - - - - -# Database - -class BottleBucket(object): - '''Memory-caching wrapper around anydbm''' - def __init__(self, name): - self.__dict__['name'] = name - self.__dict__['db'] = dbm.open(DB_PATH + '/%s.db' % name, 'c') - self.__dict__['mmap'] = {} - - def __getitem__(self, key): - if key not in self.mmap: - self.mmap[key] = pickle.loads(self.db[key]) - return self.mmap[key] - - def __setitem__(self, key, value): - self.mmap[key] = value - - def __delitem__(self, key): - if key in self.mmap: - del self.mmap[key] - del self.db[key] - - def __getattr__(self, key): - try: return self[key] - except KeyError: raise AttributeError(key) - - def __setattr__(self, key, value): - self[key] = value - - def __delattr__(self, key): - try: del self[key] - except KeyError: raise AttributeError(key) - - def __iter__(self): - return iter(self.ukeys()) - - def __contains__(self, key): - return key in self.ukeys() - - def __len__(self): - return len(self.ukeys()) - - def keys(self): - return list(self.ukeys()) - - def ukeys(self): - return set(self.db.keys()) | set(self.mmap.keys()) - - def save(self): - self.close() - self.__init__(self.name) - - def close(self): - for key in self.mmap: - pvalue = pickle.dumps(self.mmap[key], pickle.HIGHEST_PROTOCOL) - if key not in self.db or pvalue != self.db[key]: - self.db[key] = pvalue - self.mmap.clear() - self.db.close() - - def clear(self): - for key in self.db: - del self.db[key] - self.mmap.clear() - - def update(self, other): - self.mmap.update(other) - - def get(self, key, default=None): - try: - return self[key] - except KeyError: - if default: - return default - raise - - -class BottleDB(threading.local): - '''Holds multible BottleBucket instances in a thread-local way.''' - def __init__(self): - self.__dict__['open'] = {} - - def __getitem__(self, key): - if key not in self.open and not key.startswith('_'): - self.open[key] = BottleBucket(key) - return self.open[key] - - def __setitem__(self, key, value): - if isinstance(value, BottleBucket): - self.open[key] = value - elif hasattr(value, 'items'): - if key not in self.open: - self.open[key] = BottleBucket(key) - self.open[key].clear() - for k, v in value.iteritems(): - self.open[key][k] = v - else: - raise ValueError("Only dicts and BottleBuckets are allowed.") - - def __delitem__(self, key): - if key not in self.open: - self.open[key].clear() - self.open[key].save() - del self.open[key] - - def __getattr__(self, key): - try: return self[key] - except KeyError: raise AttributeError(key) - - def __setattr__(self, key, value): - self[key] = value - - def __delattr__(self, key): - try: del self[key] - except KeyError: raise AttributeError(key) - - def save(self): - self.close() - self.__init__() - - def close(self): - for db in self.open: - self.open[db].close() - self.open.clear() - - - - - - -# Modul initialization and configuration - -DB_PATH = './' -TEMPLATE_PATH = ['./%s.tpl', './views/%s.tpl'] -TEMPLATES = {} -HTTP_CODES = { - 100: 'CONTINUE', - 101: 'SWITCHING PROTOCOLS', - 200: 'OK', - 201: 'CREATED', - 202: 'ACCEPTED', - 203: 'NON-AUTHORITATIVE INFORMATION', - 204: 'NO CONTENT', - 205: 'RESET CONTENT', - 206: 'PARTIAL CONTENT', - 300: 'MULTIPLE CHOICES', - 301: 'MOVED PERMANENTLY', - 302: 'FOUND', - 303: 'SEE OTHER', - 304: 'NOT MODIFIED', - 305: 'USE PROXY', - 306: 'RESERVED', - 307: 'TEMPORARY REDIRECT', - 400: 'BAD REQUEST', - 401: 'UNAUTHORIZED', - 402: 'PAYMENT REQUIRED', - 403: 'FORBIDDEN', - 404: 'NOT FOUND', - 405: 'METHOD NOT ALLOWED', - 406: 'NOT ACCEPTABLE', - 407: 'PROXY AUTHENTICATION REQUIRED', - 408: 'REQUEST TIMEOUT', - 409: 'CONFLICT', - 410: 'GONE', - 411: 'LENGTH REQUIRED', - 412: 'PRECONDITION FAILED', - 413: 'REQUEST ENTITY TOO LARGE', - 414: 'REQUEST-URI TOO LONG', - 415: 'UNSUPPORTED MEDIA TYPE', - 416: 'REQUESTED RANGE NOT SATISFIABLE', - 417: 'EXPECTATION FAILED', - 500: 'INTERNAL SERVER ERROR', - 501: 'NOT IMPLEMENTED', - 502: 'BAD GATEWAY', - 503: 'SERVICE UNAVAILABLE', - 504: 'GATEWAY TIMEOUT', - 505: 'HTTP VERSION NOT SUPPORTED', -} - -request = Request() -response = Response() -db = BottleDB() -local = threading.local() - -def debug(mode=True): default_app().debug = bool(mode) -def optimize(mode=True): default_app().optimize = bool(mode) - - diff --git a/module/web/manage.py b/module/web/manage.py new file mode 100755 index 000000000..34b964ffc --- /dev/null +++ b/module/web/manage.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +from django.core.management import execute_manager + +try: + import settings # Assumed to be in the same directory. +except ImportError: + import sys + sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) + sys.exit(1) + +if __name__ == "__main__": + execute_manager(settings)
\ No newline at end of file diff --git a/module/web/media/default/css/default.css b/module/web/media/default/css/default.css new file mode 100644 index 000000000..3c4762012 --- /dev/null +++ b/module/web/media/default/css/default.css @@ -0,0 +1,1510 @@ +div.no {
+ display:inline;
+ margin:0;
+ padding:0;
+}
+.hidden {
+ display:none;
+}
+div.error {
+ background:#fcc url(media/img/default/error.png) 0.5em 0px no-repeat;
+ color:#000;
+ border-bottom:1px solid #faa;
+ font-size:90%;
+ margin:0;
+ padding-left:3em;
+ overflow:hidden;
+}
+div.info {
+ background:#ccf url(static/default/info.png) 0.5em 0px no-repeat;
+ color:#000;
+ border-bottom:1px solid #aaf;
+ font-size:90%;
+ margin:0;
+ padding-left:3em;
+ overflow:hidden;
+}
+div.success {
+ background:#cfc url(static/default/success.png) 0.5em 0px no-repeat;
+ color:#000;
+ border-bottom:1px solid #afa;
+ font-size:90%;
+ margin:0;
+ padding-left:3em;
+ overflow:hidden;
+}
+div.notify {
+ background:#ffc url(media/img/default/notify.png) 0.5em 0px no-repeat;
+ color:#000;
+ border-bottom:1px solid #ffa;
+ font-size:90%;
+ margin:0;
+ padding-left:3em;
+ overflow:hidden;
+}
+.medialeft {
+ float:left;
+}
+.mediaright {
+ float:right;
+}
+.mediacenter {
+ display:block;
+ margin-left:auto;
+ margin-right:auto;
+}
+.leftalign {
+ text-align:left;
+}
+.centeralign {
+ text-align:center;
+}
+.rightalign {
+ text-align:right;
+}
+em.u {
+ font-style:normal;
+ text-decoration:underline;
+}
+em em.u {
+ font-style:italic;
+}
+.code .br0 {
+ color:#6c6;
+}
+.code .co1 {
+ color:#808080;
+ font-style:italic;
+}
+.code .co2 {
+ color:#808080;
+ font-style:italic;
+}
+.code .co3 {
+ color:#808080;
+}
+.code .coMULTI {
+ color:#808080;
+ font-style:italic;
+}
+.code .es0 {
+ color:#009;
+ font-weight:bold;
+}
+.code .kw1 {
+ color:#b1b100;
+}
+.code .kw2 {
+ color:#000;
+ font-weight:bold;
+}
+.code .kw3 {
+ color:#006;
+}
+.code .kw4 {
+ color:#933;
+}
+.code .kw5 {
+ color:#00f;
+}
+.code .me1 {
+ color:#060;
+}
+.code .me2 {
+ color:#060;
+}
+.code .nu0 {
+ color:#c6c;
+}
+.code .re0 {
+ color:#00f;
+}
+.code .re1 {
+ color:#00f;
+}
+.code .re2 {
+ color:#00f;
+}
+.code .re3 {
+ color:#f33;
+ font-weight:bold;
+}
+.code .re4 {
+ color:#099;
+}
+.code .st0 {
+ color:#f00;
+}
+.code .sy0 {
+ color:#6c6;
+}
+div.dokuwiki table.pagelist, div.dokuwiki table.ul {
+ border:0;
+ padding:0;
+ border-spacing:0;
+ margin-bottom:1em;
+ border-collapse:collapse;
+}
+div.dokuwiki table.pagelist tr {
+ border-top:1px solid #8cacbb;
+ border-bottom:1px solid #8cacbb;
+}
+div.dokuwiki table.pagelist th, div.dokuwiki table.pagelist td {
+ padding:1px 1em 1px 0;
+}
+div.dokuwiki table.ul th, div.dokuwiki table.ul td {
+ padding:0 1em 0 0;
+}
+div.dokuwiki table.ul ul {
+ margin:0 0 0 1.5em;
+}
+div.dokuwiki table.pagelist th, div.dokuwiki table.ul th {
+ background-color:#dee7ec;
+}
+div.dokuwiki th.page, div.dokuwiki th.date, div.dokuwiki th.user, div.dokuwiki th.desc, div.dokuwiki th.comments, div.dokuwiki th.linkbacks, div.dokuwiki th.tags, div.dokuwiki td.date, div.dokuwiki td.user, div.dokuwiki td.desc, div.dokuwiki td.comments, div.dokuwiki td.linkbacks, div.dokuwiki td.tags {
+ color:#666;
+ font-size:80%;
+}
+div.dokuwiki td.date {
+ text-align:right;
+}
+div.dokuwiki div.include div.secedit {
+ float:right;
+ margin-left:1em;
+ margin-top:-18px;
+}
+div.dokuwiki div.inclmeta {
+ border-top:1px dotted #8cacbb;
+ padding-top:0.2em;
+ color:#666;
+ font-size:80%;
+ line-height:1.25;
+ margin-top:0.5em;
+ margin-bottom:2em;
+}
+div.dokuwiki div.inclmeta a.permalink {
+ background:transparent url(media/img/default/link.gif) 0px 1px no-repeat;
+ padding:1px 0px 1px 16px;
+}
+div.dokuwiki div.inclmeta abbr.published {
+ background:transparent url(media/img/default/date.gif) 0px 1px no-repeat;
+ padding:1px 0px 1px 16px;
+ border-bottom:0;
+}
+div.dokuwiki div.inclmeta span.author {
+ background:transparent url(media/img/default/user.gif) 0px 1px no-repeat;
+ padding:1px 0px 1px 16px;
+}
+div.dokuwiki div.inclmeta span.comment {
+ background:transparent url(media/img/default/comment.gif) 0px 1px no-repeat;
+ padding:1px 0px 1px 16px;
+}
+div.dokuwiki div.inclmeta div.tags {
+ border-top:0;
+ font-size:100%;
+ float:right;
+ clear:none;
+}
+#plugin__manager {
+}
+#plugin__manager h2 {
+ margin-left:0;
+}
+#plugin__manager form {
+ display:block;
+ margin:0;
+ padding:0;
+}
+#plugin__manager legend {
+ display:none;
+}
+#plugin__manager fieldset {
+ width:auto;
+}
+#plugin__manager .button {
+ margin:0;
+}
+#plugin__manager p, #plugin__manager label {
+ text-align:left;
+}
+#plugin__manager .hidden {
+ display:none;
+}
+#plugin__manager .new {
+ background:#dee7ec;
+}
+#plugin__manager input[disabled] {
+ color:#ccc;
+ border-color:#ccc;
+}
+#plugin__manager .pm_menu, #plugin__manager .pm_info {
+ margin-left:0;
+ text-align:left;
+}
+#plugin__manager .pm_menu {
+ float:left;
+ width:48%;
+}
+#plugin__manager .pm_info {
+ float:right;
+ width:50%;
+}
+#plugin__manager .common {
+}
+#plugin__manager .common form {
+}
+#plugin__manager .common fieldset {
+ margin:0;
+ padding:0 0 1.0em 0;
+ text-align:left;
+ border:none;
+}
+#plugin__manager .common label {
+ padding:0 0 0.5em 0;
+}
+#plugin__manager .common input {
+}
+#plugin__manager .common input.edit {
+ width:24em;
+ margin:0.5em;
+}
+#plugin__manager .common .button {
+}
+#plugin__manager form.plugins {
+}
+#plugin__manager .plugins fieldset {
+ color:#000;
+ background:#fff;
+ text-align:right;
+ border-top:none;
+ border-right:none;
+ border-left:none;
+}
+#plugin__manager .plugins fieldset.protected {
+ background:#fdd;
+ color:#000;
+}
+#plugin__manager .plugins fieldset.disabled {
+ background:#e0e0e0;
+ color:#a8a8a8;
+}
+#plugin__manager .plugins .legend {
+ color:#000;
+ background:inherit;
+ display:block;
+ margin:0;
+ padding:0;
+ font-size:1em;
+ line-height:1.4em;
+ font-weight:normal;
+ text-align:left;
+ float:left;
+ padding:0;
+ clear:none;
+}
+#plugin__manager .plugins .button {
+ font-size:95%;
+}
+#plugin__manager .plugins fieldset.buttons {
+ border:none;
+}
+#plugin__manager .plugins fieldset.buttons .button {
+ float:left;
+}
+#plugin__manager .pm_info h3 {
+ margin-left:0;
+}
+#plugin__manager .pm_info dl {
+ margin:1em 0;
+ padding:0;
+}
+#plugin__manager .pm_info dt {
+ width:6em;
+ float:left;
+ clear:left;
+ margin:0;
+ padding:0;
+}
+#plugin__manager .pm_info dd {
+ margin:0 0 0 7em;
+ padding:0;
+ background:none;
+}
+#plugin__manager .plugins .enable {
+ float:left;
+ width:auto;
+ margin-right:0.5em;
+}
+#config__manager div.success, #config__manager div.error, #config__manager div.info {
+ background-position:0.5em;
+ padding:0.5em;
+ text-align:center;
+}
+#config__manager fieldset {
+ margin:1em;
+ width:auto;
+ margin-bottom:2em;
+ background-color:#dee7ec;
+ color:#000;
+ padding:0 1em;
+}
+#config__manager legend {
+ font-size:1.25em;
+}
+#config__manager form {
+}
+#config__manager table {
+ margin:1em 0;
+ width:100%;
+}
+#config__manager fieldset td {
+ text-align:left;
+}
+#config__manager fieldset td.value {
+ width:31em;
+}
+#config__manager td.label {
+ padding:0.8em 0 0.6em 1em;
+ vertical-align:top;
+}
+#config__manager td.label label {
+ clear:left;
+ display:block;
+}
+#config__manager td.label img {
+ padding:0 10px;
+ vertical-align:middle;
+ float:right;
+}
+#config__manager td.label span.outkey {
+ font-size:70%;
+ margin-top:-1.7em;
+ margin-left:-1em;
+ display:block;
+ background-color:#fff;
+ color:#666;
+ float:left;
+ padding:0 0.1em;
+ position:relative;
+ z-index:1;
+}
+#config__manager td input.edit {
+ width:30em;
+}
+#config__manager td .input {
+ width:30.8em;
+}
+#config__manager td select.edit {
+}
+#config__manager td textarea.edit {
+ width:27.5em;
+ height:4em;
+}
+#config__manager tr .input, #config__manager tr input, #config__manager tr textarea, #config__manager tr select {
+ background-color:#fff;
+ color:#000;
+}
+#config__manager tr.default .input, #config__manager tr.default input, #config__manager tr.default textarea, #config__manager tr.default select, #config__manager .selectiondefault {
+ background-color:#cdf;
+ color:#000;
+}
+#config__manager tr.protected .input, #config__manager tr.protected input, #config__manager tr.protected textarea, #config__manager tr.protected select, #config__manager tr.protected .selection {
+ background-color:#fcc!important;
+ color:#000 !important;
+}
+#config__manager td.error {
+ background-color:red;
+ color:#000;
+}
+#config__manager .selection {
+ width:14.8em;
+ float:left;
+ margin:0 0.3em 2px 0;
+}
+#config__manager .selection label {
+ float:right;
+ width:14em;
+ font-size:90%;
+}
+* html #config__manager .selection label {
+ padding-top:2px;
+}
+#config__manager .selection input.checkbox {
+ padding-left:0.7em;
+}
+#config__manager .other {
+ clear:both;
+ padding-top:0.5em;
+}
+#config__manager .other label {
+ padding-left:2px;
+ font-size:90%;
+}
+.dokuwiki div.plugin_translation {
+ float:right;
+ font-size:95%;
+}
+.dokuwiki div.plugin_translation ul {
+ display:inline;
+ padding:0;
+ margin:0;
+}
+.dokuwiki div.plugin_translation ul li {
+ float:left;
+ list-style-type:none;
+ padding:0;
+ margin:0;
+}
+.dokuwiki div.plugin_translation ul li a.wikilink1:link, .dokuwiki div.plugin_translation ul li a.wikilink1:hover, .dokuwiki div.plugin_translation ul li a.wikilink1:active, .dokuwiki div.plugin_translation ul li a.wikilink1:visited {
+ background-color:#000080;
+ color:#fff !important;
+ text-decoration:none;
+ padding:0 0.2em;
+ margin:0.1em 0.2em;
+ border:none !important;
+}
+.dokuwiki div.plugin_translation ul li a.wikilink2:link, .dokuwiki div.plugin_translation ul li a.wikilink2:hover, .dokuwiki div.plugin_translation ul li a.wikilink2:active, .dokuwiki div.plugin_translation ul li a.wikilink2:visited {
+ background-color:#808080;
+ color:#fff !important;
+ text-decoration:none;
+ padding:0 0.2em;
+ margin:0.1em 0.2em;
+ border:none !important;
+}
+.dokuwiki div.plugin_translation ul li a img {
+ opacity:0.5;
+ border:0;
+}
+.dokuwiki div.plugin_translation ul li a.wikilink2 img {
+}
+.dokuwiki div.plugin_translation span.curid a img {
+ opacity:1.0;
+ height:15px;
+}
+.dokuwiki div.plugin_translation ul li a:hover img {
+ opacity:1.0;
+ height:15px;
+}
+#user__manager tr.disabled {
+ color:#6f6f6f;
+ background:#e4e4e4;
+}
+#user__manager tr.user_info {
+ vertical-align:top;
+}
+#user__manager div.edit_user {
+ width:46%;
+ float:left;
+}
+#user__manager table {
+ margin-bottom:1em;
+}
+#user__manager input.button[disabled] {
+ color:#ccc!important;
+ border-color:#ccc!important;
+}
+div.dokuwiki div.newentry_form {
+ clear:both;
+ text-align:center;
+ margin-bottom:1em;
+}
+div.dokuwiki #blog__newentry_form input.edit {
+ width:95%;
+}
+div.dokuwiki tr.draft, div.dokuwiki div.draft {
+ opacity:0.5;
+}
+div.dokuwiki div.autoarchive_selector ul {
+ list-style-type:none;
+ clear:left;
+ margin:0 0.5em 0 0;
+}
+div.dokuwiki div.autoarchive_selector ul div.li {
+ float:left;
+ margin:0 1em 0 0;
+}
+div.dokuwiki div.autoarchive_selector ul ul {
+ float:left;
+ clear:none;
+}
+div.dokuwiki div.autoarchive_selector ul ul div.li {
+ margin:0;
+}
+div#acl_manager div#acl__tree {
+ font-size:90%;
+ width:25%;
+ height:300px;
+ float:left;
+ overflow:auto;
+ border:1px solid #8cacbb;
+ text-align:left;
+}
+div#acl_manager div#acl__tree a.cur {
+ background-color:#ff9;
+ font-weight:bold;
+}
+div#acl_manager div#acl__tree ul {
+ list-style-type:none;
+ margin:0;
+ padding:0;
+}
+div#acl_manager div#acl__tree li {
+ padding-left:1em;
+}
+div#acl_manager div#acl__tree ul img {
+ margin-right:0.25em;
+ cursor:pointer;
+}
+div#acl_manager div#acl__detail {
+ width:73%;
+ height:300px;
+ float:right;
+ overflow:auto;
+}
+div#acl_manager div#acl__detail fieldset {
+ width:90%;
+}
+div#acl_manager div#acl__detail div#acl__user {
+ border:1px solid #8cacbb;
+ padding:0.5em;
+ margin-bottom:0.6em;
+}
+div#acl_manager table.inline {
+ width:100%;
+ margin:0;
+}
+div#acl_manager .aclgroup {
+ background:transparent url(media/img/default/group.png) 0px 1px no-repeat;
+ padding:1px 0px 1px 18px;
+}
+div#acl_manager .acluser {
+ background:transparent url(media/img/default/user.png) 0px 1px no-repeat;
+ padding:1px 0px 1px 18px;
+}
+div#acl_manager .aclpage {
+ background:transparent url(media/img/default/page.png) 0px 1px no-repeat;
+ padding:1px 0px 1px 18px;
+}
+div#acl_manager .aclns {
+ background:transparent url(media/img/default/ns.png) 0px 1px no-repeat;
+ padding:1px 0px 1px 18px;
+}
+div#acl_manager label.disabled {
+ color:#666!important;
+}
+#acl_manager label {
+ text-align:left;
+ font-weight:normal;
+ display:inline;
+}
+#acl_manager table {
+ margin-left:10%;
+ width:80%;
+}
+#acl_manager table tr {
+ background-color:inherit;
+}
+#acl_manager table tr:hover {
+ background-color:#dee7ec;
+}
+a.interwiki {
+ background:transparent url(/lib/images/interwiki.png) 0px 1px no-repeat;
+ padding-left:16px;
+}
+a.iw_wp {
+ background-image:url(/media/default/img/wp.gif)
+}
+a.iw_wpde {
+ background-image:url(/media/default/img/wpde.gif)
+}
+a.iw_wpmeta {
+ background-image:url(/media/default/img/wpmeta.gif)
+}
+a.iw_doku {
+ background-image:url(/media/default/img/doku.gif)
+}
+a.iw_dokubug {
+ background-image:url(/media/default/img/dokubug.gif)
+}
+a.iw_amazon {
+ background-image:url(/media/default/img/amazon.gif)
+}
+a.iw_amazon_de {
+ background-image:url(/media/default/img/amazon.de.gif)
+}
+a.iw_amazon_uk {
+ background-image:url(/media/default/img/amazon.uk.gif)
+}
+a.iw_phpfn {
+ background-image:url(/media/default/img/phpfn.gif)
+}
+a.iw_coral {
+ background-image:url(/media/default/img/coral.gif)
+}
+a.iw_sb {
+ background-image:url(/media/default/img/sb.gif)
+}
+a.iw_google {
+ background-image:url(/media/default/img/google.gif)
+}
+a.iw_meatball {
+ background-image:url(/media/default/img/meatball.gif)
+}
+a.iw_wiki {
+ background-image:url(/media/default/img/wiki.gif)
+}
+a.mediafile {
+ background:transparent url(/media/default/img/file.png) 0px 1px no-repeat;
+ padding-left:18px;
+ padding-bottom:1px;
+}
+a.mf_jpg {
+ background-image:url(/media/default/img/jpg.png)
+}
+a.mf_jpeg {
+ background-image:url(/media/default/img/jpeg.png)
+}
+a.mf_gif {
+ background-image:url(/media/default/img/gif.png)
+}
+a.mf_png {
+ background-image:url(/media/default/img/png.png)
+}
+a.mf_tgz {
+ background-image:url(/media/default/img/tgz.png)
+}
+a.mf_tar {
+ background-image:url(/media/default/img/tar.png)
+}
+a.mf_gz {
+ background-image:url(/media/default/img/gz.png)
+}
+a.mf_bz2 {
+ background-image:url(/media/default/img/bz2.png)
+}
+a.mf_zip {
+ background-image:url(/media/default/img/zip.png)
+}
+a.mf_rar {
+ background-image:url(/media/default/img/rar.png)
+}
+a.mf_pdf {
+ background-image:url(/media/default/img/pdf.png)
+}
+a.mf_ps {
+ background-image:url(/media/default/img/ps.png)
+}
+a.mf_doc {
+ background-image:url(/media/default/img/doc.png)
+}
+a.mf_xls {
+ background-image:url(/media/default/img/xls.png)
+}
+a.mf_ppt {
+ background-image:url(/media/default/img/ppt.png)
+}
+a.mf_rtf {
+ background-image:url(/media/default/img/rtf.png)
+}
+a.mf_swf {
+ background-image:url(/media/default/img/swf.png)
+}
+a.mf_rpm {
+ background-image:url(/media/default/img/rpm.png)
+}
+a.mf_deb {
+ background-image:url(/media/default/img/deb.png)
+}
+a.mf_sxw {
+ background-image:url(/media/default/img/sxw.png)
+}
+a.mf_sxc {
+ background-image:url(/media/default/img/sxc.png)
+}
+a.mf_sxi {
+ background-image:url(/media/default/img/sxi.png)
+}
+a.mf_sxd {
+ background-image:url(/media/default/img/sxd.png)
+}
+a.mf_odc {
+ background-image:url(/media/default/img/odc.png)
+}
+a.mf_odf {
+ background-image:url(/media/default/img/odf.png)
+}
+a.mf_odg {
+ background-image:url(/media/default/img/odg.png)
+}
+a.mf_odi {
+ background-image:url(/media/default/img/odi.png)
+}
+a.mf_odp {
+ background-image:url(/media/default/img/odp.png)
+}
+a.mf_ods {
+ background-image:url(/media/default/img/ods.png)
+}
+a.mf_odt {
+ background-image:url(/media/default/img/odt.png)
+}
+body {
+ margin:0px;
+ padding:0px;
+ background-color:white;
+ color:black;
+ font-size:12px;
+ font-family:Verdana, Helvetica, "Lucida Grande", Lucida, Arial, sans-serif;
+ font-family:sans-serif;
+ font-size:99, 96%;
+ font-size-adjust:none;
+ font-style:normal;
+ font-variant:normal;
+ font-weight:normal;
+ line-height:normal;
+}
+hr {
+ border-width:0px;
+ border-bottom:1px #aaa dotted;
+}
+img {
+ border:none;
+}
+form {
+ margin:0px;
+ padding:0px;
+ border:none;
+ display:inline;
+ background:transparent;
+}
+ul li {
+ margin:5px;
+}
+textarea {
+ font-family:monospace;
+}
+table {
+ margin:0.5em 0;
+ border-collapse:collapse;
+}
+td {
+ padding:0.25em;
+ border:1pt solid #ADB9CC;
+}
+a {
+ color:#3465a4;
+ text-decoration:none;
+}
+a:hover {
+ text-decoration:underline;
+}
+a.wikilink2 {
+ color:#a40000 !important;
+}
+.dokuwiki h1 a, .dokuwiki h2 a, .dokuwiki h3 a, .dokuwiki h4 a, .dokuwiki h5 a, .dokuwiki a.nolink {
+ color:#000 !important;
+ text-decoration:none !important;
+}
+option {
+ border:0px none #fff;
+}
+strong.highlight {
+ background-color:#fc9;
+ padding:1pt;
+}
+#pagebottom {
+ clear:both;
+}
+hr {
+ height:1px;
+ color:#c0c0c0;
+ background-color:#c0c0c0;
+ border:none;
+ margin:.2em 0 .2em 0;
+}
+pre {
+ padding:0.5em;
+ font-family:courier, monospace;
+ border:1px solid #c0c0c0;
+ background:#F0ECE6;
+ white-space:pre;
+ white-space:pre-wrap;
+ word-wrap:break-word;
+ white-space:-moz-pre-wrap;
+ white-space:-pre-wrap;
+ white-space:-o-pre-wrap;
+}
+.invisible {
+ margin:0px;
+ border:0px;
+ padding:0px;
+ height:0px;
+ visibility:hidden;
+}
+.left {
+ float:left !important;
+}
+.right {
+ float:right !important;
+}
+.center {
+ text-align:center;
+}
+div#body-wrapper {
+ padding:40px 40px 10px 40px;
+ font-size:127%;
+}
+div#content {
+ margin-top:-20px;
+ padding:0;
+ font-size:14px;
+ color:black;
+ line-height:1.5em;
+}
+h1, h2, h3, h4, h5, h6 {
+ background:transparent none repeat scroll 0 0;
+ border-bottom:1px solid #aaa;
+ color:black;
+ font-weight:normal;
+ margin:0;
+ padding:0;
+ padding-bottom:0.17em;
+ padding-top:0.5em;
+}
+h1 {
+ font-size:188%;
+ line-height:1.2em;
+ margin-bottom:0.1em;
+ padding-bottom:0;
+}
+h2 {
+ font-size:150%;
+}
+h3, h4, h5, h6 {
+ border-bottom:none;
+ font-weight:bold;
+}
+h3 {
+ font-size:132%;
+}
+h4 {
+ font-size:116%;
+}
+h5 {
+ font-size:100%;
+}
+h6 {
+ font-size:80%;
+}
+ul#page-actions {
+ float:right;
+ margin:10px 10px 0 10px;
+ padding:6px;
+ color:black;
+ background-color:#ececec;
+ list-style-type:none;
+ -moz-border-radius:5px;
+}
+ul#user-actions {
+ padding:5px;
+ margin:0;
+ display:inline;
+ color:black;
+ background-color:#ececec;
+ list-style-type:none;
+ -moz-border-radius:3px;
+}
+ul#page-actions li, ul#user-actions li {
+ display:inline;
+}
+ul#page-actions a, ul#user-actions a {
+ text-decoration:none;
+ color:black;
+ display:inline;
+ margin:0 3px;
+ padding:2px 0px 2px 18px;
+}
+ul#page-actions a:hover, ul#page-actions a:focus, ul#user-actions a:hover, ul#user-actions a:focus {
+ /*text-decoration:underline;*/
+}
+/***************************/
+ul#page-actions2 {
+ float:left;
+ margin:10px 10px 0 10px;
+ padding:6px;
+ color:black;
+ background-color:#ececec;
+ list-style-type:none;
+ -moz-border-radius:5px;
+}
+ul#user-actions2 {
+ padding:5px;
+ margin:0;
+ display:inline;
+ color:black;
+ background-color:#ececec;
+ list-style-type:none;
+ -moz-border-radius:3px;
+}
+ul#page-actions2 li, ul#user-actions2 li {
+ display:inline;
+}
+ul#page-actions2 a, ul#user-actions2 a {
+ text-decoration:none;
+ color:black;
+ display:inline;
+ margin:0 3px;
+ padding:2px 0px 2px 18px;
+}
+ul#page-actions2 a:hover, ul#page-actions2 a:focus, ul#user-actions2 a:hover, ul#user-actions2 a:focus {
+ color: #4e7bb4;
+}
+/****************************/
+.hidden {
+ display:none;
+}
+a.urlextern {
+ color:#36B;
+ background:transparent url(/media/default/img/external-10.2.png) no-repeat scroll right center;
+ padding:0 13px 0 0;
+}
+a[href^="http://www.pyload.org"]:after, a.noextlink:after {
+background:none;
+padding:0;
+}
+a.action.index {
+ background:transparent url(/media/default/img/wiki-tools-index.png) 0px 1px no-repeat;
+}
+a.action.recent {
+ background:transparent url(/media/default/img/wiki-tools-recent.png) 0px 1px no-repeat;
+}
+a.logout {
+ background:transparent url(/media/default/img/user-actions-logout.png) 0px 1px no-repeat;
+}
+a.admin {
+ background:transparent url(/media/default/img/user-actions-admin.png) 0px 1px no-repeat;
+}
+a.profile {
+ background:transparent url(/media/default/img/user-actions-profile.png) 0px 1px no-repeat;
+}
+a.create, a.edit {
+ background:transparent url(/media/default/img/page-tools-edit.png) 0px 1px no-repeat;
+}
+a.source, a.show {
+ background:transparent url(/media/default/img/page-tools-source.png) 0px 1px no-repeat;
+}
+a.revisions {
+ background:transparent url(/media/default/img/page-tools-revisions.png) 0px 1px no-repeat;
+}
+a.subscribe, a.unsubscribe {
+ background:transparent url(/media/default/img/page-tools-subscribe.png) 0px 1px no-repeat;
+}
+a.backlink {
+ background:transparent url(/media/default/img/page-tools-backlinks.png) 0px 1px no-repeat;
+}
+a.play {
+ background:transparent url(/media/default/img/control_play.png) 0px 1px no-repeat;
+}
+a.play:hover {
+ background:transparent url(/media/default/img/control_play_blue.png) 0px 1px no-repeat;
+}
+a.cancel {
+ background:transparent url(/media/default/img/control_cancel.png) 0px 1px no-repeat;
+}
+a.cancel:hover {
+ background:transparent url(/media/default/img/control_cancel_blue.png) 0px 1px no-repeat;
+}
+a.pause {
+ background:transparent url(/media/default/img/control_pause.png) 0px 1px no-repeat;
+}
+a.pause:hover {
+ background:transparent url(/media/default/img/control_pause_blue.png) 0px 1px no-repeat;
+ font-weight: bold;
+}
+a.stop {
+ background:transparent url(/media/default/img/control_stop.png) 0px 1px no-repeat;
+}
+a.stop:hover {
+ background:transparent url(/media/default/img/control_stop_blue.png) 0px 1px no-repeat;
+}
+a.cog {
+ background:transparent url(/media/default/img/cog.png) 0px 1px no-repeat;
+}
+#head-panel {
+ background:#525252 url(/media/default/img/head_bg1.png) bottom left repeat-x;
+}
+#head-panel h1 {
+ display:none;
+ margin:0;
+ text-decoration:none;
+ padding-top:0.8em;
+ padding-left:3.3em;
+ font-size:2.6em;
+ color:#eeeeec;
+}
+#head-panel #head-logo {
+ float:left;
+ margin:5px 0 -15px 5px;
+ padding:0;
+ overflow:visible;
+}
+#head-menu {
+ background:transparent url(/media/default/img/tabs-border-bottom.png) 0 100% repeat-x;
+ width:100%;
+ float:left;
+ margin:0;
+ padding:0;
+ padding-top:0.8em;
+}
+#head-menu ul {
+ list-style:none;
+ margin:0 1em 0 2em;
+}
+#head-menu ul li {
+ float:left;
+ margin:0;
+ margin-left:0.3em;
+ font-size:14px;
+ margin-bottom:4px;
+}
+#head-menu ul li.selected, #head-menu ul li:hover {
+ margin-bottom:0px;
+}
+#head-menu ul li a img {
+ height:22px;
+ width:22px;
+ vertical-align:middle;
+}
+#head-menu ul li a, #head-menu ul li a:link {
+ float:left;
+ text-decoration:none;
+ color:#555;
+ background:#eaeaea url(/media/default/img/tab-background.png) 0 100% repeat-x;
+ padding:3px 7px 3px 7px;
+ border:2px solid #ccc;
+ border-bottom:0px solid transparent;
+ padding-bottom:3px;
+ -moz-border-radius:5px;
+}
+#head-menu ul li a:hover, #head-menu ul li a:focus {
+ color:#111;
+ padding-bottom:7px;
+ border-bottom:0px none transparent;
+ outline:none;
+ -moz-border-radius-bottomright:0px;
+ -moz-border-radius-bottomleft:0px;
+}
+#head-menu ul li a:focus {
+ margin-bottom:-4px;
+}
+#head-menu ul li.selected a {
+ color:#3566A5;
+ background:#fff;
+ padding-bottom:7px;
+ border-bottom:0px none transparent;
+ -moz-border-radius-bottomright:0px;
+ -moz-border-radius-bottomleft:0px;
+}
+#head-menu ul li.selected a:hover, #head-menu ul li.selected a:focus {
+ color:#111;
+}
+div#head-search-and-login {
+ float:right;
+ margin:0 1em 0 0;
+ background-color:#222;
+ padding:4px;
+ color:white;
+ -moz-border-radius-bottomright:6px;
+ -moz-border-radius-bottomleft:6px;
+}
+div#head-search-and-login form {
+ display:inline;
+ padding:0 3px;
+}
+div#head-search-and-login form input {
+ border:2px solid #888;
+ background:#eee;
+ font-size:14px;
+ padding:2px;
+ -moz-border-radius:3px;
+}
+div#head-search-and-login form input:focus {
+ background:#fff;
+}
+#head-search {
+ font-size:14px;
+}
+#head-username, #head-password {
+ width:80px;
+ font-size:14px;
+}
+#pageinfo {
+ clear:both;
+ color:#888;
+ padding:0.6em 0;
+ margin:0;
+}
+#foot {
+ font-style:normal;
+ color:#888;
+ text-align:center;
+}
+#foot a {
+ color:#aaf;
+}
+#foot img {
+ vertical-align:middle;
+}
+ul.toc {
+ padding:0;
+ padding-left:20px;
+ margin-left:0;
+ margin-right:10px;
+ list-style:none;
+}
+ul.toc li {
+ list-style:circle;
+}
+ul.toc li a {
+ text-decoration:none;
+ color:black;
+}
+ul.toc li a:hover {
+ text-decoration:underline;
+}
+div.toc {
+ border:1px dotted #888;
+ background:#f0f0f0;
+ margin:1em 0 1em 1em;
+ float:right;
+ font-size:95%;
+}
+div.toc .tocheader {
+ font-weight:bold;
+ margin:0.5em 1em;
+}
+div.toc ol {
+ margin:1em 0.5em 1em 1em;
+ padding:0;
+}
+div.toc ol li {
+ margin:0;
+ padding:0;
+ margin-left:1em;
+}
+div.toc ol ol {
+ margin:0.5em 0.5em 0.5em 1em;
+ padding:0;
+}
+div.recentchanges table {
+ clear:both;
+}
+div#editor-help {
+ font-size:90%;
+ border:1px dotted #888;
+ padding:0ex 1ex 1ex 1ex;
+ background:#f7f6f2;
+}
+div#preview {
+ margin-top:1em;
+}
+label.block {
+ display:block;
+ text-align:right;
+ font-weight:bold;
+}
+label.simple {
+ display:block;
+ text-align:left;
+ font-weight:normal;
+}
+label.block input.edit {
+ width:50%;
+}
+fieldset {
+ width:300px;
+ text-align:center;
+ padding:0.5em;
+ margin:auto;
+}
+div.editor {
+ margin:0 0 0 0;
+}
+table {
+ margin:0.5em 0;
+ border-collapse:collapse;
+}
+td {
+ padding:0.25em;
+ border:1pt solid #ADB9CC;
+}
+td p {
+ margin:0;
+ padding:0;
+}
+.u {
+ text-decoration:underline;
+}
+.footnotes ul {
+ padding:0 2em;
+ margin:0 0 1em;
+}
+.footnotes li {
+ list-style:none;
+}
+.recentchanges p {
+ margin:0.25em;
+}
+.recentchanges td {
+ vertical-align:top;
+ border:none;
+ border-bottom:1pt solid #F0ECE6;
+ background:#F7F6F2;
+}
+.rcdaybreak td {
+ background:#729fcf;
+ border:none;
+}
+.rcdaybreak td a {
+ font-size:0.88em;
+}
+.rcicon1, .rcicon2 {
+ text-align:center;
+}
+.rcpagelink {
+ width:33%;
+}
+.rctime {
+ font-size:0.88em;
+ white-space:nowrap;
+}
+.rceditor {
+ white-space:nowrap;
+ font-size:0.88em;
+}
+.rccomment {
+ width:66%;
+ color:gray;
+ font-size:0.88em;
+}
+.rcrss {
+ float:right;
+}
+.recentchanges[dir="rtl"] .rcrss {
+ float:left;
+}
+.userpref table, .userpref td {
+ border:none;
+}
+div.codearea {
+ margin:0.5em 0;
+ padding:0;
+ border:1pt solid #AEBDCC;
+ background-color:#F3F5F7;
+ color:black;
+}
+div.codearea pre {
+ margin:0;
+ padding:10pt;
+ border:none;
+}
+a.codenumbers {
+ margin:0 10pt;
+ font-size:0.85em;
+ color:gray;
+}
+div.codearea pre span.LineNumber {
+ color:gray;
+}
+div.codearea pre span.ID {
+ color:#000;
+}
+div.codearea pre span.Operator {
+ color:#0000c0;
+}
+div.codearea pre span.Char {
+ color:#004080;
+}
+div.codearea pre span.Comment {
+ color:#008000;
+}
+div.codearea pre span.Number {
+ color:#0080c0;
+}
+div.codearea pre span.String {
+ color:#004080;
+}
+div.codearea pre span.SPChar {
+ color:#0000c0;
+}
+div.codearea pre span.ResWord {
+ color:#a00000;
+}
+div.codearea pre span.ConsWord {
+ color:#008080;
+ font-weight:bold;
+}
+div.codearea pre span.Error {
+ color:#ff8080;
+ border:solid 1.5pt #f00;
+}
+div.codearea pre span.ResWord2 {
+ color:#0080ff;
+ font-weight:bold;
+}
+div.codearea pre span.Special {
+ color:#00f;
+}
+div.codearea pre span.Preprc {
+ color:#803999;
+}
+#message {
+ clear:both;
+ padding:5px 10px;
+ background-color:#eee;
+ border-bottom:2px solid #ccc;
+}
+#message p {
+ margin:5px 0;
+ padding:0;
+ font-weight:bold;
+}
+#message div.buttons {
+ font-weight:normal;
+}
+.diff {
+ width:99%;
+}
+.diff-title {
+ background-color:#C0C0C0;
+}
+.searchresult dd span {
+ font-weight:bold;
+}
+.diff {
+ width:100%;
+ border:none;
+}
+.diff-blockheader {
+ font-weight:bold;
+ background:#e5e5e5;
+ font-size:1.2em;
+ border-top:2px solid #444;
+ padding:5px;
+}
+.diff th {
+ font-size:120%;
+ width:50%;
+ font-weight:normal;
+ text-align:left;
+ padding-bottom:3px;
+}
+.diff td {
+ font-family:monospace;
+ font-size:100%;
+ border:none;
+}
+.diff-addedline {
+ background-color:#dfd;
+}
+.diff-deletedline {
+ background-color:#ffb;
+}
+.diff-context {
+ color:#888;
+}
+.diff-addedline {
+ background-color:#E0FFE0;
+ vertical-align:sub;
+}
+.diff-deletedline {
+ background-color:#FFFFE0;
+ background-color:#f4cece;
+ vertical-align:sub;
+}
+.diff-addedline strong {
+ background-color:#80FF80;
+ background-color:#8ae234;
+}
+.diff-deletedline strong {
+ background-color:#FFFF80;
+ background-color:#ef2929;
+ background-color:#d78383;
+}
+.box {
+ background:url(/media/default/img/progress-bar-back.gif) right center no-repeat;
+ width:200px;
+ height:20px;
+ float:left;
+}
+.perc {
+ background:url(/media/default/img/progress-bar.gif) right center no-repeat;
+ height:20px;
+}
+.boxtext {
+ font-family:tahoma, arial, sans-serif;
+ font-size:11px;
+ color:#000;
+ float:none;
+ padding:3px 0 0 10px;
+}
+.statusbutton {
+ width:32px;
+ height:32px;
+ float:left;
+ margin-left:-32px;
+ margin-right:5px;
+ opacity:0;
+ cursor:pointer
+}
+.dlsize {
+ float:left;
+ padding-right: 8px;
+}
+.dlspeed {
+ float:left;
+ padding-right: 8px;
+}
+.package {
+ margin-bottom: 10px;
+}
+.packagename {
+ background: url(/media/default/img/folder.png) no-repeat;
+ padding-left: 20px;
+ font-weight: bold;
+ text-transform: uppercase;
+}
+.child {
+ margin-left: 20px;
+}
+.child_status {
+ margin-right: 10px;
+}
+.child_secrow {
+ font-size: 10px;
+}
+
+.header, .header th {
+ text-align: left;
+ font-weight: normal;
+ background-color:#ececec;
+ -moz-border-radius:5px;
+}
+.progress_bar {
+ background: #0C0;
+ height: 5px;
+
+}
+
+.queue {
+ border: none
+}
+
+.queue tr td {
+ border: none
+}
+
+.header, .header th{
+ text-align: left;
+ font-weight: normal;
+}
\ No newline at end of file diff --git a/module/web/media/default/css/jquery-ui-1.7.2.custom.css b/module/web/media/default/css/jquery-ui-1.7.2.custom.css new file mode 100644 index 000000000..62589261a --- /dev/null +++ b/module/web/media/default/css/jquery-ui-1.7.2.custom.css @@ -0,0 +1,406 @@ +/*
+* jQuery UI CSS Framework
+* Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
+* Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses.
+*/
+
+/* Layout helpers
+----------------------------------*/
+.ui-helper-hidden { display: none; }
+.ui-helper-hidden-accessible { position: absolute; left: -99999999px; }
+.ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; }
+.ui-helper-clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; }
+.ui-helper-clearfix { display: inline-block; }
+/* required comment for clearfix to work in Opera \*/
+* html .ui-helper-clearfix { height:1%; }
+.ui-helper-clearfix { display:block; }
+/* end clearfix */
+.ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); }
+
+
+/* Interaction Cues
+----------------------------------*/
+.ui-state-disabled { cursor: default !important; }
+
+
+/* Icons
+----------------------------------*/
+
+/* states and images */
+.ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; }
+
+
+/* Misc visuals
+----------------------------------*/
+
+/* Overlays */
+.ui-widget-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+
+
+
+/*
+* jQuery UI CSS Framework
+* Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
+* Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses.
+* To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Trebuchet%20MS,%20Tahoma,%20Verdana,%20Arial,%20sans-serif&fwDefault=bold&fsDefault=1.1em&cornerRadius=4px&bgColorHeader=f6a828&bgTextureHeader=12_gloss_wave.png&bgImgOpacityHeader=35&borderColorHeader=e78f08&fcHeader=ffffff&iconColorHeader=ffffff&bgColorContent=eeeeee&bgTextureContent=03_highlight_soft.png&bgImgOpacityContent=100&borderColorContent=dddddd&fcContent=333333&iconColorContent=222222&bgColorDefault=f6f6f6&bgTextureDefault=02_glass.png&bgImgOpacityDefault=100&borderColorDefault=cccccc&fcDefault=1c94c4&iconColorDefault=ef8c08&bgColorHover=fdf5ce&bgTextureHover=02_glass.png&bgImgOpacityHover=100&borderColorHover=fbcb09&fcHover=c77405&iconColorHover=ef8c08&bgColorActive=ffffff&bgTextureActive=02_glass.png&bgImgOpacityActive=65&borderColorActive=fbd850&fcActive=eb8f00&iconColorActive=ef8c08&bgColorHighlight=ffe45c&bgTextureHighlight=03_highlight_soft.png&bgImgOpacityHighlight=75&borderColorHighlight=fed22f&fcHighlight=363636&iconColorHighlight=228ef1&bgColorError=b81900&bgTextureError=08_diagonals_thick.png&bgImgOpacityError=18&borderColorError=cd0a0a&fcError=ffffff&iconColorError=ffd27a&bgColorOverlay=666666&bgTextureOverlay=08_diagonals_thick.png&bgImgOpacityOverlay=20&opacityOverlay=50&bgColorShadow=000000&bgTextureShadow=01_flat.png&bgImgOpacityShadow=10&opacityShadow=20&thicknessShadow=5px&offsetTopShadow=-5px&offsetLeftShadow=-5px&cornerRadiusShadow=5px
+*/
+
+
+/* Component containers
+----------------------------------*/
+.ui-widget { font-family: Trebuchet MS, Tahoma, Verdana, Arial, sans-serif; font-size: 1.1em; }
+.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Trebuchet MS, Tahoma, Verdana, Arial, sans-serif; font-size: 1em; }
+.ui-widget-content { border: 1px solid #dddddd; background: #eeeeee url(ui-lightness/images/ui-bg_highlight-soft_100_eeeeee_1x100.png) 50% top repeat-x; color: #333333; }
+.ui-widget-content a { color: #333333; }
+.ui-widget-header { border: 1px solid #e78f08; background: #f6a828 url(ui-lightness/images/ui-bg_gloss-wave_35_f6a828_500x100.png) 50% 50% repeat-x; color: #ffffff; font-weight: bold; }
+.ui-widget-header a { color: #ffffff; }
+
+/* Interaction states
+----------------------------------*/
+.ui-state-default, .ui-widget-content .ui-state-default { border: 1px solid #cccccc; background: #f6f6f6 url(ui-lightness/images/ui-bg_glass_100_f6f6f6_1x400.png) 50% 50% repeat-x; font-weight: bold; color: #1c94c4; outline: none; }
+.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #1c94c4; text-decoration: none; outline: none; }
+.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus { border: 1px solid #fbcb09; background: #fdf5ce url(ui-lightness/images/ui-bg_glass_100_fdf5ce_1x400.png) 50% 50% repeat-x; font-weight: bold; color: #c77405; outline: none; }
+.ui-state-hover a, .ui-state-hover a:hover { color: #c77405; text-decoration: none; outline: none; }
+.ui-state-active, .ui-widget-content .ui-state-active { border: 1px solid #fbd850; background: #ffffff url(ui-lightness/images/ui-bg_glass_65_ffffff_1x400.png) 50% 50% repeat-x; font-weight: bold; color: #eb8f00; outline: none; }
+.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #eb8f00; outline: none; text-decoration: none; }
+
+/* Interaction Cues
+----------------------------------*/
+.ui-state-highlight, .ui-widget-content .ui-state-highlight {border: 1px solid #fed22f; background: #ffe45c url(ui-lightness/images/ui-bg_highlight-soft_75_ffe45c_1x100.png) 50% top repeat-x; color: #363636; }
+.ui-state-highlight a, .ui-widget-content .ui-state-highlight a { color: #363636; }
+.ui-state-error, .ui-widget-content .ui-state-error {border: 1px solid #cd0a0a; background: #b81900 url(ui-lightness/images/ui-bg_diagonals-thick_18_b81900_40x40.png) 50% 50% repeat; color: #ffffff; }
+.ui-state-error a, .ui-widget-content .ui-state-error a { color: #ffffff; }
+.ui-state-error-text, .ui-widget-content .ui-state-error-text { color: #ffffff; }
+.ui-state-disabled, .ui-widget-content .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); background-image: none; }
+.ui-priority-primary, .ui-widget-content .ui-priority-primary { font-weight: bold; }
+.ui-priority-secondary, .ui-widget-content .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); font-weight: normal; }
+
+/* Icons
+----------------------------------*/
+
+/* states and images */
+.ui-icon { width: 16px; height: 16px; background-image: url(ui-lightness/images/ui-icons_222222_256x240.png); }
+.ui-widget-content .ui-icon {background-image: url(ui-lightness/images/ui-icons_222222_256x240.png); }
+.ui-widget-header .ui-icon {background-image: url(ui-lightness/images/ui-icons_ffffff_256x240.png); }
+.ui-state-default .ui-icon { background-image: url(ui-lightness/images/ui-icons_ef8c08_256x240.png); }
+.ui-state-hover .ui-icon, .ui-state-focus .ui-icon {background-image: url(ui-lightness/images/ui-icons_ef8c08_256x240.png); }
+.ui-state-active .ui-icon {background-image: url(ui-lightness/images/ui-icons_ef8c08_256x240.png); }
+.ui-state-highlight .ui-icon {background-image: url(ui-lightness/images/ui-icons_228ef1_256x240.png); }
+.ui-state-error .ui-icon, .ui-state-error-text .ui-icon {background-image: url(ui-lightness/images/ui-icons_ffd27a_256x240.png); }
+
+/* positioning */
+.ui-icon-carat-1-n { background-position: 0 0; }
+.ui-icon-carat-1-ne { background-position: -16px 0; }
+.ui-icon-carat-1-e { background-position: -32px 0; }
+.ui-icon-carat-1-se { background-position: -48px 0; }
+.ui-icon-carat-1-s { background-position: -64px 0; }
+.ui-icon-carat-1-sw { background-position: -80px 0; }
+.ui-icon-carat-1-w { background-position: -96px 0; }
+.ui-icon-carat-1-nw { background-position: -112px 0; }
+.ui-icon-carat-2-n-s { background-position: -128px 0; }
+.ui-icon-carat-2-e-w { background-position: -144px 0; }
+.ui-icon-triangle-1-n { background-position: 0 -16px; }
+.ui-icon-triangle-1-ne { background-position: -16px -16px; }
+.ui-icon-triangle-1-e { background-position: -32px -16px; }
+.ui-icon-triangle-1-se { background-position: -48px -16px; }
+.ui-icon-triangle-1-s { background-position: -64px -16px; }
+.ui-icon-triangle-1-sw { background-position: -80px -16px; }
+.ui-icon-triangle-1-w { background-position: -96px -16px; }
+.ui-icon-triangle-1-nw { background-position: -112px -16px; }
+.ui-icon-triangle-2-n-s { background-position: -128px -16px; }
+.ui-icon-triangle-2-e-w { background-position: -144px -16px; }
+.ui-icon-arrow-1-n { background-position: 0 -32px; }
+.ui-icon-arrow-1-ne { background-position: -16px -32px; }
+.ui-icon-arrow-1-e { background-position: -32px -32px; }
+.ui-icon-arrow-1-se { background-position: -48px -32px; }
+.ui-icon-arrow-1-s { background-position: -64px -32px; }
+.ui-icon-arrow-1-sw { background-position: -80px -32px; }
+.ui-icon-arrow-1-w { background-position: -96px -32px; }
+.ui-icon-arrow-1-nw { background-position: -112px -32px; }
+.ui-icon-arrow-2-n-s { background-position: -128px -32px; }
+.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; }
+.ui-icon-arrow-2-e-w { background-position: -160px -32px; }
+.ui-icon-arrow-2-se-nw { background-position: -176px -32px; }
+.ui-icon-arrowstop-1-n { background-position: -192px -32px; }
+.ui-icon-arrowstop-1-e { background-position: -208px -32px; }
+.ui-icon-arrowstop-1-s { background-position: -224px -32px; }
+.ui-icon-arrowstop-1-w { background-position: -240px -32px; }
+.ui-icon-arrowthick-1-n { background-position: 0 -48px; }
+.ui-icon-arrowthick-1-ne { background-position: -16px -48px; }
+.ui-icon-arrowthick-1-e { background-position: -32px -48px; }
+.ui-icon-arrowthick-1-se { background-position: -48px -48px; }
+.ui-icon-arrowthick-1-s { background-position: -64px -48px; }
+.ui-icon-arrowthick-1-sw { background-position: -80px -48px; }
+.ui-icon-arrowthick-1-w { background-position: -96px -48px; }
+.ui-icon-arrowthick-1-nw { background-position: -112px -48px; }
+.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; }
+.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; }
+.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; }
+.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; }
+.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; }
+.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; }
+.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; }
+.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; }
+.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; }
+.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; }
+.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; }
+.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; }
+.ui-icon-arrowreturn-1-w { background-position: -64px -64px; }
+.ui-icon-arrowreturn-1-n { background-position: -80px -64px; }
+.ui-icon-arrowreturn-1-e { background-position: -96px -64px; }
+.ui-icon-arrowreturn-1-s { background-position: -112px -64px; }
+.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; }
+.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; }
+.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; }
+.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; }
+.ui-icon-arrow-4 { background-position: 0 -80px; }
+.ui-icon-arrow-4-diag { background-position: -16px -80px; }
+.ui-icon-extlink { background-position: -32px -80px; }
+.ui-icon-newwin { background-position: -48px -80px; }
+.ui-icon-refresh { background-position: -64px -80px; }
+.ui-icon-shuffle { background-position: -80px -80px; }
+.ui-icon-transfer-e-w { background-position: -96px -80px; }
+.ui-icon-transferthick-e-w { background-position: -112px -80px; }
+.ui-icon-folder-collapsed { background-position: 0 -96px; }
+.ui-icon-folder-open { background-position: -16px -96px; }
+.ui-icon-document { background-position: -32px -96px; }
+.ui-icon-document-b { background-position: -48px -96px; }
+.ui-icon-note { background-position: -64px -96px; }
+.ui-icon-mail-closed { background-position: -80px -96px; }
+.ui-icon-mail-open { background-position: -96px -96px; }
+.ui-icon-suitcase { background-position: -112px -96px; }
+.ui-icon-comment { background-position: -128px -96px; }
+.ui-icon-person { background-position: -144px -96px; }
+.ui-icon-print { background-position: -160px -96px; }
+.ui-icon-trash { background-position: -176px -96px; }
+.ui-icon-locked { background-position: -192px -96px; }
+.ui-icon-unlocked { background-position: -208px -96px; }
+.ui-icon-bookmark { background-position: -224px -96px; }
+.ui-icon-tag { background-position: -240px -96px; }
+.ui-icon-home { background-position: 0 -112px; }
+.ui-icon-flag { background-position: -16px -112px; }
+.ui-icon-calendar { background-position: -32px -112px; }
+.ui-icon-cart { background-position: -48px -112px; }
+.ui-icon-pencil { background-position: -64px -112px; }
+.ui-icon-clock { background-position: -80px -112px; }
+.ui-icon-disk { background-position: -96px -112px; }
+.ui-icon-calculator { background-position: -112px -112px; }
+.ui-icon-zoomin { background-position: -128px -112px; }
+.ui-icon-zoomout { background-position: -144px -112px; }
+.ui-icon-search { background-position: -160px -112px; }
+.ui-icon-wrench { background-position: -176px -112px; }
+.ui-icon-gear { background-position: -192px -112px; }
+.ui-icon-heart { background-position: -208px -112px; }
+.ui-icon-star { background-position: -224px -112px; }
+.ui-icon-link { background-position: -240px -112px; }
+.ui-icon-cancel { background-position: 0 -128px; }
+.ui-icon-plus { background-position: -16px -128px; }
+.ui-icon-plusthick { background-position: -32px -128px; }
+.ui-icon-minus { background-position: -48px -128px; }
+.ui-icon-minusthick { background-position: -64px -128px; }
+.ui-icon-close { background-position: -80px -128px; }
+.ui-icon-closethick { background-position: -96px -128px; }
+.ui-icon-key { background-position: -112px -128px; }
+.ui-icon-lightbulb { background-position: -128px -128px; }
+.ui-icon-scissors { background-position: -144px -128px; }
+.ui-icon-clipboard { background-position: -160px -128px; }
+.ui-icon-copy { background-position: -176px -128px; }
+.ui-icon-contact { background-position: -192px -128px; }
+.ui-icon-image { background-position: -208px -128px; }
+.ui-icon-video { background-position: -224px -128px; }
+.ui-icon-script { background-position: -240px -128px; }
+.ui-icon-alert { background-position: 0 -144px; }
+.ui-icon-info { background-position: -16px -144px; }
+.ui-icon-notice { background-position: -32px -144px; }
+.ui-icon-help { background-position: -48px -144px; }
+.ui-icon-check { background-position: -64px -144px; }
+.ui-icon-bullet { background-position: -80px -144px; }
+.ui-icon-radio-off { background-position: -96px -144px; }
+.ui-icon-radio-on { background-position: -112px -144px; }
+.ui-icon-pin-w { background-position: -128px -144px; }
+.ui-icon-pin-s { background-position: -144px -144px; }
+.ui-icon-play { background-position: 0 -160px; }
+.ui-icon-pause { background-position: -16px -160px; }
+.ui-icon-seek-next { background-position: -32px -160px; }
+.ui-icon-seek-prev { background-position: -48px -160px; }
+.ui-icon-seek-end { background-position: -64px -160px; }
+.ui-icon-seek-first { background-position: -80px -160px; }
+.ui-icon-stop { background-position: -96px -160px; }
+.ui-icon-eject { background-position: -112px -160px; }
+.ui-icon-volume-off { background-position: -128px -160px; }
+.ui-icon-volume-on { background-position: -144px -160px; }
+.ui-icon-power { background-position: 0 -176px; }
+.ui-icon-signal-diag { background-position: -16px -176px; }
+.ui-icon-signal { background-position: -32px -176px; }
+.ui-icon-battery-0 { background-position: -48px -176px; }
+.ui-icon-battery-1 { background-position: -64px -176px; }
+.ui-icon-battery-2 { background-position: -80px -176px; }
+.ui-icon-battery-3 { background-position: -96px -176px; }
+.ui-icon-circle-plus { background-position: 0 -192px; }
+.ui-icon-circle-minus { background-position: -16px -192px; }
+.ui-icon-circle-close { background-position: -32px -192px; }
+.ui-icon-circle-triangle-e { background-position: -48px -192px; }
+.ui-icon-circle-triangle-s { background-position: -64px -192px; }
+.ui-icon-circle-triangle-w { background-position: -80px -192px; }
+.ui-icon-circle-triangle-n { background-position: -96px -192px; }
+.ui-icon-circle-arrow-e { background-position: -112px -192px; }
+.ui-icon-circle-arrow-s { background-position: -128px -192px; }
+.ui-icon-circle-arrow-w { background-position: -144px -192px; }
+.ui-icon-circle-arrow-n { background-position: -160px -192px; }
+.ui-icon-circle-zoomin { background-position: -176px -192px; }
+.ui-icon-circle-zoomout { background-position: -192px -192px; }
+.ui-icon-circle-check { background-position: -208px -192px; }
+.ui-icon-circlesmall-plus { background-position: 0 -208px; }
+.ui-icon-circlesmall-minus { background-position: -16px -208px; }
+.ui-icon-circlesmall-close { background-position: -32px -208px; }
+.ui-icon-squaresmall-plus { background-position: -48px -208px; }
+.ui-icon-squaresmall-minus { background-position: -64px -208px; }
+.ui-icon-squaresmall-close { background-position: -80px -208px; }
+.ui-icon-grip-dotted-vertical { background-position: 0 -224px; }
+.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; }
+.ui-icon-grip-solid-vertical { background-position: -32px -224px; }
+.ui-icon-grip-solid-horizontal { background-position: -48px -224px; }
+.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; }
+.ui-icon-grip-diagonal-se { background-position: -80px -224px; }
+
+
+/* Misc visuals
+----------------------------------*/
+
+/* Corner radius */
+.ui-corner-tl { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; }
+.ui-corner-tr { -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; }
+.ui-corner-bl { -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; }
+.ui-corner-br { -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; }
+.ui-corner-top { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; }
+.ui-corner-bottom { -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; }
+.ui-corner-right { -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; }
+.ui-corner-left { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; }
+.ui-corner-all { -moz-border-radius: 4px; -webkit-border-radius: 4px; }
+
+/* Overlays */
+.ui-widget-overlay { background: #666666 url(ui-lightness/images/ui-bg_diagonals-thick_20_666666_40x40.png) 50% 50% repeat; opacity: .50;filter:Alpha(Opacity=50); }
+.ui-widget-shadow { margin: -5px 0 0 -5px; padding: 5px; background: #000000 url(ui-lightness/images/ui-bg_flat_10_000000_40x100.png) 50% 50% repeat-x; opacity: .20;filter:Alpha(Opacity=20); -moz-border-radius: 5px; -webkit-border-radius: 5px; }/* Accordion
+----------------------------------*/
+.ui-accordion .ui-accordion-header { cursor: pointer; position: relative; margin-top: 1px; zoom: 1; }
+.ui-accordion .ui-accordion-li-fix { display: inline; }
+.ui-accordion .ui-accordion-header-active { border-bottom: 0 !important; }
+.ui-accordion .ui-accordion-header a { display: block; font-size: 1em; padding: .5em .5em .5em 2.2em; }
+.ui-accordion .ui-accordion-header .ui-icon { position: absolute; left: .5em; top: 50%; margin-top: -8px; }
+.ui-accordion .ui-accordion-content { padding: 1em 2.2em; border-top: 0; margin-top: -2px; position: relative; top: 1px; margin-bottom: 2px; overflow: auto; display: none; }
+.ui-accordion .ui-accordion-content-active { display: block; }/* Datepicker
+----------------------------------*/
+.ui-datepicker { width: 17em; padding: .2em .2em 0; }
+.ui-datepicker .ui-datepicker-header { position:relative; padding:.2em 0; }
+.ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next { position:absolute; top: 2px; width: 1.8em; height: 1.8em; }
+.ui-datepicker .ui-datepicker-prev-hover, .ui-datepicker .ui-datepicker-next-hover { top: 1px; }
+.ui-datepicker .ui-datepicker-prev { left:2px; }
+.ui-datepicker .ui-datepicker-next { right:2px; }
+.ui-datepicker .ui-datepicker-prev-hover { left:1px; }
+.ui-datepicker .ui-datepicker-next-hover { right:1px; }
+.ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span { display: block; position: absolute; left: 50%; margin-left: -8px; top: 50%; margin-top: -8px; }
+.ui-datepicker .ui-datepicker-title { margin: 0 2.3em; line-height: 1.8em; text-align: center; }
+.ui-datepicker .ui-datepicker-title select { float:left; font-size:1em; margin:1px 0; }
+.ui-datepicker select.ui-datepicker-month-year {width: 100%;}
+.ui-datepicker select.ui-datepicker-month,
+.ui-datepicker select.ui-datepicker-year { width: 49%;}
+.ui-datepicker .ui-datepicker-title select.ui-datepicker-year { float: right; }
+.ui-datepicker table {width: 100%; font-size: .9em; border-collapse: collapse; margin:0 0 .4em; }
+.ui-datepicker th { padding: .7em .3em; text-align: center; font-weight: bold; border: 0; }
+.ui-datepicker td { border: 0; padding: 1px; }
+.ui-datepicker td span, .ui-datepicker td a { display: block; padding: .2em; text-align: right; text-decoration: none; }
+.ui-datepicker .ui-datepicker-buttonpane { background-image: none; margin: .7em 0 0 0; padding:0 .2em; border-left: 0; border-right: 0; border-bottom: 0; }
+.ui-datepicker .ui-datepicker-buttonpane button { float: right; margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width:auto; overflow:visible; }
+.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { float:left; }
+
+/* with multiple calendars */
+.ui-datepicker.ui-datepicker-multi { width:auto; }
+.ui-datepicker-multi .ui-datepicker-group { float:left; }
+.ui-datepicker-multi .ui-datepicker-group table { width:95%; margin:0 auto .4em; }
+.ui-datepicker-multi-2 .ui-datepicker-group { width:50%; }
+.ui-datepicker-multi-3 .ui-datepicker-group { width:33.3%; }
+.ui-datepicker-multi-4 .ui-datepicker-group { width:25%; }
+.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header { border-left-width:0; }
+.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { border-left-width:0; }
+.ui-datepicker-multi .ui-datepicker-buttonpane { clear:left; }
+.ui-datepicker-row-break { clear:both; width:100%; }
+
+/* RTL support */
+.ui-datepicker-rtl { direction: rtl; }
+.ui-datepicker-rtl .ui-datepicker-prev { right: 2px; left: auto; }
+.ui-datepicker-rtl .ui-datepicker-next { left: 2px; right: auto; }
+.ui-datepicker-rtl .ui-datepicker-prev:hover { right: 1px; left: auto; }
+.ui-datepicker-rtl .ui-datepicker-next:hover { left: 1px; right: auto; }
+.ui-datepicker-rtl .ui-datepicker-buttonpane { clear:right; }
+.ui-datepicker-rtl .ui-datepicker-buttonpane button { float: left; }
+.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current { float:right; }
+.ui-datepicker-rtl .ui-datepicker-group { float:right; }
+.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header { border-right-width:0; border-left-width:1px; }
+.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { border-right-width:0; border-left-width:1px; }
+
+/* IE6 IFRAME FIX (taken from datepicker 1.5.3 */
+.ui-datepicker-cover {
+ display: none; /*sorry for IE5*/
+ display/**/: block; /*sorry for IE5*/
+ position: absolute; /*must have*/
+ z-index: -1; /*must have*/
+ filter: mask(); /*must have*/
+ top: -4px; /*must have*/
+ left: -4px; /*must have*/
+ width: 200px; /*must have*/
+ height: 200px; /*must have*/
+}/* Dialog
+----------------------------------*/
+.ui-dialog { position: relative; padding: .2em; width: 300px; }
+.ui-dialog .ui-dialog-titlebar { padding: .5em .3em .3em 1em; position: relative; }
+.ui-dialog .ui-dialog-title { float: left; margin: .1em 0 .2em; }
+.ui-dialog .ui-dialog-titlebar-close { position: absolute; right: .3em; top: 50%; width: 19px; margin: -10px 0 0 0; padding: 1px; height: 18px; }
+.ui-dialog .ui-dialog-titlebar-close span { display: block; margin: 1px; }
+.ui-dialog .ui-dialog-titlebar-close:hover, .ui-dialog .ui-dialog-titlebar-close:focus { padding: 0; }
+.ui-dialog .ui-dialog-content { border: 0; padding: .5em 1em; background: none; overflow: auto; zoom: 1; }
+.ui-dialog .ui-dialog-buttonpane { text-align: left; border-width: 1px 0 0 0; background-image: none; margin: .5em 0 0 0; padding: .3em 1em .5em .4em; }
+.ui-dialog .ui-dialog-buttonpane button { float: right; margin: .5em .4em .5em 0; cursor: pointer; padding: .2em .6em .3em .6em; line-height: 1.4em; width:auto; overflow:visible; }
+.ui-dialog .ui-resizable-se { width: 14px; height: 14px; right: 3px; bottom: 3px; }
+.ui-draggable .ui-dialog-titlebar { cursor: move; }
+/* Progressbar
+----------------------------------*/
+.ui-progressbar { height:2em; text-align: left; }
+.ui-progressbar .ui-progressbar-value {margin: -1px; height:100%; }/* Resizable
+----------------------------------*/
+.ui-resizable { position: relative;}
+.ui-resizable-handle { position: absolute;font-size: 0.1px;z-index: 99999; display: block;}
+.ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { display: none; }
+.ui-resizable-n { cursor: n-resize; height: 7px; width: 100%; top: -5px; left: 0px; }
+.ui-resizable-s { cursor: s-resize; height: 7px; width: 100%; bottom: -5px; left: 0px; }
+.ui-resizable-e { cursor: e-resize; width: 7px; right: -5px; top: 0px; height: 100%; }
+.ui-resizable-w { cursor: w-resize; width: 7px; left: -5px; top: 0px; height: 100%; }
+.ui-resizable-se { cursor: se-resize; width: 12px; height: 12px; right: 1px; bottom: 1px; }
+.ui-resizable-sw { cursor: sw-resize; width: 9px; height: 9px; left: -5px; bottom: -5px; }
+.ui-resizable-nw { cursor: nw-resize; width: 9px; height: 9px; left: -5px; top: -5px; }
+.ui-resizable-ne { cursor: ne-resize; width: 9px; height: 9px; right: -5px; top: -5px;}/* Slider
+----------------------------------*/
+.ui-slider { position: relative; text-align: left; }
+.ui-slider .ui-slider-handle { position: absolute; z-index: 2; width: 1.2em; height: 1.2em; cursor: default; }
+.ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; }
+
+.ui-slider-horizontal { height: .8em; }
+.ui-slider-horizontal .ui-slider-handle { top: -.3em; margin-left: -.6em; }
+.ui-slider-horizontal .ui-slider-range { top: 0; height: 100%; }
+.ui-slider-horizontal .ui-slider-range-min { left: 0; }
+.ui-slider-horizontal .ui-slider-range-max { right: 0; }
+
+.ui-slider-vertical { width: .8em; height: 100px; }
+.ui-slider-vertical .ui-slider-handle { left: -.3em; margin-left: 0; margin-bottom: -.6em; }
+.ui-slider-vertical .ui-slider-range { left: 0; width: 100%; }
+.ui-slider-vertical .ui-slider-range-min { bottom: 0; }
+.ui-slider-vertical .ui-slider-range-max { top: 0; }/* Tabs
+----------------------------------*/
+.ui-tabs { padding: .2em; zoom: 1; }
+.ui-tabs .ui-tabs-nav { list-style: none; position: relative; padding: .2em .2em 0; }
+.ui-tabs .ui-tabs-nav li { position: relative; float: left; border-bottom-width: 0 !important; margin: 0 .2em -1px 0; padding: 0; }
+.ui-tabs .ui-tabs-nav li a { float: left; text-decoration: none; padding: .5em 1em; }
+.ui-tabs .ui-tabs-nav li.ui-tabs-selected { padding-bottom: 1px; border-bottom-width: 0; }
+.ui-tabs .ui-tabs-nav li.ui-tabs-selected a, .ui-tabs .ui-tabs-nav li.ui-state-disabled a, .ui-tabs .ui-tabs-nav li.ui-state-processing a { cursor: text; }
+.ui-tabs .ui-tabs-nav li a, .ui-tabs.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-selected a { cursor: pointer; } /* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */
+.ui-tabs .ui-tabs-panel { padding: 1em 1.4em; display: block; border-width: 0; background: none; }
+.ui-tabs .ui-tabs-hide { display: none !important; }
diff --git a/module/web/media/default/css/window.css b/module/web/media/default/css/window.css new file mode 100644 index 000000000..4c209f33b --- /dev/null +++ b/module/web/media/default/css/window.css @@ -0,0 +1,75 @@ +/* ----------- My Form ----------- */
+.myform{
+margin:0 auto;
+width:600px;
+padding:14px;
+
+left:50%;
+top:150px;
+margin-left: -350px;
+position: absolute;
+background: #FFF;
+display:none;
+}
+
+/* ----------- stylized ----------- */
+#add_box{
+border:solid 2px #b7ddf2;
+background:#ebf4fb;
+}
+#add_box h1 {
+font-size:14px;
+font-weight:bold;
+margin-bottom:8px;
+}
+#add_box p{
+font-size:11px;
+color:#666666;
+margin-bottom:20px;
+border-bottom:solid 1px #b7ddf2;
+padding-bottom:10px;
+}
+#add_box label{
+display:block;
+font-weight:bold;
+text-align:right;
+width:240px;
+float:left;
+}
+#add_box .small{
+color:#666666;
+display:block;
+font-size:11px;
+font-weight:normal;
+text-align:right;
+width:240px;
+}
+#add_box input{
+float:left;
+font-size:12px;
+padding:4px 2px;
+border:solid 1px #aacfe4;
+width:300px;
+margin:2px 0 20px 10px;
+}
+#add_box textarea{
+float:left;
+font-size:12px;
+padding:4px 2px;
+border:solid 1px #aacfe4;
+width:300px;
+margin:2px 0 20px 10px;
+}
+#add_box button{
+clear:both;
+margin-left:150px;
+width:125px;
+height:31px;
+background:#666666 url(../img/button.png) no-repeat;
+text-align:center;
+line-height:31px;
+color:#FFFFFF;
+font-size:11px;
+font-weight:bold;
+border: 0px;
+}
\ No newline at end of file diff --git a/module/web/static/default/Button-Add-grey.png b/module/web/media/default/img/Button-Add-grey.png Binary files differindex 6659e230e..6659e230e 100644 --- a/module/web/static/default/Button-Add-grey.png +++ b/module/web/media/default/img/Button-Add-grey.png diff --git a/module/web/static/default/Button-Add.png b/module/web/media/default/img/Button-Add.png Binary files differindex 602da4131..602da4131 100644 --- a/module/web/static/default/Button-Add.png +++ b/module/web/media/default/img/Button-Add.png diff --git a/module/web/static/default/Button-Pause-grey.png b/module/web/media/default/img/Button-Pause-grey.png Binary files differindex d1017e974..d1017e974 100644 --- a/module/web/static/default/Button-Pause-grey.png +++ b/module/web/media/default/img/Button-Pause-grey.png diff --git a/module/web/static/default/Button-Pause.png b/module/web/media/default/img/Button-Pause.png Binary files differindex 68f3ffc3a..68f3ffc3a 100644 --- a/module/web/static/default/Button-Pause.png +++ b/module/web/media/default/img/Button-Pause.png diff --git a/module/web/static/default/Button-Play-grey.png b/module/web/media/default/img/Button-Play-grey.png Binary files differindex 9f44c2289..9f44c2289 100644 --- a/module/web/static/default/Button-Play-grey.png +++ b/module/web/media/default/img/Button-Play-grey.png diff --git a/module/web/static/default/Button-Play.png b/module/web/media/default/img/Button-Play.png Binary files differindex 1ce1ed913..1ce1ed913 100644 --- a/module/web/static/default/Button-Play.png +++ b/module/web/media/default/img/Button-Play.png diff --git a/module/web/media/default/img/arrow_refresh.png b/module/web/media/default/img/arrow_refresh.png Binary files differnew file mode 100644 index 000000000..0de26566d --- /dev/null +++ b/module/web/media/default/img/arrow_refresh.png diff --git a/module/web/static/window/big_button.gif b/module/web/media/default/img/big_button.gif Binary files differindex 7680490ea..7680490ea 100644 --- a/module/web/static/window/big_button.gif +++ b/module/web/media/default/img/big_button.gif diff --git a/module/web/static/window/big_button_over.gif b/module/web/media/default/img/big_button_over.gif Binary files differindex 2e3ee10d2..2e3ee10d2 100644 --- a/module/web/static/window/big_button_over.gif +++ b/module/web/media/default/img/big_button_over.gif diff --git a/module/web/static/window/body.png b/module/web/media/default/img/body.png Binary files differindex 7ff1043e0..7ff1043e0 100644 --- a/module/web/static/window/body.png +++ b/module/web/media/default/img/body.png diff --git a/module/web/media/default/img/button.png b/module/web/media/default/img/button.png Binary files differnew file mode 100644 index 000000000..890160614 --- /dev/null +++ b/module/web/media/default/img/button.png diff --git a/module/web/static/window/closebtn.gif b/module/web/media/default/img/closebtn.gif Binary files differindex 3e27e6030..3e27e6030 100644 --- a/module/web/static/window/closebtn.gif +++ b/module/web/media/default/img/closebtn.gif diff --git a/module/web/media/default/img/cog.png b/module/web/media/default/img/cog.png Binary files differnew file mode 100644 index 000000000..67de2c6cc --- /dev/null +++ b/module/web/media/default/img/cog.png diff --git a/module/web/media/default/img/control_cancel.png b/module/web/media/default/img/control_cancel.png Binary files differnew file mode 100644 index 000000000..7b9bc3fba --- /dev/null +++ b/module/web/media/default/img/control_cancel.png diff --git a/module/web/media/default/img/control_cancel_blue.png b/module/web/media/default/img/control_cancel_blue.png Binary files differnew file mode 100644 index 000000000..0c5c96ce3 --- /dev/null +++ b/module/web/media/default/img/control_cancel_blue.png diff --git a/module/web/media/default/img/control_pause.png b/module/web/media/default/img/control_pause.png Binary files differnew file mode 100644 index 000000000..2d9ce9c4e --- /dev/null +++ b/module/web/media/default/img/control_pause.png diff --git a/module/web/media/default/img/control_pause_blue.png b/module/web/media/default/img/control_pause_blue.png Binary files differnew file mode 100644 index 000000000..ec61099b0 --- /dev/null +++ b/module/web/media/default/img/control_pause_blue.png diff --git a/module/web/media/default/img/control_play.png b/module/web/media/default/img/control_play.png Binary files differnew file mode 100644 index 000000000..0846555d0 --- /dev/null +++ b/module/web/media/default/img/control_play.png diff --git a/module/web/media/default/img/control_play_blue.png b/module/web/media/default/img/control_play_blue.png Binary files differnew file mode 100644 index 000000000..f8c8ec683 --- /dev/null +++ b/module/web/media/default/img/control_play_blue.png diff --git a/module/web/media/default/img/control_stop.png b/module/web/media/default/img/control_stop.png Binary files differnew file mode 100644 index 000000000..893bb60e5 --- /dev/null +++ b/module/web/media/default/img/control_stop.png diff --git a/module/web/media/default/img/control_stop_blue.png b/module/web/media/default/img/control_stop_blue.png Binary files differnew file mode 100644 index 000000000..e6f75d232 --- /dev/null +++ b/module/web/media/default/img/control_stop_blue.png diff --git a/module/web/media/default/img/delete.png b/module/web/media/default/img/delete.png Binary files differnew file mode 100644 index 000000000..08f249365 --- /dev/null +++ b/module/web/media/default/img/delete.png diff --git a/module/web/static/window/drag_corner.gif b/module/web/media/default/img/drag_corner.gif Binary files differindex befb1adf1..befb1adf1 100644 --- a/module/web/static/window/drag_corner.gif +++ b/module/web/media/default/img/drag_corner.gif diff --git a/module/web/media/default/img/folder.png b/module/web/media/default/img/folder.png Binary files differnew file mode 100644 index 000000000..784e8fa48 --- /dev/null +++ b/module/web/media/default/img/folder.png diff --git a/module/web/static/window/full.png b/module/web/media/default/img/full.png Binary files differindex fea52af76..fea52af76 100644 --- a/module/web/static/window/full.png +++ b/module/web/media/default/img/full.png diff --git a/module/web/static/default/head-login.png b/module/web/media/default/img/head-login.png Binary files differindex b59b7cbbf..b59b7cbbf 100644 --- a/module/web/static/default/head-login.png +++ b/module/web/media/default/img/head-login.png diff --git a/module/web/static/default/head-menu-development.png b/module/web/media/default/img/head-menu-development.png Binary files differindex 8ef08e2e5..8ef08e2e5 100644 --- a/module/web/static/default/head-menu-development.png +++ b/module/web/media/default/img/head-menu-development.png diff --git a/module/web/static/default/head-menu-download.png b/module/web/media/default/img/head-menu-download.png Binary files differindex 98c5da9db..98c5da9db 100644 --- a/module/web/static/default/head-menu-download.png +++ b/module/web/media/default/img/head-menu-download.png diff --git a/module/web/static/default/head-menu-home.png b/module/web/media/default/img/head-menu-home.png Binary files differindex 9d62109aa..9d62109aa 100644 --- a/module/web/static/default/head-menu-home.png +++ b/module/web/media/default/img/head-menu-home.png diff --git a/module/web/static/default/head-menu-index.png b/module/web/media/default/img/head-menu-index.png Binary files differindex 44d631064..44d631064 100644 --- a/module/web/static/default/head-menu-index.png +++ b/module/web/media/default/img/head-menu-index.png diff --git a/module/web/static/default/head-menu-news.png b/module/web/media/default/img/head-menu-news.png Binary files differindex 43950ebc9..43950ebc9 100644 --- a/module/web/static/default/head-menu-news.png +++ b/module/web/media/default/img/head-menu-news.png diff --git a/module/web/static/default/head-menu-recent.png b/module/web/media/default/img/head-menu-recent.png Binary files differindex fc9b0497f..fc9b0497f 100644 --- a/module/web/static/default/head-menu-recent.png +++ b/module/web/media/default/img/head-menu-recent.png diff --git a/module/web/static/default/head-menu-wiki.png b/module/web/media/default/img/head-menu-wiki.png Binary files differindex 07cf0102d..07cf0102d 100644 --- a/module/web/static/default/head-menu-wiki.png +++ b/module/web/media/default/img/head-menu-wiki.png diff --git a/module/web/static/default/head-search-noshadow.png b/module/web/media/default/img/head-search-noshadow.png Binary files differindex aafdae015..aafdae015 100644 --- a/module/web/static/default/head-search-noshadow.png +++ b/module/web/media/default/img/head-search-noshadow.png diff --git a/module/web/static/default/head_bg1.png b/module/web/media/default/img/head_bg1.png Binary files differindex f2848c3cc..f2848c3cc 100644 --- a/module/web/static/default/head_bg1.png +++ b/module/web/media/default/img/head_bg1.png diff --git a/module/web/static/default/page-tools-backlinks.png b/module/web/media/default/img/page-tools-backlinks.png Binary files differindex 3eb6a9ce3..3eb6a9ce3 100644 --- a/module/web/static/default/page-tools-backlinks.png +++ b/module/web/media/default/img/page-tools-backlinks.png diff --git a/module/web/static/default/page-tools-edit.png b/module/web/media/default/img/page-tools-edit.png Binary files differindex 188e1c12b..188e1c12b 100644 --- a/module/web/static/default/page-tools-edit.png +++ b/module/web/media/default/img/page-tools-edit.png diff --git a/module/web/static/default/page-tools-revisions.png b/module/web/media/default/img/page-tools-revisions.png Binary files differindex 5c3b8587f..5c3b8587f 100644 --- a/module/web/static/default/page-tools-revisions.png +++ b/module/web/media/default/img/page-tools-revisions.png diff --git a/module/web/static/default/pyload-logo-edited3.5-new-font-small.png b/module/web/media/default/img/pyload-logo-edited3.5-new-font-small.png Binary files differindex 2443cd8b1..2443cd8b1 100644 --- a/module/web/static/default/pyload-logo-edited3.5-new-font-small.png +++ b/module/web/media/default/img/pyload-logo-edited3.5-new-font-small.png diff --git a/module/web/media/default/img/status_None.png b/module/web/media/default/img/status_None.png Binary files differnew file mode 100644 index 000000000..293b13f77 --- /dev/null +++ b/module/web/media/default/img/status_None.png diff --git a/module/web/media/default/img/status_aborted.png b/module/web/media/default/img/status_aborted.png Binary files differnew file mode 100644 index 000000000..0cfd58596 --- /dev/null +++ b/module/web/media/default/img/status_aborted.png diff --git a/module/web/media/default/img/status_downloading.png b/module/web/media/default/img/status_downloading.png Binary files differnew file mode 100644 index 000000000..fb4ebc850 --- /dev/null +++ b/module/web/media/default/img/status_downloading.png diff --git a/module/web/media/default/img/status_failed.png b/module/web/media/default/img/status_failed.png Binary files differnew file mode 100644 index 000000000..0cfd58596 --- /dev/null +++ b/module/web/media/default/img/status_failed.png diff --git a/module/web/media/default/img/status_finished.png b/module/web/media/default/img/status_finished.png Binary files differnew file mode 100644 index 000000000..89c8129a4 --- /dev/null +++ b/module/web/media/default/img/status_finished.png diff --git a/module/web/media/default/img/status_waiting.png b/module/web/media/default/img/status_waiting.png Binary files differnew file mode 100644 index 000000000..2842cc338 --- /dev/null +++ b/module/web/media/default/img/status_waiting.png diff --git a/module/web/static/default/tab-background.png b/module/web/media/default/img/tab-background.png Binary files differindex 29a5d1991..29a5d1991 100644 --- a/module/web/static/default/tab-background.png +++ b/module/web/media/default/img/tab-background.png diff --git a/module/web/static/default/tabs-border-bottom.png b/module/web/media/default/img/tabs-border-bottom.png Binary files differindex 02440f428..02440f428 100644 --- a/module/web/static/default/tabs-border-bottom.png +++ b/module/web/media/default/img/tabs-border-bottom.png diff --git a/module/web/static/default/user-actions-logout.png b/module/web/media/default/img/user-actions-logout.png Binary files differindex 0010931e2..0010931e2 100644 --- a/module/web/static/default/user-actions-logout.png +++ b/module/web/media/default/img/user-actions-logout.png diff --git a/module/web/static/default/user-actions-profile.png b/module/web/media/default/img/user-actions-profile.png Binary files differindex 46573fff6..46573fff6 100644 --- a/module/web/static/default/user-actions-profile.png +++ b/module/web/media/default/img/user-actions-profile.png diff --git a/module/web/media/default/js/funktions.js b/module/web/media/default/js/funktions.js new file mode 100644 index 000000000..9ca165b36 --- /dev/null +++ b/module/web/media/default/js/funktions.js @@ -0,0 +1,23 @@ +// JavaScript Document
+function SecToRightTime(sek)
+{
+ vreturn = sek > 86400 ? sprintf('%d Tag%s ', sek / 86400, Math.floor(sek / 86400) != 1 ? 'e':'') : '';
+ vreturn += sprintf('%02d:%02d:%02d', sek / 3600 % 24, sek / 60 % 60, sek % 60 );
+ return vreturn;
+}
+
+function HumanFileSize(size)
+{
+ var filesizename = new Array("KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB");
+ var loga = Math.log(size)/Math.log(1024);
+ var i = Math.floor(loga);
+ var a = Math.pow(1024, i);
+ return Math.round( size / a , 2) + " " + filesizename[i];
+}
+
+Array.prototype.remove = function(from, to) {
+ var rest = this.slice((to || from) + 1 || this.length);
+ this.length = from < 0 ? this.length + from : from;
+ if (this.length == 0) return [];
+ return this.push.apply(this, rest);
+};
\ No newline at end of file diff --git a/module/web/media/default/js/jquery.timers-1.2.js b/module/web/media/default/js/jquery.timers-1.2.js new file mode 100644 index 000000000..ad22e93ce --- /dev/null +++ b/module/web/media/default/js/jquery.timers-1.2.js @@ -0,0 +1,138 @@ +/**
+ * jQuery.timers - Timer abstractions for jQuery
+ * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
+ * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
+ * Date: 2009/10/16
+ *
+ * @author Blair Mitchelmore
+ * @version 1.2
+ *
+ **/
+
+jQuery.fn.extend({
+ everyTime: function(interval, label, fn, times) {
+ return this.each(function() {
+ jQuery.timer.add(this, interval, label, fn, times);
+ });
+ },
+ oneTime: function(interval, label, fn) {
+ return this.each(function() {
+ jQuery.timer.add(this, interval, label, fn, 1);
+ });
+ },
+ stopTime: function(label, fn) {
+ return this.each(function() {
+ jQuery.timer.remove(this, label, fn);
+ });
+ }
+});
+
+jQuery.extend({
+ timer: {
+ global: [],
+ guid: 1,
+ dataKey: "jQuery.timer",
+ regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
+ powers: {
+ // Yeah this is major overkill...
+ 'ms': 1,
+ 'cs': 10,
+ 'ds': 100,
+ 's': 1000,
+ 'das': 10000,
+ 'hs': 100000,
+ 'ks': 1000000
+ },
+ timeParse: function(value) {
+ if (value == undefined || value == null)
+ return null;
+ var result = this.regex.exec(jQuery.trim(value.toString()));
+ if (result[2]) {
+ var num = parseFloat(result[1]);
+ var mult = this.powers[result[2]] || 1;
+ return num * mult;
+ } else {
+ return value;
+ }
+ },
+ add: function(element, interval, label, fn, times) {
+ var counter = 0;
+
+ if (jQuery.isFunction(label)) {
+ if (!times)
+ times = fn;
+ fn = label;
+ label = interval;
+ }
+
+ interval = jQuery.timer.timeParse(interval);
+
+ if (typeof interval != 'number' || isNaN(interval) || interval < 0)
+ return;
+
+ if (typeof times != 'number' || isNaN(times) || times < 0)
+ times = 0;
+
+ times = times || 0;
+
+ var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
+
+ if (!timers[label])
+ timers[label] = {};
+
+ fn.timerID = fn.timerID || this.guid++;
+
+ var handler = function() {
+ if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
+ jQuery.timer.remove(element, label, fn);
+ };
+
+ handler.timerID = fn.timerID;
+
+ if (!timers[label][fn.timerID])
+ timers[label][fn.timerID] = window.setInterval(handler,interval);
+
+ this.global.push( element );
+
+ },
+ remove: function(element, label, fn) {
+ var timers = jQuery.data(element, this.dataKey), ret;
+
+ if ( timers ) {
+
+ if (!label) {
+ for ( label in timers )
+ this.remove(element, label, fn);
+ } else if ( timers[label] ) {
+ if ( fn ) {
+ if ( fn.timerID ) {
+ window.clearInterval(timers[label][fn.timerID]);
+ delete timers[label][fn.timerID];
+ }
+ } else {
+ for ( var fn in timers[label] ) {
+ window.clearInterval(timers[label][fn]);
+ delete timers[label][fn];
+ }
+ }
+
+ for ( ret in timers[label] ) break;
+ if ( !ret ) {
+ ret = null;
+ delete timers[label];
+ }
+ }
+
+ for ( ret in timers ) break;
+ if ( !ret )
+ jQuery.removeData(element, this.dataKey);
+ }
+ }
+ }
+});
+
+jQuery(window).bind("unload", function() {
+ jQuery.each(jQuery.timer.global, function(index, item) {
+ jQuery.timer.remove(item);
+ });
+});
\ No newline at end of file diff --git a/module/web/static/mootools-1.2.3-core.js b/module/web/media/default/js/mootools-1.2.3-core.js index 25f1f9d03..25f1f9d03 100644 --- a/module/web/static/mootools-1.2.3-core.js +++ b/module/web/media/default/js/mootools-1.2.3-core.js diff --git a/module/web/static/mootools-1.2.3.1-more.js b/module/web/media/default/js/mootools-1.2.3.1-more.js index f3e4b4121..f3e4b4121 100644 --- a/module/web/static/mootools-1.2.3.1-more.js +++ b/module/web/media/default/js/mootools-1.2.3.1-more.js diff --git a/module/web/media/default/js/mootools-1.2.4-core.js b/module/web/media/default/js/mootools-1.2.4-core.js new file mode 100644 index 000000000..6ea6a530a --- /dev/null +++ b/module/web/media/default/js/mootools-1.2.4-core.js @@ -0,0 +1,337 @@ +//MooTools, <http://mootools.net>, My Object Oriented (JavaScript) Tools. Copyright (c) 2006-2009 Valerio Proietti, <http://mad4milk.net>, MIT Style License. + +var MooTools={version:"1.2.4",build:"0d9113241a90b9cd5643b926795852a2026710d4"};var Native=function(k){k=k||{};var a=k.name;var i=k.legacy;var b=k.protect; +var c=k.implement;var h=k.generics;var f=k.initialize;var g=k.afterImplement||function(){};var d=f||i;h=h!==false;d.constructor=Native;d.$family={name:"native"}; +if(i&&f){d.prototype=i.prototype;}d.prototype.constructor=d;if(a){var e=a.toLowerCase();d.prototype.$family={name:e};Native.typize(d,e);}var j=function(n,l,o,m){if(!b||m||!n.prototype[l]){n.prototype[l]=o; +}if(h){Native.genericize(n,l,b);}g.call(n,l,o);return n;};d.alias=function(n,l,p){if(typeof n=="string"){var o=this.prototype[n];if((n=o)){return j(this,l,n,p); +}}for(var m in n){this.alias(m,n[m],l);}return this;};d.implement=function(m,l,o){if(typeof m=="string"){return j(this,m,l,o);}for(var n in m){j(this,n,m[n],l); +}return this;};if(c){d.implement(c);}return d;};Native.genericize=function(b,c,a){if((!a||!b[c])&&typeof b.prototype[c]=="function"){b[c]=function(){var d=Array.prototype.slice.call(arguments); +return b.prototype[c].apply(d.shift(),d);};}};Native.implement=function(d,c){for(var b=0,a=d.length;b<a;b++){d[b].implement(c);}};Native.typize=function(a,b){if(!a.type){a.type=function(c){return($type(c)===b); +};}};(function(){var a={Array:Array,Date:Date,Function:Function,Number:Number,RegExp:RegExp,String:String};for(var h in a){new Native({name:h,initialize:a[h],protect:true}); +}var d={"boolean":Boolean,"native":Native,object:Object};for(var c in d){Native.typize(d[c],c);}var f={Array:["concat","indexOf","join","lastIndexOf","pop","push","reverse","shift","slice","sort","splice","toString","unshift","valueOf"],String:["charAt","charCodeAt","concat","indexOf","lastIndexOf","match","replace","search","slice","split","substr","substring","toLowerCase","toUpperCase","valueOf"]}; +for(var e in f){for(var b=f[e].length;b--;){Native.genericize(a[e],f[e][b],true);}}})();var Hash=new Native({name:"Hash",initialize:function(a){if($type(a)=="hash"){a=$unlink(a.getClean()); +}for(var b in a){this[b]=a[b];}return this;}});Hash.implement({forEach:function(b,c){for(var a in this){if(this.hasOwnProperty(a)){b.call(c,this[a],a,this); +}}},getClean:function(){var b={};for(var a in this){if(this.hasOwnProperty(a)){b[a]=this[a];}}return b;},getLength:function(){var b=0;for(var a in this){if(this.hasOwnProperty(a)){b++; +}}return b;}});Hash.alias("forEach","each");Array.implement({forEach:function(c,d){for(var b=0,a=this.length;b<a;b++){c.call(d,this[b],b,this);}}});Array.alias("forEach","each"); +function $A(b){if(b.item){var a=b.length,c=new Array(a);while(a--){c[a]=b[a];}return c;}return Array.prototype.slice.call(b);}function $arguments(a){return function(){return arguments[a]; +};}function $chk(a){return !!(a||a===0);}function $clear(a){clearTimeout(a);clearInterval(a);return null;}function $defined(a){return(a!=undefined);}function $each(c,b,d){var a=$type(c); +((a=="arguments"||a=="collection"||a=="array")?Array:Hash).each(c,b,d);}function $empty(){}function $extend(c,a){for(var b in (a||{})){c[b]=a[b];}return c; +}function $H(a){return new Hash(a);}function $lambda(a){return($type(a)=="function")?a:function(){return a;};}function $merge(){var a=Array.slice(arguments); +a.unshift({});return $mixin.apply(null,a);}function $mixin(e){for(var d=1,a=arguments.length;d<a;d++){var b=arguments[d];if($type(b)!="object"){continue; +}for(var c in b){var g=b[c],f=e[c];e[c]=(f&&$type(g)=="object"&&$type(f)=="object")?$mixin(f,g):$unlink(g);}}return e;}function $pick(){for(var b=0,a=arguments.length; +b<a;b++){if(arguments[b]!=undefined){return arguments[b];}}return null;}function $random(b,a){return Math.floor(Math.random()*(a-b+1)+b);}function $splat(b){var a=$type(b); +return(a)?((a!="array"&&a!="arguments")?[b]:b):[];}var $time=Date.now||function(){return +new Date;};function $try(){for(var b=0,a=arguments.length;b<a; +b++){try{return arguments[b]();}catch(c){}}return null;}function $type(a){if(a==undefined){return false;}if(a.$family){return(a.$family.name=="number"&&!isFinite(a))?false:a.$family.name; +}if(a.nodeName){switch(a.nodeType){case 1:return"element";case 3:return(/\S/).test(a.nodeValue)?"textnode":"whitespace";}}else{if(typeof a.length=="number"){if(a.callee){return"arguments"; +}else{if(a.item){return"collection";}}}}return typeof a;}function $unlink(c){var b;switch($type(c)){case"object":b={};for(var e in c){b[e]=$unlink(c[e]); +}break;case"hash":b=new Hash(c);break;case"array":b=[];for(var d=0,a=c.length;d<a;d++){b[d]=$unlink(c[d]);}break;default:return c;}return b;}var Browser=$merge({Engine:{name:"unknown",version:0},Platform:{name:(window.orientation!=undefined)?"ipod":(navigator.platform.match(/mac|win|linux/i)||["other"])[0].toLowerCase()},Features:{xpath:!!(document.evaluate),air:!!(window.runtime),query:!!(document.querySelector)},Plugins:{},Engines:{presto:function(){return(!window.opera)?false:((arguments.callee.caller)?960:((document.getElementsByClassName)?950:925)); +},trident:function(){return(!window.ActiveXObject)?false:((window.XMLHttpRequest)?((document.querySelectorAll)?6:5):4);},webkit:function(){return(navigator.taintEnabled)?false:((Browser.Features.xpath)?((Browser.Features.query)?525:420):419); +},gecko:function(){return(!document.getBoxObjectFor&&window.mozInnerScreenX==null)?false:((document.getElementsByClassName)?19:18);}}},Browser||{});Browser.Platform[Browser.Platform.name]=true; +Browser.detect=function(){for(var b in this.Engines){var a=this.Engines[b]();if(a){this.Engine={name:b,version:a};this.Engine[b]=this.Engine[b+a]=true; +break;}}return{name:b,version:a};};Browser.detect();Browser.Request=function(){return $try(function(){return new XMLHttpRequest();},function(){return new ActiveXObject("MSXML2.XMLHTTP"); +},function(){return new ActiveXObject("Microsoft.XMLHTTP");});};Browser.Features.xhr=!!(Browser.Request());Browser.Plugins.Flash=(function(){var a=($try(function(){return navigator.plugins["Shockwave Flash"].description; +},function(){return new ActiveXObject("ShockwaveFlash.ShockwaveFlash").GetVariable("$version");})||"0 r0").match(/\d+/g);return{version:parseInt(a[0]||0+"."+a[1],10)||0,build:parseInt(a[2],10)||0}; +})();function $exec(b){if(!b){return b;}if(window.execScript){window.execScript(b);}else{var a=document.createElement("script");a.setAttribute("type","text/javascript"); +a[(Browser.Engine.webkit&&Browser.Engine.version<420)?"innerText":"text"]=b;document.head.appendChild(a);document.head.removeChild(a);}return b;}Native.UID=1; +var $uid=(Browser.Engine.trident)?function(a){return(a.uid||(a.uid=[Native.UID++]))[0];}:function(a){return a.uid||(a.uid=Native.UID++);};var Window=new Native({name:"Window",legacy:(Browser.Engine.trident)?null:window.Window,initialize:function(a){$uid(a); +if(!a.Element){a.Element=$empty;if(Browser.Engine.webkit){a.document.createElement("iframe");}a.Element.prototype=(Browser.Engine.webkit)?window["[[DOMElement.prototype]]"]:{}; +}a.document.window=a;return $extend(a,Window.Prototype);},afterImplement:function(b,a){window[b]=Window.Prototype[b]=a;}});Window.Prototype={$family:{name:"window"}}; +new Window(window);var Document=new Native({name:"Document",legacy:(Browser.Engine.trident)?null:window.Document,initialize:function(a){$uid(a);a.head=a.getElementsByTagName("head")[0]; +a.html=a.getElementsByTagName("html")[0];if(Browser.Engine.trident&&Browser.Engine.version<=4){$try(function(){a.execCommand("BackgroundImageCache",false,true); +});}if(Browser.Engine.trident){a.window.attachEvent("onunload",function(){a.window.detachEvent("onunload",arguments.callee);a.head=a.html=a.window=null; +});}return $extend(a,Document.Prototype);},afterImplement:function(b,a){document[b]=Document.Prototype[b]=a;}});Document.Prototype={$family:{name:"document"}}; +new Document(document);Array.implement({every:function(c,d){for(var b=0,a=this.length;b<a;b++){if(!c.call(d,this[b],b,this)){return false;}}return true; +},filter:function(d,e){var c=[];for(var b=0,a=this.length;b<a;b++){if(d.call(e,this[b],b,this)){c.push(this[b]);}}return c;},clean:function(){return this.filter($defined); +},indexOf:function(c,d){var a=this.length;for(var b=(d<0)?Math.max(0,a+d):d||0;b<a;b++){if(this[b]===c){return b;}}return -1;},map:function(d,e){var c=[]; +for(var b=0,a=this.length;b<a;b++){c[b]=d.call(e,this[b],b,this);}return c;},some:function(c,d){for(var b=0,a=this.length;b<a;b++){if(c.call(d,this[b],b,this)){return true; +}}return false;},associate:function(c){var d={},b=Math.min(this.length,c.length);for(var a=0;a<b;a++){d[c[a]]=this[a];}return d;},link:function(c){var a={}; +for(var e=0,b=this.length;e<b;e++){for(var d in c){if(c[d](this[e])){a[d]=this[e];delete c[d];break;}}}return a;},contains:function(a,b){return this.indexOf(a,b)!=-1; +},extend:function(c){for(var b=0,a=c.length;b<a;b++){this.push(c[b]);}return this;},getLast:function(){return(this.length)?this[this.length-1]:null;},getRandom:function(){return(this.length)?this[$random(0,this.length-1)]:null; +},include:function(a){if(!this.contains(a)){this.push(a);}return this;},combine:function(c){for(var b=0,a=c.length;b<a;b++){this.include(c[b]);}return this; +},erase:function(b){for(var a=this.length;a--;a){if(this[a]===b){this.splice(a,1);}}return this;},empty:function(){this.length=0;return this;},flatten:function(){var d=[]; +for(var b=0,a=this.length;b<a;b++){var c=$type(this[b]);if(!c){continue;}d=d.concat((c=="array"||c=="collection"||c=="arguments")?Array.flatten(this[b]):this[b]); +}return d;},hexToRgb:function(b){if(this.length!=3){return null;}var a=this.map(function(c){if(c.length==1){c+=c;}return c.toInt(16);});return(b)?a:"rgb("+a+")"; +},rgbToHex:function(d){if(this.length<3){return null;}if(this.length==4&&this[3]==0&&!d){return"transparent";}var b=[];for(var a=0;a<3;a++){var c=(this[a]-0).toString(16); +b.push((c.length==1)?"0"+c:c);}return(d)?b:"#"+b.join("");}});Function.implement({extend:function(a){for(var b in a){this[b]=a[b];}return this;},create:function(b){var a=this; +b=b||{};return function(d){var c=b.arguments;c=(c!=undefined)?$splat(c):Array.slice(arguments,(b.event)?1:0);if(b.event){c=[d||window.event].extend(c); +}var e=function(){return a.apply(b.bind||null,c);};if(b.delay){return setTimeout(e,b.delay);}if(b.periodical){return setInterval(e,b.periodical);}if(b.attempt){return $try(e); +}return e();};},run:function(a,b){return this.apply(b,$splat(a));},pass:function(a,b){return this.create({bind:b,arguments:a});},bind:function(b,a){return this.create({bind:b,arguments:a}); +},bindWithEvent:function(b,a){return this.create({bind:b,arguments:a,event:true});},attempt:function(a,b){return this.create({bind:b,arguments:a,attempt:true})(); +},delay:function(b,c,a){return this.create({bind:c,arguments:a,delay:b})();},periodical:function(c,b,a){return this.create({bind:b,arguments:a,periodical:c})(); +}});Number.implement({limit:function(b,a){return Math.min(a,Math.max(b,this));},round:function(a){a=Math.pow(10,a||0);return Math.round(this*a)/a;},times:function(b,c){for(var a=0; +a<this;a++){b.call(c,a,this);}},toFloat:function(){return parseFloat(this);},toInt:function(a){return parseInt(this,a||10);}});Number.alias("times","each"); +(function(b){var a={};b.each(function(c){if(!Number[c]){a[c]=function(){return Math[c].apply(null,[this].concat($A(arguments)));};}});Number.implement(a); +})(["abs","acos","asin","atan","atan2","ceil","cos","exp","floor","log","max","min","pow","sin","sqrt","tan"]);String.implement({test:function(a,b){return((typeof a=="string")?new RegExp(a,b):a).test(this); +},contains:function(a,b){return(b)?(b+this+b).indexOf(b+a+b)>-1:this.indexOf(a)>-1;},trim:function(){return this.replace(/^\s+|\s+$/g,"");},clean:function(){return this.replace(/\s+/g," ").trim(); +},camelCase:function(){return this.replace(/-\D/g,function(a){return a.charAt(1).toUpperCase();});},hyphenate:function(){return this.replace(/[A-Z]/g,function(a){return("-"+a.charAt(0).toLowerCase()); +});},capitalize:function(){return this.replace(/\b[a-z]/g,function(a){return a.toUpperCase();});},escapeRegExp:function(){return this.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1"); +},toInt:function(a){return parseInt(this,a||10);},toFloat:function(){return parseFloat(this);},hexToRgb:function(b){var a=this.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/); +return(a)?a.slice(1).hexToRgb(b):null;},rgbToHex:function(b){var a=this.match(/\d{1,3}/g);return(a)?a.rgbToHex(b):null;},stripScripts:function(b){var a=""; +var c=this.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi,function(){a+=arguments[1]+"\n";return"";});if(b===true){$exec(a);}else{if($type(b)=="function"){b(a,c); +}}return c;},substitute:function(a,b){return this.replace(b||(/\\?\{([^{}]+)\}/g),function(d,c){if(d.charAt(0)=="\\"){return d.slice(1);}return(a[c]!=undefined)?a[c]:""; +});}});Hash.implement({has:Object.prototype.hasOwnProperty,keyOf:function(b){for(var a in this){if(this.hasOwnProperty(a)&&this[a]===b){return a;}}return null; +},hasValue:function(a){return(Hash.keyOf(this,a)!==null);},extend:function(a){Hash.each(a||{},function(c,b){Hash.set(this,b,c);},this);return this;},combine:function(a){Hash.each(a||{},function(c,b){Hash.include(this,b,c); +},this);return this;},erase:function(a){if(this.hasOwnProperty(a)){delete this[a];}return this;},get:function(a){return(this.hasOwnProperty(a))?this[a]:null; +},set:function(a,b){if(!this[a]||this.hasOwnProperty(a)){this[a]=b;}return this;},empty:function(){Hash.each(this,function(b,a){delete this[a];},this); +return this;},include:function(a,b){if(this[a]==undefined){this[a]=b;}return this;},map:function(b,c){var a=new Hash;Hash.each(this,function(e,d){a.set(d,b.call(c,e,d,this)); +},this);return a;},filter:function(b,c){var a=new Hash;Hash.each(this,function(e,d){if(b.call(c,e,d,this)){a.set(d,e);}},this);return a;},every:function(b,c){for(var a in this){if(this.hasOwnProperty(a)&&!b.call(c,this[a],a)){return false; +}}return true;},some:function(b,c){for(var a in this){if(this.hasOwnProperty(a)&&b.call(c,this[a],a)){return true;}}return false;},getKeys:function(){var a=[]; +Hash.each(this,function(c,b){a.push(b);});return a;},getValues:function(){var a=[];Hash.each(this,function(b){a.push(b);});return a;},toQueryString:function(a){var b=[]; +Hash.each(this,function(f,e){if(a){e=a+"["+e+"]";}var d;switch($type(f)){case"object":d=Hash.toQueryString(f,e);break;case"array":var c={};f.each(function(h,g){c[g]=h; +});d=Hash.toQueryString(c,e);break;default:d=e+"="+encodeURIComponent(f);}if(f!=undefined){b.push(d);}});return b.join("&");}});Hash.alias({keyOf:"indexOf",hasValue:"contains"}); +var Event=new Native({name:"Event",initialize:function(a,f){f=f||window;var k=f.document;a=a||f.event;if(a.$extended){return a;}this.$extended=true;var j=a.type; +var g=a.target||a.srcElement;while(g&&g.nodeType==3){g=g.parentNode;}if(j.test(/key/)){var b=a.which||a.keyCode;var m=Event.Keys.keyOf(b);if(j=="keydown"){var d=b-111; +if(d>0&&d<13){m="f"+d;}}m=m||String.fromCharCode(b).toLowerCase();}else{if(j.match(/(click|mouse|menu)/i)){k=(!k.compatMode||k.compatMode=="CSS1Compat")?k.html:k.body; +var i={x:a.pageX||a.clientX+k.scrollLeft,y:a.pageY||a.clientY+k.scrollTop};var c={x:(a.pageX)?a.pageX-f.pageXOffset:a.clientX,y:(a.pageY)?a.pageY-f.pageYOffset:a.clientY}; +if(j.match(/DOMMouseScroll|mousewheel/)){var h=(a.wheelDelta)?a.wheelDelta/120:-(a.detail||0)/3;}var e=(a.which==3)||(a.button==2);var l=null;if(j.match(/over|out/)){switch(j){case"mouseover":l=a.relatedTarget||a.fromElement; +break;case"mouseout":l=a.relatedTarget||a.toElement;}if(!(function(){while(l&&l.nodeType==3){l=l.parentNode;}return true;}).create({attempt:Browser.Engine.gecko})()){l=false; +}}}}return $extend(this,{event:a,type:j,page:i,client:c,rightClick:e,wheel:h,relatedTarget:l,target:g,code:b,key:m,shift:a.shiftKey,control:a.ctrlKey,alt:a.altKey,meta:a.metaKey}); +}});Event.Keys=new Hash({enter:13,up:38,down:40,left:37,right:39,esc:27,space:32,backspace:8,tab:9,"delete":46});Event.implement({stop:function(){return this.stopPropagation().preventDefault(); +},stopPropagation:function(){if(this.event.stopPropagation){this.event.stopPropagation();}else{this.event.cancelBubble=true;}return this;},preventDefault:function(){if(this.event.preventDefault){this.event.preventDefault(); +}else{this.event.returnValue=false;}return this;}});function Class(b){if(b instanceof Function){b={initialize:b};}var a=function(){Object.reset(this);if(a._prototyping){return this; +}this._current=$empty;var c=(this.initialize)?this.initialize.apply(this,arguments):this;delete this._current;delete this.caller;return c;}.extend(this); +a.implement(b);a.constructor=Class;a.prototype.constructor=a;return a;}Function.prototype.protect=function(){this._protected=true;return this;};Object.reset=function(a,c){if(c==null){for(var e in a){Object.reset(a,e); +}return a;}delete a[c];switch($type(a[c])){case"object":var d=function(){};d.prototype=a[c];var b=new d;a[c]=Object.reset(b);break;case"array":a[c]=$unlink(a[c]); +break;}return a;};new Native({name:"Class",initialize:Class}).extend({instantiate:function(b){b._prototyping=true;var a=new b;delete b._prototyping;return a; +},wrap:function(a,b,c){if(c._origin){c=c._origin;}return function(){if(c._protected&&this._current==null){throw new Error('The method "'+b+'" cannot be called.'); +}var e=this.caller,f=this._current;this.caller=f;this._current=arguments.callee;var d=c.apply(this,arguments);this._current=f;this.caller=e;return d;}.extend({_owner:a,_origin:c,_name:b}); +}});Class.implement({implement:function(a,d){if($type(a)=="object"){for(var e in a){this.implement(e,a[e]);}return this;}var f=Class.Mutators[a];if(f){d=f.call(this,d); +if(d==null){return this;}}var c=this.prototype;switch($type(d)){case"function":if(d._hidden){return this;}c[a]=Class.wrap(this,a,d);break;case"object":var b=c[a]; +if($type(b)=="object"){$mixin(b,d);}else{c[a]=$unlink(d);}break;case"array":c[a]=$unlink(d);break;default:c[a]=d;}return this;}});Class.Mutators={Extends:function(a){this.parent=a; +this.prototype=Class.instantiate(a);this.implement("parent",function(){var b=this.caller._name,c=this.caller._owner.parent.prototype[b];if(!c){throw new Error('The method "'+b+'" has no parent.'); +}return c.apply(this,arguments);}.protect());},Implements:function(a){$splat(a).each(function(b){if(b instanceof Function){b=Class.instantiate(b);}this.implement(b); +},this);}};var Chain=new Class({$chain:[],chain:function(){this.$chain.extend(Array.flatten(arguments));return this;},callChain:function(){return(this.$chain.length)?this.$chain.shift().apply(this,arguments):false; +},clearChain:function(){this.$chain.empty();return this;}});var Events=new Class({$events:{},addEvent:function(c,b,a){c=Events.removeOn(c);if(b!=$empty){this.$events[c]=this.$events[c]||[]; +this.$events[c].include(b);if(a){b.internal=true;}}return this;},addEvents:function(a){for(var b in a){this.addEvent(b,a[b]);}return this;},fireEvent:function(c,b,a){c=Events.removeOn(c); +if(!this.$events||!this.$events[c]){return this;}this.$events[c].each(function(d){d.create({bind:this,delay:a,"arguments":b})();},this);return this;},removeEvent:function(b,a){b=Events.removeOn(b); +if(!this.$events[b]){return this;}if(!a.internal){this.$events[b].erase(a);}return this;},removeEvents:function(c){var d;if($type(c)=="object"){for(d in c){this.removeEvent(d,c[d]); +}return this;}if(c){c=Events.removeOn(c);}for(d in this.$events){if(c&&c!=d){continue;}var b=this.$events[d];for(var a=b.length;a--;a){this.removeEvent(d,b[a]); +}}return this;}});Events.removeOn=function(a){return a.replace(/^on([A-Z])/,function(b,c){return c.toLowerCase();});};var Options=new Class({setOptions:function(){this.options=$merge.run([this.options].extend(arguments)); +if(!this.addEvent){return this;}for(var a in this.options){if($type(this.options[a])!="function"||!(/^on[A-Z]/).test(a)){continue;}this.addEvent(a,this.options[a]); +delete this.options[a];}return this;}});var Element=new Native({name:"Element",legacy:window.Element,initialize:function(a,b){var c=Element.Constructors.get(a); +if(c){return c(b);}if(typeof a=="string"){return document.newElement(a,b);}return document.id(a).set(b);},afterImplement:function(a,b){Element.Prototype[a]=b; +if(Array[a]){return;}Elements.implement(a,function(){var c=[],g=true;for(var e=0,d=this.length;e<d;e++){var f=this[e][a].apply(this[e],arguments);c.push(f); +if(g){g=($type(f)=="element");}}return(g)?new Elements(c):c;});}});Element.Prototype={$family:{name:"element"}};Element.Constructors=new Hash;var IFrame=new Native({name:"IFrame",generics:false,initialize:function(){var f=Array.link(arguments,{properties:Object.type,iframe:$defined}); +var d=f.properties||{};var c=document.id(f.iframe);var e=d.onload||$empty;delete d.onload;d.id=d.name=$pick(d.id,d.name,c?(c.id||c.name):"IFrame_"+$time()); +c=new Element(c||"iframe",d);var b=function(){var g=$try(function(){return c.contentWindow.location.host;});if(!g||g==window.location.host){var h=new Window(c.contentWindow); +new Document(c.contentWindow.document);$extend(h.Element.prototype,Element.Prototype);}e.call(c.contentWindow,c.contentWindow.document);};var a=$try(function(){return c.contentWindow; +});((a&&a.document.body)||window.frames[d.id])?b():c.addListener("load",b);return c;}});var Elements=new Native({initialize:function(f,b){b=$extend({ddup:true,cash:true},b); +f=f||[];if(b.ddup||b.cash){var g={},e=[];for(var c=0,a=f.length;c<a;c++){var d=document.id(f[c],!b.cash);if(b.ddup){if(g[d.uid]){continue;}g[d.uid]=true; +}if(d){e.push(d);}}f=e;}return(b.cash)?$extend(f,this):f;}});Elements.implement({filter:function(a,b){if(!a){return this;}return new Elements(Array.filter(this,(typeof a=="string")?function(c){return c.match(a); +}:a,b));}});Document.implement({newElement:function(a,b){if(Browser.Engine.trident&&b){["name","type","checked"].each(function(c){if(!b[c]){return;}a+=" "+c+'="'+b[c]+'"'; +if(c!="checked"){delete b[c];}});a="<"+a+">";}return document.id(this.createElement(a)).set(b);},newTextNode:function(a){return this.createTextNode(a); +},getDocument:function(){return this;},getWindow:function(){return this.window;},id:(function(){var a={string:function(d,c,b){d=b.getElementById(d);return(d)?a.element(d,c):null; +},element:function(b,e){$uid(b);if(!e&&!b.$family&&!(/^object|embed$/i).test(b.tagName)){var c=Element.Prototype;for(var d in c){b[d]=c[d];}}return b;},object:function(c,d,b){if(c.toElement){return a.element(c.toElement(b),d); +}return null;}};a.textnode=a.whitespace=a.window=a.document=$arguments(0);return function(c,e,d){if(c&&c.$family&&c.uid){return c;}var b=$type(c);return(a[b])?a[b](c,e,d||document):null; +};})()});if(window.$==null){Window.implement({$:function(a,b){return document.id(a,b,this.document);}});}Window.implement({$$:function(a){if(arguments.length==1&&typeof a=="string"){return this.document.getElements(a); +}var f=[];var c=Array.flatten(arguments);for(var d=0,b=c.length;d<b;d++){var e=c[d];switch($type(e)){case"element":f.push(e);break;case"string":f.extend(this.document.getElements(e,true)); +}}return new Elements(f);},getDocument:function(){return this.document;},getWindow:function(){return this;}});Native.implement([Element,Document],{getElement:function(a,b){return document.id(this.getElements(a,true)[0]||null,b); +},getElements:function(a,d){a=a.split(",");var c=[];var b=(a.length>1);a.each(function(e){var f=this.getElementsByTagName(e.trim());(b)?c.extend(f):c=f; +},this);return new Elements(c,{ddup:b,cash:!d});}});(function(){var h={},f={};var i={input:"checked",option:"selected",textarea:(Browser.Engine.webkit&&Browser.Engine.version<420)?"innerHTML":"value"}; +var c=function(l){return(f[l]||(f[l]={}));};var g=function(n,l){if(!n){return;}var m=n.uid;if(Browser.Engine.trident){if(n.clearAttributes){var q=l&&n.cloneNode(false); +n.clearAttributes();if(q){n.mergeAttributes(q);}}else{if(n.removeEvents){n.removeEvents();}}if((/object/i).test(n.tagName)){for(var o in n){if(typeof n[o]=="function"){n[o]=$empty; +}}Element.dispose(n);}}if(!m){return;}h[m]=f[m]=null;};var d=function(){Hash.each(h,g);if(Browser.Engine.trident){$A(document.getElementsByTagName("object")).each(g); +}if(window.CollectGarbage){CollectGarbage();}h=f=null;};var j=function(n,l,s,m,p,r){var o=n[s||l];var q=[];while(o){if(o.nodeType==1&&(!m||Element.match(o,m))){if(!p){return document.id(o,r); +}q.push(o);}o=o[l];}return(p)?new Elements(q,{ddup:false,cash:!r}):null;};var e={html:"innerHTML","class":"className","for":"htmlFor",defaultValue:"defaultValue",text:(Browser.Engine.trident||(Browser.Engine.webkit&&Browser.Engine.version<420))?"innerText":"textContent"}; +var b=["compact","nowrap","ismap","declare","noshade","checked","disabled","readonly","multiple","selected","noresize","defer"];var k=["value","type","defaultValue","accessKey","cellPadding","cellSpacing","colSpan","frameBorder","maxLength","readOnly","rowSpan","tabIndex","useMap"]; +b=b.associate(b);Hash.extend(e,b);Hash.extend(e,k.associate(k.map(String.toLowerCase)));var a={before:function(m,l){if(l.parentNode){l.parentNode.insertBefore(m,l); +}},after:function(m,l){if(!l.parentNode){return;}var n=l.nextSibling;(n)?l.parentNode.insertBefore(m,n):l.parentNode.appendChild(m);},bottom:function(m,l){l.appendChild(m); +},top:function(m,l){var n=l.firstChild;(n)?l.insertBefore(m,n):l.appendChild(m);}};a.inside=a.bottom;Hash.each(a,function(l,m){m=m.capitalize();Element.implement("inject"+m,function(n){l(this,document.id(n,true)); +return this;});Element.implement("grab"+m,function(n){l(document.id(n,true),this);return this;});});Element.implement({set:function(o,m){switch($type(o)){case"object":for(var n in o){this.set(n,o[n]); +}break;case"string":var l=Element.Properties.get(o);(l&&l.set)?l.set.apply(this,Array.slice(arguments,1)):this.setProperty(o,m);}return this;},get:function(m){var l=Element.Properties.get(m); +return(l&&l.get)?l.get.apply(this,Array.slice(arguments,1)):this.getProperty(m);},erase:function(m){var l=Element.Properties.get(m);(l&&l.erase)?l.erase.apply(this):this.removeProperty(m); +return this;},setProperty:function(m,n){var l=e[m];if(n==undefined){return this.removeProperty(m);}if(l&&b[m]){n=!!n;}(l)?this[l]=n:this.setAttribute(m,""+n); +return this;},setProperties:function(l){for(var m in l){this.setProperty(m,l[m]);}return this;},getProperty:function(m){var l=e[m];var n=(l)?this[l]:this.getAttribute(m,2); +return(b[m])?!!n:(l)?n:n||null;},getProperties:function(){var l=$A(arguments);return l.map(this.getProperty,this).associate(l);},removeProperty:function(m){var l=e[m]; +(l)?this[l]=(l&&b[m])?false:"":this.removeAttribute(m);return this;},removeProperties:function(){Array.each(arguments,this.removeProperty,this);return this; +},hasClass:function(l){return this.className.contains(l," ");},addClass:function(l){if(!this.hasClass(l)){this.className=(this.className+" "+l).clean(); +}return this;},removeClass:function(l){this.className=this.className.replace(new RegExp("(^|\\s)"+l+"(?:\\s|$)"),"$1");return this;},toggleClass:function(l){return this.hasClass(l)?this.removeClass(l):this.addClass(l); +},adopt:function(){Array.flatten(arguments).each(function(l){l=document.id(l,true);if(l){this.appendChild(l);}},this);return this;},appendText:function(m,l){return this.grab(this.getDocument().newTextNode(m),l); +},grab:function(m,l){a[l||"bottom"](document.id(m,true),this);return this;},inject:function(m,l){a[l||"bottom"](this,document.id(m,true));return this;},replaces:function(l){l=document.id(l,true); +l.parentNode.replaceChild(this,l);return this;},wraps:function(m,l){m=document.id(m,true);return this.replaces(m).grab(m,l);},getPrevious:function(l,m){return j(this,"previousSibling",null,l,false,m); +},getAllPrevious:function(l,m){return j(this,"previousSibling",null,l,true,m);},getNext:function(l,m){return j(this,"nextSibling",null,l,false,m);},getAllNext:function(l,m){return j(this,"nextSibling",null,l,true,m); +},getFirst:function(l,m){return j(this,"nextSibling","firstChild",l,false,m);},getLast:function(l,m){return j(this,"previousSibling","lastChild",l,false,m); +},getParent:function(l,m){return j(this,"parentNode",null,l,false,m);},getParents:function(l,m){return j(this,"parentNode",null,l,true,m);},getSiblings:function(l,m){return this.getParent().getChildren(l,m).erase(this); +},getChildren:function(l,m){return j(this,"nextSibling","firstChild",l,true,m);},getWindow:function(){return this.ownerDocument.window;},getDocument:function(){return this.ownerDocument; +},getElementById:function(o,n){var m=this.ownerDocument.getElementById(o);if(!m){return null;}for(var l=m.parentNode;l!=this;l=l.parentNode){if(!l){return null; +}}return document.id(m,n);},getSelected:function(){return new Elements($A(this.options).filter(function(l){return l.selected;}));},getComputedStyle:function(m){if(this.currentStyle){return this.currentStyle[m.camelCase()]; +}var l=this.getDocument().defaultView.getComputedStyle(this,null);return(l)?l.getPropertyValue([m.hyphenate()]):null;},toQueryString:function(){var l=[]; +this.getElements("input, select, textarea",true).each(function(m){if(!m.name||m.disabled||m.type=="submit"||m.type=="reset"||m.type=="file"){return;}var n=(m.tagName.toLowerCase()=="select")?Element.getSelected(m).map(function(o){return o.value; +}):((m.type=="radio"||m.type=="checkbox")&&!m.checked)?null:m.value;$splat(n).each(function(o){if(typeof o!="undefined"){l.push(m.name+"="+encodeURIComponent(o)); +}});});return l.join("&");},clone:function(o,l){o=o!==false;var r=this.cloneNode(o);var n=function(v,u){if(!l){v.removeAttribute("id");}if(Browser.Engine.trident){v.clearAttributes(); +v.mergeAttributes(u);v.removeAttribute("uid");if(v.options){var w=v.options,s=u.options;for(var t=w.length;t--;){w[t].selected=s[t].selected;}}}var x=i[u.tagName.toLowerCase()]; +if(x&&u[x]){v[x]=u[x];}};if(o){var p=r.getElementsByTagName("*"),q=this.getElementsByTagName("*");for(var m=p.length;m--;){n(p[m],q[m]);}}n(r,this);return document.id(r); +},destroy:function(){Element.empty(this);Element.dispose(this);g(this,true);return null;},empty:function(){$A(this.childNodes).each(function(l){Element.destroy(l); +});return this;},dispose:function(){return(this.parentNode)?this.parentNode.removeChild(this):this;},hasChild:function(l){l=document.id(l,true);if(!l){return false; +}if(Browser.Engine.webkit&&Browser.Engine.version<420){return $A(this.getElementsByTagName(l.tagName)).contains(l);}return(this.contains)?(this!=l&&this.contains(l)):!!(this.compareDocumentPosition(l)&16); +},match:function(l){return(!l||(l==this)||(Element.get(this,"tag")==l));}});Native.implement([Element,Window,Document],{addListener:function(o,n){if(o=="unload"){var l=n,m=this; +n=function(){m.removeListener("unload",n);l();};}else{h[this.uid]=this;}if(this.addEventListener){this.addEventListener(o,n,false);}else{this.attachEvent("on"+o,n); +}return this;},removeListener:function(m,l){if(this.removeEventListener){this.removeEventListener(m,l,false);}else{this.detachEvent("on"+m,l);}return this; +},retrieve:function(m,l){var o=c(this.uid),n=o[m];if(l!=undefined&&n==undefined){n=o[m]=l;}return $pick(n);},store:function(m,l){var n=c(this.uid);n[m]=l; +return this;},eliminate:function(l){var m=c(this.uid);delete m[l];return this;}});window.addListener("unload",d);})();Element.Properties=new Hash;Element.Properties.style={set:function(a){this.style.cssText=a; +},get:function(){return this.style.cssText;},erase:function(){this.style.cssText="";}};Element.Properties.tag={get:function(){return this.tagName.toLowerCase(); +}};Element.Properties.html=(function(){var c=document.createElement("div");var a={table:[1,"<table>","</table>"],select:[1,"<select>","</select>"],tbody:[2,"<table><tbody>","</tbody></table>"],tr:[3,"<table><tbody><tr>","</tr></tbody></table>"]}; +a.thead=a.tfoot=a.tbody;var b={set:function(){var e=Array.flatten(arguments).join("");var f=Browser.Engine.trident&&a[this.get("tag")];if(f){var g=c;g.innerHTML=f[1]+e+f[2]; +for(var d=f[0];d--;){g=g.firstChild;}this.empty().adopt(g.childNodes);}else{this.innerHTML=e;}}};b.erase=b.set;return b;})();if(Browser.Engine.webkit&&Browser.Engine.version<420){Element.Properties.text={get:function(){if(this.innerText){return this.innerText; +}var a=this.ownerDocument.newElement("div",{html:this.innerHTML}).inject(this.ownerDocument.body);var b=a.innerText;a.destroy();return b;}};}Element.Properties.events={set:function(a){this.addEvents(a); +}};Native.implement([Element,Window,Document],{addEvent:function(e,g){var h=this.retrieve("events",{});h[e]=h[e]||{keys:[],values:[]};if(h[e].keys.contains(g)){return this; +}h[e].keys.push(g);var f=e,a=Element.Events.get(e),c=g,i=this;if(a){if(a.onAdd){a.onAdd.call(this,g);}if(a.condition){c=function(j){if(a.condition.call(this,j)){return g.call(this,j); +}return true;};}f=a.base||f;}var d=function(){return g.call(i);};var b=Element.NativeEvents[f];if(b){if(b==2){d=function(j){j=new Event(j,i.getWindow()); +if(c.call(i,j)===false){j.stop();}};}this.addListener(f,d);}h[e].values.push(d);return this;},removeEvent:function(c,b){var a=this.retrieve("events");if(!a||!a[c]){return this; +}var f=a[c].keys.indexOf(b);if(f==-1){return this;}a[c].keys.splice(f,1);var e=a[c].values.splice(f,1)[0];var d=Element.Events.get(c);if(d){if(d.onRemove){d.onRemove.call(this,b); +}c=d.base||c;}return(Element.NativeEvents[c])?this.removeListener(c,e):this;},addEvents:function(a){for(var b in a){this.addEvent(b,a[b]);}return this; +},removeEvents:function(a){var c;if($type(a)=="object"){for(c in a){this.removeEvent(c,a[c]);}return this;}var b=this.retrieve("events");if(!b){return this; +}if(!a){for(c in b){this.removeEvents(c);}this.eliminate("events");}else{if(b[a]){while(b[a].keys[0]){this.removeEvent(a,b[a].keys[0]);}b[a]=null;}}return this; +},fireEvent:function(d,b,a){var c=this.retrieve("events");if(!c||!c[d]){return this;}c[d].keys.each(function(e){e.create({bind:this,delay:a,"arguments":b})(); +},this);return this;},cloneEvents:function(d,a){d=document.id(d);var c=d.retrieve("events");if(!c){return this;}if(!a){for(var b in c){this.cloneEvents(d,b); +}}else{if(c[a]){c[a].keys.each(function(e){this.addEvent(a,e);},this);}}return this;}});Element.NativeEvents={click:2,dblclick:2,mouseup:2,mousedown:2,contextmenu:2,mousewheel:2,DOMMouseScroll:2,mouseover:2,mouseout:2,mousemove:2,selectstart:2,selectend:2,keydown:2,keypress:2,keyup:2,focus:2,blur:2,change:2,reset:2,select:2,submit:2,load:1,unload:1,beforeunload:2,resize:1,move:1,DOMContentLoaded:1,readystatechange:1,error:1,abort:1,scroll:1}; +(function(){var a=function(b){var c=b.relatedTarget;if(c==undefined){return true;}if(c===false){return false;}return($type(this)!="document"&&c!=this&&c.prefix!="xul"&&!this.hasChild(c)); +};Element.Events=new Hash({mouseenter:{base:"mouseover",condition:a},mouseleave:{base:"mouseout",condition:a},mousewheel:{base:(Browser.Engine.gecko)?"DOMMouseScroll":"mousewheel"}}); +})();Element.Properties.styles={set:function(a){this.setStyles(a);}};Element.Properties.opacity={set:function(a,b){if(!b){if(a==0){if(this.style.visibility!="hidden"){this.style.visibility="hidden"; +}}else{if(this.style.visibility!="visible"){this.style.visibility="visible";}}}if(!this.currentStyle||!this.currentStyle.hasLayout){this.style.zoom=1;}if(Browser.Engine.trident){this.style.filter=(a==1)?"":"alpha(opacity="+a*100+")"; +}this.style.opacity=a;this.store("opacity",a);},get:function(){return this.retrieve("opacity",1);}};Element.implement({setOpacity:function(a){return this.set("opacity",a,true); +},getOpacity:function(){return this.get("opacity");},setStyle:function(b,a){switch(b){case"opacity":return this.set("opacity",parseFloat(a));case"float":b=(Browser.Engine.trident)?"styleFloat":"cssFloat"; +}b=b.camelCase();if($type(a)!="string"){var c=(Element.Styles.get(b)||"@").split(" ");a=$splat(a).map(function(e,d){if(!c[d]){return"";}return($type(e)=="number")?c[d].replace("@",Math.round(e)):e; +}).join(" ");}else{if(a==String(Number(a))){a=Math.round(a);}}this.style[b]=a;return this;},getStyle:function(g){switch(g){case"opacity":return this.get("opacity"); +case"float":g=(Browser.Engine.trident)?"styleFloat":"cssFloat";}g=g.camelCase();var a=this.style[g];if(!$chk(a)){a=[];for(var f in Element.ShortStyles){if(g!=f){continue; +}for(var e in Element.ShortStyles[f]){a.push(this.getStyle(e));}return a.join(" ");}a=this.getComputedStyle(g);}if(a){a=String(a);var c=a.match(/rgba?\([\d\s,]+\)/); +if(c){a=a.replace(c[0],c[0].rgbToHex());}}if(Browser.Engine.presto||(Browser.Engine.trident&&!$chk(parseInt(a,10)))){if(g.test(/^(height|width)$/)){var b=(g=="width")?["left","right"]:["top","bottom"],d=0; +b.each(function(h){d+=this.getStyle("border-"+h+"-width").toInt()+this.getStyle("padding-"+h).toInt();},this);return this["offset"+g.capitalize()]-d+"px"; +}if((Browser.Engine.presto)&&String(a).test("px")){return a;}if(g.test(/(border(.+)Width|margin|padding)/)){return"0px";}}return a;},setStyles:function(b){for(var a in b){this.setStyle(a,b[a]); +}return this;},getStyles:function(){var a={};Array.flatten(arguments).each(function(b){a[b]=this.getStyle(b);},this);return a;}});Element.Styles=new Hash({left:"@px",top:"@px",bottom:"@px",right:"@px",width:"@px",height:"@px",maxWidth:"@px",maxHeight:"@px",minWidth:"@px",minHeight:"@px",backgroundColor:"rgb(@, @, @)",backgroundPosition:"@px @px",color:"rgb(@, @, @)",fontSize:"@px",letterSpacing:"@px",lineHeight:"@px",clip:"rect(@px @px @px @px)",margin:"@px @px @px @px",padding:"@px @px @px @px",border:"@px @ rgb(@, @, @) @px @ rgb(@, @, @) @px @ rgb(@, @, @)",borderWidth:"@px @px @px @px",borderStyle:"@ @ @ @",borderColor:"rgb(@, @, @) rgb(@, @, @) rgb(@, @, @) rgb(@, @, @)",zIndex:"@",zoom:"@",fontWeight:"@",textIndent:"@px",opacity:"@"}); +Element.ShortStyles={margin:{},padding:{},border:{},borderWidth:{},borderStyle:{},borderColor:{}};["Top","Right","Bottom","Left"].each(function(g){var f=Element.ShortStyles; +var b=Element.Styles;["margin","padding"].each(function(h){var i=h+g;f[h][i]=b[i]="@px";});var e="border"+g;f.border[e]=b[e]="@px @ rgb(@, @, @)";var d=e+"Width",a=e+"Style",c=e+"Color"; +f[e]={};f.borderWidth[d]=f[e][d]=b[d]="@px";f.borderStyle[a]=f[e][a]=b[a]="@";f.borderColor[c]=f[e][c]=b[c]="rgb(@, @, @)";});(function(){Element.implement({scrollTo:function(h,i){if(b(this)){this.getWindow().scrollTo(h,i); +}else{this.scrollLeft=h;this.scrollTop=i;}return this;},getSize:function(){if(b(this)){return this.getWindow().getSize();}return{x:this.offsetWidth,y:this.offsetHeight}; +},getScrollSize:function(){if(b(this)){return this.getWindow().getScrollSize();}return{x:this.scrollWidth,y:this.scrollHeight};},getScroll:function(){if(b(this)){return this.getWindow().getScroll(); +}return{x:this.scrollLeft,y:this.scrollTop};},getScrolls:function(){var i=this,h={x:0,y:0};while(i&&!b(i)){h.x+=i.scrollLeft;h.y+=i.scrollTop;i=i.parentNode; +}return h;},getOffsetParent:function(){var h=this;if(b(h)){return null;}if(!Browser.Engine.trident){return h.offsetParent;}while((h=h.parentNode)&&!b(h)){if(d(h,"position")!="static"){return h; +}}return null;},getOffsets:function(){if(this.getBoundingClientRect){var j=this.getBoundingClientRect(),m=document.id(this.getDocument().documentElement),p=m.getScroll(),k=this.getScrolls(),i=this.getScroll(),h=(d(this,"position")=="fixed"); +return{x:j.left.toInt()+k.x-i.x+((h)?0:p.x)-m.clientLeft,y:j.top.toInt()+k.y-i.y+((h)?0:p.y)-m.clientTop};}var l=this,n={x:0,y:0};if(b(this)){return n; +}while(l&&!b(l)){n.x+=l.offsetLeft;n.y+=l.offsetTop;if(Browser.Engine.gecko){if(!f(l)){n.x+=c(l);n.y+=g(l);}var o=l.parentNode;if(o&&d(o,"overflow")!="visible"){n.x+=c(o); +n.y+=g(o);}}else{if(l!=this&&Browser.Engine.webkit){n.x+=c(l);n.y+=g(l);}}l=l.offsetParent;}if(Browser.Engine.gecko&&!f(this)){n.x-=c(this);n.y-=g(this); +}return n;},getPosition:function(k){if(b(this)){return{x:0,y:0};}var l=this.getOffsets(),i=this.getScrolls();var h={x:l.x-i.x,y:l.y-i.y};var j=(k&&(k=document.id(k)))?k.getPosition():{x:0,y:0}; +return{x:h.x-j.x,y:h.y-j.y};},getCoordinates:function(j){if(b(this)){return this.getWindow().getCoordinates();}var h=this.getPosition(j),i=this.getSize(); +var k={left:h.x,top:h.y,width:i.x,height:i.y};k.right=k.left+k.width;k.bottom=k.top+k.height;return k;},computePosition:function(h){return{left:h.x-e(this,"margin-left"),top:h.y-e(this,"margin-top")}; +},setPosition:function(h){return this.setStyles(this.computePosition(h));}});Native.implement([Document,Window],{getSize:function(){if(Browser.Engine.presto||Browser.Engine.webkit){var i=this.getWindow(); +return{x:i.innerWidth,y:i.innerHeight};}var h=a(this);return{x:h.clientWidth,y:h.clientHeight};},getScroll:function(){var i=this.getWindow(),h=a(this); +return{x:i.pageXOffset||h.scrollLeft,y:i.pageYOffset||h.scrollTop};},getScrollSize:function(){var i=a(this),h=this.getSize();return{x:Math.max(i.scrollWidth,h.x),y:Math.max(i.scrollHeight,h.y)}; +},getPosition:function(){return{x:0,y:0};},getCoordinates:function(){var h=this.getSize();return{top:0,left:0,bottom:h.y,right:h.x,height:h.y,width:h.x}; +}});var d=Element.getComputedStyle;function e(h,i){return d(h,i).toInt()||0;}function f(h){return d(h,"-moz-box-sizing")=="border-box";}function g(h){return e(h,"border-top-width"); +}function c(h){return e(h,"border-left-width");}function b(h){return(/^(?:body|html)$/i).test(h.tagName);}function a(h){var i=h.getDocument();return(!i.compatMode||i.compatMode=="CSS1Compat")?i.html:i.body; +}})();Element.alias("setPosition","position");Native.implement([Window,Document,Element],{getHeight:function(){return this.getSize().y;},getWidth:function(){return this.getSize().x; +},getScrollTop:function(){return this.getScroll().y;},getScrollLeft:function(){return this.getScroll().x;},getScrollHeight:function(){return this.getScrollSize().y; +},getScrollWidth:function(){return this.getScrollSize().x;},getTop:function(){return this.getPosition().y;},getLeft:function(){return this.getPosition().x; +}});Native.implement([Document,Element],{getElements:function(h,g){h=h.split(",");var c,e={};for(var d=0,b=h.length;d<b;d++){var a=h[d],f=Selectors.Utils.search(this,a,e); +if(d!=0&&f.item){f=$A(f);}c=(d==0)?f:(c.item)?$A(c).concat(f):c.concat(f);}return new Elements(c,{ddup:(h.length>1),cash:!g});}});Element.implement({match:function(b){if(!b||(b==this)){return true; +}var d=Selectors.Utils.parseTagAndID(b);var a=d[0],e=d[1];if(!Selectors.Filters.byID(this,e)||!Selectors.Filters.byTag(this,a)){return false;}var c=Selectors.Utils.parseSelector(b); +return(c)?Selectors.Utils.filter(this,c,{}):true;}});var Selectors={Cache:{nth:{},parsed:{}}};Selectors.RegExps={id:(/#([\w-]+)/),tag:(/^(\w+|\*)/),quick:(/^(\w+|\*)$/),splitter:(/\s*([+>~\s])\s*([a-zA-Z#.*:\[])/g),combined:(/\.([\w-]+)|\[(\w+)(?:([!*^$~|]?=)(["']?)([^\4]*?)\4)?\]|:([\w-]+)(?:\(["']?(.*?)?["']?\)|$)/g)}; +Selectors.Utils={chk:function(b,c){if(!c){return true;}var a=$uid(b);if(!c[a]){return c[a]=true;}return false;},parseNthArgument:function(h){if(Selectors.Cache.nth[h]){return Selectors.Cache.nth[h]; +}var e=h.match(/^([+-]?\d*)?([a-z]+)?([+-]?\d*)?$/);if(!e){return false;}var g=parseInt(e[1],10);var d=(g||g===0)?g:1;var f=e[2]||false;var c=parseInt(e[3],10)||0; +if(d!=0){c--;while(c<1){c+=d;}while(c>=d){c-=d;}}else{d=c;f="index";}switch(f){case"n":e={a:d,b:c,special:"n"};break;case"odd":e={a:2,b:0,special:"n"}; +break;case"even":e={a:2,b:1,special:"n"};break;case"first":e={a:0,special:"index"};break;case"last":e={special:"last-child"};break;case"only":e={special:"only-child"}; +break;default:e={a:(d-1),special:"index"};}return Selectors.Cache.nth[h]=e;},parseSelector:function(e){if(Selectors.Cache.parsed[e]){return Selectors.Cache.parsed[e]; +}var d,h={classes:[],pseudos:[],attributes:[]};while((d=Selectors.RegExps.combined.exec(e))){var i=d[1],g=d[2],f=d[3],b=d[5],c=d[6],j=d[7];if(i){h.classes.push(i); +}else{if(c){var a=Selectors.Pseudo.get(c);if(a){h.pseudos.push({parser:a,argument:j});}else{h.attributes.push({name:c,operator:"=",value:j});}}else{if(g){h.attributes.push({name:g,operator:f,value:b}); +}}}}if(!h.classes.length){delete h.classes;}if(!h.attributes.length){delete h.attributes;}if(!h.pseudos.length){delete h.pseudos;}if(!h.classes&&!h.attributes&&!h.pseudos){h=null; +}return Selectors.Cache.parsed[e]=h;},parseTagAndID:function(b){var a=b.match(Selectors.RegExps.tag);var c=b.match(Selectors.RegExps.id);return[(a)?a[1]:"*",(c)?c[1]:false]; +},filter:function(f,c,e){var d;if(c.classes){for(d=c.classes.length;d--;d){var g=c.classes[d];if(!Selectors.Filters.byClass(f,g)){return false;}}}if(c.attributes){for(d=c.attributes.length; +d--;d){var b=c.attributes[d];if(!Selectors.Filters.byAttribute(f,b.name,b.operator,b.value)){return false;}}}if(c.pseudos){for(d=c.pseudos.length;d--;d){var a=c.pseudos[d]; +if(!Selectors.Filters.byPseudo(f,a.parser,a.argument,e)){return false;}}}return true;},getByTagAndID:function(b,a,d){if(d){var c=(b.getElementById)?b.getElementById(d,true):Element.getElementById(b,d,true); +return(c&&Selectors.Filters.byTag(c,a))?[c]:[];}else{return b.getElementsByTagName(a);}},search:function(o,h,t){var b=[];var c=h.trim().replace(Selectors.RegExps.splitter,function(k,j,i){b.push(j); +return":)"+i;}).split(":)");var p,e,A;for(var z=0,v=c.length;z<v;z++){var y=c[z];if(z==0&&Selectors.RegExps.quick.test(y)){p=o.getElementsByTagName(y); +continue;}var a=b[z-1];var q=Selectors.Utils.parseTagAndID(y);var B=q[0],r=q[1];if(z==0){p=Selectors.Utils.getByTagAndID(o,B,r);}else{var d={},g=[];for(var x=0,w=p.length; +x<w;x++){g=Selectors.Getters[a](g,p[x],B,r,d);}p=g;}var f=Selectors.Utils.parseSelector(y);if(f){e=[];for(var u=0,s=p.length;u<s;u++){A=p[u];if(Selectors.Utils.filter(A,f,t)){e.push(A); +}}p=e;}}return p;}};Selectors.Getters={" ":function(h,g,j,a,e){var d=Selectors.Utils.getByTagAndID(g,j,a);for(var c=0,b=d.length;c<b;c++){var f=d[c];if(Selectors.Utils.chk(f,e)){h.push(f); +}}return h;},">":function(h,g,j,a,f){var c=Selectors.Utils.getByTagAndID(g,j,a);for(var e=0,d=c.length;e<d;e++){var b=c[e];if(b.parentNode==g&&Selectors.Utils.chk(b,f)){h.push(b); +}}return h;},"+":function(c,b,a,e,d){while((b=b.nextSibling)){if(b.nodeType==1){if(Selectors.Utils.chk(b,d)&&Selectors.Filters.byTag(b,a)&&Selectors.Filters.byID(b,e)){c.push(b); +}break;}}return c;},"~":function(c,b,a,e,d){while((b=b.nextSibling)){if(b.nodeType==1){if(!Selectors.Utils.chk(b,d)){break;}if(Selectors.Filters.byTag(b,a)&&Selectors.Filters.byID(b,e)){c.push(b); +}}}return c;}};Selectors.Filters={byTag:function(b,a){return(a=="*"||(b.tagName&&b.tagName.toLowerCase()==a));},byID:function(a,b){return(!b||(a.id&&a.id==b)); +},byClass:function(b,a){return(b.className&&b.className.contains&&b.className.contains(a," "));},byPseudo:function(a,d,c,b){return d.call(a,c,b);},byAttribute:function(c,d,b,e){var a=Element.prototype.getProperty.call(c,d); +if(!a){return(b=="!=");}if(!b||e==undefined){return true;}switch(b){case"=":return(a==e);case"*=":return(a.contains(e));case"^=":return(a.substr(0,e.length)==e); +case"$=":return(a.substr(a.length-e.length)==e);case"!=":return(a!=e);case"~=":return a.contains(e," ");case"|=":return a.contains(e,"-");}return false; +}};Selectors.Pseudo=new Hash({checked:function(){return this.checked;},empty:function(){return !(this.innerText||this.textContent||"").length;},not:function(a){return !Element.match(this,a); +},contains:function(a){return(this.innerText||this.textContent||"").contains(a);},"first-child":function(){return Selectors.Pseudo.index.call(this,0);},"last-child":function(){var a=this; +while((a=a.nextSibling)){if(a.nodeType==1){return false;}}return true;},"only-child":function(){var b=this;while((b=b.previousSibling)){if(b.nodeType==1){return false; +}}var a=this;while((a=a.nextSibling)){if(a.nodeType==1){return false;}}return true;},"nth-child":function(g,e){g=(g==undefined)?"n":g;var c=Selectors.Utils.parseNthArgument(g); +if(c.special!="n"){return Selectors.Pseudo[c.special].call(this,c.a,e);}var f=0;e.positions=e.positions||{};var d=$uid(this);if(!e.positions[d]){var b=this; +while((b=b.previousSibling)){if(b.nodeType!=1){continue;}f++;var a=e.positions[$uid(b)];if(a!=undefined){f=a+f;break;}}e.positions[d]=f;}return(e.positions[d]%c.a==c.b); +},index:function(a){var b=this,c=0;while((b=b.previousSibling)){if(b.nodeType==1&&++c>a){return false;}}return(c==a);},even:function(b,a){return Selectors.Pseudo["nth-child"].call(this,"2n+1",a); +},odd:function(b,a){return Selectors.Pseudo["nth-child"].call(this,"2n",a);},selected:function(){return this.selected;},enabled:function(){return(this.disabled===false); +}});Element.Events.domready={onAdd:function(a){if(Browser.loaded){a.call(this);}}};(function(){var b=function(){if(Browser.loaded){return;}Browser.loaded=true; +window.fireEvent("domready");document.fireEvent("domready");};window.addEvent("load",b);if(Browser.Engine.trident){var a=document.createElement("div"); +(function(){($try(function(){a.doScroll();return document.id(a).inject(document.body).set("html","temp").dispose();}))?b():arguments.callee.delay(50);})(); +}else{if(Browser.Engine.webkit&&Browser.Engine.version<525){(function(){(["loaded","complete"].contains(document.readyState))?b():arguments.callee.delay(50); +})();}else{document.addEvent("DOMContentLoaded",b);}}})();var JSON=new Hash(this.JSON&&{stringify:JSON.stringify,parse:JSON.parse}).extend({$specialChars:{"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},$replaceChars:function(a){return JSON.$specialChars[a]||"\\u00"+Math.floor(a.charCodeAt()/16).toString(16)+(a.charCodeAt()%16).toString(16); +},encode:function(b){switch($type(b)){case"string":return'"'+b.replace(/[\x00-\x1f\\"]/g,JSON.$replaceChars)+'"';case"array":return"["+String(b.map(JSON.encode).clean())+"]"; +case"object":case"hash":var a=[];Hash.each(b,function(e,d){var c=JSON.encode(e);if(c){a.push(JSON.encode(d)+":"+c);}});return"{"+a+"}";case"number":case"boolean":return String(b); +case false:return"null";}return null;},decode:function(string,secure){if($type(string)!="string"||!string.length){return null;}if(secure&&!(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(string.replace(/\\./g,"@").replace(/"[^"\\\n\r]*"/g,""))){return null; +}return eval("("+string+")");}});Native.implement([Hash,Array,String,Number],{toJSON:function(){return JSON.encode(this);}});var Fx=new Class({Implements:[Chain,Events,Options],options:{fps:50,unit:false,duration:500,link:"ignore"},initialize:function(a){this.subject=this.subject||this; +this.setOptions(a);this.options.duration=Fx.Durations[this.options.duration]||this.options.duration.toInt();var b=this.options.wait;if(b===false){this.options.link="cancel"; +}},getTransition:function(){return function(a){return -(Math.cos(Math.PI*a)-1)/2;};},step:function(){var a=$time();if(a<this.time+this.options.duration){var b=this.transition((a-this.time)/this.options.duration); +this.set(this.compute(this.from,this.to,b));}else{this.set(this.compute(this.from,this.to,1));this.complete();}},set:function(a){return a;},compute:function(c,b,a){return Fx.compute(c,b,a); +},check:function(){if(!this.timer){return true;}switch(this.options.link){case"cancel":this.cancel();return true;case"chain":this.chain(this.caller.bind(this,arguments)); +return false;}return false;},start:function(b,a){if(!this.check(b,a)){return this;}this.from=b;this.to=a;this.time=0;this.transition=this.getTransition(); +this.startTimer();this.onStart();return this;},complete:function(){if(this.stopTimer()){this.onComplete();}return this;},cancel:function(){if(this.stopTimer()){this.onCancel(); +}return this;},onStart:function(){this.fireEvent("start",this.subject);},onComplete:function(){this.fireEvent("complete",this.subject);if(!this.callChain()){this.fireEvent("chainComplete",this.subject); +}},onCancel:function(){this.fireEvent("cancel",this.subject).clearChain();},pause:function(){this.stopTimer();return this;},resume:function(){this.startTimer(); +return this;},stopTimer:function(){if(!this.timer){return false;}this.time=$time()-this.time;this.timer=$clear(this.timer);return true;},startTimer:function(){if(this.timer){return false; +}this.time=$time()-this.time;this.timer=this.step.periodical(Math.round(1000/this.options.fps),this);return true;}});Fx.compute=function(c,b,a){return(b-c)*a+c; +};Fx.Durations={"short":250,normal:500,"long":1000};Fx.CSS=new Class({Extends:Fx,prepare:function(d,e,b){b=$splat(b);var c=b[1];if(!$chk(c)){b[1]=b[0]; +b[0]=d.getStyle(e);}var a=b.map(this.parse);return{from:a[0],to:a[1]};},parse:function(a){a=$lambda(a)();a=(typeof a=="string")?a.split(" "):$splat(a); +return a.map(function(c){c=String(c);var b=false;Fx.CSS.Parsers.each(function(f,e){if(b){return;}var d=f.parse(c);if($chk(d)){b={value:d,parser:f};}}); +b=b||{value:c,parser:Fx.CSS.Parsers.String};return b;});},compute:function(d,c,b){var a=[];(Math.min(d.length,c.length)).times(function(e){a.push({value:d[e].parser.compute(d[e].value,c[e].value,b),parser:d[e].parser}); +});a.$family={name:"fx:css:value"};return a;},serve:function(c,b){if($type(c)!="fx:css:value"){c=this.parse(c);}var a=[];c.each(function(d){a=a.concat(d.parser.serve(d.value,b)); +});return a;},render:function(a,d,c,b){a.setStyle(d,this.serve(c,b));},search:function(a){if(Fx.CSS.Cache[a]){return Fx.CSS.Cache[a];}var b={};Array.each(document.styleSheets,function(e,d){var c=e.href; +if(c&&c.contains("://")&&!c.contains(document.domain)){return;}var f=e.rules||e.cssRules;Array.each(f,function(j,g){if(!j.style){return;}var h=(j.selectorText)?j.selectorText.replace(/^\w+/,function(i){return i.toLowerCase(); +}):null;if(!h||!h.test("^"+a+"$")){return;}Element.Styles.each(function(k,i){if(!j.style[i]||Element.ShortStyles[i]){return;}k=String(j.style[i]);b[i]=(k.test(/^rgb/))?k.rgbToHex():k; +});});});return Fx.CSS.Cache[a]=b;}});Fx.CSS.Cache={};Fx.CSS.Parsers=new Hash({Color:{parse:function(a){if(a.match(/^#[0-9a-f]{3,6}$/i)){return a.hexToRgb(true); +}return((a=a.match(/(\d+),\s*(\d+),\s*(\d+)/)))?[a[1],a[2],a[3]]:false;},compute:function(c,b,a){return c.map(function(e,d){return Math.round(Fx.compute(c[d],b[d],a)); +});},serve:function(a){return a.map(Number);}},Number:{parse:parseFloat,compute:Fx.compute,serve:function(b,a){return(a)?b+a:b;}},String:{parse:$lambda(false),compute:$arguments(1),serve:$arguments(0)}}); +Fx.Tween=new Class({Extends:Fx.CSS,initialize:function(b,a){this.element=this.subject=document.id(b);this.parent(a);},set:function(b,a){if(arguments.length==1){a=b; +b=this.property||this.options.property;}this.render(this.element,b,a,this.options.unit);return this;},start:function(c,e,d){if(!this.check(c,e,d)){return this; +}var b=Array.flatten(arguments);this.property=this.options.property||b.shift();var a=this.prepare(this.element,this.property,b);return this.parent(a.from,a.to); +}});Element.Properties.tween={set:function(a){var b=this.retrieve("tween");if(b){b.cancel();}return this.eliminate("tween").store("tween:options",$extend({link:"cancel"},a)); +},get:function(a){if(a||!this.retrieve("tween")){if(a||!this.retrieve("tween:options")){this.set("tween",a);}this.store("tween",new Fx.Tween(this,this.retrieve("tween:options"))); +}return this.retrieve("tween");}};Element.implement({tween:function(a,c,b){this.get("tween").start(arguments);return this;},fade:function(c){var e=this.get("tween"),d="opacity",a; +c=$pick(c,"toggle");switch(c){case"in":e.start(d,1);break;case"out":e.start(d,0);break;case"show":e.set(d,1);break;case"hide":e.set(d,0);break;case"toggle":var b=this.retrieve("fade:flag",this.get("opacity")==1); +e.start(d,(b)?0:1);this.store("fade:flag",!b);a=true;break;default:e.start(d,arguments);}if(!a){this.eliminate("fade:flag");}return this;},highlight:function(c,a){if(!a){a=this.retrieve("highlight:original",this.getStyle("background-color")); +a=(a=="transparent")?"#fff":a;}var b=this.get("tween");b.start("background-color",c||"#ffff88",a).chain(function(){this.setStyle("background-color",this.retrieve("highlight:original")); +b.callChain();}.bind(this));return this;}});Fx.Morph=new Class({Extends:Fx.CSS,initialize:function(b,a){this.element=this.subject=document.id(b);this.parent(a); +},set:function(a){if(typeof a=="string"){a=this.search(a);}for(var b in a){this.render(this.element,b,a[b],this.options.unit);}return this;},compute:function(e,d,c){var a={}; +for(var b in e){a[b]=this.parent(e[b],d[b],c);}return a;},start:function(b){if(!this.check(b)){return this;}if(typeof b=="string"){b=this.search(b);}var e={},d={}; +for(var c in b){var a=this.prepare(this.element,c,b[c]);e[c]=a.from;d[c]=a.to;}return this.parent(e,d);}});Element.Properties.morph={set:function(a){var b=this.retrieve("morph"); +if(b){b.cancel();}return this.eliminate("morph").store("morph:options",$extend({link:"cancel"},a));},get:function(a){if(a||!this.retrieve("morph")){if(a||!this.retrieve("morph:options")){this.set("morph",a); +}this.store("morph",new Fx.Morph(this,this.retrieve("morph:options")));}return this.retrieve("morph");}};Element.implement({morph:function(a){this.get("morph").start(a); +return this;}});var Request=new Class({Implements:[Chain,Events,Options],options:{url:"",data:"",headers:{"X-Requested-With":"XMLHttpRequest",Accept:"text/javascript, text/html, application/xml, text/xml, */*"},async:true,format:false,method:"post",link:"ignore",isSuccess:null,emulation:true,urlEncoded:true,encoding:"utf-8",evalScripts:false,evalResponse:false,noCache:false},initialize:function(a){this.xhr=new Browser.Request(); +this.setOptions(a);this.options.isSuccess=this.options.isSuccess||this.isSuccess;this.headers=new Hash(this.options.headers);},onStateChange:function(){if(this.xhr.readyState!=4||!this.running){return; +}this.running=false;this.status=0;$try(function(){this.status=this.xhr.status;}.bind(this));this.xhr.onreadystatechange=$empty;if(this.options.isSuccess.call(this,this.status)){this.response={text:this.xhr.responseText,xml:this.xhr.responseXML}; +this.success(this.response.text,this.response.xml);}else{this.response={text:null,xml:null};this.failure();}},isSuccess:function(){return((this.status>=200)&&(this.status<300)); +},processScripts:function(a){if(this.options.evalResponse||(/(ecma|java)script/).test(this.getHeader("Content-type"))){return $exec(a);}return a.stripScripts(this.options.evalScripts); +},success:function(b,a){this.onSuccess(this.processScripts(b),a);},onSuccess:function(){this.fireEvent("complete",arguments).fireEvent("success",arguments).callChain(); +},failure:function(){this.onFailure();},onFailure:function(){this.fireEvent("complete").fireEvent("failure",this.xhr);},setHeader:function(a,b){this.headers.set(a,b); +return this;},getHeader:function(a){return $try(function(){return this.xhr.getResponseHeader(a);}.bind(this));},check:function(){if(!this.running){return true; +}switch(this.options.link){case"cancel":this.cancel();return true;case"chain":this.chain(this.caller.bind(this,arguments));return false;}return false;},send:function(k){if(!this.check(k)){return this; +}this.running=true;var i=$type(k);if(i=="string"||i=="element"){k={data:k};}var d=this.options;k=$extend({data:d.data,url:d.url,method:d.method},k);var g=k.data,b=String(k.url),a=k.method.toLowerCase(); +switch($type(g)){case"element":g=document.id(g).toQueryString();break;case"object":case"hash":g=Hash.toQueryString(g);}if(this.options.format){var j="format="+this.options.format; +g=(g)?j+"&"+g:j;}if(this.options.emulation&&!["get","post"].contains(a)){var h="_method="+a;g=(g)?h+"&"+g:h;a="post";}if(this.options.urlEncoded&&a=="post"){var c=(this.options.encoding)?"; charset="+this.options.encoding:""; +this.headers.set("Content-type","application/x-www-form-urlencoded"+c);}if(this.options.noCache){var f="noCache="+new Date().getTime();g=(g)?f+"&"+g:f; +}var e=b.lastIndexOf("/");if(e>-1&&(e=b.indexOf("#"))>-1){b=b.substr(0,e);}if(g&&a=="get"){b=b+(b.contains("?")?"&":"?")+g;g=null;}this.xhr.open(a.toUpperCase(),b,this.options.async); +this.xhr.onreadystatechange=this.onStateChange.bind(this);this.headers.each(function(m,l){try{this.xhr.setRequestHeader(l,m);}catch(n){this.fireEvent("exception",[l,m]); +}},this);this.fireEvent("request");this.xhr.send(g);if(!this.options.async){this.onStateChange();}return this;},cancel:function(){if(!this.running){return this; +}this.running=false;this.xhr.abort();this.xhr.onreadystatechange=$empty;this.xhr=new Browser.Request();this.fireEvent("cancel");return this;}});(function(){var a={}; +["get","post","put","delete","GET","POST","PUT","DELETE"].each(function(b){a[b]=function(){var c=Array.link(arguments,{url:String.type,data:$defined}); +return this.send($extend(c,{method:b}));};});Request.implement(a);})();Element.Properties.send={set:function(a){var b=this.retrieve("send");if(b){b.cancel(); +}return this.eliminate("send").store("send:options",$extend({data:this,link:"cancel",method:this.get("method")||"post",url:this.get("action")},a));},get:function(a){if(a||!this.retrieve("send")){if(a||!this.retrieve("send:options")){this.set("send",a); +}this.store("send",new Request(this.retrieve("send:options")));}return this.retrieve("send");}};Element.implement({send:function(a){var b=this.get("send"); +b.send({data:this,url:a||b.options.url});return this;}});Request.HTML=new Class({Extends:Request,options:{update:false,append:false,evalScripts:true,filter:false},processHTML:function(c){var b=c.match(/<body[^>]*>([\s\S]*?)<\/body>/i); +c=(b)?b[1]:c;var a=new Element("div");return $try(function(){var d="<root>"+c+"</root>",g;if(Browser.Engine.trident){g=new ActiveXObject("Microsoft.XMLDOM"); +g.async=false;g.loadXML(d);}else{g=new DOMParser().parseFromString(d,"text/xml");}d=g.getElementsByTagName("root")[0];if(!d){return null;}for(var f=0,e=d.childNodes.length; +f<e;f++){var h=Element.clone(d.childNodes[f],true,true);if(h){a.grab(h);}}return a;})||a.set("html",c);},success:function(d){var c=this.options,b=this.response; +b.html=d.stripScripts(function(e){b.javascript=e;});var a=this.processHTML(b.html);b.tree=a.childNodes;b.elements=a.getElements("*");if(c.filter){b.tree=b.elements.filter(c.filter); +}if(c.update){document.id(c.update).empty().set("html",b.html);}else{if(c.append){document.id(c.append).adopt(a.getChildren());}}if(c.evalScripts){$exec(b.javascript); +}this.onSuccess(b.tree,b.elements,b.html,b.javascript);}});Element.Properties.load={set:function(a){var b=this.retrieve("load");if(b){b.cancel();}return this.eliminate("load").store("load:options",$extend({data:this,link:"cancel",update:this,method:"get"},a)); +},get:function(a){if(a||!this.retrieve("load")){if(a||!this.retrieve("load:options")){this.set("load",a);}this.store("load",new Request.HTML(this.retrieve("load:options"))); +}return this.retrieve("load");}};Element.implement({load:function(){this.get("load").send(Array.link(arguments,{data:Object.type,url:String.type}));return this; +}});Request.JSON=new Class({Extends:Request,options:{secure:true},initialize:function(a){this.parent(a);this.headers.extend({Accept:"application/json","X-Request":"JSON"}); +},success:function(a){this.response.json=JSON.decode(a,this.options.secure);this.onSuccess(this.response.json,a);}});
\ No newline at end of file diff --git a/module/web/media/default/js/mootools-1.2.4.2-more.js b/module/web/media/default/js/mootools-1.2.4.2-more.js new file mode 100644 index 000000000..eb04477df --- /dev/null +++ b/module/web/media/default/js/mootools-1.2.4.2-more.js @@ -0,0 +1,134 @@ +//MooTools More, <http://mootools.net/more>. Copyright (c) 2006-2009 Aaron Newton <http://clientcide.com/>, Valerio Proietti <http://mad4milk.net> & the MooTools team <http://mootools.net/developers>, MIT Style License. + +MooTools.More={version:"1.2.4.2",build:"bd5a93c0913cce25917c48cbdacde568e15e02ef"};Class.refactor=function(b,a){$each(a,function(e,d){var c=b.prototype[d]; +if(c&&(c=c._origin)&&typeof e=="function"){b.implement(d,function(){var f=this.previous;this.previous=c;var g=e.apply(this,arguments);this.previous=f;return g; +});}else{b.implement(d,e);}});return b;};Class.Mutators.Binds=function(a){return a;};Class.Mutators.initialize=function(a){return function(){$splat(this.Binds).each(function(b){var c=this[b]; +if(c){this[b]=c.bind(this);}},this);return a.apply(this,arguments);};};Class.Occlude=new Class({occlude:function(c,b){b=document.id(b||this.element);var a=b.retrieve(c||this.property); +if(a&&!$defined(this.occluded)){return this.occluded=a;}this.occluded=false;b.store(c||this.property,this);return this.occluded;}});String.implement({parseQueryString:function(){var b=this.split(/[&;]/),a={}; +if(b.length){b.each(function(g){var c=g.indexOf("="),d=c<0?[""]:g.substr(0,c).match(/[^\]\[]+/g),e=decodeURIComponent(g.substr(c+1)),f=a;d.each(function(j,h){var k=f[j]; +if(h<d.length-1){f=f[j]=k||{};}else{if($type(k)=="array"){k.push(e);}else{f[j]=$defined(k)?[k,e]:e;}}});});}return a;},cleanQueryString:function(a){return this.split("&").filter(function(e){var b=e.indexOf("="),c=b<0?"":e.substr(0,b),d=e.substr(b+1); +return a?a.run([c,d]):$chk(d);}).join("&");}});Element.implement({measure:function(e){var g=function(h){return !!(!h||h.offsetHeight||h.offsetWidth);}; +if(g(this)){return e.apply(this);}var d=this.getParent(),f=[],b=[];while(!g(d)&&d!=document.body){b.push(d.expose());d=d.getParent();}var c=this.expose(); +var a=e.apply(this);c();b.each(function(h){h();});return a;},expose:function(){if(this.getStyle("display")!="none"){return $empty;}var a=this.style.cssText; +this.setStyles({display:"block",position:"absolute",visibility:"hidden"});return function(){this.style.cssText=a;}.bind(this);},getDimensions:function(a){a=$merge({computeSize:false},a); +var f={};var d=function(g,e){return(e.computeSize)?g.getComputedSize(e):g.getSize();};var b=this.getParent("body");if(b&&this.getStyle("display")=="none"){f=this.measure(function(){return d(this,a); +});}else{if(b){try{f=d(this,a);}catch(c){}}else{f={x:0,y:0};}}return $chk(f.x)?$extend(f,{width:f.x,height:f.y}):$extend(f,{x:f.width,y:f.height});},getComputedSize:function(a){a=$merge({styles:["padding","border"],plains:{height:["top","bottom"],width:["left","right"]},mode:"both"},a); +var c={width:0,height:0};switch(a.mode){case"vertical":delete c.width;delete a.plains.width;break;case"horizontal":delete c.height;delete a.plains.height; +break;}var b=[];$each(a.plains,function(g,f){g.each(function(h){a.styles.each(function(i){b.push((i=="border")?i+"-"+h+"-width":i+"-"+h);});});});var e={}; +b.each(function(f){e[f]=this.getComputedStyle(f);},this);var d=[];$each(a.plains,function(g,f){var h=f.capitalize();c["total"+h]=c["computed"+h]=0;g.each(function(i){c["computed"+i.capitalize()]=0; +b.each(function(k,j){if(k.test(i)){e[k]=e[k].toInt()||0;c["total"+h]=c["total"+h]+e[k];c["computed"+i.capitalize()]=c["computed"+i.capitalize()]+e[k];}if(k.test(i)&&f!=k&&(k.test("border")||k.test("padding"))&&!d.contains(k)){d.push(k); +c["computed"+h]=c["computed"+h]-e[k];}});});});["Width","Height"].each(function(g){var f=g.toLowerCase();if(!$chk(c[f])){return;}c[f]=c[f]+this["offset"+g]+c["computed"+g]; +c["total"+g]=c[f]+c["total"+g];delete c["computed"+g];},this);return $extend(e,c);}});(function(){var a=Element.prototype.position;Element.implement({position:function(h){if(h&&($defined(h.x)||$defined(h.y))){return a?a.apply(this,arguments):this; +}$each(h||{},function(w,u){if(!$defined(w)){delete h[u];}});h=$merge({relativeTo:document.body,position:{x:"center",y:"center"},edge:false,offset:{x:0,y:0},returnPos:false,relFixedPosition:false,ignoreMargins:false,ignoreScroll:false,allowNegative:false},h); +var s={x:0,y:0},f=false;var c=this.measure(function(){return document.id(this.getOffsetParent());});if(c&&c!=this.getDocument().body){s=c.measure(function(){return this.getPosition(); +});f=c!=document.id(h.relativeTo);h.offset.x=h.offset.x-s.x;h.offset.y=h.offset.y-s.y;}var t=function(u){if($type(u)!="string"){return u;}u=u.toLowerCase(); +var v={};if(u.test("left")){v.x="left";}else{if(u.test("right")){v.x="right";}else{v.x="center";}}if(u.test("upper")||u.test("top")){v.y="top";}else{if(u.test("bottom")){v.y="bottom"; +}else{v.y="center";}}return v;};h.edge=t(h.edge);h.position=t(h.position);if(!h.edge){if(h.position.x=="center"&&h.position.y=="center"){h.edge={x:"center",y:"center"}; +}else{h.edge={x:"left",y:"top"};}}this.setStyle("position","absolute");var g=document.id(h.relativeTo)||document.body,d=g==document.body?window.getScroll():g.getPosition(),n=d.y,i=d.x; +var e=g.getScrolls();n+=e.y;i+=e.x;var o=this.getDimensions({computeSize:true,styles:["padding","border","margin"]});var k={},p=h.offset.y,r=h.offset.x,l=window.getSize(); +switch(h.position.x){case"left":k.x=i+r;break;case"right":k.x=i+r+g.offsetWidth;break;default:k.x=i+((g==document.body?l.x:g.offsetWidth)/2)+r;break;}switch(h.position.y){case"top":k.y=n+p; +break;case"bottom":k.y=n+p+g.offsetHeight;break;default:k.y=n+((g==document.body?l.y:g.offsetHeight)/2)+p;break;}if(h.edge){var b={};switch(h.edge.x){case"left":b.x=0; +break;case"right":b.x=-o.x-o.computedRight-o.computedLeft;break;default:b.x=-(o.totalWidth/2);break;}switch(h.edge.y){case"top":b.y=0;break;case"bottom":b.y=-o.y-o.computedTop-o.computedBottom; +break;default:b.y=-(o.totalHeight/2);break;}k.x+=b.x;k.y+=b.y;}k={left:((k.x>=0||f||h.allowNegative)?k.x:0).toInt(),top:((k.y>=0||f||h.allowNegative)?k.y:0).toInt()}; +var j={left:"x",top:"y"};["minimum","maximum"].each(function(u){["left","top"].each(function(v){var w=h[u]?h[u][j[v]]:null;if(w!=null&&k[v]<w){k[v]=w;}}); +});if(g.getStyle("position")=="fixed"||h.relFixedPosition){var m=window.getScroll();k.top+=m.y;k.left+=m.x;}if(h.ignoreScroll){var q=g.getScroll();k.top-=q.y; +k.left-=q.x;}if(h.ignoreMargins){k.left+=(h.edge.x=="right"?o["margin-right"]:h.edge.x=="center"?-o["margin-left"]+((o["margin-right"]+o["margin-left"])/2):-o["margin-left"]); +k.top+=(h.edge.y=="bottom"?o["margin-bottom"]:h.edge.y=="center"?-o["margin-top"]+((o["margin-bottom"]+o["margin-top"])/2):-o["margin-top"]);}k.left=Math.ceil(k.left); +k.top=Math.ceil(k.top);if(h.returnPos){return k;}else{this.setStyles(k);}return this;}});})();Element.implement({isDisplayed:function(){return this.getStyle("display")!="none"; +},isVisible:function(){var a=this.offsetWidth,b=this.offsetHeight;return(a==0&&b==0)?false:(a>0&&b>0)?true:this.isDisplayed();},toggle:function(){return this[this.isDisplayed()?"hide":"show"](); +},hide:function(){var b;try{if((b=this.getStyle("display"))=="none"){b=null;}}catch(a){}return this.store("originalDisplay",b||"block").setStyle("display","none"); +},show:function(a){return this.setStyle("display",a||this.retrieve("originalDisplay")||"block");},swapClass:function(a,b){return this.removeClass(a).addClass(b); +}});if(!window.Form){window.Form={};}(function(){Form.Request=new Class({Binds:["onSubmit","onFormValidate"],Implements:[Options,Events,Class.Occlude],options:{requestOptions:{evalScripts:true,useSpinner:true,emulation:false,link:"ignore"},extraData:{},resetForm:true},property:"form.request",initialize:function(b,c,a){this.element=document.id(b); +if(this.occlude()){return this.occluded;}this.update=document.id(c);this.setOptions(a);this.makeRequest();if(this.options.resetForm){this.request.addEvent("success",function(){$try(function(){this.element.reset(); +}.bind(this));if(window.OverText){OverText.update();}}.bind(this));}this.attach();},toElement:function(){return this.element;},makeRequest:function(){this.request=new Request.HTML($merge({url:this.element.get("action"),update:this.update,emulation:false,spinnerTarget:this.element,method:this.element.get("method")||"post"},this.options.requestOptions)).addEvents({success:function(b,a){["success","complete"].each(function(c){this.fireEvent(c,[this.update,b,a]); +},this);}.bind(this),failure:function(a){this.fireEvent("failure",a);}.bind(this),exception:function(){this.fireEvent("failure",xhr);}.bind(this)});},attach:function(a){a=$pick(a,true); +method=a?"addEvent":"removeEvent";var b=this.element.retrieve("validator");if(b){b[method]("onFormValidate",this.onFormValidate);}if(!b||!a){this.element[method]("submit",this.onSubmit); +}},detach:function(){this.attach(false);},enable:function(){this.attach();},disable:function(){this.detach();},onFormValidate:function(b,a,c){if(b||!fv.options.stopOnFailure){if(c&&c.stop){c.stop(); +}this.send();}},onSubmit:function(a){if(this.element.retrieve("validator")){this.detach();this.addFormEvent();return;}a.stop();this.send();},send:function(){var b=this.element.toQueryString().trim(); +var a=$H(this.options.extraData).toQueryString();if(b){b+="&"+a;}else{b=a;}this.fireEvent("send",[this.element,b]);this.request.send({data:b});return this; +}});Element.Properties.formRequest={set:function(){var a=Array.link(arguments,{options:Object.type,update:Element.type,updateId:String.type});var c=a.update||a.updateId; +var b=this.retrieve("form.request");if(c){if(b){b.update=document.id(c);}this.store("form.request:update",c);}if(a.options){if(b){b.setOptions(a.options); +}this.store("form.request:options",a.options);}return this;},get:function(){var a=Array.link(arguments,{options:Object.type,update:Element.type,updateId:String.type}); +var b=a.update||a.updateId;if(a.options||b||!this.retrieve("form.request")){if(a.options||!this.retrieve("form.request:options")){this.set("form.request",a.options); +}if(b){this.set("form.request",b);}this.store("form.request",new Form.Request(this,this.retrieve("form.request:update"),this.retrieve("form.request:options"))); +}return this.retrieve("form.request");}};Element.implement({formUpdate:function(b,a){this.get("form.request",b,a).send();return this;}});})();Fx.Reveal=new Class({Extends:Fx.Morph,options:{link:"cancel",styles:["padding","border","margin"],transitionOpacity:!Browser.Engine.trident4,mode:"vertical",display:"block",hideInputs:Browser.Engine.trident?"select, input, textarea, object, embed":false},dissolve:function(){try{if(!this.hiding&&!this.showing){if(this.element.getStyle("display")!="none"){this.hiding=true; +this.showing=false;this.hidden=true;this.cssText=this.element.style.cssText;var d=this.element.getComputedSize({styles:this.options.styles,mode:this.options.mode}); +this.element.setStyle("display","block");if(this.options.transitionOpacity){d.opacity=1;}var b={};$each(d,function(f,e){b[e]=[f,0];},this);this.element.setStyle("overflow","hidden"); +var a=this.options.hideInputs?this.element.getElements(this.options.hideInputs):null;this.$chain.unshift(function(){if(this.hidden){this.hiding=false;$each(d,function(f,e){d[e]=f; +},this);this.element.style.cssText=this.cssText;this.element.setStyle("display","none");if(a){a.setStyle("visibility","visible");}}this.fireEvent("hide",this.element); +this.callChain();}.bind(this));if(a){a.setStyle("visibility","hidden");}this.start(b);}else{this.callChain.delay(10,this);this.fireEvent("complete",this.element); +this.fireEvent("hide",this.element);}}else{if(this.options.link=="chain"){this.chain(this.dissolve.bind(this));}else{if(this.options.link=="cancel"&&!this.hiding){this.cancel(); +this.dissolve();}}}}catch(c){this.hiding=false;this.element.setStyle("display","none");this.callChain.delay(10,this);this.fireEvent("complete",this.element); +this.fireEvent("hide",this.element);}return this;},reveal:function(){try{if(!this.showing&&!this.hiding){if(this.element.getStyle("display")=="none"||this.element.getStyle("visiblity")=="hidden"||this.element.getStyle("opacity")==0){this.showing=true; +this.hiding=this.hidden=false;var d;this.cssText=this.element.style.cssText;this.element.measure(function(){d=this.element.getComputedSize({styles:this.options.styles,mode:this.options.mode}); +}.bind(this));$each(d,function(f,e){d[e]=f;});if($chk(this.options.heightOverride)){d.height=this.options.heightOverride.toInt();}if($chk(this.options.widthOverride)){d.width=this.options.widthOverride.toInt(); +}if(this.options.transitionOpacity){this.element.setStyle("opacity",0);d.opacity=1;}var b={height:0,display:this.options.display};$each(d,function(f,e){b[e]=0; +});this.element.setStyles($merge(b,{overflow:"hidden"}));var a=this.options.hideInputs?this.element.getElements(this.options.hideInputs):null;if(a){a.setStyle("visibility","hidden"); +}this.start(d);this.$chain.unshift(function(){this.element.style.cssText=this.cssText;this.element.setStyle("display",this.options.display);if(!this.hidden){this.showing=false; +}if(a){a.setStyle("visibility","visible");}this.callChain();this.fireEvent("show",this.element);}.bind(this));}else{this.callChain();this.fireEvent("complete",this.element); +this.fireEvent("show",this.element);}}else{if(this.options.link=="chain"){this.chain(this.reveal.bind(this));}else{if(this.options.link=="cancel"&&!this.showing){this.cancel(); +this.reveal();}}}}catch(c){this.element.setStyles({display:this.options.display,visiblity:"visible",opacity:1});this.showing=false;this.callChain.delay(10,this); +this.fireEvent("complete",this.element);this.fireEvent("show",this.element);}return this;},toggle:function(){if(this.element.getStyle("display")=="none"||this.element.getStyle("visiblity")=="hidden"||this.element.getStyle("opacity")==0){this.reveal(); +}else{this.dissolve();}return this;},cancel:function(){this.parent.apply(this,arguments);this.element.style.cssText=this.cssText;this.hidding=false;this.showing=false; +}});Element.Properties.reveal={set:function(a){var b=this.retrieve("reveal");if(b){b.cancel();}return this.eliminate("reveal").store("reveal:options",a); +},get:function(a){if(a||!this.retrieve("reveal")){if(a||!this.retrieve("reveal:options")){this.set("reveal",a);}this.store("reveal",new Fx.Reveal(this,this.retrieve("reveal:options"))); +}return this.retrieve("reveal");}};Element.Properties.dissolve=Element.Properties.reveal;Element.implement({reveal:function(a){this.get("reveal",a).reveal(); +return this;},dissolve:function(a){this.get("reveal",a).dissolve();return this;},nix:function(){var a=Array.link(arguments,{destroy:Boolean.type,options:Object.type}); +this.get("reveal",a.options).dissolve().chain(function(){this[a.destroy?"destroy":"dispose"]();}.bind(this));return this;},wink:function(){var b=Array.link(arguments,{duration:Number.type,options:Object.type}); +var a=this.get("reveal",b.options);a.reveal().chain(function(){(function(){a.dissolve();}).delay(b.duration||2000);});}});Request.implement({options:{initialDelay:5000,delay:5000,limit:60000},startTimer:function(b){var a=function(){if(!this.running){this.send({data:b}); +}};this.timer=a.delay(this.options.initialDelay,this);this.lastDelay=this.options.initialDelay;this.completeCheck=function(c){$clear(this.timer);this.lastDelay=(c)?this.options.delay:(this.lastDelay+this.options.delay).min(this.options.limit); +this.timer=a.delay(this.lastDelay,this);};return this.addEvent("complete",this.completeCheck);},stopTimer:function(){$clear(this.timer);return this.removeEvent("complete",this.completeCheck); +}});var Color=new Native({initialize:function(b,c){if(arguments.length>=3){c="rgb";b=Array.slice(arguments,0,3);}else{if(typeof b=="string"){if(b.match(/rgb/)){b=b.rgbToHex().hexToRgb(true); +}else{if(b.match(/hsb/)){b=b.hsbToRgb();}else{b=b.hexToRgb(true);}}}}c=c||"rgb";switch(c){case"hsb":var a=b;b=b.hsbToRgb();b.hsb=a;break;case"hex":b=b.hexToRgb(true); +break;}b.rgb=b.slice(0,3);b.hsb=b.hsb||b.rgbToHsb();b.hex=b.rgbToHex();return $extend(b,this);}});Color.implement({mix:function(){var a=Array.slice(arguments); +var c=($type(a.getLast())=="number")?a.pop():50;var b=this.slice();a.each(function(d){d=new Color(d);for(var e=0;e<3;e++){b[e]=Math.round((b[e]/100*(100-c))+(d[e]/100*c)); +}});return new Color(b,"rgb");},invert:function(){return new Color(this.map(function(a){return 255-a;}));},setHue:function(a){return new Color([a,this.hsb[1],this.hsb[2]],"hsb"); +},setSaturation:function(a){return new Color([this.hsb[0],a,this.hsb[2]],"hsb");},setBrightness:function(a){return new Color([this.hsb[0],this.hsb[1],a],"hsb"); +}});var $RGB=function(d,c,a){return new Color([d,c,a],"rgb");};var $HSB=function(d,c,a){return new Color([d,c,a],"hsb");};var $HEX=function(a){return new Color(a,"hex"); +};Array.implement({rgbToHsb:function(){var b=this[0],c=this[1],j=this[2],g=0;var i=Math.max(b,c,j),e=Math.min(b,c,j);var k=i-e;var h=i/255,f=(i!=0)?k/i:0; +if(f!=0){var d=(i-b)/k;var a=(i-c)/k;var l=(i-j)/k;if(b==i){g=l-a;}else{if(c==i){g=2+d-l;}else{g=4+a-d;}}g/=6;if(g<0){g++;}}return[Math.round(g*360),Math.round(f*100),Math.round(h*100)]; +},hsbToRgb:function(){var c=Math.round(this[2]/100*255);if(this[1]==0){return[c,c,c];}else{var a=this[0]%360;var e=a%60;var g=Math.round((this[2]*(100-this[1]))/10000*255); +var d=Math.round((this[2]*(6000-this[1]*e))/600000*255);var b=Math.round((this[2]*(6000-this[1]*(60-e)))/600000*255);switch(Math.floor(a/60)){case 0:return[c,b,g]; +case 1:return[d,c,g];case 2:return[g,c,b];case 3:return[g,d,c];case 4:return[b,g,c];case 5:return[c,g,d];}}return false;}});String.implement({rgbToHsb:function(){var a=this.match(/\d{1,3}/g); +return(a)?a.rgbToHsb():null;},hsbToRgb:function(){var a=this.match(/\d{1,3}/g);return(a)?a.hsbToRgb():null;}});var IframeShim=new Class({Implements:[Options,Events,Class.Occlude],options:{className:"iframeShim",src:'javascript:false;document.write("");',display:false,zIndex:null,margin:0,offset:{x:0,y:0},browsers:(Browser.Engine.trident4||(Browser.Engine.gecko&&!Browser.Engine.gecko19&&Browser.Platform.mac))},property:"IframeShim",initialize:function(b,a){this.element=document.id(b); +if(this.occlude()){return this.occluded;}this.setOptions(a);this.makeShim();return this;},makeShim:function(){if(this.options.browsers){var c=this.element.getStyle("zIndex").toInt(); +if(!c){c=1;var b=this.element.getStyle("position");if(b=="static"||!b){this.element.setStyle("position","relative");}this.element.setStyle("zIndex",c); +}c=($chk(this.options.zIndex)&&c>this.options.zIndex)?this.options.zIndex:c-1;if(c<0){c=1;}this.shim=new Element("iframe",{src:this.options.src,scrolling:"no",frameborder:0,styles:{zIndex:c,position:"absolute",border:"none",filter:"progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)"},"class":this.options.className}).store("IframeShim",this); +var a=(function(){this.shim.inject(this.element,"after");this[this.options.display?"show":"hide"]();this.fireEvent("inject");}).bind(this);if(IframeShim.ready){window.addEvent("load",a); +}else{a();}}else{this.position=this.hide=this.show=this.dispose=$lambda(this);}},position:function(){if(!IframeShim.ready||!this.shim){return this;}var a=this.element.measure(function(){return this.getSize(); +});if(this.options.margin!=undefined){a.x=a.x-(this.options.margin*2);a.y=a.y-(this.options.margin*2);this.options.offset.x+=this.options.margin;this.options.offset.y+=this.options.margin; +}this.shim.set({width:a.x,height:a.y}).position({relativeTo:this.element,offset:this.options.offset});return this;},hide:function(){if(this.shim){this.shim.setStyle("display","none"); +}return this;},show:function(){if(this.shim){this.shim.setStyle("display","block");}return this.position();},dispose:function(){if(this.shim){this.shim.dispose(); +}return this;},destroy:function(){if(this.shim){this.shim.destroy();}return this;}});window.addEvent("load",function(){IframeShim.ready=true;});var Mask=new Class({Implements:[Options,Events],Binds:["resize"],options:{style:{},"class":"mask",maskMargins:false,useIframeShim:true},initialize:function(b,a){this.target=document.id(b)||document.body; +this.target.store("mask",this);this.setOptions(a);this.render();this.inject();},render:function(){this.element=new Element("div",{"class":this.options["class"],id:this.options.id||"mask-"+$time(),styles:$merge(this.options.style,{display:"none"}),events:{click:function(){this.fireEvent("click"); +if(this.options.hideOnClick){this.hide();}}.bind(this)}});this.hidden=true;},toElement:function(){return this.element;},inject:function(b,a){a=a||this.options.inject?this.options.inject.where:""||this.target==document.body?"inside":"after"; +b=b||this.options.inject?this.options.inject.target:""||this.target;this.element.inject(b,a);if(this.options.useIframeShim){this.shim=new IframeShim(this.element); +this.addEvents({show:this.shim.show.bind(this.shim),hide:this.shim.hide.bind(this.shim),destroy:this.shim.destroy.bind(this.shim)});}},position:function(){this.resize(this.options.width,this.options.height); +this.element.position({relativeTo:this.target,position:"topLeft",ignoreMargins:!this.options.maskMargins,ignoreScroll:this.target==document.body});return this; +},resize:function(a,e){var b={styles:["padding","border"]};if(this.options.maskMargins){b.styles.push("margin");}var d=this.target.getComputedSize(b);if(this.target==document.body){var c=window.getSize(); +if(d.totalHeight<c.y){d.totalHeight=c.y;}if(d.totalWidth<c.x){d.totalWidth=c.x;}}this.element.setStyles({width:$pick(a,d.totalWidth,d.x),height:$pick(e,d.totalHeight,d.y)}); +return this;},show:function(){if(!this.hidden){return this;}this.target.addEvent("resize",this.resize);if(this.target!=document.body){document.id(document.body).addEvent("resize",this.resize); +}this.position();this.showMask.apply(this,arguments);return this;},showMask:function(){this.element.setStyle("display","block");this.hidden=false;this.fireEvent("show"); +},hide:function(){if(this.hidden){return this;}this.target.removeEvent("resize",this.resize);this.hideMask.apply(this,arguments);if(this.options.destroyOnHide){return this.destroy(); +}return this;},hideMask:function(){this.element.setStyle("display","none");this.hidden=true;this.fireEvent("hide");},toggle:function(){this[this.hidden?"show":"hide"](); +},destroy:function(){this.hide();this.element.destroy();this.fireEvent("destroy");this.target.eliminate("mask");}});Element.Properties.mask={set:function(b){var a=this.retrieve("mask"); +return this.eliminate("mask").store("mask:options",b);},get:function(a){if(a||!this.retrieve("mask")){if(this.retrieve("mask")){this.retrieve("mask").destroy(); +}if(a||!this.retrieve("mask:options")){this.set("mask",a);}this.store("mask",new Mask(this,this.retrieve("mask:options")));}return this.retrieve("mask"); +}};Element.implement({mask:function(a){this.get("mask",a).show();return this;},unmask:function(){this.get("mask").hide();return this;}});var Spinner=new Class({Extends:Mask,options:{"class":"spinner",containerPosition:{},content:{"class":"spinner-content"},messageContainer:{"class":"spinner-msg"},img:{"class":"spinner-img"},fxOptions:{link:"chain"}},initialize:function(){this.parent.apply(this,arguments); +this.target.store("spinner",this);var a=function(){this.active=false;}.bind(this);this.addEvents({hide:a,show:a});},render:function(){this.parent();this.element.set("id",this.options.id||"spinner-"+$time()); +this.content=document.id(this.options.content)||new Element("div",this.options.content);this.content.inject(this.element);if(this.options.message){this.msg=document.id(this.options.message)||new Element("p",this.options.messageContainer).appendText(this.options.message); +this.msg.inject(this.content);}if(this.options.img){this.img=document.id(this.options.img)||new Element("div",this.options.img);this.img.inject(this.content); +}this.element.set("tween",this.options.fxOptions);},show:function(a){if(this.active){return this.chain(this.show.bind(this));}if(!this.hidden){this.callChain.delay(20,this); +return this;}this.active=true;return this.parent(a);},showMask:function(a){var b=function(){this.content.position($merge({relativeTo:this.element},this.options.containerPosition)); +}.bind(this);if(a){this.parent();b();}else{this.element.setStyles({display:"block",opacity:0}).tween("opacity",this.options.style.opacity||0.9);b();this.hidden=false; +this.fireEvent("show");this.callChain();}},hide:function(a){if(this.active){return this.chain(this.hide.bind(this));}if(this.hidden){this.callChain.delay(20,this); +return this;}this.active=true;return this.parent(a);},hideMask:function(a){if(a){return this.parent();}this.element.tween("opacity",0).get("tween").chain(function(){this.element.setStyle("display","none"); +this.hidden=true;this.fireEvent("hide");this.callChain();}.bind(this));},destroy:function(){this.content.destroy();this.parent();this.target.eliminate("spinner"); +}});Spinner.implement(new Chain);if(window.Request){Request=Class.refactor(Request,{options:{useSpinner:false,spinnerOptions:{},spinnerTarget:false},initialize:function(a){this._send=this.send; +this.send=function(c){if(this.spinner){this.spinner.chain(this._send.bind(this,c)).show();}else{this._send(c);}return this;};this.previous(a);var b=document.id(this.options.spinnerTarget)||document.id(this.options.update); +if(this.options.useSpinner&&b){this.spinner=b.get("spinner",this.options.spinnerOptions);["onComplete","onException","onCancel"].each(function(c){this.addEvent(c,this.spinner.hide.bind(this.spinner)); +},this);}},getSpinner:function(){return this.spinner;}});}Element.Properties.spinner={set:function(a){var b=this.retrieve("spinner");return this.eliminate("spinner").store("spinner:options",a); +},get:function(a){if(a||!this.retrieve("spinner")){if(this.retrieve("spinner")){this.retrieve("spinner").destroy();}if(a||!this.retrieve("spinner:options")){this.set("spinner",a); +}new Spinner(this,this.retrieve("spinner:options"));}return this.retrieve("spinner");}};Element.implement({spin:function(a){this.get("spinner",a).show(); +return this;},unspin:function(){var a=Array.link(arguments,{options:Object.type,callback:Function.type});this.get("spinner",a.options).hide(a.callback); +return this;}});
\ No newline at end of file diff --git a/module/web/media/default/js/sprintf.js b/module/web/media/default/js/sprintf.js new file mode 100644 index 000000000..30d9046de --- /dev/null +++ b/module/web/media/default/js/sprintf.js @@ -0,0 +1,123 @@ +// JavaScript Document
+sprintfWrapper = {
+
+ init : function () {
+
+ if (typeof arguments == "undefined") { return null; }
+ if (arguments.length < 1) { return null; }
+ if (typeof arguments[0] != "string") { return null; }
+ if (typeof RegExp == "undefined") { return null; }
+
+ var string = arguments[0];
+ var exp = new RegExp(/(%([%]|(\-)?(\+|\x20)?(0)?(\d+)?(\.(\d)?)?([bcdfosxX])))/g);
+ var matches = new Array();
+ var strings = new Array();
+ var convCount = 0;
+ var stringPosStart = 0;
+ var stringPosEnd = 0;
+ var matchPosEnd = 0;
+ var newString = '';
+ var match = null;
+
+ while (match = exp.exec(string)) {
+ if (match[9]) { convCount += 1; }
+
+ stringPosStart = matchPosEnd;
+ stringPosEnd = exp.lastIndex - match[0].length;
+ strings[strings.length] = string.substring(stringPosStart, stringPosEnd);
+
+ matchPosEnd = exp.lastIndex;
+ matches[matches.length] = {
+ match: match[0],
+ left: match[3] ? true : false,
+ sign: match[4] || '',
+ pad: match[5] || ' ',
+ min: match[6] || 0,
+ precision: match[8],
+ code: match[9] || '%',
+ negative: parseInt(arguments[convCount]) < 0 ? true : false,
+ argument: String(arguments[convCount])
+ };
+ }
+ strings[strings.length] = string.substring(matchPosEnd);
+
+ if (matches.length == 0) { return string; }
+ if ((arguments.length - 1) < convCount) { return null; }
+
+ var code = null;
+ var match = null;
+ var i = null;
+
+ for (i=0; i<matches.length; i++) {
+
+ if (matches[i].code == '%') { substitution = '%' }
+ else if (matches[i].code == 'b') {
+ matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(2));
+ substitution = sprintfWrapper.convert(matches[i], true);
+ }
+ else if (matches[i].code == 'c') {
+ matches[i].argument = String(String.fromCharCode(parseInt(Math.abs(parseInt(matches[i].argument)))));
+ substitution = sprintfWrapper.convert(matches[i], true);
+ }
+ else if (matches[i].code == 'd') {
+ matches[i].argument = String(Math.abs(parseInt(matches[i].argument)));
+ substitution = sprintfWrapper.convert(matches[i]);
+ }
+ else if (matches[i].code == 'f') {
+ matches[i].argument = String(Math.abs(parseFloat(matches[i].argument)).toFixed(matches[i].precision ? matches[i].precision : 6));
+ substitution = sprintfWrapper.convert(matches[i]);
+ }
+ else if (matches[i].code == 'o') {
+ matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(8));
+ substitution = sprintfWrapper.convert(matches[i]);
+ }
+ else if (matches[i].code == 's') {
+ matches[i].argument = matches[i].argument.substring(0, matches[i].precision ? matches[i].precision : matches[i].argument.length)
+ substitution = sprintfWrapper.convert(matches[i], true);
+ }
+ else if (matches[i].code == 'x') {
+ matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
+ substitution = sprintfWrapper.convert(matches[i]);
+ }
+ else if (matches[i].code == 'X') {
+ matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
+ substitution = sprintfWrapper.convert(matches[i]).toUpperCase();
+ }
+ else {
+ substitution = matches[i].match;
+ }
+
+ newString += strings[i];
+ newString += substitution;
+
+ }
+ newString += strings[i];
+
+ return newString;
+
+ },
+
+ convert : function(match, nosign){
+ if (nosign) {
+ match.sign = '';
+ } else {
+ match.sign = match.negative ? '-' : match.sign;
+ }
+ var l = match.min - match.argument.length + 1 - match.sign.length;
+ var pad = new Array(l < 0 ? 0 : l).join(match.pad);
+ if (!match.left) {
+ if (match.pad == "0" || nosign) {
+ return match.sign + pad + match.argument;
+ } else {
+ return pad + match.sign + match.argument;
+ }
+ } else {
+ if (match.pad == "0" || nosign) {
+ return match.sign + match.argument + pad.replace(/0/g, ' ');
+ } else {
+ return match.sign + match.argument + pad;
+ }
+ }
+ }
+}
+sprintf = sprintfWrapper.init;
\ No newline at end of file diff --git a/module/web/static/default/status.js b/module/web/media/default/js/status.js index 31a4e0032..3923e80ca 100644 --- a/module/web/static/default/status.js +++ b/module/web/media/default/js/status.js @@ -39,11 +39,11 @@ window.addEvent('domready', function(){ new Request({ method: 'post', - url: '/json/addlinks', + url: '/json/addpackage', onSuccess: function(){ document.id('linkarea').value = "" } - }).send('links='+document.id('linkarea').value) + }).send('links='+document.id('linkarea').value+"&name="+document.id('pname').value) }) diff --git a/module/web/static/favicon.ico b/module/web/media/img/favicon.ico Binary files differindex 58b1f4b89..58b1f4b89 100644 --- a/module/web/static/favicon.ico +++ b/module/web/media/img/favicon.ico diff --git a/module/web/pyload/__init__.py b/module/web/pyload/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/module/web/pyload/__init__.py diff --git a/module/web/pyload/admin.py b/module/web/pyload/admin.py new file mode 100644 index 000000000..99cb28836 --- /dev/null +++ b/module/web/pyload/admin.py @@ -0,0 +1,15 @@ +# -*- 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 new file mode 100644 index 000000000..86962f23c --- /dev/null +++ b/module/web/pyload/models.py @@ -0,0 +1,31 @@ +# -*- 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/tests.py b/module/web/pyload/tests.py new file mode 100644 index 000000000..2247054b3 --- /dev/null +++ b/module/web/pyload/tests.py @@ -0,0 +1,23 @@ +""" +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 new file mode 100644 index 000000000..73ba08c21 --- /dev/null +++ b/module/web/pyload/urls.py @@ -0,0 +1,22 @@ +# -*- 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'^logs/$', 'views.logs',{}, 'logs'), + (r'^logs/(?P<page>\d+)$', 'views.logs',{}, 'logs'), + (r'^$', 'views.home',{}, 'home'), + ) + +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'), +)
\ No newline at end of file diff --git a/module/web/pyload/views.py b/module/web/pyload/views.py new file mode 100644 index 000000000..ea9d5f1be --- /dev/null +++ b/module/web/pyload/views.py @@ -0,0 +1,153 @@ +# -*- coding: utf-8 -*- + +# Create your views here. +import mimetypes +from os import listdir +from os import stat +from os.path import isdir +from os.path import isfile +from os.path import join + +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.shortcuts import render_to_response +from django.template import RequestContext + + +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()} + + +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): + return render_to_response(join(settings.TEMPLATE, 'home.html'), RequestContext(request, {'content': settings.PYLOAD.status_downloads()}, [status_proc])) + + +@login_required +@permission('pyload.can_see_dl') +@check_server +def queue(request): + queue = settings.PYLOAD.get_queue() + for pack in queue: + pack["children"] = map(settings.PYLOAD.get_file_info, settings.PYLOAD.get_package_files(pack["id"])) + return render_to_response(join(settings.TEMPLATE, 'queue.html'), RequestContext(request, {'content': queue}, [status_proc])) + + +@login_required +@permission('pyload.can_download') +@check_server +def downloads(request): + if not isdir(settings.DL_ROOT): + return base(request, ['Download directory not found.']) + data = { + 'folder': [], + 'files': [] + } + + for item in listdir(settings.DL_ROOT): + if isdir(join(settings.DL_ROOT, item)): + folder = { + 'name': item, + 'files': [] + } + for file in listdir(join(settings.DL_ROOT, item)): + if isfile(join(settings.DL_ROOT, item, file)): + folder['files'].append(file) + + data['folder'].append(folder) + elif isfile(join(settings.DL_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 = path.split("/") + + dir = join(settings.DL_ROOT, path[1].replace('..', '')) + if isdir(dir) or isfile(dir): + if isdir(dir): filepath = join(dir, path[2]) + elif isfile(dir): filepath = dir + + print filepath + 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, page=0): + + log = file(join(settings.LOG_ROOT, "log.txt")).readlines() + data = [] + page = int(page) + for i in range(page, page + 20): + data.append({'line': i + 1, 'content':log[i]}) + + return render_to_response(join(settings.TEMPLATE, 'logs.html'), RequestContext(request, {'log': data, 'next': str(page + 20), 'prev': 0 if page-20 < 0 else page-20}, [status_proc])) diff --git a/module/web/run_unix.py b/module/web/run_unix.py new file mode 100755 index 000000000..09c67b282 --- /dev/null +++ b/module/web/run_unix.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +from __future__ import with_statement +import os + +pid = os.fork() +if pid: + with open("webserver.pid", "w") as f: + f.write(str(pid)) +else: + from django.core.management import execute_manager + + try: + import settings # Assumed to be in the same directory. + except ImportError: + import sys + sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) + sys.exit(1) + + if __name__ == "__main__": + execute_manager(settings)
\ No newline at end of file diff --git a/module/web/settings.py b/module/web/settings.py new file mode 100644 index 000000000..dff1dc29d --- /dev/null +++ b/module/web/settings.py @@ -0,0 +1,135 @@ +# -*- coding: utf-8 -*-
+# Django settings for pyload project.
+
+DEBUG = True
+TEMPLATE_DEBUG = DEBUG
+
+import os.path
+import sys
+import xmlrpclib
+
+SERVER_VERSION = "0.3"
+
+PROJECT_DIR = os.path.dirname(__file__)
+
+#chdir(dirname(abspath(__file__)) + sep)
+
+PYLOAD_DIR = os.path.join(PROJECT_DIR,"..","..")
+
+sys.path.append(os.path.join(PYLOAD_DIR, "module"))
+from XMLConfigParser import XMLConfigParser
+config = XMLConfigParser(os.path.join(PYLOAD_DIR,"module","config","core.xml"))
+
+#DEBUG = config.get("general","debug")
+
+
+ssl = ""
+
+if config.get("ssl", "activated") == "True":
+ ssl = "s"
+
+server_url = "http%s://%s:%s@%s:%s/" % (
+ ssl,
+ config.get("remote", "username"),
+ config.get("remote", "password"),
+ config.get("remote", "listenaddr"),
+ config.get("remote", "port")
+ )
+
+PYLOAD = xmlrpclib.ServerProxy(server_url, allow_none=True)
+
+TEMPLATE = config.get('webinterface','template')
+DL_ROOT = os.path.join(PYLOAD_DIR, config.get('general','download_folder'))
+LOG_ROOT = os.path.join(PYLOAD_DIR, config.get('log','log_folder'))
+
+ADMINS = (
+ # ('Your Name', 'your_email@domain.com'),
+ )
+
+MANAGERS = ADMINS
+
+DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
+DATABASE_NAME = os.path.join(PROJECT_DIR, 'pyload.db') # Or path to database file if using sqlite3.
+DATABASE_USER = '' # Not used with sqlite3.
+DATABASE_PASSWORD = '' # Not used with sqlite3.
+DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
+DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
+
+# Local time zone for this installation. Choices can be found here:
+# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
+# although not all choices may be available on all operating systems.
+# If running in a Windows environment this must be set to the same as your
+# system time zone.
+TIME_ZONE = 'Europe'
+
+# Language code for this installation. All choices can be found here:
+# http://www.i18nguy.com/unicode/language-identifiers.html
+LANGUAGE_CODE = 'en-us'
+
+SITE_ID = 1
+
+# If you set this to False, Django will make some optimizations so as not
+# to load the internationalization machinery.
+USE_I18N = True
+
+# Absolute path to the directory that holds media.
+# Example: "/home/media/media.lawrence.com/"
+MEDIA_ROOT = os.path.join(PROJECT_DIR, "media/")
+
+
+# URL that handles the media served from MEDIA_ROOT. Make sure to use a
+# trailing slash if there is a path component (optional in other cases).
+# Examples: "http://media.lawrence.com", "http://example.com/media/"
+
+#MEDIA_URL = 'http://localhost:8000/media'
+MEDIA_URL = '/media/' + config.get('webinterface','template') + '/'
+#MEDIA_URL = os.path.join(PROJECT_DIR, "media/")
+
+LOGIN_REDIRECT_URL = "/"
+
+# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
+# trailing slash.
+# Examples: "http://foo.com/media/", "/media/".
+ADMIN_MEDIA_PREFIX = '/media/admin/'
+
+# Make this unique, and don't share it with anybody.
+SECRET_KEY = '+u%%1t&c7!e$0$*gu%w2$@to)h0!&x-r*9e+-=wa4*zxat%x^t'
+
+# List of callables that know how to import templates from various sources.
+TEMPLATE_LOADERS = (
+ 'django.template.loaders.filesystem.load_template_source',
+ 'django.template.loaders.app_directories.load_template_source',
+ # 'django.template.loaders.eggs.load_template_source',
+ )
+
+
+MIDDLEWARE_CLASSES = (
+ 'django.middleware.gzip.GZipMiddleware',
+ 'django.middleware.http.ConditionalGetMiddleware',
+ 'django.middleware.common.CommonMiddleware',
+ 'django.contrib.sessions.middleware.SessionMiddleware',
+ 'django.contrib.auth.middleware.AuthenticationMiddleware',
+ )
+
+ROOT_URLCONF = 'urls'
+
+TEMPLATE_DIRS = (
+ # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
+ # Always use forward slashes, even on Windows.
+ # Don't forget to use absolute paths, not relative paths.
+ os.path.join(PROJECT_DIR, "templates"),
+ )
+
+INSTALLED_APPS = (
+ 'django.contrib.auth',
+ 'django.contrib.contenttypes',
+ 'django.contrib.sessions',
+ #'django.contrib.sites',
+ 'django.contrib.admin',
+ 'pyload',
+ 'ajax',
+ )
+
+
+AUTH_PROFILE_MODULE = 'pyload.UserProfile'
+LOGIN_URL = '/login'
\ No newline at end of file diff --git a/module/web/static/default.css b/module/web/static/default.css deleted file mode 100644 index fd2e85eb9..000000000 --- a/module/web/static/default.css +++ /dev/null @@ -1,189 +0,0 @@ -a.interwiki{background:transparent url(static/default/interwiki.png) 0px 1px no-repeat;padding-left:16px;} -a.iw_wp{background-image:url(static/default/interwiki/wp.gif)} -a.iw_wpde{background-image:url(static/default/interwiki/wpde.gif)} -a.iw_wpmeta{background-image:url(static/default/interwiki/wpmeta.gif)} -a.iw_doku{background-image:url(static/default/interwiki/doku.gif)} -a.iw_dokubug{background-image:url(static/default/interwiki/dokubug.gif)} -a.iw_amazon{background-image:url(static/default/interwiki/amazon.gif)} -a.iw_amazon_de{background-image:url(static/default/interwiki/amazon.de.gif)} -a.iw_amazon_uk{background-image:url(static/default/interwiki/amazon.uk.gif)} -a.iw_phpfn{background-image:url(static/default/interwiki/phpfn.gif)} -a.iw_coral{background-image:url(static/default/interwiki/coral.gif)} -a.iw_sb{background-image:url(static/default/interwiki/sb.gif)} -a.iw_google{background-image:url(static/default/interwiki/google.gif)} -a.iw_meatball{background-image:url(static/default/interwiki/meatball.gif)} -a.iw_wiki{background-image:url(static/default/interwiki/wiki.gif)} -a.mediafile{background:transparent url(static/default/file.png) 0px 1px no-repeat;padding-left:18px;padding-bottom:1px;} -a.mf_jpg{background-image:url(static/default/jpg.png)} -a.mf_jpeg{background-image:url(static/default/jpeg.png)} -a.mf_gif{background-image:url(static/default/gif.png)} -a.mf_png{background-image:url(static/default/png.png)} -a.mf_tgz{background-image:url(static/default/tgz.png)} -a.mf_tar{background-image:url(static/default/tar.png)} -a.mf_gz{background-image:url(static/default/gz.png)} -a.mf_bz2{background-image:url(static/default/bz2.png)} -a.mf_zip{background-image:url(static/default/zip.png)} -a.mf_rar{background-image:url(static/default/rar.png)} -a.mf_pdf{background-image:url(static/default/pdf.png)} -a.mf_ps{background-image:url(static/default/ps.png)} -a.mf_doc{background-image:url(static/default/doc.png)} -a.mf_xls{background-image:url(static/default/xls.png)} -a.mf_ppt{background-image:url(static/default/ppt.png)} -a.mf_rtf{background-image:url(static/default/rtf.png)} -a.mf_swf{background-image:url(static/default/swf.png)} -a.mf_rpm{background-image:url(static/default/rpm.png)} -a.mf_deb{background-image:url(static/default/deb.png)} -a.mf_sxw{background-image:url(static/default/sxw.png)} -a.mf_sxc{background-image:url(static/default/sxc.png)} -a.mf_sxi{background-image:url(static/default/sxi.png)} -a.mf_sxd{background-image:url(static/default/sxd.png)} -a.mf_odc{background-image:url(static/default/odc.png)} -a.mf_odf{background-image:url(static/default/odf.png)} -a.mf_odg{background-image:url(static/default/odg.png)}a.mf_odi{background-image:url(static/default/odi.png)} -a.mf_odp{background-image:url(static/default/odp.png)}a.mf_ods{background-image:url(static/default/ods.png)} -a.mf_odt{background-image:url(static/default/odt.png)}div.clearer{clear:both;line-height:0;height:0;overflow:hidden;} -div.no{display:inline;margin:0;padding:0;}.hidden{display:none;} -div.error{background:#fcc url(static/default/error.png) 0.5em 0px no-repeat;color:#000;border-bottom:1px solid #faa;font-size:90%;margin:0;padding-left:3em;overflow:hidden;} -div.info{background:#ccf url(static/default/info.png) 0.5em 0px no-repeat;color:#000;border-bottom:1px solid #aaf;font-size:90%;margin:0;padding-left:3em;overflow:hidden;} -div.success{background:#cfc url(static/default/success.png) 0.5em 0px no-repeat;color:#000;border-bottom:1px solid #afa;font-size:90%;margin:0;padding-left:3em;overflow:hidden;} -div.notify{background:#ffc url(static/default/notify.png) 0.5em 0px no-repeat;color:#000;border-bottom:1px solid #ffa;font-size:90%;margin:0;padding-left:3em;overflow:hidden;} -.medialeft{float:left;}.mediaright{float:right;} -.mediacenter{display:block;margin-left:auto;margin-right:auto;} -.leftalign{text-align:left;} -.centeralign{text-align:center;} -.rightalign{text-align:right;} -em.u{font-style:normal;text-decoration:underline;} -em em.u{font-style:italic;} -.code .br0{color:#6c6;} -.code .co1{color:#808080;font-style:italic;} -.code .co2{color:#808080;font-style:italic;} -.code .co3{color:#808080;} -.code .coMULTI{color:#808080;font-style:italic;} -.code .es0{color:#009;font-weight:bold;}.code .kw1{color:#b1b100;} -.code .kw2{color:#000;font-weight:bold;}.code .kw3{color:#006;} -.code .kw4{color:#933;}.code .kw5{color:#00f;}.code .me1{color:#060;}.code .me2{color:#060;} -.code .nu0{color:#c6c;}.code .re0{color:#00f;}.code .re1{color:#00f;}.code .re2{color:#00f;}.code .re3{color:#f33;font-weight:bold;}.code .re4{color:#099;}.code .st0{color:#f00;}.code .sy0{color:#6c6;} -div.dokuwiki table.pagelist,div.dokuwiki table.ul{border:0;padding:0;border-spacing:0;margin-bottom:1em;border-collapse:collapse;} -div.dokuwiki table.pagelist tr{border-top:1px solid #8cacbb;border-bottom:1px solid #8cacbb;} -div.dokuwiki table.pagelist th,div.dokuwiki table.pagelist td{padding:1px 1em 1px 0;} -div.dokuwiki table.ul th,div.dokuwiki table.ul td{padding:0 1em 0 0;} -div.dokuwiki table.ul ul{margin:0 0 0 1.5em;} -div.dokuwiki table.pagelist th,div.dokuwiki table.ul th{background-color:#dee7ec;} -div.dokuwiki th.page,div.dokuwiki th.date,div.dokuwiki th.user,div.dokuwiki th.desc,div.dokuwiki th.comments,div.dokuwiki th.linkbacks,div.dokuwiki th.tags,div.dokuwiki td.date,div.dokuwiki td.user,div.dokuwiki td.desc,div.dokuwiki td.comments,div.dokuwiki td.linkbacks,div.dokuwiki td.tags{color:#666;font-size:80%;} -div.dokuwiki td.date{text-align:right;}div.dokuwiki div.include div.secedit{float:right;margin-left:1em;margin-top:-18px;} -div.dokuwiki div.inclmeta{border-top:1px dotted #8cacbb;padding-top:0.2em;color:#666;font-size:80%;line-height:1.25;margin-top:0.5em;margin-bottom:2em;} -div.dokuwiki div.inclmeta a.permalink{background:transparent url(static/default/link.gif) 0px 1px no-repeat;padding:1px 0px 1px 16px;} -div.dokuwiki div.inclmeta abbr.published{background:transparent url(static/default/date.gif) 0px 1px no-repeat;padding:1px 0px 1px 16px;border-bottom:0;} -div.dokuwiki div.inclmeta span.author{background:transparent url(static/default/user.gif) 0px 1px no-repeat;padding:1px 0px 1px 16px;} -div.dokuwiki div.inclmeta span.comment{background:transparent url(static/default/comment.gif) 0px 1px no-repeat;padding:1px 0px 1px 16px;} -div.dokuwiki div.inclmeta div.tags{border-top:0;font-size:100%;float:right;clear:none;}#plugin__manager{}#plugin__manager h2{margin-left:0;} -#plugin__manager form{display:block;margin:0;padding:0;} -#plugin__manager legend{display:none;} -#plugin__manager fieldset{width:auto;} -#plugin__manager .button{margin:0;} -#plugin__manager p,#plugin__manager label{text-align:left;} -#plugin__manager .hidden{display:none;}#plugin__manager .new{background:#dee7ec;} -#plugin__manager input[disabled]{color:#ccc;border-color:#ccc;} -#plugin__manager .pm_menu,#plugin__manager .pm_info{margin-left:0;text-align:left;} -#plugin__manager .pm_menu{float:left;width:48%;} -#plugin__manager .pm_info{float:right;width:50%;} -#plugin__manager .common{}#plugin__manager .common form{} -#plugin__manager .common fieldset{margin:0;padding:0 0 1.0em 0;text-align:left;border:none;} -#plugin__manager .common label{padding:0 0 0.5em 0;} -#plugin__manager .common input{} -#plugin__manager .common input.edit{width:24em;margin:0.5em;} -#plugin__manager .common .button{} -#plugin__manager form.plugins{} -#plugin__manager .plugins fieldset{color:#000;background:#fff;text-align:right;border-top:none;border-right:none;border-left:none;} -#plugin__manager .plugins fieldset.protected{background:#fdd;color:#000;} -#plugin__manager .plugins fieldset.disabled{background:#e0e0e0;color:#a8a8a8;} -#plugin__manager .plugins .legend{color:#000;background:inherit;display:block;margin:0;padding:0;font-size:1em;line-height:1.4em;font-weight:normal;text-align:left;float:left;padding:0;clear:none;} -#plugin__manager .plugins .button{font-size:95%;}#plugin__manager .plugins fieldset.buttons{border:none;} -#plugin__manager .plugins fieldset.buttons .button{float:left;} -#plugin__manager .pm_info h3{margin-left:0;}#plugin__manager .pm_info dl{margin:1em 0;padding:0;} -#plugin__manager .pm_info dt{width:6em;float:left;clear:left;margin:0;padding:0;} -#plugin__manager .pm_info dd{margin:0 0 0 7em;padding:0;background:none;} -#plugin__manager .plugins .enable{float:left;width:auto;margin-right:0.5em;} -#config__manager div.success,#config__manager div.error,#config__manager div.info{background-position:0.5em;padding:0.5em;text-align:center;} -#config__manager fieldset{margin:1em;width:auto;margin-bottom:2em;background-color:#dee7ec;color:#000;padding:0 1em;} -#config__manager legend{font-size:1.25em;} -#config__manager form{}#config__manager table{margin:1em 0;width:100%;}#config__manager fieldset td{text-align:left;} -#config__manager fieldset td.value{width:31em;}#config__manager td.label{padding:0.8em 0 0.6em 1em;vertical-align:top; -}#config__manager td.label label{clear:left;display:block;} -#config__manager td.label img{padding:0 10px;vertical-align:middle;float:right;} -#config__manager td.label span.outkey{font-size:70%;margin-top:-1.7em;margin-left:-1em;display:block;background-color:#fff;color:#666;float:left;padding:0 0.1em;position:relative;z-index:1;} -#config__manager td input.edit{width:30em;}#config__manager td .input{width:30.8em;} -#config__manager td select.edit{}#config__manager td textarea.edit{width:27.5em;height:4em;} -#config__manager tr .input,#config__manager tr input,#config__manager tr textarea,#config__manager tr select{background-color:#fff;color:#000;} -#config__manager tr.default .input,#config__manager tr.default input,#config__manager tr.default textarea,#config__manager tr.default select,#config__manager .selectiondefault{background-color:#cdf;color:#000;} -#config__manager tr.protected .input,#config__manager tr.protected input,#config__manager tr.protected textarea,#config__manager tr.protected select,#config__manager tr.protected .selection{background-color:#fcc!important;color:#000 !important;} -#config__manager td.error{background-color:red;color:#000;}#config__manager .selection{width:14.8em;float:left;margin:0 0.3em 2px 0;}#config__manager .selection label{float:right;width:14em;font-size:90%;} -* html #config__manager .selection label{padding-top:2px;} -#config__manager .selection input.checkbox{padding-left:0.7em;} -#config__manager .other{clear:both;padding-top:0.5em;} -#config__manager .other label{padding-left:2px;font-size:90%;}.dokuwiki div.plugin_translation{float:right;font-size:95%;} -.dokuwiki div.plugin_translation ul{display:inline;padding:0;margin:0;} -.dokuwiki div.plugin_translation ul li{float:left;list-style-type:none;padding:0;margin:0;} -.dokuwiki div.plugin_translation ul li a.wikilink1:link,.dokuwiki div.plugin_translation ul li a.wikilink1:hover,.dokuwiki div.plugin_translation ul li a.wikilink1:active,.dokuwiki div.plugin_translation ul li a.wikilink1:visited{background-color:#000080;color:#fff !important;text-decoration:none;padding:0 0.2em;margin:0.1em 0.2em;border:none !important;} -.dokuwiki div.plugin_translation ul li a.wikilink2:link,.dokuwiki div.plugin_translation ul li a.wikilink2:hover,.dokuwiki div.plugin_translation ul li a.wikilink2:active,.dokuwiki div.plugin_translation ul li a.wikilink2:visited{background-color:#808080;color:#fff !important;text-decoration:none;padding:0 0.2em;margin:0.1em 0.2em;border:none !important;} -.dokuwiki div.plugin_translation ul li a img{opacity:0.5;border:0;} -.dokuwiki div.plugin_translation ul li a.wikilink2 img{}.dokuwiki div.plugin_translation span.curid a img{opacity:1.0;height:15px;} -.dokuwiki div.plugin_translation ul li a:hover img{opacity:1.0;height:15px;}#user__manager tr.disabled{color:#6f6f6f;background:#e4e4e4;} -#user__manager tr.user_info{vertical-align:top;} -#user__manager div.edit_user{width:46%;float:left;}#user__manager table{margin-bottom:1em;}#user__manager input.button[disabled]{color:#ccc!important;border-color:#ccc!important;}div.dokuwiki div.newentry_form{clear:both;text-align:center;margin-bottom:1em;} -div.dokuwiki #blog__newentry_form input.edit{width:95%;}div.dokuwiki tr.draft,div.dokuwiki div.draft{opacity:0.5;} -div.dokuwiki div.autoarchive_selector ul{list-style-type:none;clear:left;margin:0 0.5em 0 0;} -div.dokuwiki div.autoarchive_selector ul div.li{float:left;margin:0 1em 0 0;} -div.dokuwiki div.autoarchive_selector ul ul{float:left;clear:none;}div.dokuwiki div.autoarchive_selector ul ul div.li{margin:0;}div#acl_manager div#acl__tree{font-size:90%;width:25%;height:300px;float:left;overflow:auto;border:1px solid #8cacbb;text-align:left;} -div#acl_manager div#acl__tree a.cur{background-color:#ff9;font-weight:bold;} -div#acl_manager div#acl__tree ul{list-style-type:none;margin:0;padding:0;}div#acl_manager div#acl__tree li{padding-left:1em;}div#acl_manager div#acl__tree ul img{margin-right:0.25em;cursor:pointer;} -div#acl_manager div#acl__detail{width:73%;height:300px;float:right;overflow:auto;} -div#acl_manager div#acl__detail fieldset{width:90%;} -div#acl_manager div#acl__detail div#acl__user{border:1px solid #8cacbb;padding:0.5em;margin-bottom:0.6em;} -div#acl_manager table.inline{width:100%;margin:0;} -div#acl_manager .aclgroup{background:transparent url(static/default/group.png) 0px 1px no-repeat;padding:1px 0px 1px 18px;} -div#acl_manager .acluser{background:transparent url(static/default/user.png) 0px 1px no-repeat;padding:1px 0px 1px 18px;} -div#acl_manager .aclpage{background:transparent url(static/default/page.png) 0px 1px no-repeat;padding:1px 0px 1px 18px;} -div#acl_manager .aclns{background:transparent url(static/default/ns.png) 0px 1px no-repeat;padding:1px 0px 1px 18px;} -div#acl_manager label.disabled{color:#666!important;} -#acl_manager label{text-align:left;font-weight:normal;display:inline;} -#acl_manager table{margin-left:10%;width:80%;}#acl_manager table tr{background-color:inherit;} -#acl_manager table tr:hover{background-color:#dee7ec;} - - -a.interwiki{background:transparent url(/lib/images/interwiki.png) 0px 1px no-repeat;padding-left:16px;} -a.iw_wp{background-image:url(/static/default/wp.gif)} -a.iw_wpde{background-image:url(/static/default/wpde.gif)} -a.iw_wpmeta{background-image:url(/static/default/wpmeta.gif)} -a.iw_doku{background-image:url(/static/default/doku.gif)} -a.iw_dokubug{background-image:url(/static/default/dokubug.gif)} -a.iw_amazon{background-image:url(/static/default/amazon.gif)} -a.iw_amazon_de{background-image:url(/static/default/amazon.de.gif)} -a.iw_amazon_uk{background-image:url(/static/default/amazon.uk.gif)} -a.iw_phpfn{background-image:url(/static/default/phpfn.gif)} -a.iw_coral{background-image:url(/static/default/coral.gif)} -a.iw_sb{background-image:url(/static/default/sb.gif)} -a.iw_google{background-image:url(/static/default/google.gif)} -a.iw_meatball{background-image:url(/static/default/meatball.gif)} -a.iw_wiki{background-image:url(/static/default/wiki.gif)} -a.mediafile{background:transparent url(/static/default/file.png) 0px 1px no-repeat;padding-left:18px;padding-bottom:1px;}a.mf_jpg{background-image:url(/static/default/jpg.png)}a.mf_jpeg{background-image:url(/static/default/jpeg.png)}a.mf_gif{background-image:url(/static/default/gif.png)}a.mf_png{background-image:url(/static/default/png.png)}a.mf_tgz{background-image:url(/static/default/tgz.png)}a.mf_tar{background-image:url(/static/default/tar.png)}a.mf_gz{background-image:url(/static/default/gz.png)}a.mf_bz2{background-image:url(/static/default/bz2.png)} -a.mf_zip{background-image:url(/static/default/zip.png)}a.mf_rar{background-image:url(/static/default/rar.png)}a.mf_pdf{background-image:url(/static/default/pdf.png)}a.mf_ps{background-image:url(/static/default/ps.png)}a.mf_doc{background-image:url(/static/default/doc.png)}a.mf_xls{background-image:url(/static/default/xls.png)}a.mf_ppt{background-image:url(/static/default/ppt.png)}a.mf_rtf{background-image:url(/static/default/rtf.png)}a.mf_swf{background-image:url(/static/default/swf.png)}a.mf_rpm{background-image:url(/static/default/rpm.png)}a.mf_deb{background-image:url(/static/default/deb.png)}a.mf_sxw{background-image:url(/static/default/sxw.png)}a.mf_sxc{background-image:url(/static/default/sxc.png)}a.mf_sxi{background-image:url(/static/default/sxi.png)}a.mf_sxd{background-image:url(/static/default/sxd.png)}a.mf_odc{background-image:url(/static/default/odc.png)}a.mf_odf{background-image:url(/static/default/odf.png)}a.mf_odg{background-image:url(/static/default/odg.png)} -a.mf_odi{background-image:url(/static/default/odi.png)}a.mf_odp{background-image:url(/static/default/odp.png)}a.mf_ods{background-image:url(/static/default/ods.png)}a.mf_odt{background-image:url(/static/default/odt.png)}body{margin:0px;padding:0px;background-color:white;color:black;font-size:12px;font-family:Verdana,Helvetica,"Lucida Grande",Lucida,Arial,sans-serif;font-family:sans-serif;font-size:99,96%;font-size-adjust:none;font-style:normal;font-variant:normal;font-weight:normal;line-height:normal;}hr{border-width:0px;border-bottom:1px #aaa dotted;}img{border:none;}form{margin:0px;padding:0px;border:none;display:inline;background:transparent;}ul li{margin:5px;}textarea{font-family:monospace;}table{margin:0.5em 0;border-collapse:collapse;}td{padding:0.25em;border:1pt solid #ADB9CC;}a{color:#3465a4;text-decoration:none;}a:hover{text-decoration:underline;} -a.wikilink2{color:#a40000 !important;}.dokuwiki h1 a,.dokuwiki h2 a,.dokuwiki h3 a,.dokuwiki h4 a,.dokuwiki h5 a,.dokuwiki a.nolink{color:#000 !important;text-decoration:none !important;} -option{border:0px none #fff;}strong.highlight{background-color:#fc9;padding:1pt;}#pagebottom{clear:both;}hr{height:1px;color:#c0c0c0;background-color:#c0c0c0;border:none;margin:.2em 0 .2em 0;}pre{padding:0.5em;font-family:courier,monospace;border:1px solid #c0c0c0;background:#F0ECE6;white-space:pre;white-space:pre-wrap;word-wrap:break-word;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space:-o-pre-wrap;}.invisible{margin:0px;border:0px;padding:0px;height:0px;visibility:hidden;}.left{float:left !important;}.right{float:right !important;}.center{text-align:center;}div#body-wrapper{padding:40px 40px 10px 40px;font-size:127%;} -div#content{margin-top:-20px;padding:0;font-size:14px;color:black;line-height:1.5em;}h1,h2,h3,h4,h5,h6{background:transparent none repeat scroll 0 0;border-bottom:1px solid #aaa;color:black;font-weight:normal;margin:0;padding:0;padding-bottom:0.17em;padding-top:0.5em;}h1{font-size:188%;line-height:1.2em;margin-bottom:0.1em;padding-bottom:0;}h2{font-size:150%;}h3,h4,h5,h6{border-bottom:none;font-weight:bold;}h3{font-size:132%;}h4{font-size:116%;}h5{font-size:100%;}h6{font-size:80%;}ul#page-actions{float:right;margin:10px 10px 0 10px;padding:6px;color:black;background-color:#ececec;list-style-type:none;-moz-border-radius:5px;}ul#user-actions{padding:5px;margin:0;display:inline;color:black;background-color:#ececec;list-style-type:none;-moz-border-radius:3px;}ul#page-actions li,ul#user-actions li{display:inline;}ul#page-actions a,ul#user-actions a{text-decoration:none;color:black;display:inline;margin:0 3px;padding:2px 0px 2px 18px;} -ul#page-actions a:hover,ul#page-actions a:focus,ul#user-actions a:hover,ul#user-actions a:focus{text-decoration:underline;}.hidden{display:none;}a.urlextern{color:#36B;background:transparent url(/static/default/external-10.2.png) no-repeat scroll right center;padding:0 13px 0 0;}a[href^="http://www.pyload.org"]:after,a.noextlink:after{background:none;padding:0;}a.action.index{background:transparent url(/static/default/wiki-tools-index.png) 0px 1px no-repeat;}a.action.recent{background:transparent url(/static/default/wiki-tools-recent.png) 0px 1px no-repeat;}a.logout{background:transparent url(/static/default/user-actions-logout.png) 0px 1px no-repeat;} -a.admin{background:transparent url(/static/default/user-actions-admin.png) 0px 1px no-repeat;}a.profile{background:transparent url(/static/default/user-actions-profile.png) 0px 1px no-repeat;}a.create,a.edit{background:transparent url(/static/default/page-tools-edit.png) 0px 1px no-repeat;}a.source,a.show{background:transparent url(/static/default/page-tools-source.png) 0px 1px no-repeat;}a.revisions{background:transparent url(/static/default/page-tools-revisions.png) 0px 1px no-repeat;}a.subscribe,a.unsubscribe{background:transparent url(/static/default/page-tools-subscribe.png) 0px 1px no-repeat;}a.backlink{background:transparent url(/static/default/page-tools-backlinks.png) 0px 1px no-repeat;}#head-panel{background:#525252 url(/static/default/head_bg1.png) bottom left repeat-x;}#head-panel h1{display:none;margin:0;text-decoration:none;padding-top:0.8em;padding-left:3.3em;font-size:2.6em;color:#eeeeec;}#head-panel #head-logo{float:left;margin:5px 0 -15px 5px;padding:0;overflow:visible;}#head-menu{background:transparent url(/static/default/tabs-border-bottom.png) 0 100% repeat-x;width:100%;float:left;margin:0;padding:0;padding-top:0.8em;} -#head-menu ul{list-style:none;margin:0 1em 0 2em;}#head-menu ul li{float:left;margin:0;margin-left:0.3em;font-size:14px;margin-bottom:4px;}#head-menu ul li.selected,#head-menu ul li:hover{margin-bottom:0px;}#head-menu ul li a img{height:22px;width:22px;vertical-align:middle;}#head-menu ul li a,#head-menu ul li a:link{float:left;text-decoration:none;color:#555;background:#eaeaea url(/static/default/tab-background.png) 0 100% repeat-x;padding:3px 7px 3px 7px;border:2px solid #ccc;border-bottom:0px solid transparent;padding-bottom:3px;-moz-border-radius:5px;}#head-menu ul li a:hover,#head-menu ul li a:focus{color:#111;padding-bottom:7px;border-bottom:0px none transparent;outline:none;-moz-border-radius-bottomright:0px;-moz-border-radius-bottomleft:0px;}#head-menu ul li a:focus{margin-bottom:-4px;}#head-menu ul li.selected a{color:#3566A5;background:#fff;padding-bottom:7px;border-bottom:0px none transparent;-moz-border-radius-bottomright:0px;-moz-border-radius-bottomleft:0px;}#head-menu ul li.selected a:hover,#head-menu ul li.selected a:focus{color:#111;}div#head-search-and-login{float:right;margin:0 1em 0 0;background-color:#222;padding:4px;color:white;-moz-border-radius-bottomright:6px;-moz-border-radius-bottomleft:6px;}div#head-search-and-login form{display:inline;padding:0 3px;}div#head-search-and-login form input{border:2px solid #888;background:#eee;font-size:14px;padding:2px;-moz-border-radius:3px;}div#head-search-and-login form input:focus{background:#fff;}#head-search{font-size:14px;}#head-username,#head-password{width:80px;font-size:14px;}#pageinfo{clear:both;color:#888;padding:0.6em 0;margin:0;}#foot{font-style:normal;color:#888;text-align:center;}#foot a{color:#aaf;}#foot img{vertical-align:middle;}ul.toc{padding:0;padding-left:20px;margin-left:0;margin-right:10px;list-style:none;}ul.toc li{list-style:circle;}ul.toc li a{text-decoration:none;color:black;}ul.toc li a:hover{text-decoration:underline;}div.toc{border:1px dotted #888;background:#f0f0f0;margin:1em 0 1em 1em;float:right;font-size:95%;}div.toc .tocheader{font-weight:bold;margin:0.5em 1em;}div.toc ol{margin:1em 0.5em 1em 1em;padding:0;}div.toc ol li{margin:0;padding:0;margin-left:1em;}div.toc ol ol{margin:0.5em 0.5em 0.5em 1em;padding:0;}div.recentchanges table{clear:both;}div#editor-help{font-size:90%;border:1px dotted #888;padding:0ex 1ex 1ex 1ex;background:#f7f6f2;}div#preview{margin-top:1em;}label.block{display:block;text-align:right;font-weight:bold;}label.simple{display:block;text-align:left;font-weight:normal;}label.block input.edit{width:50%;}fieldset{width:300px;text-align:center;padding:0.5em;margin:auto;}div.editor{margin:0 0 0 0;}table{margin:0.5em 0;border-collapse:collapse;}td{padding:0.25em;border:1pt solid #ADB9CC;}td p{margin:0;padding:0;}.u{text-decoration:underline;}.footnotes ul{padding:0 2em;margin:0 0 1em;}.footnotes li{list-style:none;}.recentchanges p{margin:0.25em;}.recentchanges td{vertical-align:top;border:none;border-bottom:1pt solid #F0ECE6;background:#F7F6F2;}.rcdaybreak td{background:#729fcf;border:none;}.rcdaybreak td a{font-size:0.88em;}.rcicon1,.rcicon2{text-align:center;}.rcpagelink{width:33%;}.rctime{font-size:0.88em;white-space:nowrap;}.rceditor{white-space:nowrap;font-size:0.88em;}.rccomment{width:66%;color:gray;font-size:0.88em;}.rcrss{float:right;}.recentchanges[dir="rtl"] .rcrss{float:left;}.userpref table,.userpref td{border:none;}div.codearea{margin:0.5em 0;padding:0;border:1pt solid #AEBDCC;background-color:#F3F5F7;color:black;}div.codearea pre{margin:0;padding:10pt;border:none;}a.codenumbers{margin:0 10pt;font-size:0.85em;color:gray;}div.codearea pre span.LineNumber{color:gray;}div.codearea pre span.ID{color:#000;}div.codearea pre span.Operator{color:#0000c0;}div.codearea pre span.Char{color:#004080;}div.codearea pre span.Comment{color:#008000;}div.codearea pre span.Number{color:#0080c0;}div.codearea pre span.String{color:#004080;}div.codearea pre span.SPChar{color:#0000c0;}div.codearea pre span.ResWord{color:#a00000;}div.codearea pre span.ConsWord{color:#008080;font-weight:bold;}div.codearea pre span.Error{color:#ff8080;border:solid 1.5pt #f00;}div.codearea pre span.ResWord2{color:#0080ff;font-weight:bold;}div.codearea pre span.Special{color:#00f;}div.codearea pre span.Preprc{color:#803999;}#message{clear:both;padding:5px 10px;background-color:#eee;border-bottom:2px solid #ccc;}#message p{margin:5px 0;padding:0;font-weight:bold;}#message div.buttons{font-weight:normal;}.diff{width:99%;}.diff-title{background-color:#C0C0C0;}.searchresult dd span{font-weight:bold;}.diff{width:100%;border:none;}.diff-blockheader{font-weight:bold;background:#e5e5e5;font-size:1.2em;border-top:2px solid #444;padding:5px;}.diff th{font-size:120%;width:50%;font-weight:normal;text-align:left;padding-bottom:3px;}.diff td{font-family:monospace;font-size:100%;border:none;}.diff-addedline{background-color:#dfd;}.diff-deletedline{background-color:#ffb;}.diff-context{color:#888;}.diff-addedline{background-color:#E0FFE0;vertical-align:sub;}.diff-deletedline{background-color:#FFFFE0;background-color:#f4cece;vertical-align:sub;} -.diff-addedline strong{background-color:#80FF80;background-color:#8ae234;} -.diff-deletedline strong{background-color:#FFFF80;background-color:#ef2929;background-color:#d78383;} - - - -.box{ background:url(/static/default/progress-bar-back.gif) right center no-repeat; width:200px; height:20px; float:left; } -.perc{ background:url(/static/default/progress-bar.gif) right center no-repeat; height:20px; } -.boxtext{ font-family:tahoma, arial, sans-serif; font-size:11px; color:#000; float:none; padding:3px 0 0 10px; } -.statusbutton{width:32px;height:32px;float:left;margin-left:-32px;margin-right:5px;opacity:0;cursor:pointer} - -.dlsize{float:left; padding-right: 8px;} -.dlspeed{float:left; padding-right: 8px;}
\ No newline at end of file diff --git a/module/web/static/default/home.js b/module/web/static/default/home.js deleted file mode 100644 index 0d74aa17a..000000000 --- a/module/web/static/default/home.js +++ /dev/null @@ -1,212 +0,0 @@ -var dwProgressBar = new Class({ - - //implements - Implements: [Options], - - //options - options: { - container: $$('body')[0], - boxID:'', - percentageID:'', - displayID:'', - startPercentage: 0, - displayText: false, - speed:10 - }, - - //initialization - initialize: function(options) { - //set options - this.setOptions(options); - //create elements - this.createElements(); - }, - - //creates the box and percentage elements - createElements: function() { - var box = new Element('div', { - id:this.options.boxID + this.options.id, - 'class' : this.options.boxID - }); - var perc = new Element('div', { - id:this.options.percentageID + this.options.id, - 'style':'width:0px;', - 'class' : this.options.percentageID - }); - perc.inject(box); - box.inject(this.options.container); - if(this.options.displayText) { - var text = new Element('div', { - id:this.options.displayID + this.options.id, - 'class' : this.options.displayID - }); - text.inject(this.options.container); - } - this.set(this.options.startPercentage); - }, - - //calculates width in pixels from percentage - calculate: function(percentage) { - return (document.id(this.options.boxID+ this.options.id).getStyle('width').replace('px','') * (percentage / 100)).toInt(); - }, - - //animates the change in percentage - animate: function(to) { - document.id(this.options.percentageID+ this.options.id).set('morph', { - duration: this.options.speed, - link:'cancel' - }).morph({ - width:this.calculate(to.toInt()) - }); - if(this.options.displayText) { - document.id(this.options.displayID+ this.options.id).set('text', to.toInt() + '%'); - } - }, - - //sets the percentage from its current state to desired percentage - set: function(to) { - this.animate(to); - } - -}); - - -req = new Request.JSON({ - onSuccess: renderTable, - method: 'get', - url: '/json/links', - initialDelay: 0, - delay: 1000, - limit: 20000 -}); - - -var dls = [] -var pbs = [] - -function renderTable(data){ - - data.downloads.each(function(dl){ - - if (dls.contains(dl.id)){ - - var div = $('dl'+dl.id) - - pbs[dl.id].set(dl.percent) - - div.getChildren("b")[0].textContent = dl.name - - if (dl.status == "downloading"){ - - size = Math.round((dl.size - dl.kbleft) / 1024) + "/" + Math.round(dl.size / 1024) + " MB" - speed = Math.round(dl.speed) + " kb/s" - eta = dl.eta - - - }else if (dl.status == "waiting"){ - - size = "waiting "+ dl.wait - speed = "" - eta = "" - - } - div.getChildren(".dlsize")[0].textContent = size - div.getChildren(".dlspeed")[0].textContent = speed - div.getChildren(".dltime")[0].textContent = eta - - }else{ - - dls.push(dl.id) - - container = $("dlcontainer") - - dldiv = new Element('div', { - 'id' : 'dl'+dl.id, - 'class': 'download', - 'styles': { - 'display': 'None' - } - }) - - new Element('p').inject(dldiv) - - new Element('b', { - 'html': dl.name - }).inject(dldiv) - - new Element('br').inject(dldiv) - - dldiv.inject(container) - - pbs[dl.id] = new dwProgressBar({ - container: $(dldiv), - startPercentage: 0, - speed: 1000, - id: dl.id, - boxID: 'box', - percentageID: 'perc', - displayText: true, - displayID: 'boxtext' - }); - - new Element('div', { - 'class': 'dlsize', - 'html': Math.round((dl.size - dl.kbleft) / 1024) + "/" + Math.round(dl.size / 1024) + " MB" - }).inject(dldiv) - - new Element('div', { - 'class': 'dlspeed', - 'html': Math.round(dl.speed) + " kb/s" - }).inject(dldiv) - - new Element('div', { - 'class': 'dltime', - 'html': dl.eta - }).inject(dldiv) - - //dldiv.dissolve({duration : 0}) - - dldiv.reveal() - - } - }) - - dls.each(function(id, index){ - - if (data.ids.contains(id)){ - - }else{ - - //$("dl"+id).reveal() - dls.erase(id) - $('dl'+id).nix() - - } - - }) - -} - -window.addEvent('domready', function(){ - - /* -//create the progress bar for example 1 -pb = new dwProgressBar({ - container: $$('.level1 p')[0], - startPercentage: 25, - speed: 1000, - id: 1, - boxID: 'box', - percentageID: 'perc', - displayText: true, - displayID: 'boxtext' -}); -*/ - - req.startTimer(); - - -}); - - - diff --git a/module/web/static/default/progress-bar-back.gif b/module/web/static/default/progress-bar-back.gif Binary files differdeleted file mode 100644 index 0c8f68211..000000000 --- a/module/web/static/default/progress-bar-back.gif +++ /dev/null diff --git a/module/web/static/default/progress-bar.gif b/module/web/static/default/progress-bar.gif Binary files differdeleted file mode 100644 index 746f77175..000000000 --- a/module/web/static/default/progress-bar.gif +++ /dev/null diff --git a/module/web/static/window.css b/module/web/static/window.css deleted file mode 100644 index aaccae082..000000000 --- a/module/web/static/window.css +++ /dev/null @@ -1,17 +0,0 @@ -.SWclearfix:after {content: "."; display: block; height: 0; clear: both; visibility: hidden;} -.SWclearfix {display: inline-table;} -* html .SWclearfix {height: 1%;} -.SWclearfix {display: block;} - -div.DefaultStickyWin div.body{font-family:verdana; font-size:11px; line-height: 13px;} -div.DefaultStickyWin div.top_ul{background:url(/static/window/full.png) top left no-repeat; height:30px; width:15px; float:left} -div.DefaultStickyWin div.top_ur{position:relative; left:0px !important; left:-4px; background:url(/static/window/full.png) top right !important; height:30px; margin:0px 0px 0px 15px !important; margin-right:-4px; padding:0px} -div.DefaultStickyWin h1.caption{clear: none !important; margin:0px !important; overflow: hidden; padding:0 !important; font-weight:bold; color:#555; font-size:14px !important; position:relative; top:8px !important; left:5px !important; float: left; height: 22px !important;} -div.DefaultStickyWin div.middle, div.DefaultStickyWin div.closeBody {background:url(/static/window/body.png) top left repeat-y; margin:0px 20px 0px 0px !important; margin-bottom: -3px; position: relative; top: 0px !important; top: -3px;} -div.DefaultStickyWin div.body{background:url(/static/window/body.png) top right repeat-y; padding:8px 30px 8px 0px !important; margin-left:5px !important; position:relative; right:-20px !important;} -div.DefaultStickyWin div.bottom{clear:both}div.DefaultStickyWin div.bottom_ll{background:url(/static/window/full.png) bottom left no-repeat; width:15px; height:15px; float:left} -div.DefaultStickyWin div.bottom_lr{background:url(/static/window/full.png) bottom right; position:relative; left:0px !important; left:-4px; margin:0px 0px 0px 15px !important; margin-right:-4px; height:15px} -div.DefaultStickyWin div.closeButtons{text-align: center; background:url(/static/window/body.png) top right repeat-y; padding: 0px 30px 8px 0px; margin-left:5px; position:relative; right:-20px} -div.DefaultStickyWin a.button:hover{background:url(/static/window/big_button_over.gif) repeat-x}div.DefaultStickyWin a.button {background:url(/static/window/big_button.gif) repeat-x; margin: 2px 8px 2px 8px; padding: 2px 12px; cursor:pointer; border: 1px solid #999 !important; text-decoration:none; color: #000 !important;} -div.DefaultStickyWin div.closeButton{width:13px; height:13px; background:url(/static/window/closebtn.gif) no-repeat; position: absolute; right: 0px; margin:10px 15px 0px 0px !important; cursor:pointer;top:0px} -div.DefaultStickyWin div.dragHandle { width: 11px; height: 25px; position: relative; top: 5px; left: -3px; cursor: move; background: url(/static/window/drag_corner.gif); float: left;}
\ No newline at end of file diff --git a/module/web/templates/default.tpl b/module/web/templates/default.tpl deleted file mode 100644 index 13be260b6..000000000 --- a/module/web/templates/default.tpl +++ /dev/null @@ -1,230 +0,0 @@ -%header = 'pyLoad Webinterface' -%js = ['mootools-1.2.3-core.js','mootools-1.2.3.1-more.js'] - -%if page== "home": js.append('default/home.js') -%end -%if page== "loggedin": red=True -%else: red=False -%end -%if page != "loggedin" and page != "login": js.append('default/status.js') -%end - -%include header title=header, use_js=js, use_css=['default.css','window.css'], redirect=red - -%include window id="addlinks", width=400, caption="Add links", body="<textarea rows=10 style='width: 345px;' id='linkarea'></textarea>", button="Add" - -<a class="anchor" name="top" id="top"></a> - -<div id="head-panel"> - - - <div id="head-search-and-login"> - -%if page != "login": - <img src="static/default/head-login.png" alt="User:" style="vertical-align:middle; margin:2px" /><span style="padding-right: 2px;">{{user}}</span> - <ul id="user-actions"> - <li><a href="/logout" class="action logout" rel="nofollow">Logout</a></li> - <li></li> - <li></li> - </ul> -%else: - <span style="padding-right: 2px;">Please Login!</span> - - -%end - </div> - - <a href="/"><img id="head-logo" src="/static/default/pyload-logo-edited3.5-new-font-small.png" alt="pyLoad" /></a> - - <div id="head-menu"> - <ul> - <li class=" - %if page == "home" or page == "login": - selected - %endif - "><a href="/" title=""><img src="static/default/head-menu-home.png" alt="" /> Home</a></li> - <li class=" - %if page == "queue": - selected - %endif - "><a href="/queue" title=""><img src="static/default/head-menu-download.png" alt="" /> Queue</a></li> - <li class=" - %if page == "downloads": - selected - %endif - "><a href="/downloads" title=""><img src="static/default/head-menu-development.png" alt="" /> Downloads</a></li> - <li class="right"><a href="/logs" class="action index" accesskey="x" rel="nofollow"><img src="static/default/head-menu-index.png" alt="" />Logs</a></li> </ul> - </div> - - <div style="clear:both;"></div> -</div> - -<ul id="page-actions"> - <li><a href="" class="action revisions" accesskey="o" rel="nofollow">Reload page</a></li> - -</ul> - -<div id="body-wrapper" class="dokuwiki"> - - <div id="content" lang="en" dir="ltr"> - - -<h1><a name="pyload_download_manager_for_1_click_hoster" id="pyload_download_manager_for_1_click_hoster">pyLoad — Webinterface</a> -</h1> - - -%if page != "loggedin" and page != "login": - -<div id="statusbar"> - <div id="status" style="float: left;padding: 8px;"> -Status: -</div> - <div id="speed" style="float: left;padding: 8px"> -Speed: -</div> - - <div id="queue" style="float: left;padding: 8px"> -Files in queue: -</div> - -<div style="padding-top:2px"> - -<div style="background-image:url(static/default/Button-Play.png);width:32px;height:32px;float:left"></div> -<div class= "statusbutton" style="background-image:url(static/default/Button-Play-grey.png); visibility: visible; opacity: 0.01"></div> -<div style="background-image:url(static/default/Button-Pause.png);width:32px;height:32px;float:left"></div> -<div class= "statusbutton" style="background-image:url(static/default/Button-Pause-grey.png); visibility: visible; opacity: 0.01"></div> -<div style="background-image:url(static/default/Button-Add.png);width:32px;height:32px;float:left"></div> -<div class= "statusbutton" style="background-image:url(static/default/Button-Add-grey.png); visibility: visible; opacity: 0.01"></div> - - -</div> - -</div> - -%end - - -<br> - -<div class="level1" style="clear:both"> - -%if page == "login": - -</div> -<div class="centeralign"> -<form action="" method="post" accept-charset="utf-8" id="login"><div class="no"> -<input type="hidden" name="do" value="login" /><fieldset ><legend>Login</legend> -<label class="block" for="focus__this"><span>Username</span> <input type="text" id="focus__this" name="u" class="edit" /></label><br /> -<label class="block"><span>Password</span> <input type="password" name="p" class="edit" /></label><br /> -<input type="submit" value="Login" class="button" /> -</fieldset> -</div></form> -</div> -<br> - -%elif page== "home": -<h2>Downloads:</h2> - -<div id="dlcontainer"> - -% for link in links: - - -<div class="download" id="dl{{link['id']}}" style="color: #000"> -<p></p> - -<b>{{link['name']}}</b> -<br> -<script type="text/javascript"> -pbs[{{link['id']}}] = new dwProgressBar({ - container: document.id('dl{{link['id']}}'), - startPercentage: {{link['percent']}}, - speed: 1000, - id: {{link['id']}}, - boxID: 'box', - percentageID: 'perc', - displayText: true, - displayID: 'boxtext' -}); - -dls.push({{link['id']}}) - -</script> - - -<div class="dlsize"> -{{int((link['size'] - link['kbleft']) / 1024)}}/{{int(link['size']) / 1024}} MB -</div> - - -<div class="dlspeed"> -{{int(link['speed'])}} kb/s -</div> - - -<div class="dltime"> -{{link['eta']}} -</div> - - -</div> - - -<script type="text/javascript"> -$$("#dl{{link['id']}}")[0].hover(function(e){ - -this.morph({'color': '#f00'}); - -}, function(e){ - -this.morph({'color': '#000'}); - -}); - - -</script> - - -%end - -</div> - - -%elif page=="loggedin": - - -<b>You were successfully logged in</b> - -%elif page=="queue": - -<ul> - -%for id in links['order']: - -<li>{{links[id].url}}</li> - -%end - -</ul> - -Currently in Development - -%elif page=="downloads": - -Currently in Development - - -%end - <hr style="clear: both;" /> - -<div id="foot">© 2008-2009 the pyLoad Team - - <a href="#top" class="action top" accesskey="x"><span>Back to top</span></a><br /> - <!--<div class="breadcrumbs"></div>--> - - -</div> - -</div> - -%include footer use_js=[]
\ No newline at end of file diff --git a/module/web/templates/default/add.html b/module/web/templates/default/add.html new file mode 100644 index 000000000..525cb99bd --- /dev/null +++ b/module/web/templates/default/add.html @@ -0,0 +1,12 @@ +{% extends 'default/base.html' %}
+
+{% block subtitle %}
+Add Links / Container
+{% endblock %}
+
+
+
+{% block content %}
+<textarea rows="5" style=" width: 100%;"></textarea>
+<input type="file" />
+{% endblock %}
\ No newline at end of file diff --git a/module/web/templates/default/base.html b/module/web/templates/default/base.html new file mode 100644 index 000000000..2a2490088 --- /dev/null +++ b/module/web/templates/default/base.html @@ -0,0 +1,213 @@ +<?xml version="1.0" ?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
+<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/default.css">
+<!--<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/jquery-ui-1.7.2.custom.css">-->
+<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/window.css">
+<!--<script src="{{ MEDIA_URL }}js/jquery-1.3.2.min.js"></script>-->
+<script src="{{ MEDIA_URL }}js/sprintf.js"></script>
+<script src="{{ MEDIA_URL }}js/funktions.js"></script>
+<script src="{{ MEDIA_URL }}js/mootools-1.2.4-core.js"></script>
+<script src="{{ MEDIA_URL }}js/mootools-1.2.4.2-more.js"></script>
+
+<!--<script src="{{ MEDIA_URL }}js/jquery.progressbar.js"></script>-->
+<!--<script src="{{ MEDIA_URL }}js/jquery.form.js"></script>-->
+
+<title>{% block title %}pyLoad Webinterface{% endblock %}</title>
+
+<script type="text/javascript">
+var add_bg,add_box
+document.addEvent("domready", function(){
+
+ add_bg = new Fx.Tween($('add_bg'));
+ add_box = new Fx.Tween($('add_box'));
+
+ $('add_form').onsubmit=function() {
+ $('add_form').target = 'upload_target'; //'upload_target' is the name of the iframe
+ out();
+ }
+
+ $('add_reset').addEvent('click', function(){
+ out();
+ });
+
+ var jsonStatus = new Request.JSON({
+ url: "/json/status",
+ onSuccess: LoadJsonToContent,
+ secure: false,
+ async: true,
+ initialDelay: 0,
+ delay: 4000,
+ limit: 30000
+ })
+
+ $('action_play').addEvent('click', function(){
+ new Request({method: 'get', url: '/json/unpause'}).send();
+ });
+
+
+ $('action_cancel').addEvent('click', function(){
+ new Request({method: 'get', url: '/json/cancel'}).send();
+ });
+
+
+ $('action_stop').addEvent('click', function(){
+ new Request({method: 'get', url: '/json/pause'}).send();
+ });
+
+ jsonStatus.startTimer();
+
+});
+
+/*function UpdateLinks( SetInver, index )
+{
+ $("#aktiv_percent").text(parseInt($("#aktiv_percent").text)+1)
+ setTimeout( UpdateLinks( SetInver, index+1 ), SetInver[index]*1000);
+}*/
+
+function LoadJsonToContent(data)
+{
+ $("speed").set('text', Math.round(data.speed*100)/100);
+ $("aktiv").set('text', data.activ);
+ $("aktiv_from").set('text', data.queue);
+}
+function show(){
+ add_bg.set('opacity', 0);
+ $("add_bg").setStyle('display', 'block');
+ add_bg.start('opacity',0.8);
+
+ add_box.set('opacity', 0)
+ $("add_box").setStyle('display', 'block');
+ add_box.start('opacity',1)
+}
+
+function out(){
+ add_bg.start('opacity',0).chain(function(){
+ $('add_bg').setStyle('display', 'none');
+ });
+
+ add_box.start('opacity',0).chain(function(){
+ $('add_box').setStyle('display', 'none');
+ });
+}
+
+function AddBox()
+{
+ if ($("add_box").getStyle("display") == "hidden" || $("add_box").getStyle("display") == "none" || $("add_box").getStyle("opacity" == 0))
+ {
+ show();
+ }
+ else
+ {
+ out();
+ }
+}
+
+</script>
+
+{% block head %}
+{% endblock %}
+</head>
+
+<a class="anchor" name="top" id="top"></a>
+
+<div id="head-panel">
+
+<div id="head-search-and-login">
+
+{% if user.is_authenticated %}
+<img src="{{ MEDIA_URL }}img/head-login.png" alt="User:" style="vertical-align:middle; margin:2px" /><span style="padding-right: 2px;">{{user.username}}</span>
+ <ul id="user-actions">
+ <li><a href="/logout" class="action logout" rel="nofollow">Logout</a></li>
+ {% if user.is_staff %}
+ <li><a href="/admin" class="action profile" rel="nofollow">Administrate</a></li>
+ {% endif %}
+ <li></li>
+ <li></li>
+ </ul>
+{% else %}
+ <span style="padding-right: 2px;">Please Login!</span>
+{% endif %}
+
+ </div>
+
+ <a href="/"><img id="head-logo" src="{{ MEDIA_URL }}img/pyload-logo-edited3.5-new-font-small.png" alt="pyLoad" /></a>
+
+ <div id="head-menu">
+ <ul>
+
+ {% block menu %}
+ <li class="selected">
+ <a href="/" title=""><img src="{{ MEDIA_URL }}img/head-menu-home.png" alt="" /> Home</a>
+ </li>
+ <li>
+ <a href="/queue/" title=""><img src="{{ MEDIA_URL }}img/head-menu-download.png" alt="" /> Queue</a></li>
+ <li>
+ <a href="/downloads/" title=""><img src="{{ MEDIA_URL }}img/head-menu-development.png" alt="" /> Downloads</a></li>
+ <li class="right">
+ <a href="/logs/" class="action index" accesskey="x" rel="nofollow"><img src="{{ MEDIA_URL }}img/head-menu-index.png" alt="" />Logs</a>
+ </li>
+ {% endblock %}
+
+ </ul>
+ </div>
+
+ <div style="clear:both;"></div>
+</div>
+
+{% if perms.pyload.can_change_status %}
+<ul id="page-actions2">
+ <li id="action_play"><a href="#" class="action play" accesskey="o" rel="nofollow">Play</a></li>
+ <li id="action_cancel"><a href="#" class="action cancel" accesskey="o" rel="nofollow">Cancel</a></li>
+ <li id="action_stop"><a href="#" class="action stop" accesskey="o" rel="nofollow">Stop</a></li>
+ <li id="action_add"><a href="javascript:AddBox();" class="action stop" accesskey="o" rel="nofollow" >Add</a></li>
+</ul>
+{% endif %}
+
+{% if perms.pyload.can_see_dl %}
+<ul id="page-actions">
+ <li><a class="action backlink">Speed: <b id="speed">{{ status.speed }}</b> kb/s</a></li>
+ <li><a class="action cog">Active: <b id="aktiv">{{ status.activ }}</b> / <b id="aktiv_from">{{ status.queue }}</b></a></li>
+ <li><a href="" class="action revisions" accesskey="o" rel="nofollow">Reload page</a></li>
+</ul><br />
+{% endif %}
+
+<div id="body-wrapper" class="dokuwiki">
+
+<div id="content" lang="en" dir="ltr">
+
+<h1>{% block subtitle %}pyLoad - Webinterface{% endblock %}</h1>
+
+{% block statusbar %}
+{% endblock %}
+
+
+<br>
+
+<div class="level1" style="clear:both">
+</div>
+
+{% for message in messages %}
+ <b><p>{{message}}</p></b>
+{% endfor %}
+
+{% block content %}
+{% endblock content %}
+
+ <hr style="clear: both;" />
+
+<div id="foot">© 2008-2010 the pyLoad Team
+
+ <a href="#top" class="action top" accesskey="x"><span>Back to top</span></a><br />
+ <!--<div class="breadcrumbs"></div>-->
+
+
+</div>
+</div>
+
+{% include "default/window.html" %}
+<body>
diff --git a/module/web/templates/default/downloads.html b/module/web/templates/default/downloads.html new file mode 100644 index 000000000..3f07bec47 --- /dev/null +++ b/module/web/templates/default/downloads.html @@ -0,0 +1,44 @@ +{% extends 'default/base.html' %} + +{% block title %}Downloads - {{block.super}} {% endblock %} + +{% block menu %} +<li> + <a href="{% url home %}" title=""><img src="{{ MEDIA_URL }}img/head-menu-home.png" alt="" /> Home</a> +</li> +<li> + <a href="{% url queue %}" title=""><img src="{{ MEDIA_URL }}img/head-menu-download.png" alt="" /> Queue</a></li> +<li class="selected"> + <a href="{% url downloads %}" title=""><img src="{{ MEDIA_URL }}img/head-menu-development.png" alt="" /> Downloads</a></li> +<li class="right"> + <a href="{% url logs %}" class="action index" accesskey="x" rel="nofollow"><img src="{{ MEDIA_URL }}img/head-menu-index.png" alt="" />Logs</a> +</li> +{% endblock %} + +{% block subtitle %} +Downloads +{% endblock %} + +{% block content %} + +It's recommend not to download Files bigger than ~10MB from here. + +<ul> + {% for folder in files.folder %} + <li> + {{ folder.name }} + <ul> + {% for file in folder.files %} + <li><a href='{% url download 'get/' %}{{ folder.name }}/{{ file }}'>{{ file }}</a></li> + {% endfor %} + </ul> + </li> + {% endfor %} + + {% for file in files.files %} + <li> <a href={% url download 'get/' %}{{ file }}>{{ file }}</a></li> + {% endfor %} + +</ul> + +{% endblock %}
\ No newline at end of file diff --git a/module/web/templates/default/home.html b/module/web/templates/default/home.html new file mode 100644 index 000000000..ab2135800 --- /dev/null +++ b/module/web/templates/default/home.html @@ -0,0 +1,233 @@ +{% extends 'default/base.html' %}
+
+{% block head %}
+
+<script type="text/javascript">
+
+/*function UpdateLinks( SetInver, index )
+{
+ $("#aktiv_percent").text(parseInt($("#aktiv_percent").text)+1)
+ setTimeout( UpdateLinks( SetInver, index+1 ), SetInver[index]*1000);
+}*/
+var em;
+
+document.addEvent("domready", function(){
+ em = new EntryManager();
+});
+
+var EntryManager = new Class({
+ initialize: function(){
+ this.json = new Request.JSON({
+ url: "json/links",
+ secure: false,
+ async: true,
+ onSuccess: this.update.bind(this),
+ initialDelay: 0,
+ delay: 2500,
+ limit: 30000
+ });
+
+ this.ids = [{% for link in content %}
+ {% if forloop.last %}
+ {{ link.id }}
+ {% else %}
+ {{ link.id }},
+ {% endif %}
+ {% endfor %}];
+
+ this.entries = [];
+ this.container = $('LinksAktiv');
+
+ this.parseFromContent();
+
+ this.json.startTimer();
+ },
+ parseFromContent: function(){
+ this.ids.each(function(id,index){
+ entry = new LinkEntry(id)
+ entry.parse()
+ this.entries.push(entry)
+ }, this);
+ },
+ update: function(data){
+
+ try{
+ this.ids = this.entries.map(function(item){
+ return item.id
+ });
+
+ this.ids.filter(function(id){
+ return !this.ids.contains(id)
+ },data).each(function(id){
+ index = this.ids.indexOf(id);
+ this.entries[index].remove();
+ this.entries = this.entries.filter(function(item){return item.id != this},id);
+ this.ids = this.ids.erase(id)
+ }, this);
+
+ data.links.each(function(link, i){
+ if (this.ids.contains(link.id)){
+
+ index = this.ids.indexOf(link.id)
+ this.entries[index].update(link)
+
+ }else{
+ entry = new LinkEntry(link.id);
+ entry.insert(link);
+ this.entries.push(entry);
+ this.ids.push(link.id);
+ this.container.adopt(entry.elements.tr,entry.elements.pgbTr);
+ entry.fade.start('opacity', 1);
+ entry.fadeBar.start('opacity', 1);
+
+ }
+ }, this)
+ }catch(e){alert(e)}
+ }
+})
+
+
+var LinkEntry = new Class({
+ initialize: function(id){
+ this.id = id
+ },
+ parse: function(){
+ this.elements = {
+ tr: $("link_{id}".substitute({id: this.id})),
+ name: $("link_{id}_name".substitute({id: this.id})),
+ status: $("link_{id}_status".substitute({id: this.id})),
+ info: $("link_{id}_info".substitute({id: this.id})),
+ kbleft: $("link_{id}_kbleft".substitute({id: this.id})),
+ percent: $("link_{id}_percent".substitute({id: this.id})),
+ remove: $("link_{id}_remove".substitute({id: this.id})),
+ pgbTr: $("link_{id}_pgb_tr".substitute({id: this.id})),
+ pgb: $("link_{id}_pgb".substitute({id: this.id}))
+ }
+ this.initEffects();
+ },
+ insert: function(item){
+ try{
+ info = SecToRightTime(item.eta) +' @ '+ Math.round(item.speed*100)/100+' kb/s' ;
+
+ this.elements = {
+ tr: new Element('tr', {
+ 'html': '',
+ 'styles':{
+ 'opacity': 0
+ }
+ }),
+ name: new Element('td', {
+ 'html': item.name
+ }),
+ status: new Element('td', {
+ 'html': item.status
+ }),
+ info: new Element('td', {
+ 'html': info
+ }),
+ kbleft: new Element('td', {
+ 'html': HumanFileSize(item.size)
+ }),
+ percent: new Element('font', {
+ 'html': item.percent+ '% / '+ HumanFileSize(item.size-item.kbleft)
+ }),
+ remove: new Element('img',{
+ 'html': '',
+ 'src': 'media/default/img/control_cancel.png',
+ 'styles':{
+ 'vertical-align': 'middle',
+ 'margin-right': '-20px',
+ 'margin-left': '5px',
+ 'margin-top': '-2px',
+ 'cursor': 'pointer'
+ }
+ }),
+ pgbTr: new Element('tr', {
+ 'html':''
+ }),
+ pgb: new Element('div', {
+ 'html': ' ',
+ 'styles':{
+ 'height': '4px',
+ 'width': item.percent+'%',
+ 'background-color': '#ddd',
+ }
+ })
+ }
+
+ this.elements.tr.adopt(this.elements.name,this.elements.status,this.elements.info,this.elements.kbleft,new Element('td').adopt(this.elements.percent,this.elements.remove));
+ this.elements.pgbTr.adopt(new Element('td',{'colspan':5}).adopt(this.elements.pgb));
+ this.initEffects();
+ }catch(e){
+ alert(e)
+ }
+ },
+ initEffects: function(){
+ this.bar = new Fx.Morph(this.elements.pgb, {unit: '%', duration: 5000, link: 'link', fps:30});
+ this.fade = new Fx.Tween(this.elements.tr);
+ this.fadeBar = new Fx.Tween(this.elements.pgbTr);
+
+ this.elements.remove.addEvent('click', function(){
+ new Request({method: 'get', url: '/json/abort_link/'+this.id}).send();
+ }.bind(this));
+
+ },
+ update: function(item){
+ this.elements.name.set('text', item.name);
+ this.elements.status.set('text', item.status);
+ this.elements.info.set('text', SecToRightTime(item.eta)+' @ '+Math.round(item.speed*100)/100+' kb/s');
+ this.elements.kbleft.set('text', HumanFileSize(item.size));
+ this.elements.percent.set('text', item.percent+ '% / '+ HumanFileSize(item.size-item.kbleft));
+ this.bar.start({
+ 'width': item.percent,
+ 'background-color': [Math.round(120/100*item.percent),100,100].hsbToRgb().rgbToHex()
+ });
+ },
+ remove: function(){
+ this.fade.start('opacity',0).chain(function(){this.elements.tr.dispose();}.bind(this));
+ this.fadeBar.start('opacity',0).chain(function(){this.elements.pgbTr.dispose();}.bind(this));
+
+ }
+ });
+</script>
+
+{% endblock %}
+
+{% block subtitle %}
+Active Downloads
+{% endblock %}
+
+{% block content %}
+<table width="100%" class="queue">
+ <thead>
+ <tr class="header">
+ <th>Name</th>
+ <th>Status</th>
+ <th>Infos</th>
+ <th>Size</th>
+ <th>Progress</th>
+ </tr>
+ </thead>
+ <tbody id="LinksAktiv">
+
+ {% for link in content %}
+ <tr id="link_{{ link.id }}">
+ <td id="link_{{ link.id }}_name">{{ link.name }}</td>
+ <td id="link_{{ link.id }}_status">{{ link.status }}</td>
+ <td id="link_{{ link.id }}_info">{{ link.info }}</td>
+ <td id="link_{{ link.id }}_kbleft">{{ link.size }}</td>
+ <td>
+ <font id="link_{{ link.id }}_percent">{{ link.percent }}% /{{ link.kbleft }}</font>
+ <img id="link_{{ link.id }}_remove" style="vertical-align: middle; margin-right: -20px; margin-left: 5px; margin-top: -2px; cursor:pointer;" src="media/default/img/control_cancel.png"/>
+ </td>
+ </tr>
+ <tr id="link_{{ link.id }}_pgb_tr">
+ <td colspan="5">
+ <div id="link_{{ link.id }}_pgb" class="progressBar" style="background-color: green; height:4px; width: {{ link.percent }}%;"> </div>
+ </td>
+ </tr>
+ {% endfor %}
+
+ <tbody>
+</table>
+{% endblock %}
\ No newline at end of file diff --git a/module/web/templates/default/login.html b/module/web/templates/default/login.html new file mode 100644 index 000000000..851802c4f --- /dev/null +++ b/module/web/templates/default/login.html @@ -0,0 +1,35 @@ +{% extends 'default/base.html' %} + +{% block title %}Login - {{block.super}} {% endblock %} + +{% block content %} + +<div class="centeralign"> +<form action="" method="post" accept-charset="utf-8" id="login"> + <div class="no"> + <input type="hidden" name="do" value="login" /> + <fieldset> + <legend>Login</legend> + <label class="block" for="focus__this"> + <span>Username</span> + {{ form.username }} + </label> + <br /> + <label class="block"> + <span>Password</span> + {{ form.password }} + </label> + <br /> + <input type="submit" value="Login" class="button" /> + </fieldset> + </div> +</form> + +{% if form.errors %} +<p>Your username and password didn't match. Please try again.</p> +{% endif %} + +</div> +<br> + +{% endblock %}
\ No newline at end of file diff --git a/module/web/templates/default/logout.html b/module/web/templates/default/logout.html new file mode 100644 index 000000000..4d00bf6d5 --- /dev/null +++ b/module/web/templates/default/logout.html @@ -0,0 +1,9 @@ +{% extends 'default/base.html' %} + +{% block head %} +<meta http-equiv="refresh" content="3; url=/"> +{% endblock %} + +{% block content %} +<p><b>You were successfully logged out.</b></p> +{% endblock %}
\ No newline at end of file diff --git a/module/web/templates/default/logs.html b/module/web/templates/default/logs.html new file mode 100644 index 000000000..f9b0504d9 --- /dev/null +++ b/module/web/templates/default/logs.html @@ -0,0 +1,25 @@ +{% extends 'default/base.html' %} + +{% block title %}Logs - {{block.super}} {% endblock %} + +{% block menu %} +<li> + <a href="{% url home %}" title=""><img src="{{ MEDIA_URL }}img/head-menu-home.png" alt="" /> Home</a> +</li> +<li> + <a href="{% url queue %}" title=""><img src="{{ MEDIA_URL }}img/head-menu-download.png" alt="" /> Queue</a></li> +<li> + <a href="{% url downloads %}" title=""><img src="{{ MEDIA_URL }}img/head-menu-development.png" alt="" /> Downloads</a></li> +<li class="right" class="selected"> + <a href="{% url logs %}" class="action index" accesskey="x" rel="nofollow"><img src="{{ MEDIA_URL }}img/head-menu-index.png" alt="" />Logs</a> +</li> +{% endblock %} + +{% block content %} +<ul> +{% for line in log %} + <li>{{line.line}}: {{line.content}}</li> +{% endfor %} +</ul> +<a href="{% url logs %}"><< Start</a> <a href="{% url logs prev %}">< prev</a> <a href="{% url logs next %}">next ></a> +{% endblock %}
\ No newline at end of file diff --git a/module/web/templates/default/queue.html b/module/web/templates/default/queue.html new file mode 100644 index 000000000..aa21390a0 --- /dev/null +++ b/module/web/templates/default/queue.html @@ -0,0 +1,125 @@ +{% extends 'default/base.html' %}
+
+{% block head %}
+<script type="text/javascript">
+
+document.addEvent("domready", function(){
+ $$('.package').each(function(item){
+ id = item.get('id').match(/[0-9]+/)
+
+ imgs = item.getElements('img');
+ imgs[0].addEvent('click', function(e){
+ new Request({
+ method: 'get',
+ url: '/json/remove_package/'+this,
+ onSuccess: function(){
+ $('package_'+this).nix()
+ }.bind(this)
+ }).send();
+ e.stop();
+ }.bind(id));
+
+ imgs[1].addEvent('click', function(e){
+ new Request({
+ method: 'get',
+ url: '/json/restart_package/'+this,
+ onSuccess: function(){
+ $('package_'+this).nix()
+ }.bind(this)
+ }).send();
+ e.stop();
+ }.bind(id));
+
+
+ item.getElement('.packagename').addEvent('click', function(){
+
+ child = item.getElement('.children')
+ if (child.getStyle('display') == "block"){
+ child.dissolve();
+ }else{
+ child.reveal();
+ }
+ }.bind(item));
+
+
+ item.getElements('.child').each(function(child){
+ id = child.get('id').match(/[0-9]+/)
+ imgs = child.getElements('.child_secrow img')
+ imgs[0].addEvent('click', function(e){
+ new Request({
+ method: 'get',
+ url: '/json/remove_link/'+this,
+ onSuccess: function(){
+ $('file_'+this).nix()
+ }.bind(this)
+ }).send();
+ }.bind(id));
+
+ imgs[1].addEvent('click', function(e){
+ new Request({
+ method: 'get',
+ url: '/json/restart_link/'+this,
+ onSuccess: function(){
+ $('file_'+this).nix()
+ }.bind(this)
+ }).send();
+ }.bind(id));
+ });
+
+ })
+});
+</script>
+{% endblock %}
+
+{% block title %}Queue - {{block.super}} {% endblock %}
+
+{% block menu %}
+<li> <a href="{% url home %}" title=""><img src="{{ MEDIA_URL }}img/head-menu-home.png" alt="" /> Home</a> </li>
+<li class="selected"> <a href="{% url queue %}" title=""><img src="{{ MEDIA_URL }}img/head-menu-download.png" alt="" /> Queue</a></li>
+<li> <a href="{% url downloads %}" title=""><img src="{{ MEDIA_URL }}img/head-menu-development.png" alt="" /> Downloads</a></li>
+<li class="right"> <a href="{% url logs %}" class="action index" accesskey="x" rel="nofollow"><img src="{{ MEDIA_URL }}img/head-menu-index.png" alt="" />Logs</a> </li>
+{% endblock %}
+
+{% block content %}
+{% for package in content %}
+<div id="package_{{package.id}}" class="package">
+ <div class="packagename" style="cursor: pointer;">
+ {{ package.package_name }}
+
+ <img width="12px" height="12px" src="{{ MEDIA_URL }}img/delete.png" />
+
+ <img style="margin-left: -10px" height="12px" src="{{ MEDIA_URL }}img/arrow_refresh.png" />
+ </div>
+ <div id="children_{{package.id}}" style="display: none;" class="children">
+ {% for child in package.children %}
+ <div class="child" id="file_{{child.id}}">
+ <span class="child_status">
+ <img src="/media/default/img/status_{{child.status_type}}.png" style="width: 12px; height:12px;"/>
+ </span>
+ <span style="font-size: 15px">{{ child.filename }}</span><br />
+ <div class="child_secrow">
+ <span class="child_status">{{ child.status_type }}</span>{{child.status_error}}
+ <span class="child_status">{{ child.size }} KB</span>
+ <span class="child_status">{{ child.plugin }}</span>
+ <span class="child_status">Folder: {{child.folder}}</span>
+
+ <img style="cursor: pointer;" width="10px" height="10px" src="{{ MEDIA_URL }}img/delete.png" />
+
+ <img style="cursor: pointer;margin-left: -4px" width="10px" height="10px" src="{{ MEDIA_URL }}img/arrow_refresh.png" />
+ </div>
+ </div>
+ {% endfor %}
+ </div>
+</div>
+{% endfor %}
+<!--table >
+ <tr>
+ <td colspan="3"><h1>!Paketname!</h1></td>
+ </tr>
+ <tr>
+ <td><h2>test.png</h2></td>
+ <td>loading</td>
+ <td><a href="/"><img id="button" src="/img/button-delete.gif" alt="delete" /></a><a href="/"><img id="button" src="/img/button-unpause.gif" alt="unpause" /></a></td>
+ </tr>
+</table-->
+{% endblock %}
\ No newline at end of file diff --git a/module/web/templates/default/window.html b/module/web/templates/default/window.html new file mode 100644 index 000000000..7e5c249e6 --- /dev/null +++ b/module/web/templates/default/window.html @@ -0,0 +1,33 @@ +<iframe id="upload_target" name="upload_target" src="" style="display: none; width:0;height:0"></iframe>
+<div id="add_bg" style="filter:alpha(opacity:80);KHTMLOpacity:0.80;MozOpacity:0.80;opacity:0.80; background:#000; width:100%; height: 100%; position:absolute; top:0px; left:0px; display:none;"> </div>
+<!--<div id="add_box" style="left:50%; top:200px; margin-left: -450px; width: 900px; position: absolute; background: #FFF; padding: 10px 10px 10px 10px; display:none;">-->
+
+ <!--<div style="width: 900px; text-align: right;"><b onclick="AddBox();">[Close]</b></div>-->
+<div id="add_box" class="myform">
+<form id="add_form" action="/json/add_package" method="POST" enctype="multipart/form-data">
+<h1>Add Package</h1>
+<p>Paste your links or upload a container.</p>
+<label>Name
+<span class="small">The name of the new package.</span>
+</label>
+<input name="add_name" type="text" size="20" />
+
+<label>Links
+<span class="small">Paste your links here</span>
+</label>
+<textarea rows="5" name="add_links" id="add_links"></textarea>
+
+<label>File
+<span class="small">Upload a container.</span>
+</label>
+<input type="file" name="add_file" id="add_file"/>
+
+<button type="submit">Add Package</button>
+<button id="add_reset" style="margin-left:0px;" type="reset">Reset</button>
+<div class="spacer"></div>
+
+</form>
+
+</div>
+
+</div>
diff --git a/module/web/templates/footer.tpl b/module/web/templates/footer.tpl deleted file mode 100644 index a59b414bf..000000000 --- a/module/web/templates/footer.tpl +++ /dev/null @@ -1,6 +0,0 @@ -%for item in use_js: -<script type="text/javascript" src="static/{{item}}"></script> -%end - -</body> -</html> diff --git a/module/web/templates/header.tpl b/module/web/templates/header.tpl deleted file mode 100644 index 22c252e3c..000000000 --- a/module/web/templates/header.tpl +++ /dev/null @@ -1,24 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" - "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> - -%for item in use_js: -<script type="text/javascript" src="static/{{item}}"></script> -%end - -%for item in use_css: -<link rel="stylesheet" type="text/css" href="static/{{item}}"> -%end - -<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> - -%if redirect: -<meta http-equiv="refresh" content="3; url=/"> -%end - -<title>{{title}}</title> - -</head> -<body> diff --git a/module/web/templates/window.tpl b/module/web/templates/window.tpl deleted file mode 100644 index f756c4352..000000000 --- a/module/web/templates/window.tpl +++ /dev/null @@ -1,28 +0,0 @@ -<div id="{{id}}" class="StickyWinInstance SWclearfix" style="overflow: visible;visibility: visible;display: none; position: absolute; z-index: 10000; opacity: 1; left: 0px; top: 0px;"> -<div class="DefaultStickyWin" style="width: {{width}}px;"> - -<div class="top"> -<div class="top_ul"></div> -<div class="top_ur"><h1 class="caption dragHandle">{{caption}}</h1> -</div></div> - -<div class="middle"> -<div class="body">{{body}} -</div></div> - -<div class="closeBody"> -<div class="closeButtons"> -<a class="closeSticky button" id="bt{{button}}">{{button}}</a><a class="closeSticky button">Close</a> -</div> -</div> - -<div class="bottom"> -<div class="bottom_ll"> -</div> - -<div class="bottom_lr"></div> -</div> -<div class="closeButton closeSticky"></div> - -</div> -</div>
\ No newline at end of file diff --git a/module/web/urls.py b/module/web/urls.py new file mode 100644 index 000000000..1392b827a --- /dev/null +++ b/module/web/urls.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +from django.conf.urls.defaults import * +from django.contrib import admin +from django.conf import settings + + +admin.autodiscover() + +urlpatterns = patterns('', + # Example: + + # 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')), + + (r'^admin/', include(admin.site.urls)), # django 1.0 not working + (r'^json/', include('ajax.urls')), + (r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', {'url': '/media/img/favicon.ico'}), + (r'^media/(?P<path>.*)$', 'django.views.static.serve', + {'document_root': settings.MEDIA_ROOT}), + (r'^', include('pyload.urls')), + ) diff --git a/pluginconfig b/pluginconfig deleted file mode 100644 index c0fdd3d10..000000000 --- a/pluginconfig +++ /dev/null @@ -1,29 +0,0 @@ -[RapidshareCom] -#select server, empty for automatic, else Cogent, Deutsche Telekom, Level(3), Level(3) #2, GlobalCrossing, Level(3) #3, Teleglobe, GlobalCrossing #2, TeliaSonera #2, Teleglobe #2, TeliaSonera #3, TeliaSonera -server = "" -premium = False -username = namehere -password = passhere - -[NetloadIn] -premium = False -username = namehere -password = passhere - -[UploadedTo] -premium = False -username = namehere -password = passhere - -[ShareonlineBiz] -premium = False -username = namehere -password = passhere - -[YoutubeCom] -high_quality = True - -[YoutubeChannel] -#type False for no limitation -max_videos = False - diff --git a/pyLoadCli.py b/pyLoadCli.py index fd65e04da..18c3b98bc 100755 --- a/pyLoadCli.py +++ b/pyLoadCli.py @@ -17,29 +17,36 @@ # along with this program; if not, see <http://www.gnu.org/licenses/>. # ### -import ConfigParser -import subprocess import os import os.path -from os import chdir -from os.path import dirname from os.path import abspath -from os import sep -from time import sleep +from os.path import dirname +from os.path import join import sys +import threading import time +from time import sleep +import xmlrpclib -from module.remote.ClientSocket import SocketThread +from module.XMLConfigParser import XMLConfigParser class pyLoadCli: - def __init__(self, adress, port, pw): - self.thread = SocketThread(adress, int(port), pw, self) + def __init__(self, server_url): + self.core = xmlrpclib.ServerProxy(server_url, allow_none=True) self.getch = _Getch() self.input = "" - self.pos = [0, 0] + self.pos = [0, 0, 0] self.inputline = 0 self.menuline = 0 + self.new_package = {} + + try: + self.core.get_server_version() + except: + print "pyLoadCore not running" + exit() + self.links_added = 0 os.system("clear") @@ -48,7 +55,9 @@ class pyLoadCli: self.file_list = {} - self.thread.push_exec("get_links") + + self.thread = RefreshThread(self) + self.thread.start() self.start() @@ -60,7 +69,10 @@ class pyLoadCli: os.system("clear") sys.exit() # ctrl + c elif ord(inp) == 13: - self.handle_input() + try: + self.handle_input() + except Exception, e: + self.println(2, red(str(e))) self.input = "" #enter self.print_input() elif ord(inp) == 127: @@ -92,44 +104,45 @@ class pyLoadCli: self.println(self.inputline + 3, "") self.println(self.inputline + 4, "") - def data_arrived(self, obj): + def refresh(self): """Handle incoming data""" - if obj.command == "update": + data = self.core.status_downloads() #print updated information - print "\033[J" #clear screen - self.println(1, blue("py") + yellow("Load") + white(" Command Line Interface")) - self.println(2, "") - self.println(3, white("%s Downloads:" % (len(obj.data)))) - line = 4 - speed = 0 - for download in obj.data: - if download["status"] == "downloading": - percent = download["percent"] - z = percent / 4 - speed += download['speed'] - self.println(line, cyan(download["name"])) - line += 1 - self.println(line, blue("[") + yellow(z * "#" + (25-z) * " ") + blue("] ") + green(str(percent) + "%") + " Speed: " + green(str(int(download['speed'])) + " kb/s") + " Size: " + green(self.format_size(download['size'])) + " Finished in: " + green(self.format_time(download['eta'])) + " ID: " + green(str(download['id']))) - line += 1 - if download["status"] == "waiting": - self.println(line, cyan(download["name"])) - line += 1 - self.println(line, "waiting: " + green(self.format_time(download["wait_until"]- time.time()))) - line += 1 - self.println(line, "") - line += 1 - if obj.status['pause']: - self.println(line, "Status: " + red("paused") + " total Speed: " + red(str(int(speed)) + " kb/s") + " Files in queue: " + red(str(obj.status["queue"]))) - else: - self.println(line, "Status: " + red("running") + " total Speed: " + red(str(int(speed)) + " kb/s") + " Files in queue: " + red(str(obj.status["queue"]))) - line += 1 - self.println(line, "") - line += 1 - self.menuline = line - - self.build_menu() - elif obj.command == "file_list" or obj.function == "get_links": - self.file_list = obj.data + print "\033[J" #clear screen + self.println(1, blue("py") + yellow("Load") + white(" Command Line Interface")) + self.println(2, "") + self.println(3, white("%s Downloads:" % (len(data)))) + line = 4 + speed = 0 + for download in data: + if download["status"] == "downloading": + percent = download["percent"] + z = percent / 4 + speed += download['speed'] + self.println(line, cyan(download["name"])) + line += 1 + self.println(line, blue("[") + yellow(z * "#" + (25-z) * " ") + blue("] ") + green(str(percent) + "%") + " Speed: " + green(str(int(download['speed'])) + " kb/s") + " Size: " + green(self.format_size(download['size'])) + " Finished in: " + green(self.format_time(download['eta'])) + " ID: " + green(str(download['id']))) + line += 1 + if download["status"] == "waiting": + self.println(line, cyan(download["name"])) + line += 1 + self.println(line, "waiting: " + green(self.format_time(download["wait_until"]- time.time()))) + line += 1 + self.println(line, "") + line += 1 + status = self.core.status_server() + if status['pause']: + self.println(line, "Status: " + red("paused") + " total Speed: " + red(str(int(speed)) + " kb/s") + " Files in queue: " + red(str(status["queue"]))) + else: + self.println(line, "Status: " + red("running") + " total Speed: " + red(str(int(speed)) + " kb/s") + " Files in queue: " + red(str(status["queue"]))) + line += 1 + self.println(line, "") + line += 1 + self.menuline = line + + self.build_menu() + # + self.file_list = data def build_menu(self): line = self.menuline @@ -140,7 +153,7 @@ class pyLoadCli: line += 1 self.println(line, mag("1.") + " Add Links") line += 1 - self.println(line, mag("2.") + " Remove Links") + self.println(line, mag("2.") + " Manage Links") line += 1 self.println(line, mag("3.") + " (Un)Pause Server") line += 1 @@ -152,36 +165,79 @@ class pyLoadCli: line += 1 self.println(line, "") elif self.pos[0] == 1:#add links - self.println(line, "Parse the links you want to add.") - line += 1 - self.println(line, "") - line += 1 - self.println(line, "") - line += 1 - self.println(line, "Links added: " + mag(str(self.links_added))) - line += 1 - self.println(line, "") - line += 1 - self.println(line, "") - line += 1 - self.println(line, mag("0.") + " back to main menu") - line += 1 - self.println(line, "") - elif self.pos[0] == 2:#remove links - self.println(line, "Type the number of the link you want to delete.") - line += 1 - i = 0 - for id in range(self.pos[1], self.pos[1] + 5): - if id < 0 or id >= len(self.file_list['order']): - continue - item = self.file_list['order'][id] - self.println(line, mag(str(item)) + ": " + self.file_list[item].url) + + if self.pos[1] == 0: + self.println(line, "") + line += 1 + self.println(line, "Name your package.") line += 1 - i += 1 - for x in range(5-i): self.println(line, "") line += 1 - + self.println(line, "") + line += 1 + self.println(line, "") + line += 1 + self.println(line, "") + line += 1 + self.println(line, mag("0.") + " back to main menu") + line += 1 + self.println(line, "") + + else: + self.println(line, "Package: %s" % self.new_package['name']) + line += 1 + self.println(line, "Parse the links you want to add.") + line += 1 + self.println(line, "Type " + mag("END") + " when done.") + line += 1 + self.println(line, "Links added: " + mag(str(self.links_added))) + line += 1 + self.println(line, "") + line += 1 + self.println(line, "") + line += 1 + self.println(line, mag("0.") + " back to main menu") + line += 1 + self.println(line, "") + elif self.pos[0] == 2:#remove links + if self.pos[1] == 0: + pack = self.core.get_queue() + self.println(line, "Type d(number of package) to delete a package, r to restart, or w/o d,r to look into it.") + line += 1 + i = 0 + for id in range(self.pos[2], self.pos[2] + 5): + try: + self.println(line, mag(str(pack[id]['id'])) + ": " + pack[id]['package_name']) + line += 1 + i += 1 + except Exception, e: + pass + for x in range(5-i): + self.println(line, "") + line += 1 + + else: + links = self.core.get_package_files(self.pos[1]) + self.println(line, "Type d(number) of the link you want to delete or r(number) to restart.") + line += 1 + i = 0 + for id in range(self.pos[2], self.pos[2] + 5): + try: + link = self.core.get_file_info(links[id]) + + if not link['status_filename']: + self.println(line, mag(str(link['id'])) + ": " + link['url']) + else: + self.println(line, mag(str(link['id'])) + ": %s | %s | %s" % (link['filename'], link['status_type'], link['plugin'])) + line += 1 + i += 1 + + except Exception, e: + pass + for x in range(5-i): + self.println(line, "") + line += 1 + self.println(line, mag("p") + " - previous" + " | " + mag("n") + " - next") line += 1 self.println(line, mag("0.") + " back to main menu") @@ -192,7 +248,7 @@ class pyLoadCli: def handle_input(self): inp = self.input.strip() if inp == "0": - self.pos = [0, 0] + self.pos = [0, 0, 0] self.build_menu() return True @@ -204,27 +260,76 @@ class pyLoadCli: self.pos[0] = 2 self.pos[1] = 0 elif inp == "3": - self.thread.push_exec("toggle_pause") + self.core.toggle_pause() elif inp == "4": - self.thread.push_exec("kill") + self.core.kill() sys.exit() elif inp == "5": os.system('clear') sys.exit() + elif self.pos[0] == 1: #add links - if inp[:7] == "http://" or os.path.exists(inp): - self.thread.push_exec("add_links", [(inp, None)]) - self.links_added += 1 + if self.pos[1] == 0: + self.new_package['name'] = inp + self.new_package['links'] = [] + self.pos[1] = 1 + else: + if inp == "END": + self.core.add_package(self.new_package['name'], self.new_package['links']) # add package + self.pos = [0, 0, 0] + self.links_added = 0 + else: #@TODO validation + self.new_package['links'].append(inp) + self.links_added += 1 + elif self.pos[0] == 2: #remove links + if self.pos[1] == 0: + if inp.startswith("d"): + if inp.find("-") > -1: + self.core.del_packages(range(*map(int, inp[1:].split("-")))) + else: + self.core.del_packages([int(inp[1:])]) + if inp.startswith("r"): + self.core.restart_package(int(inp[1:])) + elif inp != "p" and inp != "n": + self.pos[1] = int(inp) + self.pos[2] = 0 + elif inp.startswith('r'): + if inp.find("-") > -1: + map(self.core.restart_file, range(*map(int, inp[1:].split("-")))) + else: + self.core.restart_file(int(inp[1:])) + elif inp.startswith('d') and inp != "p" and inp != "n": + if inp.find("-") > -1: + self.core.del_links(range(*map(int, inp[1:].split("-")))) + else: + self.core.del_links([int(inp[1:])]) if inp == "p": - self.pos[1] -= 5 + self.pos[2] -= 5 elif inp == "n": - self.pos[1] += 5 - else: - self.thread.push_exec("remove_links", [[inp]]) + self.pos[2] += 5 self.build_menu() +class RefreshThread(threading.Thread): + def __init__(self, cli): + threading.Thread.__init__(self) + self.cli = cli + + def run(self): + while True: + sleep(1) + try: + self.cli.refresh() + except Exception, e: + self.cli.println(2, red(str(e))) + self.cli.pos[1] = 0 + self.cli.pos[2] = 0 + + + + + class _Getch: """ Gets a single character from standard input. Does not echo to @@ -329,22 +434,35 @@ if __name__ == "__main__": opts, extraparams = __import__("getopt").getopt(sys.argv[1:], shortOptions, longOptions) for option, params in opts: if option in ("-l", "--local"): - chdir(dirname(abspath(__file__)) + sep) - config = ConfigParser.SafeConfigParser() - config.read('config') - - pipe = subprocess.PIPE - subprocess.Popen("./pyLoadCore.py", stdout=pipe, stderr=pipe) - print "Starting pyLoad Core" - sleep(1) - cli = pyLoadCli("127.0.0.1", config.get("remote", "port"), config.get("remote", "password")) - if len(extraparams) == 3: - address, port, password = sys.argv[1:4] - cli = pyLoadCli(address, port, password) + xmlconfig = XMLConfigParser(join(abspath(dirname(__file__)), "module", "config", "core.xml")) + config = xmlconfig.getConfig() + + ssl = "" + if config['ssl']['activated'] == "True": + ssl = "s" + + server_url = "http%s://%s:%s@%s:%s/" % ( + ssl, + config['remote']['username'], + config['remote']['password'], + config['remote']['listenaddr'], + config['remote']['port'] + ) + if len(extraparams) == 1: + server_url = sys.argv[1] else: - address = raw_input("Adress:") - port = raw_input("Port:") - password = raw_input("Password:") - cli = pyLoadCli(address, port, password) - + username = raw_input("Username: ") + address = raw_input("Adress: ") + ssl = raw_input("Use SSL? ([y]/n): ") + if ssl == "y" or ssl == "": + ssl = "s" + else: + ssl = "" + port = raw_input("Port: ") + from getpass import getpass + password = getpass("Password: ") + + server_url = "http%s://%s:%s@%s:%s/" % (ssl, username, password, address, port) + print server_url + cli = pyLoadCli(server_url) diff --git a/pyLoadCore.py b/pyLoadCore.py index 94a57aa70..7aa38b9b1 100755 --- a/pyLoadCore.py +++ b/pyLoadCore.py @@ -1,411 +1,603 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# -#Copyright (C) 2009 spoob, sebnapi, RaNaN -# -#This program is free software; you can redistribute it and/or modify -#it under the terms of the GNU General Public License as published by -#the Free Software Foundation; either version 3 of the License, -#or (at your option) any later version. -# -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#See the GNU General Public License for more details. -# -#You should have received a copy of the GNU General Public License -# along with this program; if not, see <http://www.gnu.org/licenses/>. -# -### -CURRENT_VERSION = '0.2.3.2' - -import ConfigParser -import gettext -from glob import glob -import logging -import logging.handlers -from os import mkdir -from os import sep -from os import chdir -from os.path import basename -from os.path import exists -from os.path import dirname -from os.path import abspath -import subprocess -from sys import argv -from sys import exit -from sys import path -from sys import stdout -import time -from time import sleep -import urllib2 -from imp import find_module -try: - find_module("Crypto") -except ImportError: - print "Install pycrypto to use pyLoad" - exit() -from module.file_list import File_List -from module.remote.RequestObject import RequestObject -from module.remote.SocketServer import ServerThread -from module.thread_list import Thread_List -from module.web.WebServer import WebServer - -class Core(object): - """ pyLoad main - """ - def __init__(self): - - chdir(dirname(abspath(__file__)) + sep) - - self.config = {} - self.plugin_folder = "module" + sep + "plugins" - self.plugins_avaible = {} - - self.read_config() - - self.do_kill = False - translation = gettext.translation("pyLoad", "locale", languages=[self.config['general']['language']]) - translation.install(unicode=True) - - self.check_installs("pycurl", "pycurl for lower memory footprint while downloading") - self.check_installs("tesseract", "tesseract for captcha reading", False) - self.check_installs("gocr", "gocr for captcha reading", False) - self.check_create(self.config['log']['log_folder'], _("folder for logs")) - self.check_create(self.config['general']['download_folder'], _("folder for downloads")) - self.check_create(self.config['general']['link_file'], _("file for links"), False) - self.check_create(self.config['general']['failed_file'], _("file for failed links"), False) - - if self.config['general']['debug_mode']: - self.init_logger(logging.DEBUG) # logging level - self.print_test_status = True - else: - self.init_logger(logging.INFO) # logging level - self.print_test_status = False - - self.check_update() - - self.logger.info(_("Downloadtime: %s") % self.is_dltime()) # debug only - - path.append(self.plugin_folder) - self.create_plugin_index() - - self.init_server() - - self.file_list = File_List(self) - self.thread_list = Thread_List(self) - - #Webserver - - self.init_webserver() - - def check_installs(self, check_name, legend, python=True, essential=False): - """check wether needed tools are installed""" - try: - if python: - find_module(check_name) - else: - pipe = subprocess.PIPE - subprocess.Popen(check_name, stdout=pipe, stderr=pipe) - except: - print "Install", legend - if essential: exit() - - def check_create(self, check_name, legend, folder=True): - """check wether needed files are exists""" - if not exists(check_name): - try: - if folder: - mkdir(check_name) - else: - open(check_name, "w") - print _("%s created") % legend - except: - print _("could not create %s") % legend - exit() - - def read_config(self): - """ read config and sets preferences - """ - self.configfile = ConfigParser.SafeConfigParser() - self.configfile.read('config') - for section in self.configfile.sections(): - self.config[section] = {} - for option in self.configfile.options(section): - self.config[section][option] = self.configfile.get(section, option) - self.config[section][option] = False if self.config[section][option].lower() == 'false' else self.config[section][option] - - def set_option(self, section, option, value): - self.config[option] = value - self.configfile.set(section, option, str(value)) - self.configfile.write(open('config', "wb")) - - def read_option(self): - return self.config - - def create_plugin_index(self): - for file_handler in glob(self.plugin_folder + sep + '*.py') + glob(self.plugin_folder + sep + 'DLC.pyc'): - plugin_pattern = "" - plugin_file = basename(file_handler).replace('.pyc', '').replace('.py', '') - if plugin_file == "DLC": - plugin_pattern = "(?!http://).*\.dlc" - else: - for line in open(file_handler, "r").readlines(): - if "props['pattern']" in line: - plugin_pattern = line.split("r\"")[1].split("\"")[0] - break - if plugin_pattern != "": - self.plugins_avaible[plugin_file] = plugin_pattern - self.logger.debug(plugin_file + _(" added")) - self.logger.info(_("created index of plugins")) - - def read_links(self): - """read links from txt""" - txt = open(self.config['general']['link_file'], 'r') - new_links = 0 - links = txt.readlines() - for link in links: - if link != "\n": - self.file_list.append(link) - new_links += 1 - - txt.close() - - self.file_list.save() - if new_links: - self.logger.info("Parsed link from %s: %i" % (self.config['general']['link_file'], new_links)) - - txt = open(self.config['general']['link_file'], 'w') - txt.write("") - txt.close() - - def check_update(self): - """checks newst version - """ - if not self.config['updates']['search_updates']: - return False - - newst_version = urllib2.urlopen("http://update.pyload.org/index.php?do=" + CURRENT_VERSION).readline() - if newst_version == "True": - if not self.config['updates']['install_updates']: - self.logger.info("New version available, please run Updater") - else: - updater = __import__("pyLoadUpdater") - updater.main() - else: - self.logger.info("pyLoad is up-to-date") - - def init_logger(self, level): - - file_handler = logging.handlers.RotatingFileHandler(self.config['log']['log_folder'] + sep + 'log.txt', maxBytes=102400, backupCount=int(self.config['log']['log_count'])) #100 kib each - console = logging.StreamHandler(stdout) - - frm = logging.Formatter("%(asctime)s: %(levelname)-8s %(message)s", "%d.%m.%Y %H:%M:%S") - file_handler.setFormatter(frm) - console.setFormatter(frm) - - self.logger = logging.getLogger("log") # settable in config - - if self.config['log']['file_log']: - self.logger.addHandler(file_handler) - - self.logger.addHandler(console) #if console logging - self.logger.setLevel(level) - - def is_dltime(self): - start = self.config['downloadTime']['start'].split(":") - end = self.config['downloadTime']['end'].split(":") - - return self.compare_time(start, end) - - def is_reconnect_time(self): - - start = self.config['reconnectTime']['start'].split(":") - end = self.config['reconnectTime']['end'].split(":") - - return self.compare_time(start, end) - - def compare_time(self, start, end): - - if start == end: - return True - - now = time.localtime()[3:5] - - if start < now and end > now: - return True - elif start > end and (now > start or now < end): - return True - elif start < now and end < now and start > end: - return True - else: - return False - - def format_time(self, seconds): - seconds = int(seconds) - if seconds > 60: - hours, seconds = divmod(seconds, 3600) - minutes, seconds = divmod(seconds, 60) - return "%.2i:%.2i:%.2i" % (hours, minutes, seconds) - return _("%i seconds") % seconds - - def get_downloads(self): - list = [] - for pyfile in self.thread_list.py_downloading: - download = {} - download['id'] = pyfile.id - download['name'] = pyfile.status.filename - download['speed'] = pyfile.status.get_speed() - download['eta'] = pyfile.status.get_ETA() - download['kbleft'] = pyfile.status.kB_left() - download['size'] = pyfile.status.size() - download['percent'] = pyfile.status.percent() - download['status'] = pyfile.status.type - download['wait_until'] = pyfile.status.waituntil - download['plugin'] = pyfile.status.plugin - list.append(download) - - return list - - def server_send_status(self): - obj = RequestObject() - obj.command = "update" - obj.data = self.get_downloads() - obj.status = self.server_status() - self.server.push_all(obj) - - def server_status(self): - status = {} - status['pause'] = self.thread_list.pause - status['queue'] = len(self.file_list.files) - status['speed'] = 0 - - for pyfile in self.thread_list.py_downloading: - status['speed'] += pyfile.status.get_speed() - - return status - - def init_server(self): - - try: - self.server = ServerThread(self) - self.server.start() - except Exception, e: - self.logger.error("Failed starting socket server, CLI and GUI will not be available: %s" % str(e)) - exit() - - def init_webserver(self): - - if not self.config['webinterface']['activated']: - return False - - try: - self.webserver = WebServer(self) - self.webserver.start() - except Exception, e: - self.logger.error("Failed starting webserver, no webinterface available: %s" % str(e)) - exit() - - def kill(self): - self.do_kill = True - self.logger.info("Going to kill pyLoad") - exit() - return True - - def shutdown(self): - "abort all downloads and exit" - self.thread_list.pause = True - - for pyfile in self.thread_list.py_downloading: - pyfile.plugin.req.abort = True - - while self.thread_list.py_downloading: - sleep(1) - self.logger.info("Going to shutdown pyLoad") - exit() - - def add_links(self, links): - self.file_list.extend(links) - self.file_list.save() - - def remove_links(self, ids): - for id in ids: - self.file_list.remove_id(id) - self.file_list.save() - - def get_links(self): - return self.file_list.data - - def move_links_up(self, ids): - - for id in ids: - self.file_list.move(id) - - self.file_list.save() - - def move_links_down(self, ids): - - for id in ids: - self.file_list.move(id, 1) - - self.file_list.save() - - def toggle_pause(self): - if self.thread_list.pause: - self.thread_list.pause = False - return False - elif not self.thread_list.pause: - self.thread_list.pause = True - return True - - def start(self): - """ starts the machine - """ - if len(argv) > 1: - shortOptions = 'pu:l:' - longOptions = ['print', 'url=', 'list='] - - opts, extraparams = __import__("getopt").getopt(argv[1:], shortOptions, longOptions) - for option, params in opts: - if option in ("-p", "--print"): - print "Print test output" - self.print_test_status = True - elif option in ("-u", "--url"): - self.logger.info("Add url: " + params) - self.add_links([params]) - elif option in ("-l", "--list"): - list = open(params, 'r').readlines() - self.add_links(list) - self.logger.info("Add list:" + params) - - self.read_links() - - while True: - #self.thread_list.status() - if self.print_test_status: - self._test_print_status() - self.server_send_status() - sleep(2) - if self.do_kill: - self.logger.info("pyLoad quits") - exit() - - def _test_print_status(self): - - if self.thread_list.py_downloading: - for pyfile in self.thread_list.py_downloading: - if pyfile.status.type == 'downloading': - print pyfile.status.filename + ": speed is", int(pyfile.status.get_speed()), "kb/s" - print pyfile.status.filename + ": finished in", self.format_time(pyfile.status.get_ETA()) - elif pyfile.status.type == 'waiting': - print pyfile.status.filename + ": wait", self.format_time(pyfile.status.waituntil - time.time()) - -if __name__ == "__main__": - if len(argv) > 1: - if argv[1] == "-v": - print "pyLoad", CURRENT_VERSION - exit() - - testLoader = Core() - testLoader.start() - +#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License,
+ or (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ See the GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+ @author: spoob
+ @author: sebnapi
+ @author: RaNaN
+ @author: mkaay
+ @version: v0.3
+"""
+
+CURRENT_VERSION = '0.3'
+from getopt import getopt
+import gettext
+from glob import glob
+from imp import find_module
+import logging
+import logging.handlers
+from operator import attrgetter
+from os import execv
+from os import makedirs
+from os import remove
+from os import sep
+from os.path import basename
+from os.path import dirname
+from os.path import exists
+from os.path import join
+from re import sub
+import subprocess
+from sys import argv
+from sys import executable
+from sys import exit
+from sys import path
+from sys import stdout
+from tempfile import NamedTemporaryFile
+import thread
+import time
+from time import sleep
+from xmlrpclib import Binary
+
+from module.CaptchaManager import CaptchaManager
+from module.HookManager import HookManager
+from module.XMLConfigParser import XMLConfigParser
+from module.file_list import File_List
+from module.network.Request import Request
+import module.remote.SecureXMLRPCServer as Server
+from module.thread_list import Thread_List
+from module.web.ServerThread import WebServer
+
+class Core(object):
+ """ pyLoad Core """
+ def __init__(self):
+ self.arg_links = []
+ if len(argv) > 1:
+ try:
+ options, arguments = getopt(argv[1:], 'vcl:')
+ for option, argument in options:
+ if option == "-v":
+ print "pyLoad", CURRENT_VERSION
+ exit()
+ elif option == "-c":
+ remove(join("module", "links.pkl"))
+ print "Removed Linkliste"
+ elif option == "-l":
+ self.arg_links.append(argument)
+ print "Added %s" % argument
+ except:
+ print 'Unknown Argument(s) "%s"' % " ".join(argv[1:])
+
+ def toggle_pause(self):
+ if self.thread_list.pause:
+ self.thread_list.pause = False
+ return False
+ elif not self.thread_list.pause:
+ self.thread_list.pause = True
+ return True
+
+ def start(self):
+ """ starts the machine"""
+ self.path = dirname(__file__)
+
+ self.config = {}
+ self.plugins_avaible = {}
+
+ self.plugin_folder = join("module", "plugins")
+
+ self.xmlconfig = XMLConfigParser(join(self.path, "module", "config", "core.xml"))
+ self.config = self.xmlconfig.getConfig()
+ self.parser_plugins = XMLConfigParser(join(self.path, "module", "config", "plugin.xml"))
+ #~ self.config_plugins = self.parser_plugins.getConfig()
+
+ self.do_kill = False
+ self.do_restart = False
+ translation = gettext.translation("pyLoad", join(self.path, "locale"), languages=[self.config['general']['language']])
+ translation.install(unicode=True)
+
+ self.check_install("Crypto", "pycrypto to decode container files")
+ self.check_install("Image", "Python Image Libary (PIL) for captha reading")
+ self.check_install("pycurl", "pycurl for lower memory footprint while downloading")
+ self.check_install("django", "Django for webinterface")
+ self.check_install("tesseract", "tesseract for captcha reading", False)
+ self.check_install("gocr", "gocr for captcha reading", False)
+
+ self.check_file(self.config['log']['log_folder'], _("folder for logs"), True)
+ self.check_file(self.config['general']['download_folder'], _("folder for downloads"), True)
+ self.check_file(self.config['general']['link_file'], _("file for links"))
+ self.check_file(self.config['general']['failed_file'], _("file for failed links"))
+
+ if self.config['ssl']['activated']:
+ self.check_install("OpenSSL", "OpenSSL for secure connection", True)
+ self.check_file(self.config['ssl']['cert'], _("ssl certificate"), False, True)
+ self.check_file(self.config['ssl']['key'], _("ssl key"), False, True)
+
+ self.downloadSpeedLimit = int(self.xmlconfig.get("general", "download_speed_limit", 0))
+
+ if self.config['general']['debug_mode']:
+ self.init_logger(logging.DEBUG) # logging level
+ else:
+ self.init_logger(logging.INFO) # logging level
+
+ self.init_hooks()
+ path.append(self.plugin_folder)
+ self.create_plugin_index()
+
+ self.lastGuiConnected = 0
+
+ self.server_methods = ServerMethods(self)
+ self.file_list = File_List(self)
+ self.thread_list = Thread_List(self)
+ self.captchaManager = CaptchaManager(self)
+
+ self.last_update_check = 0
+ self.update_check_interval = 1800
+ self.update_available = self.check_update()
+ self.logger.info(_("Downloadtime: %s") % self.server_methods.is_time_download())
+
+ self.init_server()
+ self.init_webserver()
+
+ linkFile = self.config['general']['link_file']
+ packs = self.server_methods.get_queue()
+ found = False
+ for data in packs:
+ if data["package_name"] == linkFile:
+ found = data["id"]
+ break
+ if found == False:
+ pid = self.file_list.packager.addNewPackage(package_name=linkFile)
+ else:
+ pid = found
+ lid = self.file_list.collector.addLink(linkFile)
+ self.file_list.packager.addFileToPackage(pid, self.file_list.collector.popFile(lid))
+ if self.arg_links:
+ for link in self.arg_links:
+ lid = self.file_list.collector.addLink(link)
+ self.file_list.packager.addFileToPackage(pid, self.file_list.collector.popFile(lid))
+
+ self.file_list.packager.pushPackage2Queue(pid)
+ self.file_list.continueAborted()
+
+ while True:
+ sleep(2)
+ if self.do_restart:
+ self.logger.info("restarting pyLoad")
+ self.restart()
+ if self.do_kill:
+ self.shutdown()
+ self.logger.info("pyLoad quits")
+ exit()
+ if self.last_update_check + self.update_check_interval <= time.time():
+ self.update_available = self.check_update()
+
+ def init_server(self):
+ try:
+ server_addr = (self.config['remote']['listenaddr'], int(self.config['remote']['port']))
+ usermap = {self.config['remote']['username']: self.config['remote']['password']}
+ if self.config['ssl']['activated']:
+ self.server = Server.SecureXMLRPCServer(server_addr, self.config['ssl']['cert'], self.config['ssl']['key'], usermap)
+ self.logger.info("Secure XMLRPC Server Started")
+ else:
+ self.server = Server.AuthXMLRPCServer(server_addr, usermap)
+ self.logger.info("Auth XMLRPC Server Started")
+
+ self.server.register_instance(self.server_methods)
+
+ thread.start_new_thread(self.server.serve_forever, ())
+ except Exception, e:
+ self.logger.error("Failed starting socket server, CLI and GUI will not be available: %s" % str(e))
+ if self.config['general']['debug_mode']:
+ import traceback
+ traceback.print_exc()
+
+
+ def init_webserver(self):
+ #pyloadDBFile = join(self.path, "module", "web", "pyload.db")
+ #pyloadDefaultDBFile = join(self.path, "module", "web", "pyload_default.db")
+ #if not exists(pyloadDBFile):
+ # copyfile(pyloadDefaultDBFile, pyloadDBFile)
+ if self.config['webinterface']['activated']:
+ self.webserver = WebServer(self)
+ self.webserver.start()
+
+ def init_logger(self, level):
+ console = logging.StreamHandler(stdout)
+ frm = logging.Formatter("%(asctime)s: %(levelname)-8s %(message)s", "%d.%m.%Y %H:%M:%S")
+ console.setFormatter(frm)
+ self.logger = logging.getLogger("log") # settable in config
+
+ if self.config['log']['file_log']:
+ file_handler = logging.handlers.RotatingFileHandler(self.config['log']['log_folder'] + sep + 'log.txt', maxBytes=102400, backupCount=int(self.config['log']['log_count'])) #100 kib each
+ file_handler.setFormatter(frm)
+ self.logger.addHandler(file_handler)
+
+ self.logger.addHandler(console) #if console logging
+ self.logger.setLevel(level)
+
+ def init_hooks(self):
+ self.hookManager = HookManager(self)
+
+ def check_install(self, check_name, legend, python=True, essential=False):
+ """check wether needed tools are installed"""
+ try:
+ if python:
+ find_module(check_name)
+ else:
+ pipe = subprocess.PIPE
+ subprocess.Popen(check_name, stdout=pipe, stderr=pipe)
+ except:
+ print "Install", legend
+ if essential: exit()
+
+ def check_file(self, check_names, description="", folder=False, empty=True, essential=False):
+ """check wether needed files are exists"""
+ tmp_names = []
+ if not type(check_names) == list:
+ tmp_names.append(check_names)
+ else:
+ tmp_names.extend(check_names)
+ file_created = True
+ file_exists = True
+ for tmp_name in tmp_names:
+ if not exists(tmp_name):
+ file_exists = False
+ if empty:
+ try:
+ if folder:
+ tmp_name = tmp_name.replace("/", sep)
+ makedirs(tmp_name)
+ else:
+ open(tmp_name, "w")
+ except:
+ file_created = False
+ else:
+ file_created = False
+ if not file_exists:
+ if file_created:
+ print _("%s created") % description
+ else:
+ if not empty:
+ print _("could not find %s: %s") % (description, tmp_name)
+ else:
+ print _("could not create %s: %s") % (description, tmp_name)
+ if essential:
+ exit()
+
+ def isGUIConnected(self):
+ return self.lastGuiConnected + 10 > time.time()
+
+ def restart(self):
+ self.shutdown()
+ execv(executable, [executable, "pyLoadCore.py"])
+
+ def create_plugin_index(self):
+ plugins = glob(join(self.plugin_folder, "hoster", "*.py"))
+ plugins += glob(join(self.plugin_folder, "decrypter", "*.py"))
+ plugins += glob(join(self.plugin_folder, "container", "*.py"))
+ plugins += glob(join(self.plugin_folder, "container", "DLC.pyc"))
+ for file_handler in plugins:
+ plugin_pattern = ""
+ plugin_file = sub("(\.pyc|\.py)", "", basename(file_handler))
+ if plugin_file == "DLC":
+ plugin_pattern = "(?!http://).*\.dlc"
+ else:
+ for line in open(file_handler, "r").readlines():
+ if "props['pattern']" in line:
+ plugin_pattern = line.split("r\"")[1].split("\"")[0]
+ break
+ if plugin_pattern != "":
+ self.plugins_avaible[plugin_file] = plugin_pattern
+ self.logger.debug(plugin_file + _(" added"))
+ self.logger.info(_("created index of plugins"))
+
+ def compare_time(self, start, end):
+
+ start = map(int, start)
+ end = map(int, end)
+
+ if start == end: return True
+
+ now = time.localtime()[3:5]
+ if start < now and end > now: return True
+ elif start > end and (now > start or now < end): return True
+ elif start < now and end < now and start > end: return True
+ else: return False
+
+ def getMaxSpeed(self):
+ return self.downloadSpeedLimit
+
+ def shutdown(self):
+ self.logger.info("shutting down...")
+ if self.config['webinterface']['activated']:
+ self.webserver.quit()
+ self.webserver.join()
+ for thread in self.thread_list.threads:
+ thread.shutdown = True
+ self.thread_list.stopAllDownloads()
+ for thread in self.thread_list.threads:
+ thread.join(15)
+ self.file_list.save()
+
+ def check_update(self):
+ try:
+ if self.config['updates']['search_updates']:
+ version_check = Request().load("http://get.pyload.org/check/%s/" % (CURRENT_VERSION, ))
+ if version_check == "":
+ self.logger.info("No Updates for pyLoad")
+ return False
+ else:
+ self.logger.info("New pyLoad Version %s available" % version_check)
+ return True
+ else:
+ return False
+ finally:
+ self.last_update_check = time.time()
+
+ def install_update(self):
+ if self.config['updates']['search_updates']:
+ if self.core.config['updates']['install_updates']:
+ version_check = Request().load("http://get.pyload.org/get/update/%s/" % (CURRENT_VERSION, ))
+ else:
+ version_check = Request().load("http://get.pyload.org/check/%s/" % (CURRENT_VERSION, ))
+ if version_check == "":
+ return False
+ else:
+ if self.config['updates']['install_updates']:
+ try:
+ tmp_zip_name = __import__("tempfile").NamedTemporaryFile(suffix=".zip").name
+ tmp_zip = open(tmp_zip_name, 'wb')
+ tmp_zip.write(version_check)
+ tmp_zip.close()
+ __import__("module.Unzip", globals(), locals(), "Unzip", -1).Unzip().extract(tmp_zip_name, "Test/")
+ return True
+ except:
+ self.logger.info("Auto install Failed")
+ return False
+ else:
+ return False
+ else:
+ return False
+
+ ####################################
+ ########## XMLRPC Methods ##########
+ ####################################
+
+class ServerMethods():
+ def __init__(self, core):
+ self.core = core
+
+ def status_downloads(self):
+ downloads = []
+ for pyfile in self.core.thread_list.py_downloading:
+ download = {}
+ download['id'] = pyfile.id
+ download['name'] = pyfile.status.filename
+ download['speed'] = pyfile.status.get_speed()
+ download['eta'] = pyfile.status.get_ETA()
+ download['kbleft'] = pyfile.status.kB_left()
+ download['size'] = pyfile.status.size()
+ download['percent'] = pyfile.status.percent()
+ download['status'] = pyfile.status.type
+ download['wait_until'] = pyfile.status.waituntil
+ download['package'] = pyfile.package.data["package_name"]
+ downloads.append(download)
+ return downloads
+
+ def get_conf_val(self, cat, var):
+ if var != "username" and var != "password":
+ return self.core.config[cat][var]
+ else:
+ raise Exception("not allowed!")
+
+ def pause_server(self):
+ self.core.thread_list.pause = True
+
+ def unpause_server(self):
+ self.core.thread_list.pause = False
+
+ def toggle_pause(self):
+ if self.core.thread_list.pause:
+ self.core.thread_list.pause = False
+ else:
+ self.core.thread_list.pause = True
+ return self.core.thread_list.pause
+
+ def status_server(self):
+ status = {}
+ status['pause'] = self.core.thread_list.pause
+ status['activ'] = len(self.core.thread_list.py_downloading)
+ status['queue'] = self.core.file_list.countDownloads()
+ status['total'] = len(self.core.file_list.data['queue'])
+ status['speed'] = 0
+
+ for pyfile in self.core.thread_list.py_downloading:
+ status['speed'] += pyfile.status.get_speed()
+
+ return status
+
+ def file_exists(self, path): #@XXX: security?!
+ return exists(path)
+
+ def get_server_version(self):
+ return CURRENT_VERSION
+
+ def add_urls(self, links):
+ for link in links:
+ link = link.strip()
+ if link.startswith("http") or exists(link):
+ self.core.file_list.collector.addLink(link)
+ self.core.file_list.save()
+
+ def add_package(self, name, links):
+ pid = self.new_package(name)
+ self.core.file_list.packager.pushPackage2Queue(pid)
+ fids = map(self.core.file_list.collector.addLink, links)
+ map(lambda fid: self.move_file_2_package(fid, pid), fids)
+ self.push_package_2_queue(pid)
+ self.core.file_list.save()
+
+ def new_package(self, name):
+ id = self.core.file_list.packager.addNewPackage(name)
+ self.core.file_list.save()
+ return id
+
+ def get_package_data(self, id):
+ return self.core.file_list.packager.getPackageData(id)
+
+ def get_package_files(self, id):
+ return self.core.file_list.packager.getPackageFiles(id)
+
+ def get_file_info(self, id):
+ return self.core.file_list.getFileInfo(id)
+
+ def del_links(self, ids):
+ for id in ids:
+ try:
+ self.core.file_list.collector.removeFile(id)
+ except:
+ self.core.file_list.packager.removeFile(id)
+ self.core.file_list.save()
+
+ def del_packages(self, ids):
+ map(self.core.file_list.packager.removePackage, ids)
+ self.core.file_list.save()
+
+ def kill(self):
+ self.core.do_kill = True
+ return True
+
+ def restart(self):
+ self.core.do_restart = True
+
+ def get_queue(self):
+ return map(attrgetter("data"), self.core.file_list.data["queue"])
+
+ def get_collector_packages(self):
+ return map(attrgetter("data"), self.core.file_list.data["packages"])
+
+ def get_collector_files(self):
+ return map(attrgetter("id"), self.core.file_list.data["collector"])
+
+ def move_file_2_package(self, fid, pid):
+ try:
+ pyfile = self.core.file_list.collector.getFile(fid)
+ self.core.file_list.packager.addFileToPackage(pid, pyfile)
+ except:
+ return
+ else:
+ self.core.file_list.collector.removeFile(fid)
+
+ def push_package_2_queue(self, id):
+ self.core.file_list.packager.pushPackage2Queue(id)
+
+ def restart_package(self, packid):
+ map(self.core.file_list.packager.resetFileStatus, self.core.file_list.packager.getPackageFiles(packid))
+
+ def restart_file(self, fileid):
+ self.core.file_list.packager.resetFileStatus(fileid)
+
+ def upload_container(self, filename, type, content):
+ th = NamedTemporaryFile(mode="w", suffix="." + type, delete=False)
+ th.write(content)
+ path = th.name
+ th.close()
+ pid = self.core.file_list.packager.addNewPackage(filename)
+ cid = self.core.file_list.collector.addLink(path)
+ self.move_file_2_package(cid, pid)
+ self.core.file_list.save()
+
+ def get_log(self, offset=0):
+ filename = self.core.config['log']['log_folder'] + sep + 'log.txt'
+ fh = open(filename, "r")
+ content = fh.read()
+ fh.close()
+ lines = content.splitlines()
+ if offset >= len(lines):
+ return None
+ return lines[offset:]
+
+ def stop_downloads(self):
+ self.core.thread_list.stopAllDownloads()
+
+ def stop_download(self, type, id):
+ if type == "pack":
+ ids = self.core.file_list.getPackageFiles(id)
+ for fid in ids:
+ self.core.file_list.packager.abortFile(fid)
+ else:
+ self.core.file_list.packager.abortFile(id)
+
+ def update_available(self):
+ return self.core.update_available
+
+ def set_package_name(self, pid, name):
+ self.core.file_list.packager.setPackageData(pid, package_name=name)
+
+ def pull_out_package(self, pid):
+ self.core.file_list.packager.pullOutPackage(pid)
+
+ def is_captcha_waiting(self):
+ self.core.lastGuiConnected = time.time()
+ task = self.core.captchaManager.getTask()
+ return not task == None
+
+ def get_captcha_task(self):
+ task = self.core.captchaManager.getTask()
+ if task:
+ task.setWatingForUser()
+ c = task.getCaptcha()
+ return str(task.getID()), Binary(c[0]), str(c[1])
+ else:
+ return None, None, None
+
+ def set_captcha_result(self, tid, result):
+ task = self.core.captchaManager.getTaskFromID(tid)
+ if task:
+ task.setResult(result)
+ task.setDone()
+ return True
+ else:
+ return False
+
+ #def move_urls_up(self, ids):
+ # for id in ids:
+ # self.core.file_list.move(id)
+ # self.core.file_list.save()
+
+ #def move_urls_down(self, ids):
+ # for id in ids:
+ # self.core.file_list.move(id, 1)
+ # self.core.file_list.save()
+
+ def is_time_download(self):
+ start = self.core.config['downloadTime']['start'].split(":")
+ end = self.core.config['downloadTime']['end'].split(":")
+ return self.core.compare_time(start, end)
+
+ def is_time_reconnect(self):
+ start = self.core.config['reconnect']['startTime'].split(":")
+ end = self.core.config['reconnect']['endTime'].split(":")
+ return self.core.compare_time(start, end)
+
+# And so it begins...
+if __name__ == "__main__":
+ pyload_core = Core()
+ try:
+ pyload_core.start()
+ except KeyboardInterrupt:
+ pyload_core.shutdown()
+ pyload_core.logger.info("killed pyLoad from Terminal")
+ exit()
diff --git a/pyLoadGui.py b/pyLoadGui.py index 806c4437c..9e04cc003 100755 --- a/pyLoadGui.py +++ b/pyLoadGui.py @@ -1,336 +1,612 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -# -#Copyright (C) 2009 KingZero -# -#This program is free software; you can redistribute it and/or modify -#it under the terms of the GNU General Public License as published by -#the Free Software Foundation; either version 3 of the License, -#or (at your option) any later version. -# -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#See the GNU General Public License for more details. -# -#You should have received a copy of the GNU General Public License -# along with this program; if not, see <http://www.gnu.org/licenses/>. -# -### -import socket -import subprocess -from os import sep -from os.path import abspath, dirname -from time import sleep +""" + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, + or (at your option) any later version. -import wxversion -wxversion.select('2.8') + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU General Public License for more details. -import wx -import wx.lib.newevent -import wx.lib.sized_controls as sized_control -from module.remote.ClientSocket import SocketThread - -(DataArrived, EVT_DATA_ARRIVED) = wx.lib.newevent.NewEvent() - -class _Download_Dialog(sized_control.SizedDialog): - def __init__(self, parent, id): - sized_control.SizedDialog.__init__(self, parent, id, "Downloads hinzufügen", - style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) - - pane = self.GetContentsPane() - - self.links = wx.TextCtrl(pane, -1, style=wx.TE_MULTILINE, size=(500, 200)) - self.links.SetSizerProps(expand=True, proportion=1) - - self.SetButtonSizer(self.CreateStdDialogButtonSizer(wx.OK | wx.CANCEL)) - - self.Fit() - self.SetMinSize(self.GetSize()) - - #Clipboard - self.data = wx.TextDataObject() - if wx.TheClipboard.Open(): - wx.TheClipboard.GetData(self.data) - for link in self.data.GetText().split('\n'): - if link.startswith("http"): - self.links.write(link + "\n") - wx.TheClipboard.Close() - -class Download_Liste(wx.ListCtrl): - def __init__(self, parent): - wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT | wx.LC_VIRTUAL) - - # columns - self.InsertColumn(0, 'Name', width=300) - self.InsertColumn(1, 'Status', width=120) - self.InsertColumn(2, 'Größe') - self.InsertColumn(3, 'Übertragen', width=100) - self.InsertColumn(4, 'Prozent', width=60) - self.InsertColumn(5, 'Dauer', width=100) - self.InsertColumn(7, 'Geschwindigkeit', width=120) - - - self.itemDataMap = {} - self.itemIndexMap = [] - self.SetItemCount(len(self.itemIndexMap)) - - def reload(self, links, data): - - self.itemIndexMap = data['order'] - - self.create_data(links, data) + You should have received a copy of the GNU General Public License + along with this program; if not, see <http://www.gnu.org/licenses/>. + + @author: mkaay + @version: v0.3 +""" + +import sys + +from time import sleep, time + +from PyQt4.QtCore import * +from PyQt4.QtGui import * + +from uuid import uuid4 as uuid +import re +from os.path import basename + +from module.gui.ConnectionManager import * +from module.gui.connector import * +from module.gui.MainWindow import * +from module.gui.PWInputWindow import * +from module.gui.Queue import * +from module.gui.Collector import * +from module.gui.XMLParser import * + +class main(QObject): + def __init__(self): + """ + main setup + """ + QObject.__init__(self) + self.app = QApplication(sys.argv) + self.init(True) + + def init(self, first=False): + """ + set main things up + """ + self.mainWindow = MainWindow() + self.pwWindow = PWInputWindow() + self.connWindow = ConnectionManager() + self.connector = connector() + self.mainloop = self.Loop(self) + self.connectSignals() + self.parser = XMLParser("module/config/gui.xml", "module/config/gui_default.xml") - self.SetItemCount(len(self.itemIndexMap)) - self.Refresh() - - def create_data(self, links, data): - - self.itemDataMap = {} - - for key, value in data.iteritems(): - if key != 'version' and key != 'order': - self.itemDataMap[key] = [value.url] - - for link in links: - self.itemDataMap[link['id']][0] = link['name'] - self.itemDataMap[link['id']].append(link['status']) - self.itemDataMap[link['id']].append(str(link['size']) + " kb") - self.itemDataMap[link['id']].append(str(link['size'] - link['kbleft']) + " kb") - self.itemDataMap[link['id']].append(str(link['percent']) + " %") - self.itemDataMap[link['id']].append(format_time(link['eta'])) - self.itemDataMap[link['id']].append(str(int(link['speed'])) + " kb/s") - - # virtual methods - def OnGetItemText(self, item, col): - index = self.itemIndexMap[item] - try: - s = self.itemDataMap[index][col] - except: - s = "" - return s - - def OnGetItemAttr(self, item): + self.checkClipboard = False + default = self.refreshConnections() + self.connData = None + self.captchaProcessing = False + if not first: + self.connWindow.show() + else: + self.connWindow.edit.setData(default) + data = self.connWindow.edit.getData() + self.slotConnect(data) + + def startMain(self): + """ + start all refresh threads and show main window + """ + if not self.connector.canConnect(): + self.init() + return + self.connector.start() + sleep(1) + self.restoreMainWindow() + self.mainWindow.show() + self.initQueue() + self.initPackageCollector() + self.initLinkCollector() + self.mainloop.start() + self.clipboard = self.app.clipboard() + self.connect(self.clipboard, SIGNAL('dataChanged()'), self.slotClipboardChange) + self.connect(self.mainWindow, SIGNAL("pauseItemUpdate"), self.packageCollector.pauseItemUpdate) + self.mainWindow.actions["clipboard"].setChecked(self.checkClipboard) + + def stopMain(self): + """ + stop all refresh threads and hide main window + """ + self.disconnect(self.clipboard, SIGNAL('dataChanged()'), self.slotClipboardChange) + self.disconnect(self.mainWindow, SIGNAL("pauseItemUpdate"), self.packageCollector.pauseItemUpdate) + self.mainloop.stop() + self.connector.stop() + self.mainWindow.saveWindow() + self.mainWindow.hide() + self.queue.stop() + self.linkCollector.stop() + self.packageCollector.stop() + self.mainloop.wait() + self.connector.wait() + self.queue.wait() + self.linkCollector.wait() + self.packageCollector.wait() + + def connectSignals(self): + """ + signal and slot stuff, yay! + """ + self.connect(self.connector, SIGNAL("error_box"), self.slotErrorBox) + self.connect(self.connWindow, SIGNAL("saveConnection"), self.slotSaveConnection) + self.connect(self.connWindow, SIGNAL("removeConnection"), self.slotRemoveConnection) + self.connect(self.connWindow, SIGNAL("connect"), self.slotConnect) + self.connect(self.pwWindow, SIGNAL("ok"), self.slotPasswordTyped) + self.connect(self.pwWindow, SIGNAL("cancel"), self.quit) + self.connect(self.mainWindow, SIGNAL("connector"), self.slotShowConnector) + self.connect(self.mainWindow, SIGNAL("addLinks"), self.slotAddLinks) + self.connect(self.mainWindow, SIGNAL("addPackage"), self.slotAddPackage) + self.connect(self.mainWindow, SIGNAL("setDownloadStatus"), self.slotSetDownloadStatus) + self.connect(self.mainWindow, SIGNAL("saveMainWindow"), self.slotSaveMainWindow) + self.connect(self.mainWindow, SIGNAL("pushPackageToQueue"), self.slotPushPackageToQueue) + self.connect(self.mainWindow, SIGNAL("restartDownload"), self.slotRestartDownload) + self.connect(self.mainWindow, SIGNAL("removeDownload"), self.slotRemoveDownload) + self.connect(self.mainWindow, SIGNAL("addContainer"), self.slotAddContainer) + self.connect(self.mainWindow, SIGNAL("stopAllDownloads"), self.slotStopAllDownloads) + self.connect(self.mainWindow, SIGNAL("setClipboardStatus"), self.slotSetClipboardStatus) + self.connect(self.mainWindow, SIGNAL("changePackageName"), self.slotChangePackageName) + self.connect(self.mainWindow, SIGNAL("pullOutPackage"), self.slotPullOutPackage) + self.connect(self.mainWindow.captchaDock, SIGNAL("done"), self.slotCaptchaDone) + + def slotShowConnector(self): + """ + emitted from main window (menu) + hide the main window and show connection manager + (to switch to other core) + """ + self.stopMain() + self.init() + + def quit(self): + """ + quit gui + """ + self.app.quit() + + def loop(self): + """ + start application loop + """ + sys.exit(self.app.exec_()) + + def slotErrorBox(self, msg): + """ + display a nice error box + """ + msgb = QMessageBox(QMessageBox.Warning, "Error", msg) + msgb.exec_() + + def initPackageCollector(self): + """ + init the package collector view + * columns + * selection + * refresh thread + * drag'n'drop + """ + view = self.mainWindow.tabs["collector"]["package_view"] + view.setColumnCount(1) + view.setHeaderLabels(["Name"]) + view.setSelectionBehavior(QAbstractItemView.SelectRows) + view.setSelectionMode(QAbstractItemView.ExtendedSelection) + def dropEvent(klass, event): + event.setDropAction(Qt.CopyAction) + event.accept() + view = event.source() + if view == klass: + items = view.selectedItems() + for item in items: + if not hasattr(item.parent(), "getPackData"): + continue + target = view.itemAt(event.pos()) + if not hasattr(target, "getPackData"): + target = target.parent() + klass.emit(SIGNAL("droppedToPack"), target.getPackData()["id"], item.getFileData()["id"]) + event.accept() + return + items = view.selectedItems() + for item in items: + row = view.indexOfTopLevelItem(item) + view.takeTopLevelItem(row) + def dragEvent(klass, event): + view = event.source() + dragOkay = False + items = view.selectedItems() + for item in items: + if hasattr(item, "_data"): + if item._data["id"] == "fixed" or item.parent()._data["id"] == "fixed": + dragOkay = True + else: + dragOkay = True + if dragOkay: + event.accept() + else: + event.ignore() + view.dropEvent = dropEvent + view.dragEnterEvent = dragEvent + view.setDragEnabled(True) + view.setDragDropMode(QAbstractItemView.DragDrop) + view.setDropIndicatorShown(True) + view.setDragDropOverwriteMode(True) + self.connect(view, SIGNAL("droppedToPack"), self.slotAddFileToPackage) + self.packageCollector = PackageCollector(view, self.connector) + self.packageCollector.start() + + def initLinkCollector(self): + """ + init the link collector + * refresh thread + """ + self.linkCollector = LinkCollector(self.mainWindow.tabs["collector"]["package_view"], self.packageCollector.linkCollector, self.connector) + self.linkCollector.start() + + def initQueue(self): + """ + init the queue view + * columns + * refresh thread + * progressbar + """ + view = self.mainWindow.tabs["queue"]["view"] + view.setColumnCount(4) + view.setHeaderLabels(["Name", "Plugin", "Status", "Fortschritt"]) + view.setColumnWidth(0, 300) + view.setColumnWidth(1, 100) + view.setColumnWidth(2, 200) + view.setColumnWidth(3, 100) + self.queue = Queue(view, self.connector) + delegate = QueueProgressBarDelegate(view, self.queue) + view.setItemDelegateForColumn(3, delegate) + self.queue.start() + + def refreshServerStatus(self): + """ + refresh server status and overall speed in the status bar + """ + status = self.connector.getServerStatus() + if status["pause"]: + status["status"] = "Paused" + else: + status["status"] = "Running" + status["speed"] = int(status["speed"]) + text = "Status: %(status)s | Speed: %(speed)s kb/s" % status + self.mainWindow.actions["toggle_status"].setChecked(not status["pause"]) + self.mainWindow.serverStatus.setText(text) + + def refreshLog(self): + """ + update log window + """ + offset = self.mainWindow.tabs["log"]["text"].logOffset + lines = self.connector.getLog(offset) + if not lines: + return + self.mainWindow.tabs["log"]["text"].logOffset += len(lines) + for line in lines: + self.mainWindow.tabs["log"]["text"].emit(SIGNAL("append(QString)"), line) + cursor = self.mainWindow.tabs["log"]["text"].textCursor() + cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor) + self.mainWindow.tabs["log"]["text"].setTextCursor(cursor) + + def updateAvailable(self): + """ + update notification + """ + status = self.connector.updateAvailable() + if status: + self.mainWindow.statusbar.emit(SIGNAL("showMsg"), "Update Available") + else: + self.mainWindow.statusbar.emit(SIGNAL("showMsg"), "") + + def getConnections(self): + """ + parse all connections in the config file + """ + connectionsNode = self.parser.xml.elementsByTagName("connections").item(0) + if connectionsNode.isNull(): + raise Exception("null") + connections = self.parser.parseNode(connectionsNode) + ret = [] + for conn in connections: + data = {} + data["type"] = conn.attribute("type", "remote") + data["default"] = conn.attribute("default", "False") + data["id"] = conn.attribute("id", uuid().hex) + if data["default"] == "True": + data["default"] = True + else: + data["default"] = False + subs = self.parser.parseNode(conn, "dict") + if not subs.has_key("name"): + data["name"] = "Unnamed" + else: + data["name"] = subs["name"].text() + if data["type"] == "remote": + if not subs.has_key("server"): + continue + else: + data["host"] = subs["server"].text() + data["ssl"] = subs["server"].attribute("ssl", "False") + if data["ssl"] == "True": + data["ssl"] = True + else: + data["ssl"] = False + data["user"] = subs["server"].attribute("user", "admin") + data["port"] = int(subs["server"].attribute("port", "7227")) + ret.append(data) + return ret + + def slotSaveConnection(self, data): + """ + save connection to config file + """ + connectionsNode = self.parser.xml.elementsByTagName("connections").item(0) + if connectionsNode.isNull(): + raise Exception("null") + connections = self.parser.parseNode(connectionsNode) + connNode = self.parser.xml.createElement("connection") + connNode.setAttribute("default", str(data["default"])) + connNode.setAttribute("type", data["type"]) + connNode.setAttribute("id", data["id"]) + nameNode = self.parser.xml.createElement("name") + nameText = self.parser.xml.createTextNode(data["name"]) + nameNode.appendChild(nameText) + connNode.appendChild(nameNode) + if data["type"] == "remote": + serverNode = self.parser.xml.createElement("server") + serverNode.setAttribute("ssl", data["ssl"]) + serverNode.setAttribute("user", data["user"]) + serverNode.setAttribute("port", data["port"]) + hostText = self.parser.xml.createTextNode(data["host"]) + serverNode.appendChild(hostText) + connNode.appendChild(serverNode) + found = False + for c in connections: + cid = c.attribute("id", "None") + if str(cid) == str(data["id"]): + found = c + break + if found: + connectionsNode.replaceChild(connNode, found) + else: + connectionsNode.appendChild(connNode) + self.parser.saveData() + self.refreshConnections() + + def slotRemoveConnection(self, data): + """ + remove connection from config file + """ + connectionsNode = self.parser.xml.elementsByTagName("connections").item(0) + if connectionsNode.isNull(): + raise Exception("null") + connections = self.parser.parseNode(connectionsNode) + found = False + for c in connections: + cid = c.attribute("id", "None") + if str(cid) == str(data["id"]): + found = c + break + if found: + connectionsNode.removeChild(found) + self.parser.saveData() + self.refreshConnections() + + def slotConnect(self, data): + """ + slot: connect button in connectionmanager + show password window if remote connection or start connecting + """ + self.connWindow.hide() + self.connData = data + if data["type"] == "local": + self.slotPasswordTyped("") + else: + self.pwWindow.show() + + def slotPasswordTyped(self, pw): + """ + connect to a core + if connection is local, parse the core config file for data + set up connector, show main window + """ + data = self.connData + data["password"] = pw + if not data["type"] == "remote": + coreparser = XMLParser("module/config/core.xml", "module/config/core_default.xml") + sections = coreparser.parseNode(coreparser.root, "dict") + conf = coreparser.parseNode(sections["remote"], "dict") + ssl = coreparser.parseNode(sections["ssl"], "dict") + data["port"] = conf["port"].text() + data["user"] = conf["username"].text() + data["password"] = conf["password"].text() + data["host"] = "127.0.0.1" + if str(ssl["activated"].text()).lower() == "true": + data["ssl"] = True + else: + data["ssl"] = False + if data["ssl"]: + data["ssl"] = "s" + else: + data["ssl"] = "" + server_url = "http%(ssl)s://%(user)s:%(password)s@%(host)s:%(port)s/" % data + self.connector.setAddr(str(server_url)) + self.startMain() + + def refreshConnections(self): + """ + reload connetions and display them + """ + self.parser.loadData() + conns = self.getConnections() + self.connWindow.emit(SIGNAL("setConnections(connections)"), conns) + for conn in conns: + if conn["default"]: + return conn return None - -class _Upper_Panel(wx.Panel): - def __init__(self, parent): - wx.Panel.__init__(self, parent) - sizer = wx.BoxSizer(wx.HORIZONTAL) - self.parent = parent - - self.list = Download_Liste(self) - - sizer.Add(self.list, 1, wx.EXPAND) - self.SetSizer(sizer) - - def refresh(self, links, data): - self.list.reload(links, data) - - def get_selected_ids(self, deselect=False): - """return ids and deselect items""" - item = self.list.GetFirstSelected() - if deselect: self.list.Select(item, on=0) - - if item == -1: - return False - - links = [] - links.append(self.parent.data['order'][item]) - - while self.list.GetNextSelected(item) != -1: - item = self.list.GetNextSelected(item) - if deselect: self.list.Select(item, on=0) - links.append(self.parent.data['order'][item]) - - return links - -class _Lower_Panel(wx.Panel): - def __init__(self, parent): - wx.Panel.__init__(self, parent) - self.SetBackgroundColour(wx.BLACK) - -class _Host_Dialog(wx.Dialog): - def __init__(self, parent, id, title): - wx.Dialog.__init__(self, parent, id, title, size=(250, 170)) - - self.host = wx.TextCtrl(self, -1, '127.0.0.1') - host_name = wx.StaticText(self, -1, 'Host:') - self.port = wx.TextCtrl(self, -1, '7272') - port_name = wx.StaticText(self, -1, 'Port:') - self.password = wx.TextCtrl(self, -1, 'pwhere') - password_name = wx.StaticText(self, -1, 'Password:') - button_ok = wx.Button(self, wx.ID_OK, 'Ok', size=(90, 28)) - button_cancel = wx.Button(self, wx.ID_CANCEL, 'Close', size=(90, 28)) - - - fgs = wx.FlexGridSizer(3, 2, 9, 25) + + def slotAddLinks(self, links): + """ + emitted from main window + add urls to the collector + """ + self.connector.addURLs(links) + + def slotSetDownloadStatus(self, status): + """ + toolbar start/pause slot + """ + self.connector.setPause(not status) + + def slotAddPackage(self, name, ids): + """ + emitted from main window + add package to the collector + """ + packid = self.connector.newPackage(str(name)) + for fileid in ids: + self.connector.addFileToPackage(fileid, packid) + self.mainWindow.lastAddedID = packid + + def slotAddFileToPackage(self, pid, fid): + """ + emitted from collector view after a drop action + """ + self.connector.addFileToPackage(fid, pid) + + def slotAddContainer(self, path): + """ + emitted from main window + add container + """ + filename = basename(path) + type = "".join(filename.split(".")[-1]) + fh = open(path, "r") + content = fh.read() + fh.close() + self.connector.uploadContainer(filename, type, content) + + def slotSaveMainWindow(self, state, geo): + """ + save the window geometry and toolbar/dock position to config file + """ + mainWindowNode = self.parser.xml.elementsByTagName("mainWindow").item(0) + if mainWindowNode.isNull(): + mainWindowNode = self.parser.xml.createElement("mainWindow") + self.parser.root.appendChild(mainWindowNode) + stateNode = mainWindowNode.toElement().elementsByTagName("state").item(0) + geoNode = mainWindowNode.toElement().elementsByTagName("geometry").item(0) + newStateNode = self.parser.xml.createTextNode(state) + newGeoNode = self.parser.xml.createTextNode(geo) - fgs.AddMany([(host_name), (self.host, 0, wx.EXPAND), (port_name), (self.port, 1, wx.EXPAND), (password_name), (self.password, 1, wx.EXPAND), (button_ok, 1, wx.EXPAND), (button_cancel, 1, wx.EXPAND)]) + stateNode.removeChild(stateNode.firstChild()) + geoNode.removeChild(geoNode.firstChild()) + stateNode.appendChild(newStateNode) + geoNode.appendChild(newGeoNode) - fgs.AddGrowableCol(1, 1) + self.parser.saveData() + + def restoreMainWindow(self): + """ + load and restore main window geometry and toolbar/dock position from config + """ + mainWindowNode = self.parser.xml.elementsByTagName("mainWindow").item(0) + if mainWindowNode.isNull(): + return + nodes = self.parser.parseNode(mainWindowNode, "dict") - hbox = wx.BoxSizer(wx.HORIZONTAL) - hbox.Add(fgs, 1, wx.ALL | wx.EXPAND, 15) + state = str(nodes["state"].text()) + geo = str(nodes["geometry"].text()) + self.mainWindow.restoreWindow(state, geo) + self.mainWindow.captchaDock.hide() + + def slotPushPackageToQueue(self, id): + """ + emitted from main window + push the collector package to queue + """ + self.connector.pushPackageToQueue(id) + + def slotRestartDownload(self, id, isPack): + """ + emitted from main window + restart download + """ + if isPack: + self.connector.restartPackage(id) + else: + self.connector.restartFile(id) + + def slotRemoveDownload(self, id, isPack): + """ + emitted from main window + remove download + """ + if isPack: + self.connector.removePackage(id) + else: + self.connector.removeFile(id) + + def slotStopAllDownloads(self): + """ + emitted from main window + stop all running downloads + """ + self.connector.stopAllDownloads() + + def slotClipboardChange(self): + """ + called if clipboard changes + """ + if self.checkClipboard: + text = self.clipboard.text() + pattern = re.compile(r"(http|https)://[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?/.*)?") + matches = pattern.finditer(text) + for match in matches: + self.slotAddLinks([str(match.group(0))]) + + def slotSetClipboardStatus(self, status): + """ + set clipboard checking + """ + self.checkClipboard = status + + def slotChangePackageName(self, pid, name): + """ + package name edit finished + """ + self.connector.setPackageName(pid, str(name)) + + def slotPullOutPackage(self, pid, isPack): + """ + pull package out of the queue + """ + if isPack: + self.connector.pullOutPackage(pid) + + def checkCaptcha(self): + if self.connector.captchaWaiting() and self.mainWindow.captchaDock.isFree(): + cid, img, imgType = self.connector.getCaptcha() + self.mainWindow.captchaDock.emit(SIGNAL("setTask"), cid, str(img), imgType) + + def slotCaptchaDone(self, cid, result): + self.connector.setCaptchaResult(str(cid), str(result)) + + class Loop(QThread): + """ + main loop (not application loop) + """ - self.SetSizer(hbox) + def __init__(self, parent): + QThread.__init__(self) + self.parent = parent + self.running = True -class Pyload_Main_Gui(wx.Frame): - def __init__(self, parent, id, title="pyLoad"): - - wx.Frame.__init__(self, parent, id, title, size=(910, 500)) - - app_path = dirname(abspath(__file__)) + sep - - # vars - self.links = [] - self.data = {} - - # Menubar - menubar = wx.MenuBar() - menu_file = wx.Menu() - submenu_exit = menu_file.Append(-1, 'Schliessen', 'pyLoad beenden') - menubar.Append(menu_file, '&Datei') - menu_pyload = wx.Menu() - self.submenu_pyload_connect = menu_pyload.Append(-1, 'Connect', 'Connect to pyLoad') - self.submenu_pyload_disconnect = menu_pyload.Append(-1, 'Disconnect', 'Disconnect') - self.submenu_pyload_shutdown = menu_pyload.Append(-1, 'Shutdown', 'Shutdown pyLoad Core') - menubar.Append(menu_pyload, '&pyLoad') - self.SetMenuBar(menubar) + def run(self): + while self.running: + sleep(1) + self.update() - # Statusbar - self.CreateStatusBar() - - # icon - icon1 = wx.Icon(app_path + '/icons/pyload.ico', wx.BITMAP_TYPE_ICO) - self.SetIcon(icon1) - - # Toolbar - toolbar = self.CreateToolBar() - toolbar.SetToolBitmapSize((32, 32)) - add = toolbar.AddLabelTool(2, '', wx.Bitmap(app_path + '/icons/add.png')) - delete = toolbar.AddLabelTool(3, '', wx.Bitmap(app_path + '/icons/del.png')) - start = toolbar.AddLabelTool(4, '', wx.Bitmap(app_path + '/icons/start.png')) - pause = toolbar.AddLabelTool(5, '', wx.Bitmap(app_path + '/icons/pause.png')) - stop = toolbar.AddLabelTool(6, '', wx.Bitmap(app_path + '/icons/stop.png')) - up = toolbar.AddLabelTool(7, '', wx.Bitmap(app_path + '/icons/up.png')) - down = toolbar.AddLabelTool(8, '', wx.Bitmap(app_path + '/icons/down.png')) - config = toolbar.AddLabelTool(9, '', wx.Bitmap(app_path + '/icons/setup.png')) - toolbar.Realize() - - #splitter = wx.SplitterWindow(self) - self.panel_up = _Upper_Panel(self) - #panel_down = _Lower_Panel(splitter) - #splitter.SplitHorizontally(panel_up, panel_down, 300) - - # Binds - self.Bind(wx.EVT_MENU, self.exit_button_clicked, submenu_exit) - self.Bind(wx.EVT_MENU, self.connect, self.submenu_pyload_connect) - self.Bind(wx.EVT_MENU, self.disconnect, self.submenu_pyload_disconnect) - self.Bind(wx.EVT_MENU, self.shutdown, self.submenu_pyload_shutdown) - self.Bind(wx.EVT_TOOL, self.add_button_clicked, add) - self.Bind(wx.EVT_TOOL, self.delete_button_clicked, delete) - self.Bind(wx.EVT_TOOL, self.up_button_clicked, up) - self.Bind(wx.EVT_TOOL, self.down_button_clicked, down) - self.Bind(EVT_DATA_ARRIVED, self.onUpdate) - - self.Centre() - self.Show(True) + def update(self): + """ + methods to call + """ + self.parent.refreshServerStatus() + self.parent.refreshLog() + self.parent.updateAvailable() + self.parent.checkCaptcha() + def stop(self): + self.running = False - def exit_button_clicked(self, event): - self.Close() - - def connect(self, event): - socket_host = _Host_Dialog(self, -1, 'Connect to:') - res_socket = socket_host.ShowModal() - if (res_socket == wx.ID_OK): - try: - self.thread = SocketThread(socket_host.host.GetValue(), int(socket_host.port.GetValue()), socket_host.password.GetValue(), self) - self.SetStatusText('Connected to: %s:%s' % (socket_host.host.GetValue(), socket_host.port.GetValue())) - except socket.error: - if (socket_host.host.GetValue() in ['localhost', '127.0.0.1']): - if (wx.MessageDialog(None, 'Do you want to start pyLoadCore locally?', 'Start pyLoad', wx.OK | wx.CANCEL).ShowModal() == wx.ID_OK): - cmd = ['python', 'pyLoadCore.py'] - subprocess.Popen(cmd) - sleep(2) - self.thread = SocketThread(socket_host.host.GetValue(), int(socket_host.port.GetValue()), socket_host.password.GetValue(), self) - self.SetStatusText('Connected to: %s:%s' % (socket_host.host.GetValue(), socket_host.port.GetValue())) - else: - wx.MessageDialog(None, 'Cant connect to: %s:%s' % (socket_host.host.GetValue(), socket_host.port.GetValue()), 'Error', wx.OK | wx.ICON_ERROR).ShowModal() - else: - wx.MessageDialog(None, 'Cant connect to: %s:%s' % (socket_host.host.GetValue(), socket_host.port.GetValue()), 'Error', wx.OK | wx.ICON_ERROR).ShowModal() - - self.thread.push_exec("get_links") - - def disconnect(self, event): - self.thread.socket.close_when_done() - self.SetStatusText('') - - def shutdown(self, event): - self.thread.push_exec("kill") - - def add_button_clicked(self, event): - #test - #self.thread.push_exec("get_downloads") - - add_download = _Download_Dialog(None, -1) - result = add_download.ShowModal() - add_download.Destroy() - downloads = add_download.links.GetValue().split() - self.thread.push_exec('add_links', [downloads]) - - def delete_button_clicked(self, event): - - links = self.panel_up.get_selected_ids(True) - - self.thread.push_exec('remove_links', [links]) - - def up_button_clicked(self, event): - - links = self.panel_up.get_selected_ids() - self.thread.push_exec('move_links_up', [links]) - - - def down_button_clicked(self, event): - - links = self.panel_up.get_selected_ids() - - self.thread.push_exec('move_links_down', [links]) - - def show_links(self, links): - for link in links: - #wx.MessageDialog(self, str(link), 'info', style=wx.OK).ShowModal() - print str(link) - - def data_arrived(self, rep): - evt = DataArrived(obj=rep) - wx.PostEvent(self, evt) - - def onUpdate(self, evt): - - if evt.obj.function == "get_downloads": - pass - #self.show_links(evt.obj.response) - - if evt.obj.command == "update": - self.links = evt.obj.data - self.panel_up.refresh(self.links, self.data) - - if evt.obj.command == "file_list" or evt.obj.function == "get_links": - self.data = evt.obj.data - self.panel_up.refresh(self.links, self.data) - - -def format_time(seconds): - seconds = int(seconds) - hours, seconds = divmod(seconds, 3600) - minutes, seconds = divmod(seconds, 60) - return "%.2i:%.2i:%.2i" % (hours, minutes, seconds) - +if __name__ == "__main__": + app = main() + app.loop() -app = wx.App() -Pyload_Main_Gui(None, -1) -app.MainLoop() diff --git a/pyLoadUpdater.py b/pyLoadUpdater.py deleted file mode 100755 index e6395a080..000000000 --- a/pyLoadUpdater.py +++ /dev/null @@ -1,106 +0,0 @@ -import urllib -import urllib2 -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# -#Copyright (C) 2009 RaNaN -# -#This program is free software; you can redistribute it and/or modify -#it under the terms of the GNU General Public License as published by -#the Free Software Foundation; either version 3 of the License, -#or (at your option) any later version. -# -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#See the GNU General Public License for more details. -# -#You should have received a copy of the GNU General Public License -# along with this program; if not, see <http://www.gnu.org/licenses/>. -# -### - -## read version from core -import re -import zipfile -import os - -class Unzip: - def __init__(self): - pass - - def extract(self, file, dir): - if not dir.endswith(':') and not os.path.exists(dir): - os.mkdir(dir) - - zf = zipfile.ZipFile(file) - - # create directory structure to house files - self._createstructure(file, dir) - - # extract files to directory structure - for i, name in enumerate(zf.namelist()): - - if not name.endswith('/') and not name.endswith("config"): - print "extracting", name.replace("pyload/","") - outfile = open(os.path.join(dir, name.replace("pyload/","")), 'wb') - outfile.write(zf.read(name)) - outfile.flush() - outfile.close() - - def _createstructure(self, file, dir): - self._makedirs(self._listdirs(file), dir) - - def _makedirs(self, directories, basedir): - """ Create any directories that don't currently exist """ - for dir in directories: - curdir = os.path.join(basedir, dir) - if not os.path.exists(curdir): - os.mkdir(curdir) - - def _listdirs(self, file): - """ Grabs all the directories in the zip structure - This is necessary to create the structure before trying - to extract the file to it. """ - zf = zipfile.ZipFile(file) - - dirs = [] - - for name in zf.namelist(): - if name.endswith('/'): - dirs.append(name.replace("pyload/","")) - - dirs.sort() - return dirs - -def main(): - print "Updating pyLoad" - - try: - f = open("pyLoadCore.py", "rb") - version = re.search(r"CURRENT_VERSION = '([0-9.]+)'",f.read()).group(1) - f.close() - except: - version = "0.0.0" - - print "Your version:", version - - req = urllib2.urlopen("http://update.pyload.org/index.php?do="+version) - result = req.readline() - - if result == "False": - print "pyLoad is up-to-date, nothing to do." - return False - - req = urllib2.urlopen("http://update.pyload.org/index.php") - result = req.readline() - print "Newest Version:", result - print "Download new Version" - - urllib.urlretrieve("http://update.pyload.org/index.php?do=download", "lastest_version.zip") - - u = Unzip() - u.extract("lastest_version.zip",".") - -if __name__ == "__main__": - main() diff --git a/scripts/Readme.txt b/scripts/Readme.txt new file mode 100644 index 000000000..1c326801d --- /dev/null +++ b/scripts/Readme.txt @@ -0,0 +1,25 @@ + ############################# + ### pyLoad Script Support ### + ############################# + +pyLoad is able to start any kind of scripts at given events. +Simply put your script in a suitable folder and pyLoad will execute it at the given events and pass some arguments to them. + +--> Note: Scripts, which starts with # will be ignored! +For Example: #converter.sh will not be executed. + +--> Note: You have to restart pyload when you change script names or locations. + +Below you see the list of arguments, which are passed to the scripts. + +## Argument list ## + +download_preparing: pluginname url + +download_finished: pluginname url filename filelocation + +package_finshed: packagename packagelocation + +before_reconnect: oldip + +after_reconnect: newip
\ No newline at end of file |