Exemplo n.º 1
0
 def start(self):
     # TODO: recheck listening interface; may need to rebind manager to renewed IP
     if 'state_changed_alert' in self.dfm:
         raise Exception('An operation is already in progress')
     self.dfm['state_changed_alert'] = defer.Deferred()
     if not self.torrent and not self.download.metadata:
         if self.download.url:
             # Don't try to re-fetch until an attempt is done
             if self.download.status != Status.LOADING:
                 if self.download.url.startswith('magnet:'):
                     params = { 'save_path': str(self.directory), 'auto_managed': True }
                     resdata = None
                     if self.download.resume_data:
                         params['resdata'] = marshal.loads(self.download.resume_data)
                     self.download.status = Status.LOADING
                     self.torrent = lt_manager.add_magnet(self, str(self.download.url), params)
                     self.dfm['metadata_received_alert'] = defer.Deferred()
                     self.dfm['metadata_received_alert'].addCallback(self.magnet_loaded)
                     self.dfm['metadata_failed_alert'] = defer.Deferred()
                     self.dfm['metadata_failed_alert'].addCallback(self.magnet_load_failed)
                     return self.dfm['state_changed_alert']
                 else:
                     self.download.status = Status.LOADING
                     self.download.status_message = u'Getting the torrent metadata'
                     client.getPage(str(self.download.url)).addCallback(self.fetch_torrent_success).addErrback(self.fetch_torrent_failure)
             return self.dfm['state_changed_alert']
         else:
             raise Exception('Torrent metadata missing and no source URL specified')
     else:
         return self.start_real()
Exemplo n.º 2
0
def get_page(handler, *args, **kwargs):
    deferred = Deferred()
    def callback(data):
        output = handler(data)
        deferred.callback(output)
    getPage(*args, **kwargs).addCallback(callback)
    return deferred
Exemplo n.º 3
0
    def collect(self, device, log):
        """Asynchronously collect data from device. Return a deferred."""
        log.info("%s: collecting data", device.id)
        coresList = getattr(device, 'zSolrCore', None)
        if not coresList:
            log.error('No zSolrCore property set - please set this for the device')
            returnValue(None)
        else:
            response = {}
            #deviceName = device.titleOrId()
            deviceName = device.id
            for core in coresList:
                try:
		    coresDict = {}
		    coresDict['name'] = core
		    coreUrl = 'http://' + deviceName + ':8080/solr/' + core + '/admin/mbeans?stats=true&cat=CORE&key=searcher&ident=true&wt=json'
		    coreResp = yield getPage(coreUrl)
		    coreResp = json.loads(coreResp)
		    coresDict['coreUrl'] = coreResp
		    replUrl = 'http://' + deviceName + ':8080/solr/' + core + '/admin/mbeans?stats=true&cat=QUERYHANDLER&key=/replication&ident=true&wt=json'
		    replResp = yield getPage(replUrl)
		    replResp = json.loads(replResp)
		    coresDict['replUrl'] = replResp
		    response[core] = coresDict
		except Exception, e:
		    log.error(
			"%s: %s", device.id, e)
		    #returnValue(None)
                    continue
	    #log.info('Response is %s \n' % (response))
	    returnValue(response)
Exemplo n.º 4
0
	def GetWeatherInfo(self):
		self.url = "http://www.homeys-bunker.de/dm800/feeds/weatherinfo2.php?citycode=%s&metric=%s" % (config.plugins.EVOMC_wi.city.value, config.plugins.EVOMC_wi.metric.value)
		try:
			getPage(self.url).addCallback(self.UpdateWeatherInfo).addErrback(self.error)
			self["CurrentCity"].setText(_("Updating Weather Info ..."))
		except Exception, e:
			self["CurrentCity"].setText(_("Updating Weather Info failed (Twisted Web not installed)"))
Exemplo n.º 5
0
	def startRun(self):
		if self.weatherPluginEntry is not None:
			self["statustext"].text = _("Getting weather information...")
			url = "http://weather.service.msn.com/data.aspx?weadegreetype=%s&culture=%s&wealocations=%s" % (self.weatherPluginEntry.degreetype.value, self.language, self.weatherPluginEntry.weatherlocationcode.value)
			getPage(url).addCallback(self.xmlCallback).addErrback(self.error)
		else:
			self["statustext"].text = _("No locations defined...\nPress 'Menu' to do that.")
Exemplo n.º 6
0
	def filenuke(self, data, url):
		#print "drin 2"
		id = re.findall('<input type="hidden" name="id".*?value="(.*?)">', data)
		fname = re.findall('<input type="hidden" name="fname".*?alue="(.*?)">', data)
		post_data = urllib.urlencode({'op': 'download1', 'usr_login': '', 'id': id[0], 'fname': fname[0], 'referer': '', 'method_free': 'Kostenlos'})
		#print post_data
		getPage(url, method='POST', postdata = post_data, headers={'Content-Type':'application/x-www-form-urlencoded'}).addCallback(self.filenuke_data).addErrback(self.errorload)
Exemplo n.º 7
0
		def getFromXunlei(result,parameter):
			header,tailer,filename = parameter
			url = 'http://bt.box.n0808.com/%s/%s/%s' % (header,tailer,filename)
			self.transport.write('start downloading from %s\n' % url)
			getPage(url,filename).addCallbacks(
				ParseTorrent,
				lambda result:self.transport.write('download torrent failed\n'))
Exemplo n.º 8
0
	def GetWeather(self):
		timeout = config.plugins.AtileHD.refreshInterval.value * 1000 * 60
		if timeout > 0:
			self.timer.start(timeout, True)
			print "AtileHD lookup for ID " + str(config.plugins.AtileHD.woeid.value)
			url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%3D%22"+str(config.plugins.AtileHD.woeid.value)+"%22&format=xml"
			getPage(url,method = "GET").addCallback(self.GotWeatherData).addErrback(self.downloadError)
Exemplo n.º 9
0
	def monsteruploads(self, data, url):
		if not re.match('.*?eval\(function\(p\,a\,c\,k\,e\,d', data, re.S):
			id = re.findall('type="hidden" name="id".*?value="(.*?)"', data, re.S)
			fname = re.findall('type="hidden" name="fname".*?value="(.*?)"', data, re.S)
			referer = re.findall('type="hidden" name="referer".*?value="(.*?)"', data, re.S)
			info = urlencode({
				'op':           "download2",
				'usr_login':    "",
				'id':           id[0],
				'fname':        fname[0],
				'referer':      "",
				'method_free':  "Kostenloser Download"
				})
			getPage(url, method='POST', postdata = info, headers={'Content-Type':'application/x-www-form-urlencoded'}).addCallback(self.monsteruploads_post).addErrback(self.errorload)
			
		else:
		
			get_packedjava = re.findall("<script type=.text.javascript.>eval.function(.*?)</script>", data, re.S|re.DOTALL)
			if get_packedjava:
				sJavascript = get_packedjava[1]
				sUnpacked = cJsUnpacker().unpackByString(sJavascript)
				if sUnpacked:
					stream_url = re.findall('type="video/divx"src="(.*?)"', sUnpacked)
					if stream_url:
						print stream_url[0]
						self._callback(stream_url[0])		
					else:
						self.stream_not_found()
				else:
					self.stream_not_found()
			else:
				self.stream_not_found()
Exemplo n.º 10
0
 def render_POST(self, request):
     api_key = request.args.get('api_key', [request.getUser()])[0]
     if not api_key:
         request.setHeader('WWW-Authenticate', 'Basic realm="%s"' % 'notify.io')
         errpage = error.ErrorPage(http.UNAUTHORIZED, "Unauthorized", "401 Authentication (API key) required")
         return errpage.render(request)
     
     hash = request.path.split('/')[-1].lower()
     if not hash or hash == 'notify':
         return "No hash"
     
     if not hash in listeners:
         listeners[hash] = []
     
     replay = request.args.get('replay', [None])[0]
     if replay:
         client.getPage(url='%s/notification?hash=%s&api_key=%s&replay=%s' % (NOTIFY_WWW, hash, api_key, replay), method='POST') \
             .addCallback(self.notify_success, hash, request) \
             .addErrback(self.notify_failure, request)
             
     else:
         notification = {}
         for arg in ['title', 'text', 'icon', 'link', 'sticky']:
             value = request.args.get(arg, [None])[0]
             if value:
                 notification[arg] = value
         
         client.getPage(url='%s/notification?hash=%s&api_key=%s' % (NOTIFY_WWW, hash, api_key), method='POST', postdata=urllib.urlencode(notification)) \
             .addCallback(self.notify_success, hash, request) \
             .addErrback(self.notify_failure, request)
             
     return server.NOT_DONE_YET
Exemplo n.º 11
0
def do_verify(to_verify):
    print "Verifying %s as a subscriber to %s" % (to_verify['callback'], to_verify['topic'])
    challenge = baseN(abs(hash(time.time())), 36)
    verify_token = to_verify.get('verify_token', None)
    payload = {'hub.mode': to_verify['mode'], 'hub.topic': to_verify['topic'], 'hub.challenge': challenge}
    if verify_token:
        payload['hub.verify_token'] = verify_token
    url = '?'.join([to_verify['callback'], urllib.urlencode(payload)])
    def success(page):
        if challenge in page:
            if to_verify['mode'] == 'subscribe':
                if not to_verify['topic'] in subscriptions:
                    subscriptions[to_verify['topic']] = []
                subscriptions[to_verify['topic']].append(to_verify['callback'])
            else:
                subscriptions[to_verify['topic']].remove(to_verify['callback'])
            if 'onsuccess' in to_verify:
                to_verify['onsuccess'](page)
        else:
            if 'onfail' in to_verify:
                to_verify['onfail'](page)
    def failure(x):
        if 'onfail' in to_verify:
            to_verify['onfail'](x)
    client.getPage(url).addCallbacks(success, failure)
    verify_queue.get().addCallback(do_verify)
Exemplo n.º 12
0
def process_message(message, non_main_ns=NON_MAIN_NS, bcast_callback=None):
    msg_dict = parse_irc_message(message, non_main_ns)

    def broadcast(geo_json=None):
        if geo_json is not None:
            geo_dict = loads(geo_json)
            msg_dict['geo_ip'] = geo_dict
        bcast_callback(msg_dict)

    def report_failure_broadcast(error):
        bcast_log.debug("could not fetch from local geoip: %s", error)
        broadcast()

    if msg_dict['is_anon']:
        if bcast_callback:
            try:
                geo_url = str(LOCAL_GEOIP + '/json/' + msg_dict['user'])
            except UnicodeError:
                pass
            else:
                getPage(geo_url).addCallbacks(callback=broadcast,
                                              errback=report_failure_broadcast)
    elif bcast_callback:
        broadcast()
    return msg_dict
Exemplo n.º 13
0
	def CheckForMCUpdate(self):
		#Get Info from my webserver
		try:
			getPage(self.url + "currentversion.txt").addCallback(self.GotMCUpdateInfo).addErrback(self.error)
			self["text"].setText(_("Checking for updates..."))
		except Exception, e:
			self["text"].setText(_("Error: Twisted-Web not installed"))
Exemplo n.º 14
0
def do_fetch(url):
    subscribers = len(subscriptions.get(url, []))
    if subscribers:
        print "Fetching %s for %s subscribers" % (url, subscribers)
        client.getPage(url, headers={'X-Hub-Subscribers': subscribers}) \
            .addCallbacks(lambda p: dispatch_queue.put({'topic': url, 'data': p, 'content_type': 'application/atom+xml'}))
    fetch_queue.get().addCallback(do_fetch)
Exemplo n.º 15
0
	def getCookie(self, data=None):
		#url = "http://www.skygo.sky.de/index.html"
		url = "http://www.skygo.sky.de/skyguide"
		msg_log = "get page: '{0}'".format(url)
		print msg_log
		self.addLog(msg_log)
		getPage(url, headers=self.headers1, agent=self.agent, timeout=30, cookies=self.ck).addCallback(self.getSkyGuidePages).addErrback(self.dataError)
Exemplo n.º 16
0
	def	request(self):
		# if self.serien_name in self.termineCache:
		# 	self.__callback(self.termineCache[self.serien_name], False)
		# else:
		print "[SerienRecorder] suche ' %s '" % self.serien_name
		print self.serie_url
		getPage(getURLWithProxy(self.serie_url), agent=getUserAgent(), headers=getHeaders()).addCallback(self.__callback).addErrback(self.__errback)
Exemplo n.º 17
0
    def test_start_stop(self):
        yield self._storage.put("abc", StringIO("hello world"))
        yield self._server.start()
        # Starting multiple times is fine.
        yield self._server.start()
        storage_url = yield self._storage.get_url("abc")

        # It might not have started actually accepting connections yet...
        yield self.wait_for_server(self._server)
        self.assertEqual((yield getPage(storage_url)), "hello world")

        # Check that it can be killed by the current user (ie, is not running
        # as root) and still comes back up
        old_pid = yield self._server.get_pid()
        os.kill(old_pid, signal.SIGKILL)
        new_pid = yield self._server.get_pid()
        self.assertNotEquals(old_pid, new_pid)

        # Give it a moment to actually start serving again
        yield self.wait_for_server(self._server)
        self.assertEqual((yield getPage(storage_url)), "hello world")

        yield self._server.stop()
        # Stopping multiple times is fine too.
        yield self._server.stop()
Exemplo n.º 18
0
	def handleWebsite(self, website):
		info(website.getAttribute("name"))
		if self.number[:2] == "00":
			number = website.getAttribute("prefix") + self.number.replace(self.countrycode, "")
		else:
			number = self.number

		url = website.getAttribute("url")
		if re.search('$AREACODE', url) or re.search('$PFXAREACODE', url):
			error("(PFX)ARECODE cannot be handled")
			# self.caller = _("UNKNOWN")
			self.notifyAndReset()
			return
		#
		# Apparently, there is no attribute called (pfx)areacode anymore
		# So, this below will not work.
		#
		if re.search('\\$AREACODE', url) and website.hasAttribute("areacode"):
			areaCodeLen = int(website.getAttribute("areacode"))
			url = url.replace("$AREACODE", number[:areaCodeLen]).replace("$NUMBER", number[areaCodeLen:])
		elif re.search('\\$PFXAREACODE', url) and website.hasAttribute("pfxareacode"):
			areaCodeLen = int(website.getAttribute("pfxareacode"))
			url = url.replace("$PFXAREACODE", "%(pfxareacode)s").replace("$NUMBER", "%(number)s")
			url = url % {'pfxareacode': number[:areaCodeLen], 'number': number[areaCodeLen:]}
		elif re.search('\\$NUMBER', url):
			url = url.replace("$NUMBER", "%s") % number
		else:
			error("cannot handle websites with no $NUMBER in url")
			# self.caller = _("UNKNOWN")
			self.notifyAndReset()
			return
		info("Url to query: " + url)
		url = url.encode("UTF-8", "replace")
		self.currentWebsite = website
		getPage(url, agent="Mozilla/5.0 (Windows; U; Windows NT 6.0; de; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5").addCallback(self._gotPage).addErrback(self._gotError)
Exemplo n.º 19
0
    def delete(self):
        """
        Delete the specific workflow from VelesForge. Requires write access.
        """
        if not self._confirm():
            return
        print("Deleting %s..." % self.name)
        sys.stdout.flush()

        def finished(response):
            print("Successfully deleted %s" % self.name)
            sys.stdout.flush()
            self.stop()

        def failed(failure):
            try:
                failure.raiseException()
            except:
                self.exception("Failed to delete %s:", self.name)
            self.stop(failure, False)

        url = "%s%s?query=delete&name=%s&token=%s" % (
            self.base, root.common.forge.service_name, self.name, self.id)
        self.debug("Requesting %s", url)
        getPage(url.encode('charmap')).addCallbacks(callback=finished,
                                                    errback=failed)
Exemplo n.º 20
0
    def updateTimer(self):
        reactor.callLater(UPDATETIMER, self.updateTimer)

        def setTreeStatus(result):
            r = json.loads(result)
            status = r[u"status"]
            treename = r[u"tree"]
            changed = False
            logmsg = "Regular Tree check says: {} is {}".format(treename, status)
            if not treename in self.statusCache:
                changed = True
            if treename in self.statusCache and status != self.statusCache[treename]:
                changed = True
            if changed:
                # if status previously unknown (= bot has just started)
                # or a changed status then set the topic
                channel = tree2channel[tree]
                topic = "{} is {}!".format(treename, status)
                self.topic(channel, topic)
                logmsg += ", which is new. changing topic."
                print logmsg
            else:
                logmsg += ", just like before"
                print logmsg
            self.statusCache[treename] = status

        for tree in tree2channel:
            url = URL.format(tree)
            getPage(url).addCallbacks(callback=setTreeStatus)
Exemplo n.º 21
0
    def list(self):
        """
        Print the list of available workflows on VelesForge.
        """
        def finished(response):
            self.debug("Received %s", response)
            try:
                response = json.loads(response.decode('UTF-8'))
            except ValueError as e:
                self.exception("Failed to parse the response from server: %s",
                               response)
                self.stop(Failure(e), False)
                return
            table = PrettyTable("Name", "Description", "Author", "Version",
                                "Date")
            table.align["Name"] = table.align["Description"] = 'l'
            for item in response:
                table.add_row(*item)
            print(table)
            sys.stdout.flush()
            self.stop()

        def failed(failure):
            self.return_code = 1
            try:
                failure.raiseException()
            except:
                self.exception("Failed to list the available models:")
            self.stop(failure, False)

        url = self.base + root.common.forge.service_name + "?query=list"
        self.debug("Requesting %s", url)
        getPage(url.encode('charmap')).addCallbacks(callback=finished,
                                                    errback=failed)
Exemplo n.º 22
0
    def __init__(self, session):
        Screen.__init__(self, session)
        self["info"] = Label('Ładuję...')
        self["myPic"] = Pixmap()
        try:
            os.unlink('/tmp/meteo.png')
        except:
            pass
        self["myActionMap"] = ActionMap(["MeteoActions"],
        {
            "ok": self.cancel,
            "cancel": self.cancel,
            "menu": self.menu,
            "blue": self.menu,
            "green": self.next,
            "left": self.prev,
            "right": self.next,
            "start": self.start,
            "info": self.ShowOpis,
            "yellow": self.ShowOpis,
            "list": self.choose,
        }, -1)

        getPage('http://e2.areq.eu.org/ummeteo/version').addCallback(self.updateCB).addErrback(self.errorUpdate)

        self.onLayoutFinish.append(self.layoutFinished)
Exemplo n.º 23
0
def job():
    logger.info("Getting page")
    txt = yield client.getPage(settings.url)
    parsed_txt = html.fromstring(txt)
    # pylint:disable=E1102
    el = sel_base(parsed_txt)
    # if element does not exist
    if not len(el):
        return
    chapter_name = sel_chapter_name(el[0])[0].text.strip()
    update_date = sel_update_date(el[0])[0].text.strip()

    # do nothing if no new chapter avaliable
    if settings.current_chapter == chapter_name:
        logger.info("Current chapter is %s, not a new chapter, do nothing.", chapter_name)
        return
    else:
        # saves the new chapter name to settings
        settings.current_chapter = chapter_name

    data = {
        "chapter_name": chapter_name,
        "update_date": update_date
    }
    logger.info("{\n\tchapter_name: %s,\n\tupdate_date: %s\n}", chapter_name, update_date)

    logger.info("Sending data to webhook: %s", settings.webhook_url)
    try:
        yield client.getPage(settings.webhook_url,
                            method="POST", postdata=json.dumps(data),
                            headers={"Content-Type": "application/json; chatset=utf-8"})
    except Exception as exc:
        logger.error("Error occured while sending data.\n%s", str(exc))
    else:
        logger.info("Data sent")
Exemplo n.º 24
0
    def listenStreams(self, urlsStream):
        """
        @param urlsStream: Definit les url de stream a ecouter
        @type urlsStream: tableau d'url
        @return : Deferred
        Exemple:
            lstream = ["http://my.server.org/music.mp3", "http://m.server.org/music2.mp3"]
            instanceNabaz.listenStreams(lstreams).addCallback(lambda x: print x)
        API Nabastag : ?token=xxx&sn=xxx&urlList=http://my.server.org/music.mp3|http://m.server.org/music2.mp3
        """

        paramUrlsStream = '|'.join(urlsStream)
        print paramUrlsStream

        d = Deferred()

        def processedApiResult(result):
            d.callback(result)
            return d

        def processedApiFailed(faillure):
            d.errback(faillure)
            return d

        postdata = {"sn":self.__serialnumber,
                    "token":self.__tocken,
                    "urlList":paramUrlsStream}

        getPage(self.__urlapi,
                method="POST",
                postdata=urlencode(postdata),
                headers={'Content-Type':'application/x-www-form-urlencoded;\
                          charset=utf-8'}).addCallback(processedApiResult).addErrback(processedApiFailed)

        return d
Exemplo n.º 25
0
 def recaptcha(self, data):
     if data.find('http://goo.gl') != -1:
         self.mod.on_recaptcha(self.index, data[data.index('"id"'):].split('"')[3])
     else:
         self.challenge = data[data.index('challenge'):].split('\'')[1]
         url = '{"longUrl": "http://www.google.com/recaptcha/api/image?c=%s"}' % self.challenge
         getPage("https://www.googleapis.com/urlshortener/v1/url", method="POST", postdata=url, headers={'Content-Type': 'application/json'}).addCallback(self.recaptcha)
Exemplo n.º 26
0
    def sendMessage(self, message, voice="FR-Anastasie"):
        """
        @param message: send message to nabaztag
        @type message: str
        @return : Deferred
        """

        d = Deferred()

        def processedApiResult(result):
            d.callback(result)
            return d

        def processedApiFailed(faillure):
            d.errback(faillure)
            return d

        postdata = {"sn":self.__serialnumber,
                    "token":self.__tocken,
                    "tts":message,
                    "voice":voice}

        getPage(self.__urlapi,
                method="POST",
                postdata=urlencode(postdata),
                headers={'Content-Type':'application/x-www-form-urlencoded;\
                          charset=3Dutf-8'}).addCallback(processedApiResult).addErrback(processedApiFailed)

        return d
Exemplo n.º 27
0
    def start(self):
        try:
            data = yield getPage("%slogin/" % self.config['url'], cookies=self.cookies)
        except Exception:
            raise

        result = CSRF_RE.search(data)
        if not result:
            print "error"
            return
        token = result.group(1)

        # login
        try:
            data = yield getPage("%slogin/" % self.config['url'],
                                 method='POST',
                                 postdata=urllib.urlencode({
                                     'csrfmiddlewaretoken': token,
                                     'username': self.config['username'],
                                     'password': self.config['password'],
                                 }),
                                 cookies=self.cookies,
                                 headers={'Content-Type': 'application/x-www-form-urlencoded'})
        except Exception:
            raise

        self.task = task.LoopingCall(self.update)
        self.task.start(self.config["update_rate"])
Exemplo n.º 28
0
def _do_fetch_gitrev(build_url, base_url, sourcetarball_url, platform, logger):
    result = {}

    # get git revision from jenkins
    json_all = json.loads((yield _mk_request_jenkins_all_builds(base_url, platform, logger)))
    gitrev = None
    for i in [i for i in json_all['allBuilds'] if i['url'].encode('ascii', 'ignore') == build_url]:
        for fingerprint in i['fingerprint']:
            fp_name = fingerprint['original']['name']
            if fp_name == 'build-source-tarball-mono':
                assert gitrev is None, "should set gitrev only once"
                url = sourcetarball_url + str(fingerprint['original']['number']) + '/pollingLog/pollingLog'
                if logger:
                    logger("request: " + str(url))
                regexgitrev = re.compile("Latest remote head revision on [a-zA-Z/]+ is: (?P<gitrev>[0-9a-fA-F]+)")
                match = regexgitrev.search((yield getPage(url)))
                assert match is not None
                gitrev = match.group('gitrev')
            if fp_name == 'build-source-tarball-mono-pullrequest':
                assert gitrev is None, "should set gitrev only once"
                url = sourcetarball_url + str(fingerprint['original']['number']) + '/consoleText'
                if logger:
                    logger("request: " + str(url))
                regexgitrev = re.compile("GitHub pull request #(?P<prid>[0-9]+) of commit (?P<gitrev>[0-9a-fA-F]+)")
                match = regexgitrev.search((yield getPage(url)))
                assert match is not None
                gitrev = match.group('gitrev')
                result[PROPERTYNAME_JENKINSGITHUBPULLREQUEST] = match.group('prid')
    assert gitrev is not None, "parsing gitrev failed"
    result[PROPERTYNAME_JENKINSGITCOMMIT] = gitrev
    defer.returnValue(result)
Exemplo n.º 29
0
    def openTest(self):
                self["info"].setText("Downloading list...")
                testno = 1

                xurl = "http://www.et-view-support.com/addons/XTA-team/" + self.addon + "/list.txt"
                print "xurl =", xurl
                getPage(xurl).addCallback(self.gotPage).addErrback(self.getfeedError)
Exemplo n.º 30
0
	def eco_post(self, data):
		url = "http://www.ecostream.tv/assets/js/common.js"
		data2 = urllib.urlopen(url).read()
		post_url = re.findall("url: '(http://www.ecostream.tv/.*?)\?s=", data2, re.S)
		if post_url:
			print post_url
			sPattern = "var t=setTimeout\(\"lc\('([^']+)','([^']+)','([^']+)','([^']+)'\)"
			r = re.findall(sPattern, data)
			if r:
				for aEntry in r:
					sS = str(aEntry[0])
					sK = str(aEntry[1])
					sT = str(aEntry[2])
					sKey = str(aEntry[3])

				print "current keys:", sS, sK, sT, sKey
				sNextUrl = post_url[0]+"?s="+sS+'&k='+sK+'&t='+sT+'&key='+sKey
				print "URL:", sNextUrl
				info = urlencode({'s': sS, 'k': sK, 't': sT, 'key': sKey})
				print "POST:", info
				getPage(sNextUrl, method='POST', postdata=info, headers={'Referer':'http://www.ecostream.tv', 'X-Requested-With':'XMLHttpRequest'}).addCallback(self.eco_final).addErrback(self.errorload)
			else:
				self.stream_not_found()
		else:
			self.stream_not_found()
Exemplo n.º 31
0
 def getSections(self):
     self.setStatusLabel("loading sections")
     self.loadinginprogress = True    
     getPage("http://wap.verkehrsinfo.de/wvindex.php3").addCallback(self.sectionsLoaded).addErrback(self.sectionsLoadingFaild)
Exemplo n.º 32
0
 def getMD5(self):
     url = "http://www.dreamboxupdate.com/download/opendreambox/dreambox-nfiflasher-%s-md5sums" % self.box
     client.getPage(url).addCallback(self.md5sums_finished).addErrback(
         self.feed_failed)
Exemplo n.º 33
0
 def getItemsOfSection(self, section):
     print("loading section", section.name, section.link)
     self.setStatusLabel("loading messages "+section.name)
     self.loadinginprogress = True    
     getPage("http://wap.verkehrsinfo.de"+section.link).addCallback(self.trafficitemsLoaded).addErrback(self.trafficitemsLoadingFaild)
Exemplo n.º 34
0
 def test01(self):
     d = client.getPage('https://127.0.0.1:%s/resource' % self.ssl_port)
     def check(result):
         self.assertEquals('{}', result)
     d.addCallback(check)
     return d
Exemplo n.º 35
0
 def nfo_download(self, branch, idx):
     nfourl = (self.feedlists[branch][idx][1])[:-4] + ".nfo"
     self.nfofilename = (self.feedlists[branch][idx][0])[:-4] + ".nfo"
     print "[check_for_NFO]", nfourl
     client.getPage(nfourl).addCallback(self.nfo_finished).addErrback(
         self.nfo_failed)
Exemplo n.º 36
0
	def poll(self):
		# Reloading, reschedule
		if self.reloading:
			print("[SimpleRSS] timer triggered while reloading, rescheduling")
			self.poll_timer.start(10000, 1)
		# End of List
		elif len(self.feeds) <= self.current_feed:
			# New Items
			if self.newItemFeed.history:
				print("[SimpleRSS] got new items, calling back")
				self.doCallback()

				# Inform User
				update_notification_value = config.plugins.simpleRSS.update_notification.value
				if update_notification_value == "preview":
					from .RSSScreens import RSSFeedView

					from Tools.Notifications import AddNotificationWithID, RemovePopup

					RemovePopup(NOTIFICATIONID)

					AddNotificationWithID(
						NOTIFICATIONID,
						RSSFeedView,
						self.newItemFeed,
						newItems=True
					)
				elif update_notification_value == "notification":
					AddPopup(
						_("Received %d new news item(s).") % (len(self.newItemFeed.history)),
						MessageBox.TYPE_INFO,
						5,
						NOTIFICATIONID
					)
				elif update_notification_value == "ticker":
					from .RSSTickerView import tickerView
					if not tickerView:
						print("[SimpleRSS] missing ticker instance, something with my code is wrong :-/")
					else:
						tickerView.display(self.newItemFeed)
			# No new Items
			else:
				print("[SimpleRSS] no new items")

			self.current_feed = 0
			self.poll_timer.startLongTimer(config.plugins.simpleRSS.interval.value * 60)
		# It's updating-time
		else:
			# Assume we're cleaning history if current feed is 0
			clearHistory = self.current_feed == 0
			if config.plugins.simpleRSS.update_notification.value != "none":
				from Tools import Notifications
				if hasattr(Notifications, 'notificationQueue'):
					notifications = Notifications.notificationQueue.queue
					current_notifications = Notifications.notificationQueue.current
					handler = lambda note: (note.fnc, note.screen, note.args, note.kwargs, note.id)
					handler_current = lambda note: (note[0].id,)
				else:
					notifications = Notifications.notifications
					current_notifications = Notifications.current_notifications
					handler_current = handler = lambda note: note

				for x in current_notifications:
					if handler_current(x)[0] == NOTIFICATIONID:
						print("[SimpleRSS] timer triggered while preview on screen, rescheduling")
						self.poll_timer.start(10000, 1)
						return

				if clearHistory:
					for x in notifications:
						if handler(x)[4] == NOTIFICATIONID:
							print("[SimpleRSS] wont wipe history because it was never read")
							clearHistory = False
							break

			if clearHistory:
				del self.newItemFeed.history[:]

			# Feed supposed to autoupdate
			feed = self.feeds[self.current_feed]

			if feed.autoupdate:
				getPage(six.ensure_binary(feed.uri)).addCallback(self._gotPage).addErrback(self.error)
			# Go to next feed
			else:
				print("[SimpleRSS] passing feed")
				self.next_feed()
Exemplo n.º 37
0
 def test01_connect(self):
     d = client.getPage('http://127.0.0.1:%s/resource' % self.port)
     def check(result):
         self.assertEquals('true', result)
     d.addCallback(check)
     return d
Exemplo n.º 38
0
 def _get_changes(self, url):
     return getPage(url, timeout=self.timeout)
Exemplo n.º 39
0
    def choregraphy(self, choregraphy):
        """
        @param choregraphy: describe choregra
        @type message: str
        @return : Deferred

        LED commands

        It is a series of values separated by commas.
        1. First value : action time (' l'heure ')
            ("0" if it is the first command).
        2. Second value : 'led' , which gives a color to the LED.
        3. Third value : To define which LED you want to illuminate.
            0 : bottom LED
            1 : rabbit's left LED
            2 : middle LED
            3 : rabbit's right LED
            4 : high LED
        4. Fourth, Fifth, Sixth value : the color in RGB.
            Value from 0 to 255

        Ears commands

        This is a series of values separated by commas.
        The command is as follows :
        1. First value : Action time (l'heure)
            "0" if it is the first command.
        2. Second value : 'motor', to move an ear
        3. Third value : Ears command
            1 to command left ear
            0 to command right ear
        4. Fourth value : Angle of ear
            Possible value from 0 to 180
        5. Fifth value : Unused, set at "0"
        6. Sixth value : Rotation of the ears directions
            1 : high->back->low->front->high...
            0 : high->front->low->back->high...

        Exemple :

        0,motor,1,20,0,0

        0,led,2,0,238,0,2,led,1,250,0,0,3,led,2,0,0,0

        10,0,motor,1,20,0,0,0,led,2,0,238,0,2,led,1,250,0,0,3,led,2,0,0,0

        """

        d = Deferred()

        def processedApiResult(result):
            d.callback(result)
            return d

        def processedApiFailed(faillure):
            d.errback(faillure)
            return d

        postdata = {
            "sn": self.__serialnumber,
            "token": self.__tocken,
            "chor": choregraphy
        }

        getPage(
            self.__urlapi,
            method="POST",
            postdata=urlencode(postdata),
            headers={
                'Content-Type':
                'application/x-www-form-urlencoded;\
                          charset=3Dutf-8'
            }).addCallback(processedApiResult).addErrback(processedApiFailed)

        return d
Exemplo n.º 40
0
 def _get_page(self, url):
     return getPage(url, timeout=self.timeout)
Exemplo n.º 41
0
	def singlePoll(self, id, callback=False, errorback=None):
		getPage(six.ensure_binary(self.feeds[id].uri)).addCallback(self._gotPage, id, callback, errorback).addErrback(errorback)