1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
|
import os
import re
import sys
import sha
import time
import string
import urllib
import socket
import threading
import traceback
import subprocess
import prefs
from clock import clock
from BitTorrent.bencode import bdecode, bencode
# Should we print out warning messages. Turn off in the unit tests.
chatter = True
inDownloader = False
# this gets set to True when we're in the download process.
# Perform escapes needed for Javascript string contents.
def quoteJS(x):
x = x.replace("\\", "\\\\") # \ -> \\
x = x.replace("\"", "\\\"") # " -> \"
x = x.replace("'", "\\'") # ' -> \'
x = x.replace("\n", "\\n") # newline -> \n
x = x.replace("\r", "\\r") # CR -> \r
return x
def getNiceStack():
"""Get a stack trace that's a easier to read that the full one. """
stack = traceback.extract_stack()
# We don't care about the unit test lines
while (len(stack) > 0 and
os.path.basename(stack[0][0]) == 'unittest.py' or
(isinstance(stack[0][3], str) and
stack[0][3].startswith('unittest.main'))):
stack = stack[1:]
# remove after the call to util.failed
for i in xrange(len(stack)):
if (os.path.basename(stack[i][0]) == 'util.py' and
stack[i][2] in ('failed', 'failedExn')):
stack = stack[:i+1]
break
# remove trapCall calls
stack = [i for i in stack if i[2] != 'trapCall']
return stack
# Parse a configuration file in a very simple format. Each line is
# either whitespace or "Key = Value". Whitespace is ignored at the
# beginning of Value, but the remainder of the line is taken
# literally, including any whitespace. There is no way to put a
# newline in a value. Returns the result as a dict.
def readSimpleConfigFile(path):
ret = {}
f = open(path, "rt")
for line in f.readlines():
# Skip blank lines
if re.match("^[ \t]*$", line):
continue
# Otherwise it'd better be a configuration setting
match = re.match(r"^([^ ]+) *= *([^\r\n]*)[\r\n]*$", line)
if not match:
print "WARNING: %s: ignored bad configuration directive '%s'" % \
(path, line)
continue
key = match.group(1)
value = match.group(2)
if key in ret:
print "WARNING: %s: ignored duplicate directive '%s'" % \
(path, line)
continue
ret[key] = value
return ret
# Given a dict, write a configuration file in the format that
# readSimpleConfigFile reads.
def writeSimpleConfigFile(path, data):
f = open(path, "wt")
for (k, v) in data.iteritems():
f.write("%s = %s\n" % (k, v))
f.close()
# Called at build-time to ask Subversion for the revision number of
# this checkout. Going to fail without Cygwin. Yeah, oh well. Pass the
# file or directory you want to use as a reference point. Returns an
# integer on success or None on failure.
def queryRevision(file):
try:
p = subprocess.Popen(["svn", "info", file], stdout=subprocess.PIPE)
info = p.stdout.read()
p.stdout.close()
url = re.search("URL: (.*)", info).group(1)
revision = re.search("Revision: (.*)", info).group(1)
return (url, revision)
except KeyboardInterrupt:
raise
except:
# whatever
return None
# 'path' is a path that could be passed to open() to open a file on
# this platform. It must be an absolute path. Return the file:// URL
# that would refer to the same file.
def absolutePathToFileURL(path):
if isinstance(path, unicode):
path = path.encode("utf-8")
parts = string.split(path, os.sep)
parts = [urllib.quote(x, ':') for x in parts]
if len(parts) > 0 and parts[0] == '':
# Don't let "/foo/bar" become "file:////foo/bar", but leave
# "c:/foo/bar" becoming "file://c:/foo/bar" -- technically :
# should become | (but only in a drive name?) but most
# consumers will let us get by with that.
parts = parts[1:]
return "file:///" + '/'.join(parts)
# Shortcut for 'failed' with the exception flag.
def failedExn(when, **kwargs):
failed(when, withExn = True, **kwargs)
# Puts up a dialog with debugging information encouraging the user to
# file a ticket. (Also print a call trace to stderr or whatever, which
# hopefully will end up on the console or in a log.) 'when' should be
# something like "when trying to play a video." The user will see
# it. If 'withExn' is true, last-exception information will be printed
# to. If 'detail' is true, it will be included in the report and the
# the console/log, but not presented in the dialog box flavor text.
def failed(when, withExn = False, details = None):
print "failed() called; generating crash report."
header = ""
try:
import config # probably works at runtime only
header += "App: %s\n" % config.get(prefs.LONG_APP_NAME)
header += "Publisher: %s\n" % config.get(prefs.PUBLISHER)
header += "Platform: %s\n" % config.get(prefs.APP_PLATFORM)
header += "Version: %s\n" % config.get(prefs.APP_VERSION)
header += "Serial: %s\n" % config.get(prefs.APP_SERIAL)
header += "Revision: %s\n" % config.get(prefs.APP_REVISION)
except KeyboardInterrupt:
raise
except:
pass
header += "Time: %s\n" % time.asctime()
header += "When: %s\n" % when
header += "\n"
if withExn:
header += "Exception\n---------\n"
header += ''.join(traceback.format_exception(*sys.exc_info()))
header += "\n"
if details:
header += "Details: %s\n" % (details, )
header += "Call stack\n----------\n"
try:
stack = getNiceStack()
except KeyboardInterrupt:
raise
except:
stack = traceback.extract_stack()
header += ''.join(traceback.format_list(stack))
header += "\n"
header += "Threads\n-------\n"
header += "Current: %s\n" % threading.currentThread().getName()
header += "Active:\n"
for t in threading.enumerate():
header += " - %s%s\n" % \
(t.getName(),
t.isDaemon() and ' [Daemon]' or '')
# Combine the header with the logfile contents, if available, to
# make the dialog box crash message. {{{ and }}} are Trac
# Wiki-formatting markers that force a fixed-width font when the
# report is pasted into a ticket.
report = "{{{\n%s}}}\n" % header
def readLog(logFile, logName="Log"):
try:
f = open(logFile, "rt")
logContents = "%s\n---\n" % logName
logContents += f.read()
f.close()
except KeyboardInterrupt:
raise
except:
print "WARNING: Error reading logfile: %s" % logFile
import traceback
traceback.print_exc()
logContents = ''
return logContents
logFile = config.get(prefs.LOG_PATHNAME)
downloaderLogFile = config.get(prefs.DOWNLOADER_LOG_PATHNAME)
if logFile is None:
logContents = "No logfile available on this platform.\n"
else:
logContents = readLog(logFile)
if downloaderLogFile is not None:
if logContents is not None:
logContents += "\n" + readLog(downloaderLogFile, "Downloader Log")
else:
logContents = readLog(downloaderLogFile)
if logContents is not None:
report += "{{{\n%s}}}\n" % logContents
# Dump the header for the report we just generated to the log, in
# case there are multiple failures or the user sends in the log
# instead of the report from the dialog box. (Note that we don't
# do this until we've already read the log into the dialog
# message.)
print "----- CRASH REPORT (DANGER CAN HAPPEN) -----"
print header
print "----- END OF CRASH REPORT -----"
if not inDownloader:
try:
import app
app.delegate. \
notifyUnkownErrorOccurence(when, log = report)
except Exception, e:
print "Execption when reporting errror.."
traceback.print_exc()
else:
from dl_daemon import command, daemon
c = command.DownloaderErrorCommand(daemon.lastDaemon, report)
c.send()
class AutoflushingStream:
"""Converts a stream to an auto-flushing one. It behaves in exactly the
same way, except all write() calls are automatically followed by a
flush().
"""
def __init__(self, stream):
self.__dict__['stream'] = stream
def write(self, data):
if isinstance(data, unicode):
data = data.encode('ascii', 'backslashreplace')
self.stream.write(data)
self.stream.flush()
def __getattr__(self, name):
return self.stream.__getattr__(name)
def __setattr__(self, name, value):
return self.stream.__setattr__(name, value)
def makeDummySocketPair():
"""Create a pair of sockets connected to each other on the local
interface. Used to implement SocketHandler.wakeup().
"""
dummy_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dummy_server.bind( ('127.0.0.1', 0) )
dummy_server.listen(1)
server_address = dummy_server.getsockname()
first = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
first.connect(server_address)
second, address = dummy_server.accept()
dummy_server.close()
return first, second
def trapCall(when, function, *args, **kwargs):
"""Make a call to a function, but trap any exceptions and do a failedExn
call for them. Return True if the function successfully completed, False
if it threw an exception
"""
try:
function(*args, **kwargs)
return True
except KeyboardInterrupt:
raise
except:
failedExn(when)
return False
cumulative = {}
cancel = False
def timeTrapCall(when, function, *args, **kwargs):
global cancel
cancel = False
start = clock()
retval = trapCall (when, function, *args, **kwargs)
end = clock()
if cancel:
return retval
if end-start > 0.5:
print "WARNING: %s too slow (%.3f secs)" % (
when, end-start)
try:
total = cumulative[when]
except KeyboardInterrupt:
raise
except:
total = 0
total += end - start
cumulative[when] = total
if total > 5.0:
print "WARNING: %s cumulative is too slow (%.3f secs)" % (
when, total)
cumulative[when] = 0
cancel = True
return retval
def getTorrentInfoHash(path):
f = open(path, 'rb')
try:
data = f.read()
metainfo = bdecode(data)
infohash = sha.sha(bencode(metainfo['info'])).digest()
return infohash
finally:
f.close()
class ExponentialBackoffTracker:
"""Utility class to track exponential backoffs."""
def __init__(self, baseDelay):
self.baseDelay = self.currentDelay = baseDelay
def nextDelay(self):
rv = self.currentDelay
self.currentDelay *= 2
return rv
def reset(self):
self.currentDelay = self.baseDelay
# Gather movie files on the disk. Used by the startup dialog.
def gatherVideos(path, progressCallback):
import item
import config
keepGoing = True
parsed = 0
found = list()
try:
for root, dirs, files in os.walk(path):
for f in files:
parsed = parsed + 1
if item.isVideoFilename(f):
found.append(os.path.join(root, f))
if parsed > 1000:
adjustedParsed = int(parsed / 100.0) * 100
elif parsed > 100:
adjustedParsed = int(parsed / 10.0) * 10
else:
adjustedParsed = parsed
keepGoing = progressCallback(adjustedParsed, len(found))
if not keepGoing:
found = None
raise
if 'Democracy' in dirs:
dirs.remove('Democracy')
except KeyboardInterrupt:
raise
except:
pass
return found
def formatSizeForUser(bytes, zeroString=""):
"""Format an int containing the number of bytes into a string suitable for
printing out to the user. zeroString is the string to use if bytes == 0.
"""
from gtcache import gettext as _
if bytes > (1 << 30):
return _("%1.1fGB") % (bytes / (1024.0 * 1024.0 * 1024.0))
elif bytes > (1 << 20):
return _("%1.1fMB") % (bytes / (1024.0 * 1024.0))
elif bytes > (1 << 10):
return _("%1.1fKB") % (bytes / 1024.0)
elif bytes > 1:
return _("%0.0fB") % bytes
else:
return zeroString
def print_mem_usage(message):
pass
# Uncomment for memory usage printouts on linux.
# print message
# os.system ("ps huwwwp %d" % (os.getpid(),))
def getSingletonDDBObject(view):
view.confirmDBThread()
viewLength = view.len()
if viewLength == 1:
view.resetCursor()
return view.next()
elif viewLength == 0:
raise LookupError("Can't find singleton in %s" % repr(view))
else:
msg = "%d objects in %s" % (viewLength, len(view))
raise TooManySingletonsError(msg)
class ThreadSafeCounter:
"""Implements a counter that can be access by multiple threads."""
def __init__(self, initialValue=0):
self.value = initialValue
self.lock = threading.Lock()
def inc(self):
self.lock.acquire()
try:
self.value += 1
finally:
self.lock.release()
def dec(self):
self.lock.acquire()
try:
self.value -= 1
finally:
self.lock.release()
def getvalue(self):
self.lock.acquire()
try:
return self.value
finally:
self.lock.release()
|