Codebase list deluge / 86d860b
Imported Upstream version 1.3.13+git20161130.48cedf63 Andrew Starr-Bochicchio 7 years ago
24 changed file(s) with 206 addition(s) and 95 deletion(s). Raw diff Collapse all Expand all
3434
3535
3636 """Common functions for various parts of Deluge to use."""
37
38 from __future__ import with_statement
3739
3840 import os
3941 import time
176178 if not windows_check():
177179 from xdg.BaseDirectory import xdg_config_home
178180 try:
179 for line in open(os.path.join(xdg_config_home, 'user-dirs.dirs'), 'r'):
180 if not line.startswith('#') and line.startswith('XDG_DOWNLOAD_DIR'):
181 download_dir = os.path.expandvars(line.partition("=")[2].rstrip().strip('"'))
182 break
181 with open(os.path.join(xdg_config_home, 'user-dirs.dirs'), 'r') as _file:
182 for line in _file:
183 if not line.startswith('#') and line.startswith('XDG_DOWNLOAD_DIR'):
184 download_dir = os.path.expandvars(line.partition("=")[2].rstrip().strip('"'))
185 break
183186 except IOError:
184187 pass
185188
6565 version as this will be done internally.
6666
6767 """
68
69 from __future__ import with_statement
6870
6971 import cPickle as pickle
7072 import shutil
355357 filename = self.__config_file
356358
357359 try:
358 data = open(filename, "rb").read()
360 with open(filename, "rb") as _file:
361 data = _file.read()
359362 except IOError, e:
360363 log.warning("Unable to open config file %s: %s", filename, e)
361364 return
403406 # Check to see if the current config differs from the one on disk
404407 # We will only write a new config file if there is a difference
405408 try:
406 data = open(filename, "rb").read()
409 with open(filename, "rb") as _file:
410 data = _file.read()
407411 objects = find_json_objects(data)
408412 start, end = objects[0]
409413 version = json.loads(data[start:end])
3131 # statement from all source files in the program, then also delete it here.
3232 #
3333 #
34
35 from __future__ import with_statement
3436
3537 import os
3638 import random
117119 f = [localclient]
118120 else:
119121 # Load the auth file into a dictionary: {username: password, ...}
120 f = open(auth_file, "r").readlines()
122 with open(auth_file, "r") as _file:
123 f = _file.readlines()
121124
122125 for line in f:
123126 line = line.strip()
142145 self.__auth[username.strip()] = (password.strip(), level)
143146
144147 if "localclient" not in self.__auth:
145 open(auth_file, "a").write(self.__create_localclient_account())
148 with open(auth_file, "a") as _file:
149 _file.write(self.__create_localclient_account())
3232 #
3333 #
3434
35 from __future__ import with_statement
36
3537 from deluge._libtorrent import lt
3638
3739 import os
185187 def __load_session_state(self):
186188 """Loads the libtorrent session state"""
187189 try:
188 self.session.load_state(lt.bdecode(
189 open(deluge.configmanager.get_config_dir("session.state"), "rb").read()))
190 with open(deluge.configmanager.get_config_dir("session.state"), "rb") as _file:
191 self.session.load_state(lt.bdecode(_file.read()))
190192 except Exception, e:
191193 log.warning("Failed to load lt state: %s", e)
192194
660662 if add_to_session:
661663 options = {}
662664 options["download_location"] = os.path.split(path)[0]
663 self.add_torrent_file(os.path.split(target)[1], open(target, "rb").read(), options)
665 with open(target, "rb") as _file:
666 self.add_torrent_file(os.path.split(target)[1], _file.read(), options)
664667
665668 @export
666669 def upload_plugin(self, filename, filedump):
3131 # statement from all source files in the program, then also delete it here.
3232 #
3333
34 from __future__ import with_statement
35
3436 import os
3537 import gettext
3638 import locale
5153 if os.path.isfile(deluge.configmanager.get_config_dir("deluged.pid")):
5254 # Get the PID and the port of the supposedly running daemon
5355 try:
54 (pid, port) = open(deluge.configmanager.get_config_dir("deluged.pid")).read().strip().split(";")
56 with open(deluge.configmanager.get_config_dir("deluged.pid")) as _file:
57 (pid, port) = _file.read().strip().split(";")
5558 pid = int(pid)
5659 port = int(port)
5760 except ValueError:
168171 if not classic:
169172 # Write out a pid file all the time, we use this to see if a deluged is running
170173 # We also include the running port number to do an additional test
171 open(deluge.configmanager.get_config_dir("deluged.pid"), "wb").write(
172 "%s;%s\n" % (os.getpid(), port))
174 with open(deluge.configmanager.get_config_dir("deluged.pid"), "wb") as _file:
175 _file.write("%s;%s\n" % (os.getpid(), port))
173176
174177 component.start()
175178 try:
9090 # Check all the torrent's tracker_status for 'Error:' and only return torrent_ids
9191 # that have this substring in their tracker_status
9292 for torrent_id in torrent_ids:
93 if _("Error") + ":" in tm[torrent_id].get_status(["tracker_status"])["tracker_status"]:
93 if "Error:" in tm[torrent_id].get_status(["tracker_status"])["tracker_status"]:
9494 filtered_torrent_ids.append(torrent_id)
9595
9696 return filtered_torrent_ids
3232 #
3333 #
3434
35 from __future__ import with_statement
3536
3637 import os.path
3738 import threading
297298 if value:
298299 state = None
299300 try:
300 state = lt.bdecode(open(state_file, "rb").read())
301 with open(state_file, "rb") as _file:
302 state = lt.bdecode(_file.read())
301303 except Exception, e:
302304 log.warning("Unable to read DHT state file: %s", e)
303305
497499 if geoip_db:
498500 try:
499501 self.session.load_country_db(str(geoip_db))
500 except Exception, e:
502 except RuntimeError, e:
501503 log.error("Unable to load geoip database!")
502504 log.exception(e)
505 except AttributeError:
506 log.warning("GeoIP Unavailable")
503507
504508 def _on_cache_size(self, key, value):
505509 log.debug("%s: %s", key, value)
3333 #
3434
3535 """RPCServer Module"""
36
37 from __future__ import with_statement
3638
3739 import sys
3840 import zlib
516518
517519 # Write out files
518520 ssl_dir = deluge.configmanager.get_config_dir("ssl")
519 open(os.path.join(ssl_dir, "daemon.pkey"), "w").write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
520 open(os.path.join(ssl_dir, "daemon.cert"), "w").write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
521 with open(os.path.join(ssl_dir, "daemon.pkey"), "w") as _file:
522 _file.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
523 with open(os.path.join(ssl_dir, "daemon.cert"), "w") as _file:
524 _file.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
521525 # Make the files only readable by this user
522526 for f in ("daemon.pkey", "daemon.cert"):
523527 os.chmod(os.path.join(ssl_dir, f), stat.S_IREAD | stat.S_IWRITE)
3333
3434 """Internal Torrent class"""
3535
36 from __future__ import with_statement
37
3638 import os
3739 import time
3840 from urllib import unquote
589591 ret.append(float(file_progress[i]) / float(f["size"]))
590592 except ZeroDivisionError:
591593 ret.append(0.0)
594 except IndexError:
595 return []
592596
593597 return ret
594598
956960 md = lt.bdecode(self.torrent_info.metadata())
957961 torrent_file = {}
958962 torrent_file["info"] = md
959 open(path, "wb").write(lt.bencode(torrent_file))
963 with open(path, "wb") as _file:
964 _file.write(lt.bencode(torrent_file))
960965 except Exception, e:
961966 log.warning("Unable to save torrent file: %s", e)
962967
739739 os.fsync(state_file.fileno())
740740 state_file.close()
741741 os.rename(filepath_tmp, filepath)
742 except IOError:
742 except IOError, ex:
743743 log.error("Unable to save %s: %s", filepath, ex)
744744 if os.path.isfile(filepath_bak):
745745 log.info("Restoring backup of state from: %s", filepath_bak)
10131013
10141014 # Set the tracker status for the torrent
10151015 if alert.message() != "Got peers from DHT":
1016 torrent.set_tracker_status(_("Announce OK"))
1016 torrent.set_tracker_status("Announce OK")
10171017
10181018 # Check to see if we got any peer information from the tracker
10191019 if alert.handle.status().num_complete == -1 or \
10291029 return
10301030
10311031 # Set the tracker status for the torrent
1032 torrent.set_tracker_status(_("Announce Sent"))
1032 torrent.set_tracker_status("Announce Sent")
10331033
10341034 def on_alert_tracker_warning(self, alert):
10351035 log.debug("on_alert_tracker_warning")
10371037 torrent = self.torrents[str(alert.handle.info_hash())]
10381038 except:
10391039 return
1040 tracker_status = '%s: %s' % (_("Warning"), decode_string(alert.message()))
1040 tracker_status = '%s: %s' % ("Warning", decode_string(alert.message()))
10411041 # Set the tracker status for the torrent
10421042 torrent.set_tracker_status(tracker_status)
10431043
10541054 except (RuntimeError, KeyError):
10551055 return
10561056
1057 torrent.set_tracker_status("%s: %s" % (_("Error"), error_message))
1057 torrent.set_tracker_status("Error: %s" % error_message)
10581058
10591059 def on_alert_storage_moved(self, alert):
10601060 log.debug("on_alert_storage_moved")
3737 # user runs the command 'deluge'.
3838
3939 """Main starting point for Deluge. Contains the main() entry point."""
40
41 from __future__ import with_statement
4042
4143 import os
4244 import sys
206208 # Writes out a pidfile if necessary
207209 def write_pidfile():
208210 if options.pidfile:
209 open(options.pidfile, "wb").write("%s\n" % os.getpid())
211 with open(options.pidfile, "wb") as _file:
212 _file.write("%s\n" % os.getpid())
210213
211214 # If the donot daemonize is set, then we just skip the forking
212215 if not options.donot:
3131 # statement from all source files in the program, then also delete it here.
3232 #
3333 #
34
35 from __future__ import with_statement
3436
3537 import sys
3638 import os
217219 progress(len(pieces), num_pieces)
218220
219221 r = fd.read(piece_size)
222 fd.close()
220223
221224 torrent["info"]["pieces"] = "".join(pieces)
222225
223226 # Write out the torrent file
224 open(torrent_path, "wb").write(bencode(torrent))
227 with open(torrent_path, "wb") as _file:
228 _file.write(bencode(torrent))
225229
226230 def get_data_path(self):
227231 """
141141 command = os.path.expanduser(command)
142142
143143 cmd_args = [torrent_id, torrent_name, save_path]
144 if windows_check:
144 if windows_check():
145145 # Escape ampersand on windows (see #2784)
146146 cmd_args = [arg.replace("&", "^^^&") for arg in cmd_args]
147147
3737 all the interfaces.
3838 """
3939
40 from __future__ import with_statement
41
4042 import os
4143 import sys
4244 import urlparse
5355 from deluge.log import LOG as log
5456 import deluge.configmanager
5557
58
59 # Dummy translation list so tracker status is translatable.
60 def _(message):
61 return message
62
63
64 TRACKER_STATUS_TRANSLATION = [
65 _('Error'),
66 _('Warning'),
67 _('Announce OK'),
68 _('Announce Sent')
69 ]
70 del _
71
72
5673 class TorrentInfo(object):
5774 """
5875 Collects information about a torrent file.
6582 # Get the torrent data from the torrent file
6683 try:
6784 log.debug("Attempting to open %s.", filename)
68 self.__m_filedata = open(filename, "rb").read()
85 with open(filename, "rb") as _file:
86 self.__m_filedata = _file.read()
6987 self.__m_metadata = bencode.bdecode(self.__m_filedata)
7088 except Exception, e:
7189 log.warning("Unable to open %s: %s", filename, e)
106124 f["path"] = path
107125 f["index"] = index
108126 if "sha1" in f and len(f["sha1"]) == 20:
109 f["sha1"] = f["sha1"].encode('hex')
127 f["sha1"] = f["sha1"].encode('hex')
110128 if "ed2k" in f and len(f["ed2k"]) == 16:
111 f["ed2k"] = f["ed2k"].encode('hex')
129 f["ed2k"] = f["ed2k"].encode('hex')
130 if "filehash" in f and len(f["filehash"]) == 20:
131 f["filehash"] = f["filehash"].encode('hex')
112132 paths[path] = f
113133 dirname = os.path.dirname(path)
114134 while dirname:
408428 """
409429 auth_file = deluge.configmanager.get_config_dir("auth")
410430 if os.path.exists(auth_file):
411 for line in open(auth_file):
412 line = line.strip()
413 if line.startswith("#") or not line:
414 # This is a comment or blank line
415 continue
416
417 try:
418 lsplit = line.split(":")
419 except Exception, e:
420 log.error("Your auth file is malformed: %s", e)
421 continue
422
423 if len(lsplit) == 2:
424 username, password = lsplit
425 elif len(lsplit) == 3:
426 username, password, level = lsplit
427 else:
428 log.error("Your auth file is malformed: Incorrect number of fields!")
429 continue
430
431 if username == "localclient":
432 return (username, password)
431 with open(auth_file) as _file:
432 for line in _file:
433 line = line.strip()
434 if line.startswith("#") or not line:
435 # This is a comment or blank line
436 continue
437
438 try:
439 lsplit = line.split(":")
440 except Exception, e:
441 log.error("Your auth file is malformed: %s", e)
442 continue
443
444 if len(lsplit) == 2:
445 username, password = lsplit
446 elif len(lsplit) == 3:
447 username, password, level = lsplit
448 else:
449 log.error("Your auth file is malformed: Incorrect number of fields!")
450 continue
451
452 if username == "localclient":
453 return (username, password)
433454 return ("", "")
3232 # statement from all source files in the program, then also delete it here.
3333 #
3434 #
35
36 from __future__ import with_statement
37
3538 from twisted.internet import defer
3639
3740 from deluge.ui.console.main import BaseCommand
8588 continue
8689 self.console.write("{!info!}Attempting to add torrent: %s" % arg)
8790 filename = os.path.split(arg)[-1]
88 filedump = base64.encodestring(open(arg, "rb").read())
91 with open(arg, "rb") as _file:
92 filedump = base64.encodestring(_file.read())
8993 deferreds.append(client.core.add_torrent_file(filename, filedump, t_options).addCallback(on_success).addErrback(on_fail))
9094
9195 return defer.DeferredList(deferreds)
737737 dialog.set_default_response(gtk.RESPONSE_OK)
738738 dialog.set_transient_for(self.dialog)
739739 entry.grab_focus()
740
741 text = (gtk.clipboard_get(selection='PRIMARY').wait_for_text() or
742 gtk.clipboard_get().wait_for_text()).strip()
743 if len(text) == 40:
744 entry.set_text(text)
745
740746 dialog.show_all()
741747 response = dialog.run()
742 if response == gtk.RESPONSE_OK and len(entry.get_text()) == 40:
748 infohash = entry.get_text().strip()
749 if response == gtk.RESPONSE_OK and len(infohash) == 40:
743750 trackers = []
744751 b = textview.get_buffer()
745752 lines = b.get_text(b.get_start_iter(), b.get_end_iter()).strip().split("\n")
750757 # Convert the information to a magnet uri, this is just easier to
751758 # handle this way.
752759 log.debug("trackers: %s", trackers)
753 magnet = deluge.common.create_magnet_uri(
754 infohash=entry.get_text().decode("utf_8"),
755 trackers=trackers)
760 magnet = deluge.common.create_magnet_uri(infohash, infohash, trackers)
756761 log.debug("magnet uri: %s", magnet)
757762 self.add_from_magnets([magnet])
758763
267267
268268 if deluge.common.osx_check() and gtk.gdk.WINDOWING == "quartz":
269269 def nsapp_open_file(osxapp, filename):
270 # Will be raised at app launch (python opening main script)
271 if filename.endswith('Deluge-bin'):
270 # Ignore command name which is raised at app launch (python opening main script).
271 if filename == sys.argv[0]:
272272 return True
273273 from deluge.ui.gtkui.ipcinterface import process_args
274274 process_args([filename])
3232 #
3333 #
3434
35 from __future__ import with_statement
3536
3637 import sys
3738 import os
105106 port = random.randrange(20000, 65535)
106107 reactor.listenTCP(port, self.factory)
107108 # Store the port number in the socket file
108 open(socket, "w").write(str(port))
109 with open(socket, "w") as _file:
110 _file.write(str(port))
109111 # We need to process any args when starting this process
110112 process_args(args)
111113 else:
112114 # Send to existing deluge process
113 port = int(open(socket, "r").readline())
115 with open(socket) as _file:
116 port = int(_file.readline())
114117 self.factory = ClientFactory()
115118 self.factory.args = args
116119 self.factory.protocol = IPCProtocolClient
220223 component.get("AddTorrentDialog").add_from_files([path])
221224 component.get("AddTorrentDialog").show(config["focus_add_dialog"])
222225 else:
223 client.core.add_torrent_file(os.path.split(path)[-1], base64.encodestring(open(path, "rb").read()), None)
226 with open(path, "rb") as _file:
227 filedump = base64.encodestring(_file.read())
228 client.core.add_torrent_file(os.path.split(path)[-1], filedump, None)
3232 #
3333 #
3434
35 from __future__ import with_statement
3536
3637 import pygtk
3738 pygtk.require('2.0')
957958
958959 if not client.is_localhost():
959960 # We need to send this plugin to the daemon
960 filedump = base64.encodestring(open(filepath, "rb").read())
961 with open(filepath, "rb") as _file:
962 filedump = base64.encodestring(_file.read())
961963 client.core.upload_plugin(filename, filedump)
962964
963965 client.core.rescan_plugins()
3939 from deluge.ui.client import client
4040 import deluge.component as component
4141 import deluge.common
42 from deluge.ui.common import TRACKER_STATUS_TRANSLATION
4243 from deluge.ui.gtkui.torrentdetails import Tab
4344 from deluge.log import LOG as log
45
4446
4547 def fpeer_sized(first, second):
4648 return "%s (%s)" % (deluge.common.fsize(first), deluge.common.fsize(second))
6163 return "%s (%s %s)" % (deluge.common.fspeed(value), max_value, _("KiB/s"))
6264 else:
6365 return deluge.common.fspeed(value)
66
67 def ftranslate(text):
68 if text in TRACKER_STATUS_TRANSLATION:
69 text = _(text)
70 elif text:
71 for status in TRACKER_STATUS_TRANSLATION:
72 if status in text:
73 text = text.replace(status, _(status))
74 break
75 return text
76
6477
6578 class StatusTab(Tab):
6679 def __init__(self):
8497 (glade.get_widget("summary_peers"), deluge.common.fpeer, ("num_peers", "total_peers")),
8598 (glade.get_widget("summary_eta"), deluge.common.ftime, ("eta",)),
8699 (glade.get_widget("summary_share_ratio"), fratio, ("ratio",)),
87 (glade.get_widget("summary_tracker_status"), None, ("tracker_status",)),
100 (glade.get_widget("summary_tracker_status"), ftranslate, ("tracker_status",)),
88101 (glade.get_widget("summary_next_announce"), deluge.common.ftime, ("next_announce",)),
89102 (glade.get_widget("summary_active_time"), deluge.common.ftime, ("active_time",)),
90103 (glade.get_widget("summary_seed_time"), deluge.common.ftime, ("seeding_time",)),
3131 # statement from all source files in the program, then also delete it here.
3232 #
3333 #
34
35 from __future__ import with_statement
3436
3537 import os
3638 from HTMLParser import HTMLParser, HTMLParseError
225227 if not url:
226228 url = self.host_to_url(host)
227229 log.debug("Downloading %s %s", host, url)
228 return download_file(url, mkstemp()[1], force_filename=True)
230 fd, filename = mkstemp(prefix='deluge_ticon.')
231 os.close(fd)
232 return download_file(url, filename, force_filename=True)
229233
230234 def on_download_page_complete(self, page):
231235 """
354358
355359 if PIL_INSTALLED:
356360 try:
357 Image.open(icon_name)
361 with Image.open(icon_name):
362 pass
358363 except IOError, e:
359364 raise InvalidIconError(e)
360365 else:
428433 """
429434 if icon:
430435 filename = icon.get_filename()
431 img = Image.open(filename)
432 if img.size > (16, 16):
433 new_filename = filename.rpartition('.')[0]+".png"
434 img = img.resize((16, 16), Image.ANTIALIAS)
435 img.save(new_filename)
436 if new_filename != filename:
437 os.remove(filename)
438 icon = TrackerIcon(new_filename)
436 with Image.open(filename) as img:
437 if img.size > (16, 16):
438 new_filename = filename.rpartition('.')[0]+".png"
439 img = img.resize((16, 16), Image.ANTIALIAS)
440 img.save(new_filename)
441 if new_filename != filename:
442 os.remove(filename)
443 icon = TrackerIcon(new_filename)
439444 return icon
440445
441446 def store_icon(self, icon, host):
118118 // InterfacePage.js:78
119119 GetText.add('Allow the use of multiple filters at once', '${escape(_("Allow the use of multiple filters at once"))}')
120120
121 // StatusTab.js:119
122 GetText.add('Announce OK', '${escape(_("Announce OK"))}')
123
124 // StatusTab.js:120
125 GetText.add('Announce Sent', '${escape(_("Announce Sent"))}')
126
121127 // OptionsTab.js:347, PreferencesWindow.js:107
122128 GetText.add('Apply', '${escape(_("Apply"))}')
123129
295301 // EncryptionPage.js:41
296302 GetText.add('Encryption', '${escape(_("Encryption"))}')
297303
298 // ConnectionManager.js:316, ConnectionManager.js:372, AddConnectionWindow.js:103, UrlWindow.js:116, FileWindow.js:103, AddWindow.js:211
304 // ConnectionManager.js:316, ConnectionManager.js:372, AddConnectionWindow.js:103, StatusTab.js:117, UrlWindow.js:116, FileWindow.js:103, AddWindow.js:211
299305 GetText.add('Error', '${escape(_("Error"))}')
300306
301307 // Menus.js:323
829835 // ConnectionManager.js:90
830836 GetText.add('Version', '${escape(_("Version"))}')
831837
838 // StatusTab.js:118
839 GetText.add('Warning', '${escape(_("Warning"))}')
840
832841 // ConnectionManager.js:285
833842 GetText.add('We recommend changing the default password.<br><br>Would you like to change it now?', '${escape(_("We recommend changing the default password.<br><br>Would you like to change it now?"))}')
834843
3232 #
3333 #
3434
35 from __future__ import with_statement
36
3537 import os
3638 import time
3739 import base64
781783 client.core.add_torrent_magnet(torrent["path"], torrent["options"])
782784 else:
783785 filename = os.path.basename(torrent["path"])
784 fdump = base64.encodestring(open(torrent["path"], "rb").read())
786 with open(torrent["path"], "rb") as _file:
787 fdump = base64.encodestring(_file.read())
785788 log.info("Adding torrent from file `%s` with options `%r`",
786789 filename, torrent["options"])
787790 client.core.add_torrent_file(filename, fdump, torrent["options"])
990993 client.core.rescan_plugins()
991994 return True
992995
993 plugin_data = base64.encodestring(open(path, "rb").read())
996 with open(path, "rb") as _file:
997 plugin_data = base64.encodestring(_file.read())
994998
995999 def on_upload_complete(*args):
9961000 client.core.rescan_plugins()
233233 request.setHeader("cache-control",
234234 "public, must-revalidate, max-age=86400")
235235 request.setHeader("content-type", "image/png")
236 data = open(filename, "rb")
236 with open(filename, "rb") as _file:
237 data = _file.read()
237238 request.setResponseCode(http.OK)
238 return data.read()
239 return data
239240 else:
240241 request.setResponseCode(http.NOT_FOUND)
241242 return ""
281282 log.debug("Serving path: '%s'", path)
282283 mime_type = mimetypes.guess_type(path)
283284 request.setHeader("content-type", mime_type[0])
284 return compress(open(path, "rb").read(), request)
285 with open(path, "rb") as _file:
286 data = _file.read()
287 return compress(data, request)
285288
286289 request.setResponseCode(http.NOT_FOUND)
287290 return "<h1>404 - Not Found</h1>"
385388
386389 order_file = os.path.join(dirpath, '.order')
387390 if os.path.isfile(order_file):
388 for line in open(order_file, 'rb'):
389 line = line.strip()
390 if not line or line[0] == '#':
391 continue
392 try:
393 pos, filename = line.split()
394 files.pop(files.index(filename))
395 if pos == '+':
396 files.insert(0, filename)
397 else:
398 files.append(filename)
399 except:
400 pass
391 with open(order_file, 'rb') as _file:
392 for line in _file:
393 line = line.strip()
394 if not line or line[0] == '#':
395 continue
396 try:
397 pos, filename = line.split()
398 files.pop(files.index(filename))
399 if pos == '+':
400 files.insert(0, filename)
401 else:
402 files.append(filename)
403 except:
404 pass
401405
402406 dirpath = dirpath[len(filepath)+1:]
403407 if dirpath:
438442 log.debug("Serving path: '%s'", path)
439443 mime_type = mimetypes.guess_type(path)
440444 request.setHeader("content-type", mime_type[0])
441 return compress(open(path, "rb").read(), request)
445 with open(path, "rb") as _file:
446 data = _file.read()
447 return compress(data, request)
442448
443449 request.setResponseCode(http.NOT_FOUND)
444450 return "<h1>404 - Not Found</h1>"