def getEventTeamsMatches(self): event = {} teams = {} matches = {} requestURI = self.getCurrentDivisionURI() if "api.ftcscores.com" in requestURI: # Specific logic for ftcscores.com event, teams, matches = self.getEventTeamsMatches_ftcscores() elif "theorangealliance.org/apiv2" in requestURI: # Specific logic for theorangealliance event, teams, matches = self.getEventTeamsMatches_toa() elif "worlds.pennfirst.org/cache/TeamInfo" in requestURI: event, teams, matches = self.getEventTeamsMatches_pennfirst() else: # Default logic - ftc scoring system event, teams, matches = self.getEventTeamsMatches_default() # Now update powerscores self.__calculatePowerScore(teams, matches) LOG.debug("powerscore calculated") return (event, teams, matches)
def refresh_token(self): LOG.debug('Refreshing token') if identity_lock.acquire(blocking=False): try: data = self.send({ "path": "auth/token", "headers": { "Authorization": "Bearer " + self.identity.refresh, "Device": self.identity.uuid } }) IdentityManager.save(data, lock=False) LOG.debug('Saved credentials') except HTTPError as e: if e.response.status_code == 401: LOG.error('Could not refresh token, invalid refresh code.') else: raise finally: identity_lock.release() else: # Someone is updating the identity wait for release with identity_lock: LOG.debug('Refresh is already in progress, waiting until done') time.sleep(1.2) os.sync() self.identity = IdentityManager.load(lock=False) LOG.debug('new credentials loaded')
def refresh_token(self): LOG.debug('Refreshing token') if identity_lock.acquire(blocking=False): try: data = self.send({ "path": "auth/token", "headers": { "Authorization": "Bearer " + self.identity.refresh } }) IdentityManager.save(data, lock=False) LOG.debug('Saved credentials') except HTTPError as e: if e.response.status_code == 401: LOG.error('Could not refresh token, invalid refresh code.') else: raise finally: identity_lock.release() else: # Someone is updating the identity wait for release with identity_lock: LOG.debug('Refresh is already in progress, waiting until done') time.sleep(1.2) os.sync() self.identity = IdentityManager.load(lock=False) LOG.debug('new credentials loaded')
def delete_skill_metadata(self, uuid): """ Delete the current skill metadata from backend TODO: Real implementation when method exists on backend Args: uuid (str): unique id of the skill """ try: LOG.debug("Deleting remote metadata for {}".format(skill_gid)) self.request({ "method": "DELETE", "path": ("/" + self.identity.uuid + "/skill" + "/{}".format(skill_gid)) }) except Exception as e: LOG.error("{} cannot delete metadata because this".format(e))
def send(self, params): """ Send request to mycroft backend. The method handles Etags and will return a cached response value if nothing has changed on the remote. Arguments: params (dict): request parameters Returns: Requests response object. """ query_data = frozenset(params.get('query', {}).items()) params_key = (params.get('path'), query_data) etag = self.params_to_etag.get(params_key) method = params.get("method", "GET") headers = self.build_headers(params) data = self.build_data(params) json_body = self.build_json(params) query = self.build_query(params) url = self.build_url(params) # For an introduction to the Etag feature check out: # https://en.wikipedia.org/wiki/HTTP_ETag if etag: headers['If-None-Match'] = etag response = requests.request(method, url, headers=headers, params=query, data=data, json=json_body, timeout=(3.05, 15)) if response.status_code == 304: LOG.debug('Etag matched. Nothing changed for: ' + params['path']) response = self.etag_to_response[etag] elif 'ETag' in response.headers: etag = response.headers['ETag'].strip('"') LOG.debug('Updating etag for: ' + params['path']) self.params_to_etag[params_key] = etag self.etag_to_response[etag] = response return self.get_response(response)
def format_related(cls, abstract, query): LOG.debug('Original abstract: ' + abstract) ans = abstract if ans[-2:] == '..': while ans[-1] == '.': ans = ans[:-1] phrases = ans.split(', ') first = ', '.join(phrases[:-1]) last = phrases[-1] if last.split()[0] in cls.start_words: ans = first last_word = ans.split(' ')[-1] while last_word in cls.start_words or last_word[-3:] == 'ing': ans = ans.replace(' ' + last_word, '') last_word = ans.split(' ')[-1] category = None match = re.search('\(([a-z ]+)\)', ans) if match: start, end = match.span(1) if start <= len(query) * 2: category = match.group(1) ans = ans.replace('(' + category + ')', '()') words = ans.split() for article in cls.articles: article = article.title() if article in words: index = words.index(article) if index <= 2 * len(query.split()): name, desc = words[:index], words[index:] desc[0] = desc[0].lower() ans = ' '.join(name) + cls.is_verb + ' '.join(desc) break if category: ans = ans.replace('()', cls.in_word + category) if ans[-1] not in '.?!': ans += '.' return ans
def respond(self, query): if len(query) == 0: return 0.0 r = ddg.query(query) LOG.debug('Query: ' + str(query)) LOG.debug('Type: ' + r.type) if (r.answer is not None and r.answer.text and "HASH" not in r.answer.text): return (query + self.is_verb + r.answer.text + '.') elif len(r.abstract.text) > 0: sents = split_sentences(r.abstract.text) return sents[0] elif len(r.related) > 0 and len(r.related[0].text) > 0: related = split_sentences(r.related[0].text)[0] return (self.format_related(related, query)) else: return None
def refresh_token(self): LOG.debug('Refreshing token') if identity_lock.acquire(blocking=False): try: data = self.send({ "path": "auth/token", "headers": { "Authorization": "Bearer " + self.identity.refresh } }) IdentityManager.save(data, lock=False) LOG.debug('Saved credentials') finally: identity_lock.release() else: # Someone is updating the identity wait for release with identity_lock: LOG.debug('Refresh is already in progress, waiting until done') time.sleep(1.2) os.sync() self.identity = IdentityManager.load(lock=False) LOG.debug('new credentials loaded')
def getEventTeamsMatches_ftcscores(self): requestURI = self.getCurrentDivisionURI() event = {} teams = {} matches = {} LOG.debug("request starting ...") r = requests.get(requestURI, timeout=5) jsonResult = r.json() LOG.debug("request finished") # Just a couple of event things event['title'] = jsonResult['fullName'] event['subtitle'] = "" if "subtitle" in jsonResult: event['subtitle'] = jsonResult['subtitle'] # Assemble all the team info from the teams and rankings sections if "teams" in jsonResult: for team in jsonResult["teams"]: teamNum = jsonResult["teams"][team]["number"] teams[teamNum] = {} teams[teamNum]['number'] = teamNum teams[teamNum]['name'] = jsonResult["teams"][team]["name"] teams[teamNum]['school'] = jsonResult["teams"][team]["school"] teams[teamNum]['city'] = jsonResult["teams"][team]["city"] teams[teamNum]['state'] = jsonResult["teams"][team]["state"] teams[teamNum]['country'] = jsonResult["teams"][team][ "country"] if "rankings" in jsonResult: for ranking in jsonResult["rankings"]: teamNum = ranking["number"] teams[teamNum]['rank'] = ranking["rank"] teams[teamNum]['qp'] = ranking["current"]["qp"] teams[teamNum]['rp'] = ranking["current"]["rp"] teams[teamNum]['highest'] = ranking["current"]["highest"] teams[teamNum]['matches'] = ranking["current"]["matches"] teams[teamNum]['real_matches'] = 0 teams[teamNum]['allianceScore'] = 0 teams[teamNum]['powerScore'] = 0 # Now grab the matches, we want completed qualifier matches only if "rankings" in jsonResult: for match in jsonResult["matches"]: if ((match["number"].startswith("Q")) and (match["status"] == "done")): matches[match["number"]] = {} matches[match["number"]]['matchid'] = match["number"] matches[match["number"]]['alliances'] = {} matches[match["number"]]['alliances']['red'] = {} matches[match["number"]]['alliances']['red'][ 'team1'] = match["teams"]['red'][0]['number'] matches[match["number"]]['alliances']['red'][ 'team2'] = match["teams"]['red'][1]['number'] matches[match["number"]]['alliances']['red'][ 'total'] = match["scores"]['red'] matches[match["number"]]['alliances']['red'][ 'auto'] = match["subscoresRed"]['auto'] matches[match["number"]]['alliances']['red'][ 'teleop'] = match["subscoresRed"]['tele'] matches[match["number"]]['alliances']['red'][ 'endg'] = match["subscoresRed"]['endg'] matches[match["number"]]['alliances']['red'][ 'pen'] = match["subscoresRed"]['pen'] #also... udpate the "real matches"... to account for surrogates in powerscore teams[match["teams"]['red'][0] ['number']]['real_matches'] += 1 teams[match["teams"]['red'][1] ['number']]['real_matches'] += 1 matches[match["number"]]['alliances']['blue'] = {} matches[match["number"]]['alliances']['blue'][ 'team1'] = match["teams"]['blue'][0]['number'] matches[match["number"]]['alliances']['blue'][ 'team2'] = match["teams"]['blue'][1]['number'] matches[match["number"]]['alliances']['blue'][ 'total'] = match["scores"]['blue'] matches[match["number"]]['alliances']['blue'][ 'auto'] = match["subscoresBlue"]['auto'] matches[match["number"]]['alliances']['blue'][ 'teleop'] = match["subscoresBlue"]['tele'] matches[match["number"]]['alliances']['blue'][ 'endg'] = match["subscoresBlue"]['endg'] matches[match["number"]]['alliances']['blue'][ 'pen'] = match["subscoresBlue"]['pen'] #also... udpate the "real matches"... to account for surrogates in powerscore teams[match["teams"]['blue'][0] ['number']]['real_matches'] += 1 teams[match["teams"]['blue'][1] ['number']]['real_matches'] += 1 LOG.debug("data compiled") return (event, teams, matches)
def respond(self, query): if len(query) == 0: return 0.0 if self.autotranslate and self.lang[:2] != 'en': query_tr = translate(query, from_language=self.lang[:2], to_language='en') self.log.debug("translation: {}".format(query_tr)) r = ddg.query(query_tr) LOG.debug('Query: ' + str(query)) LOG.debug('Query_tr: ' + str(query_tr)) LOG.debug('Type: ' + r.type) if (r.answer is not None and r.answer.text and "HASH" not in r.answer.text): LOG.debug('Answer: ' + str(r.answer.text)) if self.autotranslate and self.lang[:2] != 'en': response = translate(r.answer.text, from_language='en', to_language=self.lang[:2]) else: response = r.answer.text return (query + self.is_verb + response + '.') elif len(r.abstract.text) > 0: LOG.debug('Abstract: ' + str(r.abstract.text)) sents = split_sentences(r.abstract.text) if self.autotranslate and self.lang[:2] != 'en': for sent in sents: sent = translate(sent, from_language='en', to_language=self.lang[:2]) return sents[0] elif len(r.related) > 0 and len(r.related[0].text) > 0: related = split_sentences(r.related[0].text)[0] answer = self.format_related(related, query) LOG.debug('Related: ' + str(answer)) if self.autotranslate and self.lang[:2] != 'en': answer = translate(answer, from_language='en', to_language=self.lang[:2]) return (answer) else: return None