rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
len(entry.enclosures)>0):
self.hasVideoFeed(entry.enclosures)):
def update(self): info = {} self.beginRead() try: if self.updating: return else: self.updating = True finally: self.endRead() if not self.initialHTML is None: html = self.initialHTML self.initialHTML = None else: info = grabURL(self.url,etag=self.etag,modified=self.modified) if info is None: self.beginRead() try: self....
return True
if url.endswith ('.html'): return True else: filename = urllib.unquote(url[len('file://'):]) singleclick.openFile (filename) return False
def onURLLoad(self, url): #print "DTV: got %s" % url try: # Special-case non-'action:'-format URL match = re.compile(r"^template:(.*)$").match(url) if match: self.dispatchAction('switchTemplate', name = match.group(1)) return False
domain = getBundleIdentifier() plist = Conversion.propertyListFromPythonCollection(data) defaults = NSUserDefaults.standardUserDefaults() defaults.setPersistentDomain_forName_(plist, domain) defaults.synchronize()
try: plist = Conversion.propertyListFromPythonCollection(data) except: print "WARNING!! Error while converting the settings dictionary to a property list:" print data raise else: domain = getBundleIdentifier() defaults = NSUserDefaults.standardUserDefaults() defaults.setPersistentDomain_forName_(plist, domain) defaults...
def save(data): domain = getBundleIdentifier() plist = Conversion.propertyListFromPythonCollection(data) defaults = NSUserDefaults.standardUserDefaults() defaults.setPersistentDomain_forName_(plist, domain) defaults.synchronize()
obj = db.getObjectByID(int(item)) obj.expire()
try: obj = db.getObjectByID(int(item)) obj.expire() except: print "DTV: Warning: tried to expire item that doesn't exist with id %d" % int(item)
def expireItem(self, item): obj = db.getObjectByID(int(item)) obj.expire()
self.pendingReason = "Too many manual downloads" self.expired = False
self.pendingReason = "queued for download"
def actualDownload(self,autodl=False): self.confirmDBThread() manualDownloadCount = views.manualDownloads.len()
self.expired = self.keep = self.seen = False
def actualDownload(self,autodl=False): self.confirmDBThread() manualDownloadCount = views.manualDownloads.len()
if self.downloader is None: if not self.getViewed():
if (self.downloader is None or self.downloader.getState() in ('failed', 'stopped', 'paused')): if self.pendingManualDL: return 'downloading' elif not self.getViewed():
def getState(self): """Get the state of this item. The state will be on of the following:
unwatched += child.unwatched
unwatched += child.numUnwatched()
def numUnwatched(self): unwatched = 0 for child in self.getChildrenView(): if child.showU(): unwatched += child.unwatched return unwatched
self.filename = "%s.%s" % (name, uid)
parts.append(uid)
def updateIconCache (self, url, info): self.dbItem.confirmDBThread()
print "WARNING: error parsing context menu request (%s)" % data
def handleContextMenuSelect(self, id, area, viewName): try: obj = db.getObjectByID(int(id)) except: print "WARNING: error parsing context menu request (%s)" % data traceback.print_exc() else: view = self.templateHandle.getTemplateVariable(viewName) if not controller.selection.isSelected(area, view, int(id)): self.handl...
except xml.sax.SAXException: self.askForScrape(info, html, charset)
def _generateFeedCallback(self, info, removeOnError): """This is called by grabURL to generate a feed based on the type of data found at the given URL """ # FIXME: This probably should be split up a bit. The logic is # a bit daunting
except: print "DTV: Warning couldn't parse HTML at %s" % baseurl traceback.print_exc()
def scrapeLinks(self,html,baseurl,setTitle = False,charset = None): try: if not charset is None: html = fixHTMLHeader(html,charset) xmldata = html parser = xml.sax.make_parser() parser.setFeature(xml.sax.handler.feature_namespaces, 1) if not charset is None: handler = RSSLinkGrabber(baseurl,charset) else: handler = RSS...
except (xml.sax.SAXException, IOError):
except (xml.sax.SAXException, IOError, xml.sax.SAXNotRecognizedException):
def scrapeLinks(self,html,baseurl,setTitle = False,charset = None): try: if not charset is None: html = fixHTMLHeader(html,charset) xmldata = html parser = xml.sax.make_parser() parser.setFeature(xml.sax.handler.feature_namespaces, 1) if not charset is None: handler = RSSLinkGrabber(baseurl,charset) else: handler = RSS...
self.objs = self.everything.map(self.mapToObject).sort(lambda x, y:0).filter(lambda x: x.oldID == self.goodID)
self.objs = self.everything.filter(lambda x: x.getID() == self.goodID)
def setUp(self): DDBObject.dd = DynamicDatabase() self.everything = DDBObject.dd
def mapToObject(self, obj): temp = DDBObject(add = False) temp.oldID = obj.getID() return temp
def mapToObject(self, obj):
self.totalSize / (2 ** 20))
(self.totalSize / (2 ** 20)))
def onHeaders(self, info): if info['contentLength'] != None: self.totalSize = info['contentLength'] if self.client.gotBadStatusCode: error = httpclient.UnexpectedStatusCode(info['status']) self.handleNetworkError(error) return if not self.acceptDownloadSize(self.totalSize): self.handleError(_("Not enough disk space"), ...
return (None, url, url,404)
return (None, url, url,404, None)
def getHTML(self, url): etag = None modified = None if self.linkHistory.has_key(url): if self.linkHistory[url].has_key('etag'): etag = self.linkHistory[url]['etag'] if self.linkHistory[url].has_key('modified'): modified = self.linkHistory[url]['modified'] info = grabURL(url, etag=etag, modified=modified) if info is Non...
ret = "resource:images/thumb.png" self.beginRead() try: try: for enc in self.entry.enclosures: try: ret = enc["thumbnail"]["url"] break except: pass except: try: ret = self.entry["thumbnail"]["url"] except: pass return ret finally: self.endRead()
ret = None self.beginRead() try: for enc in self.entry.enclosures: if enc.has_key('thumbnail') and enc['thumbnail'].has_key('url'): ret = enc["thumbnail"]["url"] break if (ret is None and self.entry.has_key('thumbnail') and self.entry['thumbnail'].has_key('url')): print "Got item level thumb" ret = self.entry["thumbna...
def getThumbnail(self):
try: if (port is not None): print "dtv: Client Connecting to %d" % port self.socket.connect( ('127.0.0.1',port)) connected = True except: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.settimeout(None) launchDownloadDaemon(pid) sleep(1)
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.settimeout(None) launchDownloadDaemon(pid) sleep(1)
def clientConnect(self): # There's still a possible race condition in the case where # two copies of the daemon start at nearly the same time MAX_TRIES = 3 connected = False port = None pid = None tries = 0 try: f = open(getDataFile(),"rb") port = int(f.readline()) pid = int(f.readline()) f.close() except: pass try: if...
if self.inReplace:
if self.inReplace or self.hiding:
def startElement(self,name, attrs): self.depth += 1 if self.inReplace: pass elif 't:hideIfViewEmpty' in attrs.keys() or 't:hideIfViewNotEmpty' in attrs.keys(): nodeId = generateId() if 't:hideIfViewEmpty' in attrs.keys(): viewName = attrs['t:hideIfViewEmpty'] ifInvert = False else: viewName = attrs['t:hideIfViewNotEmpt...
if not (key in ['t:hideIfKey','t:hideIfNotKey','t:hideFunctionKey','t:hideParameter','style']):
if not (key in ['t:hideIfKey','t:hideIfNotKey','t:hideFunctionKey','t:hideParameter']):
def startElement(self,name, attrs): self.depth += 1 if self.inReplace: pass elif 't:hideIfViewEmpty' in attrs.keys() or 't:hideIfViewNotEmpty' in attrs.keys(): nodeId = generateId() if 't:hideIfViewEmpty' in attrs.keys(): viewName = attrs['t:hideIfViewEmpty'] ifInvert = False else: viewName = attrs['t:hideIfViewNotEmpt...
else: self.hiding = True self.hideDepth = self.depth
def startElement(self,name, attrs): self.depth += 1 if self.inReplace: pass elif 't:hideIfViewEmpty' in attrs.keys() or 't:hideIfViewNotEmpty' in attrs.keys(): nodeId = generateId() if 't:hideIfViewEmpty' in attrs.keys(): viewName = attrs['t:hideIfViewEmpty'] ifInvert = False else: viewName = attrs['t:hideIfViewNotEmpt...
if self.inReplace:
if self.inReplace or self.hiding:
def characters(self,data): if self.inReplace: pass elif self.inRepeatView: self.repeatList.append(lambda x,y: sax.saxutils.escape(data)) else: self.outString.write(sax.saxutils.escape(data))
quitStage2()
self.quitStage2()
def callback(dialog): if dialog.choice == dialogs.BUTTON_QUIT: self.quitStage2()
def parseURL(url): (scheme, host, path, params, query, fragment) = urlparse(url) if host.count(':') > 1: host = host[0:host.rfind(':')] return (scheme, host, path, params, query, fragment)
def findHTTPAuth(host,path,realm = None,scheme = None): #print "Trying to find HTTPAuth with host %s, path %s, realm %s, and scheme %s" %(host,path,realm,scheme) ret = None defaultDatabase.beginRead() try: for obj in app.globalViewList['httpauths']: if (obj.host == host and path.startswith(obj.path) and (realm is None ...
(scheme, host, path, params, query, fragment) = urlparse(url)
(scheme, host, path, params, query, fragment) = parseURL(url)
def grabURL(url, type="GET",start = 0, etag=None,modified=None): maxDepth = 10 maxAuthAttempts = 5 redirURL = url myHeaders = {"User-Agent":"DTV/pre-release (http://participatoryculture.org/)"} (scheme, host, path, params, query, fragment) = urlparse(url) #print "grab URL called for "+host auth = findHTTPAuth(host,pa...
(scheme, host, path, params, query, fragment) = urlparse(redirURL)
(scheme, host, path, params, query, fragment) = parseURL(redirURL)
def grabURL(url, type="GET",start = 0, etag=None,modified=None): maxDepth = 10 maxAuthAttempts = 5 redirURL = url myHeaders = {"User-Agent":"DTV/pre-release (http://participatoryculture.org/)"} (scheme, host, path, params, query, fragment) = urlparse(url) #print "grab URL called for "+host auth = findHTTPAuth(host,pa...
(scheme, host, path, params, query, fragment) = urlparse(url)
(scheme, host, path, params, query, fragment) = parseURL(url)
def filenameFromURL(self,url): (scheme, host, path, params, query, fragment) = urlparse(url) if len(path): try: return re.compile("^.*?([^/]+)/?$").search(path).expand("\\1") except: return 'unknown' else: return "unknown"
elapseRe = re.compile('elapsed=(\d+)') lengthRe = re.compile('len=(\d+)')
elapseRe = re.compile('elapsed=(-?\d+)') lengthRe = re.compile('len=(-?\d+)')
def __init__(self): print "VideoDisplay init" html = template.fillStaticTemplate("video-display-vlc", {'eventCookie':self.getEventCookie(),'dtvPlatform':'xul'}) frontend.HTMLDisplay.__init__(self,html) app.VideoDisplayBase.__init__(self) print "Display initialized"
return util.readSimpleConfigFile(_getConfigFile())
return _fixTypes(util.readSimpleConfigFile(file))
def load(): file = _getConfigFile() if os.access(file, os.F_OK): return util.readSimpleConfigFile(_getConfigFile()) else: # First time running program return {}
util.writeSimpleConfigFile(_getConfigFile(), data)
file = _getConfigFile() util.writeSimpleConfigFile(file, data)
def save(data): util.writeSimpleConfigFile(_getConfigFile(), data)
link = urljoin(baseurl, quote(match.group(3))) desc = match.group(4) imgMatch = HTMLLinkGrabber.imgPattern.match(desc) if imgMatch: thumb = urljoin(baseurl, quote(imgMatch.group(1)))
try: linkURL = match.group(3).encode('ascii') except UnicodeDecodeError: print "WARNING: scraped URL is non-ascii (%s)-- discarding" \ % match.group(3)
def getLinks(self,data, baseurl): self.links = [] self.lastLink = None self.inLink = False self.inObject = False self.baseurl = baseurl self.inTitle = False self.title = None self.thumbnailUrl = None
thumb = None desc = HTMLLinkGrabber.tagPattern.sub(' ',desc) self.links.append((link, desc, thumb))
link = urljoin(baseurl, linkURL) desc = match.group(4) imgMatch = HTMLLinkGrabber.imgPattern.match(desc) if imgMatch: try: thumb = urljoin(baseurl, imgMatch.group(1).encode('ascii')) except UnicodeDecodeError: print ("WARNING: scraped thumbnail url is non-ascii " "(%s) -- discarding" % imgMatch.group(1)) thumb = None ...
def getLinks(self,data, baseurl): self.links = [] self.lastLink = None self.inLink = False self.inObject = False self.baseurl = baseurl self.inTitle = False self.title = None self.thumbnailUrl = None
return self.skip(1)
return self.skip(1, False)
def onMovieFinished(self): return self.skip(1)
for enclosure in self.entry.enclosures:
try: enclosures = self.entry.enclosures except (KeyError, AttributeError): return None for enclosure in enclosures:
def getFirstVideoEnclosure(self): self.confirmDBThread() for enclosure in self.entry.enclosures: if isVideoEnclosure(enclosure): return enclosure return None
prefJavascriptStream = None prefJavascriptQueue = []
def acceptThread(self): while True: (conn, address) = self.socket.accept() conn.settimeout(None) httpServer(conn)
raise ValueError, "Malformed HTTP request"
raise ValueError, "Malformed HTTP request: %r" % request
def requestThread(self): request = None try: try: request = self.file.readline()
httpServer.classLock.acquire() try: if httpServer.prefJavascriptStream: raise RuntimeError, \ "There can't be two prefjs's (%d)" % self.reqNum self.beginSendingChunks() if (config.get(config.RUN_AT_STARTUP)): self.queueChunk("text/plain", "setRunAtStartup(true);") else: self.queueChunk("text/plain", "setRunAtStartup(f...
self.beginSendingChunks() if (config.get(config.RUN_AT_STARTUP)): self.queueChunk("text/plain", "setRunAtStartup(true);") else: self.queueChunk("text/plain", "setRunAtStartup(false);") checkEvery = config.get(config.CHECK_CHANNELS_EVERY_X_MN) self.queueChunk("text/plain", "setCheckEvery('%s');" % checkEvery) speed = co...
def handleRequest(self, method, path): if not method == 'GET': raise ValueError, "Only GET is supported"
raise RuntimeError("Can't find xulrunner-xpcom or mozilla-xpcom")
raise RuntimeError("Can't find xulrunner-xpcom, mozilla-xpcom or firefox-xpcom")
def parsePkgConfig(command, components, options_dict = None): """Helper function to parse compiler/linker arguments from pkg-config/mozilla-config and update include_dirs, library_dirs, etc. We return a dict with the following keys, which match up with keyword arguments to the setup function: include_dirs, library_dir...
def allIsDir(directory, subdirs):
def allInDir(directory, subdirs):
def allIsDir(directory, subdirs): for subdir in subdirs: if not os.path.isdir(os.path.join(directory, subdir)): return False return True
if not os.path.isdir(os.path.join(directory, subdir)):
if not os.path.exists(os.path.join(directory, subdir)):
def allIsDir(directory, subdirs): for subdir in subdirs: if not os.path.isdir(os.path.join(directory, subdir)): return False return True
subdirs = ['dom', 'gfx', 'widget', 'commandhandler']
def allIsDir(directory, subdirs): for subdir in subdirs: if not os.path.isdir(os.path.join(directory, subdir)): return False return True
if allIsDir(dir, subdirs):
if allInDir(dir, ['dom', 'gfx', 'widget', 'nsIDOMHTMLElement.h']):
def allIsDir(directory, subdirs): for subdir in subdirs: if not os.path.isdir(os.path.join(directory, subdir)): return False return True
for subdir in ['dom', 'gfx', 'widget', 'commandhandler']:
for subdir in ['dom', 'gfx', 'widget', 'commandhandler', 'uriloader', 'webbrwsr']:
def allIsDir(directory, subdirs): for subdir in subdirs: if not os.path.isdir(os.path.join(directory, subdir)): return False return True
self.redirectedURL = None
self.redirectedURL = url
def __init__(self, url=None): # Delayed callback for eventloop. self.dc = None # If None, we have never successfully loaded the guide. Otherwise, # the <body> part of the front channel guide page from the last time # we loaded it, whenever that was (perhaps in a previous session.) self.cachedGuideBody = None # True if ...
if getBody == False: info = grabURL(url, "HEAD", start, etag, modified, findHTTPAuth) if info == None: info = grabURL (url, "GET", start, etag, modified, findHTTPAuth) else: info = grabURL(url, "GET", start, etag, modified, findHTTPAuth) if info: info["body"] = info["file-handle"].read() eventloop.addIdle (callback, (i...
info = None try: if getBody == False: info = grabURL(url, "HEAD", start, etag, modified, findHTTPAuth) if info == None: info = grabURL (url, "GET", start, etag, modified, findHTTPAuth) else: info = grabURL(url, "GET", start, etag, modified, findHTTPAuth) if info: info["body"] = info["file-handle"].read() finally: event...
def _grabURLThread(callback, url, start, etag, modified, findHTTPAuth, getBody, args, kwargs): if getBody == False: info = grabURL(url, "HEAD", start, etag, modified, findHTTPAuth) if info == None: info = grabURL (url, "GET", start, etag, modified, findHTTPAuth) else: info = grabURL(url, "GET", start, etag, modified, f...
self.initialLoadFinished = True
def webView_didFinishLoadForFrame_(self, webview, frame): if (not self.initialLoadFinished) and (frame is self.view.mainFrame()): platformutils.warnIfNotOnMainThread('ManagedWebView.webView_didFinishLoadForFrame_') # Execute any function calls we queued because the page load # hadn't completed # NEEDS: there should be ...
self.initialLoadFinished = True
def webView_didFinishLoadForFrame_(self, webview, frame): if (not self.initialLoadFinished) and (frame is self.view.mainFrame()): platformutils.warnIfNotOnMainThread('ManagedWebView.webView_didFinishLoadForFrame_') # Execute any function calls we queued because the page load # hadn't completed # NEEDS: there should be ...
def createElt(self, xml):
def createElts(self, xml):
# def printHTML(self):
parent.setInnerHTML_("<div style='height: 1px;'/>")
parent.setInnerHTML_("&nbsp;")
def createElt(self, xml): parent = self.view.mainFrame().DOMDocument().createElement_("div") if len(xml) == 0: #FIXME: this is awfully ugly but it fixes the symptoms described #in #1664. Next step is to fix the root cause. parent.setInnerHTML_("<div style='height: 1px;'/>") else: parent.setInnerHTML_(xml) #FIXME: This ...
if parent.childNodes().length() > 1: eltlist = [] for child in range(parent.childNodes().length()): eltlist.append(parent.childNodes().item_(child)) return eltlist else: return parent.firstChild()
eltlist = [] for child in range(parent.childNodes().length()): eltlist.append(parent.childNodes().item_(child)) return eltlist
def createElt(self, xml): parent = self.view.mainFrame().DOMDocument().createElement_("div") if len(xml) == 0: #FIXME: this is awfully ugly but it fixes the symptoms described #in #1664. Next step is to fix the root cause. parent.setInnerHTML_("<div style='height: 1px;'/>") else: parent.setInnerHTML_(xml) #FIXME: This ...
elt.insertBefore__(self.createElt(xml), None)
newElts = self.createElts(xml) for newElt in newElts: elt.insertBefore__(newElt, None)
def addItemAtEnd(self, xml, id): elt = self.findElt(id) if not elt: print "warning: addItemAtEnd: missing element %s" % id else: #print "add item %s at end of %s" % (elt.getAttribute_("id"), id) #print xml[0:79] elt.insertBefore__(self.createElt(xml), None)
newelts = self.createElt(xml) try: for newelt in newelts: elt.parentNode().insertBefore__(newelt, elt) except: elt.parentNode().insertBefore__(newelts, elt)
newElts = self.createElts(xml) for newElt in newElts: elt.parentNode().insertBefore__(newElt, elt)
def addItemBefore(self, xml, id): elt = self.findElt(id) if not elt: print "warning: addItemBefore: missing element %s" % id else: newelts = self.createElt(xml) try: for newelt in newelts: #print "add item %s before %s" % (newelt.getAttribute_("id"), id) elt.parentNode().insertBefore__(newelt, elt) except: #print "add ...
ret = ""
ret = datetime.max
def getPubDateParsed(self): self.beginRead() try: try: ret = datetime(*self.entry.modified_parsed[0:7]) except: ret = "" finally: self.endRead() return ret
try: self.code = fp.code except: pass try: self.msg = fp.msg except: pass
def __init__(self, fp, headers, url): # we need to do something more sophisticated here to deal with # multiple values? What about other weird crap like q-values? # basically this only works for the most simplistic case and will # break in some other cases, but for now we only care about making # this work with the BT...
return time.strftime("%H:%M:%S", time.gmtime(seconds))
return time.strftime(self.DISPLAY_TIME_FORMAT, time.gmtime(seconds))
def getDisplayTime(self): seconds = self.getCurrentTime() return time.strftime("%H:%M:%S", time.gmtime(seconds))
def allIsDir(directory, subdirs): for subdir in subdirs: if not os.path.isdir(os.path.join(directory, subdir)): return False return True
def parsePkgConfig(command, components, options_dict = None): """Helper function to parse compiler/linker arguments from pkg-config/mozilla-config and update include_dirs, library_dirs, etc. We return a dict with the following keys, which match up with keyword arguments to the setup function: include_dirs, library_dir...
mozIncludeBase = os.path.commonprefix(xpcom_includes['include_dirs'])
subdirs = ['dom', 'gfx', 'widget', 'commandhandler'] mozIncludeBase = None for dir in xpcom_includes['include_dirs']: if allIsDir(dir, subdirs): mozIncludeBase = dir if mozIncludeBase is None: raise ValueError("Can't find mozilla include base directory")
def parsePkgConfig(command, components, options_dict = None): """Helper function to parse compiler/linker arguments from pkg-config/mozilla-config and update include_dirs, library_dirs, etc. We return a dict with the following keys, which match up with keyword arguments to the setup function: include_dirs, library_dir...
available += child.available
available += child.numAvailable()
def numAvailable(self): available = 0 for child in self.getChildrenView(): if child.showA(): available += child.available return available
return isinstance(obj, guide.ChannelGuide)
return isinstance(obj, guide.ChannelGuide) and obj.url is None
def objectIsSingleton(self, obj): return isinstance(obj, guide.ChannelGuide)
def addFeed(self, url, showTemplate = None):
def addFeed(self, url, showTemplate = None, selected = '1'):
def addFeed(self, url, showTemplate = None): db.beginUpdate() db.saveCursor()
tabs = self.controller.tabs tabs.resetCursor() while True: cur = tabs.getNext() if cur == None: assert(0) if cur.feedURL() == url: break self.controller.checkSelectedTab(showTemplate)
if selected == '1': tabs = self.controller.tabs tabs.resetCursor() while True: cur = tabs.getNext() if cur == None: assert(0) if cur.feedURL() == url: break self.controller.checkSelectedTab(showTemplate)
def addFeed(self, url, showTemplate = None): db.beginUpdate() db.saveCursor()
'recentItems': (lambda x, y: str(x.feed.getID()) == y and (x.getState() == 'finished' or x.getState() == 'uploading' or x.getState() == 'watched')), 'allRecentItems': (lambda x, y: (x.getState() == 'finished' or x.getState() == 'uploading' or x.getState() == 'watched') and (str(y).lower() in x.getTitle().lower() or str...
'recentItems': recentItems, 'allRecentItems': allRecentItems, 'oldItems': oldItems, 'downloadedItems': downloadedItems, 'unDownloadedItems': undownloadedItems, 'allDownloadingItems': allDownloadingItems ,
def filterHasKey(obj,parameter): try: obj[parameter] except KeyError: return False return True
print "stop ", self.url _downloads_by_url[self.url]["count"] -= 1 if _downloads_by_url[self.url]["count"] == 0: del _downloads[self.dlid] del _downloads_by_url[self.url] c = command.StopDownloadCommand(RemoteDownloader.dldaemon, self.dlid) c.send(block=False)
if ((self.getState() in ['downloading','uploading'])): print "stop ", self.url _downloads_by_url[self.url]["count"] -= 1 if _downloads_by_url[self.url]["count"] == 0: del _downloads[self.dlid] del _downloads_by_url[self.url] c = command.StopDownloadCommand(RemoteDownloader.dldaemon, self.dlid) c.send(block=False)
def stop(self): print "stop ", self.url _downloads_by_url[self.url]["count"] -= 1 if _downloads_by_url[self.url]["count"] == 0: del _downloads[self.dlid] del _downloads_by_url[self.url] c = command.StopDownloadCommand(RemoteDownloader.dldaemon, self.dlid) c.send(block=False)
t = os.stat(os.path.join(dirpath, f)).st_mtime if t > maxTime: maxTime = t
if not f.startswith('.'): t = os.stat(os.path.join(dirpath, f)).st_mtime if t > maxTime: maxTime = t
def modifiedTime(dir): maxTime = 0 try: for (dirpath, dirnames, filenames) in os.walk(dir): for f in filenames: t = os.stat(os.path.join(dirpath, f)).st_mtime if t > maxTime: maxTime = t for f in dirnames: t = os.stat(os.path.join(dirpath, f)).st_mtime if t > maxTime: maxTime = t return maxTime except: return 0
self.stop()
Controller.instance.playbackController.stop(False)
def onDeselected(self, frame): if self.isPlaying: self.stop()
def exitPlayback(self):
def exitPlayback(self, switchDisplay=True):
def exitPlayback(self): # Warning: resetting must be done *BEFORE* calling selectDisplay because # selectDisplay can possibly trigger a call to configure, which effect # would therefore be 'canceled' by a subsequent call to reset (#786). frame = Controller.instance.frame area = frame.mainDisplay previousDisplay = self....
frame = Controller.instance.frame area = frame.mainDisplay
def exitPlayback(self): # Warning: resetting must be done *BEFORE* calling selectDisplay because # selectDisplay can possibly trigger a call to configure, which effect # would therefore be 'canceled' by a subsequent call to reset (#786). frame = Controller.instance.frame area = frame.mainDisplay previousDisplay = self....
frame.selectDisplay(previousDisplay, area)
if switchDisplay: frame = Controller.instance.frame area = frame.mainDisplay frame.selectDisplay(previousDisplay, area)
def exitPlayback(self): # Warning: resetting must be done *BEFORE* calling selectDisplay because # selectDisplay can possibly trigger a call to configure, which effect # would therefore be 'canceled' by a subsequent call to reset (#786). frame = Controller.instance.frame area = frame.mainDisplay previousDisplay = self....
def stop(self):
def stop(self, switchDisplay=True):
def stop(self): videoDisplay = Controller.instance.videoDisplay if self.currentDisplay == videoDisplay: videoDisplay.stop() self.exitPlayback()
self.exitPlayback()
self.exitPlayback(switchDisplay)
def stop(self): videoDisplay = Controller.instance.videoDisplay if self.currentDisplay == videoDisplay: videoDisplay.stop() self.exitPlayback()
try: frame.mainDisplay.hostedDisplay.onDeselected(frame) except: pass
def start(self, frame, templateNameHint): self.controller.setTabListActive(True)
allTracks = qtmovie.tracks() if qtmovie is not nil and qtmovie.duration().timeValue > 0 and len(allTracks) > 0: allMedia = [track.media() for track in allTracks] for media in allMedia: mediaType = media.attributeForKey_(QTMediaTypeAttribute) mediaDuration = media.attributeForKey_(QTMediaDurationAttribute).QTTimeValue(...
if qtmovie is not nil and qtmovie.duration().timeValue > 0: allTracks = qtmovie.tracks() if len(qtmovie.tracks()) > 0: allMedia = [track.media() for track in allTracks] for media in allMedia: mediaType = media.attributeForKey_(QTMediaTypeAttribute) mediaDuration = media.attributeForKey_(QTMediaDurationAttribute).QTTim...
def canPlayItem(self, item): canPlay = False pathname = item.getPath() if self.cachedMovie is not nil and self.cachedMovie.attributeForKey_(QTMovieFileNameAttribute) == pathname: qtmovie = self.cachedMovie else: (qtmovie, error) = QTMovie.alloc().initWithFile_error_(pathname) self.cachedMovie = qtmovie
self.adjustVideoWindowFrame()
if not self.videoWindow.isFullScreen: self.adjustVideoWindowFrame()
def setup(self, renderer, item): self.adjustVideoWindowFrame() self.videoWindow.setup(renderer, item) AppHelper.callAfter(self.activateVideoWindow)
self.selectHTML(newDisplay, area)
def selectDisplay(self, newDisplay, area): """Install the provided 'newDisplay' in the requested area"""
if app.controller is not None:
if app.controller is not None and app.controller.frame is not None:
def applicationShouldHandleReopen_hasVisibleWindows_(self, appl, flag): if not flag: self.showMainWindow_(appl) if app.controller is not None: mainWindow = app.controller.frame.controller.window() if mainWindow.isMiniaturized(): mainWindow.deminiaturize_(appl) return NO
app.controller.frame.controller.window().makeKeyAndOrderFront_(sender)
if app.controller is not None and app.controller.frame is not None: app.controller.frame.controller.window().makeKeyAndOrderFront_(sender)
def showMainWindow_(self, sender): app.controller.frame.controller.window().makeKeyAndOrderFront_(sender)
if self.status == data: return
try: if self.status == data: return except Exception, e: print "WARNING exception when compariring status: %s" % e
def updateStatus(cls, data): self = _getDownloader (dlid=data['dlid']) # print data if self is not None: if self.status == data: return wasFinished = self.isFinished() self.status = data # Store the time the download finished finished = self.isFinished() and not wasFinished self.signalChange(needsSignalItem=not finishe...
if args[0].lower().endswith('application.ini'):
if len(args) > 0 and args[0].lower().endswith('application.ini'):
def getArgumentList(commandLine): """Convert a nsICommandLine component to a list of arguments to pass to the singleclick module.""" args = [commandLine.getArgument(i) for i in range(commandLine.length)] # filter out the application.ini that gets included if args[0].lower().endswith('application.ini'): args = args[1:]...
(name, value) = pairs.pop(0).strip().split('=')
(name, value) = getAttrPair(pairs.pop(0))
def getCookiesFromResponse(self, response): """Generates a cookie dictionary from headers in response """ cookies = {} cookieStrings = [] if response.has_key('set-cookie') or response.has_key('set-cookie2'): scheme, host, port, path = parseURL(self.redirectedURL)
cookie['Version'] = attr.split('=')[1]
cookie['Version'] = getAttrPair(attr)[1]
def getCookiesFromResponse(self, response): """Generates a cookie dictionary from headers in response """ cookies = {} cookieStrings = [] if response.has_key('set-cookie') or response.has_key('set-cookie2'): scheme, host, port, path = parseURL(self.redirectedURL)
cookie['Comment'] = attr.split('=')[1]
cookie['Comment'] = getAttrPair(attr)[1]
def getCookiesFromResponse(self, response): """Generates a cookie dictionary from headers in response """ cookies = {} cookieStrings = [] if response.has_key('set-cookie') or response.has_key('set-cookie2'): scheme, host, port, path = parseURL(self.redirectedURL)
cookie['CommentURL'] = attr.split('=')[1]
cookie['CommentURL'] = getAttrPair(attr)[1]
def getCookiesFromResponse(self, response): """Generates a cookie dictionary from headers in response """ cookies = {} cookieStrings = [] if response.has_key('set-cookie') or response.has_key('set-cookie2'): scheme, host, port, path = parseURL(self.redirectedURL)
cookie['Max-Age'] = attr.split('=')[1]
cookie['Max-Age'] = getAttrPair(attr)[1]
def getCookiesFromResponse(self, response): """Generates a cookie dictionary from headers in response """ cookies = {} cookieStrings = [] if response.has_key('set-cookie') or response.has_key('set-cookie2'): scheme, host, port, path = parseURL(self.redirectedURL)
attr.split('=')[1],
getAttrPair(attr)[1],
def getCookiesFromResponse(self, response): """Generates a cookie dictionary from headers in response """ cookies = {} cookieStrings = [] if response.has_key('set-cookie') or response.has_key('set-cookie2'): scheme, host, port, path = parseURL(self.redirectedURL)
print "DTV: Warning: Can't process cookie expiration: %s" % attr.split('=')[1]
print "DTV: Warning: Can't process cookie expiration: %s" % getAttrPair(attr)[1]
def getCookiesFromResponse(self, response): """Generates a cookie dictionary from headers in response """ cookies = {} cookieStrings = [] if response.has_key('set-cookie') or response.has_key('set-cookie2'): scheme, host, port, path = parseURL(self.redirectedURL)
cookie['origDomain'] = attr.split('=')[1]
cookie['origDomain'] = getAttrPair(attr)[1]
def getCookiesFromResponse(self, response): """Generates a cookie dictionary from headers in response """ cookies = {} cookieStrings = [] if response.has_key('set-cookie') or response.has_key('set-cookie2'): scheme, host, port, path = parseURL(self.redirectedURL)
cookie['origPort'] = attr.split('=')[1]
cookie['origPort'] = getAttrPair(attr)[1]
def getCookiesFromResponse(self, response): """Generates a cookie dictionary from headers in response """ cookies = {} cookieStrings = [] if response.has_key('set-cookie') or response.has_key('set-cookie2'): scheme, host, port, path = parseURL(self.redirectedURL)
cookie['origPath'] = attr.split('=')[1]
cookie['origPath'] = getAttrPair(attr)[1]
def getCookiesFromResponse(self, response): """Generates a cookie dictionary from headers in response """ cookies = {} cookieStrings = [] if response.has_key('set-cookie') or response.has_key('set-cookie2'): scheme, host, port, path = parseURL(self.redirectedURL)
print response == gtk.RESPONSE_OK
def isScrapeAllowed(self, url): """Tell the user that URL wasn't a valid feed and ask if it should be scraped for links instead. Returns True if the user gives permission, or False if not.""" summary = "Not a DTV-style channel" message = "But we'll try our best to grab the files.\n- It may take time to list the videos\...
def removeFeed(self, feedID): obj = db.getObjectByID(int(feedID))
def removeFeed(self, feed): obj = db.getObjectByID(int(feed))
def removeFeed(self, feedID): obj = db.getObjectByID(int(feedID)) title = 'Remove Channel' description = """Are you sure you want to remove the channel \'%s\'? This operation cannot be undone.""" % obj.getTitle() dialog = dialogs.ChoiceDialog(title, description, dialogs.BUTTON_YES, dialogs.BUTTON_NO) def dialogCallback...
except IOError, e:
except Exception, e:
def migrate(self, newDir): self.confirmDBThread() if self.shortFilename is None: print """\
self.window.makeKeyAndOrderFront_(None)
self.actionButton.sendActionOn_(NSLeftMouseDownMask) self.showWindow_(None)
def awakeFromNib(self): self.window.makeKeyAndOrderFront_(None)
def openAddChannelSheet_(self, sender):
def playVideo_(self, sender): print "NOT IMPLEMENTED" def playVideoFullScreen_(self, sender): print "NOT IMPLEMENTED" def playVideoHalfScreen_(self, sender): print "NOT IMPLEMENTED" def deleteVideo_(self, sender): print "NOT IMPLEMENTED" def saveVideo_(self, sender): print "NOT IMPLEMENTED" def copyVideoLink_(self...
def splitView_resizeSubviewsWithOldSize_(self, sender, oldSize): tabBox = self.tabView.superview().superview().superview() contentBox = self.contentTemplateView.superview().superview().superview()
NSApplication.sharedApplication().beginSheet_modalForWindow_modalDelegate_didEndSelector_contextInfo_(controller.window(), self.window, self, None, 0)
NSApplication.sharedApplication().beginSheet_modalForWindow_modalDelegate_didEndSelector_contextInfo_(controller.window(), self.window(), self, None, 0) def removeChannel_(self, sender): print "NOT IMPLEMENTED" def copyChannelLink_(self, sender): print "NOT IMPLEMENTED" def updateChannel_(self, sender): print "NOT I...
def openAddChannelSheet_(self, sender): controller = AddChannelSheetController.alloc().init(self.appl) controller.retain() NSApplication.sharedApplication().beginSheet_modalForWindow_modalDelegate_didEndSelector_contextInfo_(controller.window(), self.window, self, None, 0)
menu = mainMenu.itemWithTag_(1).submenu() location = sender.convertPoint_toView_(sender.frame().origin, None) location.x += 1.0 location.y -= 4.0
tag = self.switcherMatrix.selectedCell().tag() menu = mainMenu.itemWithTag_(tag).submenu() location = sender.frame().origin location.x += 10.0 location.y += 3.0
def showActionMenu_(self, sender): mainMenu = NSApplication.sharedApplication().mainMenu() menu = mainMenu.itemWithTag_(1).submenu()
NSMenu.popUpContextMenu_withEvent_forView_( menu, curEvent, sender )
event = NSEvent.mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure_( curEvent.type(), location, curEvent.modifierFlags(), curEvent.timestamp(), curEvent.windowNumber(), None, curEvent.eventNumber(), curEvent.clickCount(), curEvent.pressure() ) NSMenu.popUpContextMe...
def showActionMenu_(self, sender): mainMenu = NSApplication.sharedApplication().mainMenu() menu = mainMenu.itemWithTag_(1).submenu()
self.controller.play_(None)
def onSelected(self, frame): self.controller.enableControls(True) self.controller.setMovieFile(self.filename)
self.videoView.movie().setRate_(2.0)
if self.videoView.movie().rate() == 1.0: self.videoView.movie().setRate_(2.0) self.fastForwardButton.sendActionOn_(NSLeftMouseUpMask) else: self.videoView.movie().setRate_(1.0) self.fastForwardButton.sendActionOn_(NSLeftMouseDownMask)
def fastForward_(self, sender): self.videoView.movie().setRate_(2.0)
self.videoView.movie().setRate_(-2.0)
if self.videoView.movie().rate() == 1.0: self.videoView.movie().setRate_(-2.0) self.fastForwardButton.sendActionOn_(NSLeftMouseUpMask) else: self.videoView.movie().setRate_(1.0) self.fastForwardButton.sendActionOn_(NSLeftMouseDownMask)
def fastBackward_(self, sender): self.videoView.movie().setRate_(-2.0)