def check_endpoint(): response = HTTPResponse() request_id = request.forms.get('request_id') identity = request.forms.get('username') password = request.forms.get('password') with open(os.path.join(BASEDIR, 'userdb.json'), 'r') as f: userdb = json.load(f) if not identity in userdb or userdb[identity]['password'] != password: response.status = 302 response.headers['Location'] = '/reject?request_id={}'.format(request_id) return response user_data = userdb[identity] db = dbm.open(os.path.join(BASEDIR, 'req.db'), 'c') oid_request = {k: v[0] for k, v in parse_qs(db[request_id].decode('utf-8')).items()} db.close() is_oid2 = 'openid.ns' in oid_request and oid_request['openid.ns'] == 'http://specs.openid.net/auth/2.0' oid_response = { 'mode': 'id_res', 'identity': identity, 'return_to': oid_request['openid.return_to'] } if is_oid2: oid_response['ns'] = 'http://specs.openid.net/auth/2.0' oid_response['op_endpoint'] = 'https://gears.headake.win/oid/' oid_response['response_nonce'] = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ') oid_response['assoc_handle'] = settings.HANDLE oid_response['claimed_id'] = oid_request['openid.claimed_id'] if 'openid.ax.required' in oid_request: ax_required = oid_request['openid.ax.required'].split(',') oid_response['ax.mode'] = 'fetch_response' for field in ax_required: oid_response['ax.type.' + field] = oid_request['openid.ax.type.' + field] oid_response['ax.value.' + field] = AX_DATA[oid_request['openid.ax.type.' + field]].format(**user_data) if 'openid.sreg.required' in oid_request: sreg_required = oid_request['openid.sreg.required'].split(',') for field in sreg_required: oid_response['sreg.' + field] = SREG_DATA[field].format(**user_data) oid_response_fields = oid_response.keys() signed_fields = ','.join(oid_response_fields) signature = base64.b64encode( hmac.new( settings.SECRET, '\n'.join(['openid.{}:{}'.format(k, oid_response[k]) for k in oid_response_fields]).encode('utf-8') ).digest() ) oid_response['assoc_handle'] = settings.HANDLE oid_response['signed'] = signed_fields oid_response['sig'] = signature response.status = 302 response.headers['Location'] = oid_request['openid.return_to'] + ('?' if oid_request['openid.return_to'].find('?') == -1 else '&') + urlencode({'openid.' + k: v for k, v in oid_response.items()}) return response
def get_ui_index(request): # args = get_request_log_args(request) # try: with open( os.path.join(os.path.dirname(__file__), '..', 'webfiles/index.html'), 'r') as f: page_body = f.read() # status = httpStatusSuccess args['result'] = logPass # args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status response.body = page_body enable_cors(response) # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def post_enterpin(request, _virginmedia_tivo): # args = get_request_log_args(request) # try: # r = _virginmedia_tivo.sendPin() # if not bool(r): status = httpStatusFailure else: status = httpStatusSuccess # args['result'] = logPass args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status # return response # except Exception as e: status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def _create_response(self, event): local_response = HTTPResponse(headers=event.headers) status, status_message = event.status local_response.status = "{code} {message}".format(code=status, message=status_message) local_response.set_header("Content-Type", event.content_type) local_response.body = "" if int(status) == 204 else self._format_response_data(event) return local_response
def get_powerstatus(request, _xbox): # args = get_request_log_args(request) # try: # isOn = _xbox.power_status() # data = {'isOn': isOn} # status = httpStatusSuccess # args['result'] = logPass args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status response.body = data enable_cors(response) # return response # except Exception as e: status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def get_commands(request, _virginmedia_tivo): # args = get_request_log_args(request) # try: # data = _virginmedia_tivo.getCommands() # status = httpStatusSuccess # args['result'] = logPass args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status response.body = data # return response # except Exception as e: status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def get_data_infoservice(service=False, resource_requested=False): # global infoservices # log = log_msg(request, uri_data_infoservice) # try: # if (not service) or (not resource_requested): log_error('{log} - {error}'.format(log=log, error='URI invalid')) raise HTTPError(404) # try: info_seq = get_cfg_info_seq(service) except Exception as e: log_error('{log} - {error}'.format(log=log, error=e)) raise HTTPError(404) # data_dict = {'data': resource_requested} # if len(request.query.decode()) > 0: data_dict.update(request.query.decode()) # # rsp = infoservices[info_seq].getData(data_dict) # response = HTTPResponse() enable_cors(response) # if isinstance(rsp, bool): if rsp: response.status = 200 else: response.status = 400 else: if bool(rsp): response.body = str(rsp) response.status = 200 else: response.status = 400 # log_general(log) return response # except Exception as e: log_error('{log} - {error}'.format(log=log, error=e)) raise HTTPError(500)
def apikeyNotValid(): response = HTTPResponse() response.status = 200 response.body = json.dumps( { 'message': 'api key not valid', } ) + "\n" return response
def success(): response = HTTPResponse() response.status = 200 response.body = json.dumps( { 'message': 'Success' } ) + "\n" return response
def cannotTweet(): response = HTTPResponse() response.status = 500 response.body = json.dumps( { 'message': 'Failed', 'Error': 'CannotTweet' } ) + "\n" return response
def reject_request(): request_id = request.query.get('request_id') db = dbm.open(os.path.join(BASEDIR, 'req.db'), 'c') oid_request = {k: v[0] for k, v in parse_qs(db[request_id].decode('utf-8')).items()} del db[request_id] db.close() response = HTTPResponse() response.status = 302 response.headers['Location'] = oid_request['openid.return_to'] + ('?' if oid_request['openid.return_to'].find('?') == -1 else '&') + urlencode({'openid.mode': 'cancel'}) return response
def badRequest(key): response = HTTPResponse() response.status = 400 response.body = json.dumps( { 'message': 'Failed', 'BadRequest': key } ) + "\n" return response
def get_headlines(request, option): # args = get_request_log_args(request) args['timestamp'] = datetime.now() args['process'] = 'inbound' # try: # data = {} # if option == 'sources': data['articles'] = cache.cache['headlines']['sources'] data['sources'] = cache.cache['sources']['sources'] elif option == 'categories': data['articles'] = cache.cache['headlines']['categories'] data['sources'] = cache.cache['sources']['categories'] elif option == 'country': data['articles'] = cache.cache['headlines']['country'] data['sources'] = cache.cache['sources']['country'] elif option == 'language': data['articles'] = cache.cache['headlines']['language'] data['sources'] = cache.cache['sources']['language'] else: data = False # if not bool(data): status = httpStatusFailure args['result'] = logFail else: status = httpStatusSuccess args['result'] = logPass # args['http_response_code'] = status args['description'] = '-' cache.logQ.put(args) # response = HTTPResponse() response.status = status # if not isinstance(data, bool): response.body = data # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e cache.logQ.put(args) # raise HTTPError(status)
def get_calendar_daterange(request, option, dateFrom, dateTo): # args = get_request_log_args(request) args['timestamp'] = datetime.now() args['process'] = 'inbound' # try: # '_dateFrom' and '_dateTo' should be in format "yyyy-mm-dd" _dateFrom = datetime.strptime(dateFrom, '%Y-%m-%d') _dateTo = datetime.strptime(dateTo, '%Y-%m-%d') # if option == str_calendar_events: data = { str_calendar_events: cache.cache['_icloud'].get_events_daterange( _dateFrom, _dateTo) } elif option == str_calendar_birthdays: data = { str_calendar_birthdays: get_birthdays_daterange(_dateFrom, _dateTo) } else: data = False # if not bool(data): status = httpStatusFailure args['result'] = logFail else: status = httpStatusSuccess args['result'] = logPass # args['http_response_code'] = status args['description'] = '-' cache.logQ.put(args) # response = HTTPResponse() response.status = status # if not isinstance(data, bool): response.body = data # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e cache.logQ.put(args) # raise HTTPError(status)
def hello(): # pylint: disable=unused-variable paper_id = str(request.params.paper_id) # pylint: disable=no-member paper_pdf_url = str(request.params.paper_pdf_url) # pylint: disable=no-member response = HTTPResponse(status=200) if (not paper_id) or (not paper_pdf_url): response.status = 400 response.body = {'status': response.status} parse_xhtml(paper_id, paper_pdf_url) return response
def indieauth_check(): response = HTTPResponse() request_id = request.forms.get('request_id') identity = request.forms.get('username') password = request.forms.get('password') with open(os.path.join(BASEDIR, 'userdb.json'), 'r') as f: userdb = json.load(f) if not identity in userdb or userdb[identity]['password'] != password: response.status = 302 response.headers['Location'] = '/iauth/reject?request_id={}'.format(request_id) return response user_data = userdb[identity] authorization_code = str(uuid.uuid4()) db = dbm.open(os.path.join(BASEDIR, 'req.db'), 'c') ia_request = {k: v[0] for k, v in parse_qs(db['ia.request:' + request_id].decode('utf-8')).items()} db['ia.auth:' + authorization_code] = json.dumps(ia_request) db.close() ia_response = { 'code': authorization_code, 'state': ia_request['state'] } response.status = 302 response.headers['Location'] = ia_request['redirect_uri'] + ('?' if ia_request['redirect_uri'].find('?') == -1 else '&') + urlencode(ia_response) return response
def get_sunrisesunset(request, _weather, _sunrisesunset, date): # # 'date' in YYYY-MM-DD format. Also accepts other date formats and even relative date formats. # If not present, date defaults to current date. Optional. # args = get_request_log_args(request) # try: # location = _weather.get_location() lat = location['latitude'] long = location['longitude'] # if date: data = _sunrisesunset.get_sunrise_sunset(lat, long, date) else: data = _sunrisesunset.get_sunrise_sunset(lat, long, 'today') # if not bool(data): status = httpStatusFailure args['result'] = logFail else: status = httpStatusSuccess args['result'] = logPass # args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status # if not isinstance(data, bool): response.body = data # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def get_all(request, _weather, _sunrisesunset): # args = get_request_log_args(request) # try: # data = _weather.get_weather_forecast() # if not bool(data): status = httpStatusFailure args['result'] = logFail else: status = httpStatusSuccess args['result'] = logPass # for day_key in data['days'].keys(): # data['days'][day_key][ 'sunRiseSet'] = _sunrisesunset.get_sunrise_sunset( data['location']['latitude'], data['location']['longitude'], data['days'][day_key]['date']) # # args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status # if not isinstance(data, bool): response.body = data # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def get_calendar_all(request, option): # args = get_request_log_args(request) args['timestamp'] = datetime.now() args['process'] = 'inbound' # try: # if option == str_calendar_events: data = {str_calendar_events: cache.cache['calendar']['events']} elif option == str_calendar_birthdays: data = { str_calendar_birthdays: cache.cache['calendar']['birthdays'] } else: data = False # if not bool(data): status = httpStatusFailure args['result'] = logFail else: status = httpStatusSuccess args['result'] = logPass # args['http_response_code'] = status args['description'] = '-' cache.logQ.put(args) # response = HTTPResponse() response.status = status # if not isinstance(data, bool): response.body = data # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e cache.logQ.put(args) # raise HTTPError(status)
def post_news_config_update(request): # args = get_request_log_args(request) args['timestamp'] = datetime.now() args['process'] = 'inbound' # try: # data = request.json # if validate_config_update(data): # r = set_cfg_details_updates(data['language'], data['country'], data['sources'], data['categories']) # if r: status = httpStatusSuccess logresult = logPass else: status = httpStatusFailure logresult = logFail # else: status = httpStatusBadrequest logresult = logPass # args['result'] = logresult args['http_response_code'] = status args['description'] = '-' cache.logQ.put(args) # response = HTTPResponse() response.status = status # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e cache.logQ.put(args) # raise HTTPError(status)
def post_command_touchMove(request, _tvlgnetcast): # args = get_request_log_args(request) # try: # data_dict = request.json # if validate_touchMove(data_dict): # x = data_dict['touchMoveX'] y = data_dict['touchMoveY'] r = _tvlgnetcast.sendTouchmove(x, y) # if not bool(r): status = httpStatusFailure result = logFail else: status = httpStatusSuccess result = logPass else: status = httpStatusBadrequest result = logFail # args['result'] = result args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status enable_cors(response) # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def post_channel(request, _virginmedia_tivo): # args = get_request_log_args(request) # try: # data_dict = request.json # if validate_channel(data_dict): # channel = data_dict['channel'] if 'plus1' in data_dict: plus1 = data_dict['plus1'] else: plus1 = False # r = _virginmedia_tivo.sendChannel(channel, plus1) # if not bool(r): status = httpStatusFailure else: status = httpStatusSuccess else: status = httpStatusBadrequest # args['result'] = logPass args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status # return response # except Exception as e: status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def get_forecast(request, _weather, option): # args = get_request_log_args(request) # try: # if option == 'all': data = _weather.get_weather_forecast() elif option == '3hourly': data = False elif option == 'daily': data = False else: data = False # if not bool(data): status = httpStatusFailure args['result'] = logFail else: status = httpStatusSuccess args['result'] = logPass # args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status # if not isinstance(data, bool): response.body = data # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def get_apps_all(request, _tvlgnetcast): # args = get_request_log_args(request) # try: # r = _tvlgnetcast.getApps_all() # # Add URI for retrieving image item for k in r.keys(): r[k]['image'] = '/img/appicon/{auid}'.format(auid=r[k]['auid']) # if not bool(r): status = httpStatusFailure result = logFail else: status = httpStatusSuccess result = logPass # args['result'] = result args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status enable_cors(response) # if not isinstance(r, bool): response.body = r # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def get_news_config_html(request): # args = get_request_log_args(request) args['timestamp'] = datetime.now() args['process'] = 'inbound' # try: # data = {} # body = build_page() # if not bool(body): status = httpStatusFailure args['result'] = logFail else: status = httpStatusSuccess args['result'] = logPass # args['http_response_code'] = status args['description'] = '-' cache.logQ.put(args) # response = HTTPResponse() response.status = status # if not isinstance(data, bool): response.body = body # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e cache.logQ.put(args) # raise HTTPError(status)
def post_2fa_code_validate(request): # args = get_request_log_args(request) args['timestamp'] = datetime.now() args['process'] = 'inbound' # try: # code = dict(request.json) code = code['2fa_code'] # r = cache.cache['_icloud'].validate_validation_code_default(code) # if not bool(r): status = httpStatusFailure args['result'] = logFail else: status = httpStatusSuccess args['result'] = logPass # args['http_response_code'] = status args['description'] = '-' # response = HTTPResponse() response.status = status enable_cors(response) # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e cache.logQ.put(args) # raise HTTPError(status)
def get_volume(request, _tvlgnetcast): # args = get_request_log_args(request) # try: # r = _tvlgnetcast.getVolume() # if not bool(r): status = httpStatusFailure result = logFail else: status = httpStatusSuccess result = logPass # args['result'] = result args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status enable_cors(response) # if not isinstance(r, bool): response.body = r # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def consume(self, event, *args, **kwargs): # There is an error that results in responding with an empty list that will cause an internal server error original_event_class, response_queue = self.responders.pop(event.event_id, None) if response_queue: accept = event.get('accept', original_event_class.content_type) if not isinstance(event, self.CONTENT_TYPE_MAP[accept]): self.logger.warning( "Incoming event did did not match the clients Accept format. Converting '{current}' to '{new}'".format( current=type(event), new=original_event_class.__name__)) event = event.convert(self.CONTENT_TYPE_MAP[accept]) local_response = HTTPResponse() status, status_message = event.status local_response.status = "{code} {message}".format(code=status, message=status_message) for header, value in event.headers.iteritems(): local_response.set_header(header, value) local_response.set_header("Content-Type", event.content_type) if int(status) == 204: response_data = "" else: response_data = self.format_response_data(event) local_response.body = response_data response_queue.put(local_response) response_queue.put(StopIteration) self.logger.info("[{status}] Service '{service}' Returned in {time:0.0f} ms".format( service=event.service, status=local_response.status, time=(datetime.now()-event.created).total_seconds() * 1000), event=event) else: self.logger.warning("Received event response for an unknown event ID. The request might have already received a response", event=event)
def get_location(request, _weather): # args = get_request_log_args(request) # try: # data = _weather.get_location() # if not bool(data): status = httpStatusFailure args['result'] = logFail else: status = httpStatusSuccess args['result'] = logPass # args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status # if not isinstance(data, bool): response.body = data # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def post_ui_modules(request): # args = get_request_log_args(request) # try: # new_modules = request.json new_modules = new_modules['modules'] # r = set_cfg_details_modules(new_modules) if r: status = httpStatusSuccess args['result'] = logPass else: status = httpStatusFailure args['result'] = logFail # args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status enable_cors(response) # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPResponse(status=status)
def post_device_specific(request, _nest, device_type, device_id): # args = get_request_log_args(request) # try: # command = request.json # if device_type == 'thermostat': if validate_thermostat(command): status = httpStatusSuccess if _nest.setThermostat(device_id, command) else httpStatusFailure else: status = httpStatusBadrequest else: status = httpStatusBadrequest # args['result'] = logPass if status == httpStatusSuccess else logFail # args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def get_devices_type(request, _nest, device_type): # args = get_request_log_args(request) # try: # r = _nest.getDevicesType(device_type) # if not bool(r): status = httpStatusFailure args['result'] = logFail else: status = httpStatusSuccess args['result'] = logPass # args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status # if not isinstance(r, bool): response.body = r # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def post_2fa_code_request(request): # args = get_request_log_args(request) args['timestamp'] = datetime.now() args['process'] = 'inbound' # try: r = cache.cache['_icloud'].request_validation_code_default() # if r['result']: status = httpStatusSuccess args['result'] = logPass else: status = httpStatusFailure args['result'] = logFail # args['http_response_code'] = status args['description'] = '-' cache.logQ.put(args) # response = HTTPResponse() response.status = status response.body = r enable_cors(response) # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e cache.logQ.put(args) # raise HTTPError(status)
def post_command_touchClick(request, _tvlgnetcast): # args = get_request_log_args(request) # try: # r = _tvlgnetcast.sendTouchclick() # if not bool(r): status = httpStatusFailure result = logFail else: status = httpStatusSuccess result = logPass # args['result'] = result args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status enable_cors(response) # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def get_recordings(request, _virginmedia_tivo): # args = get_request_log_args(request) # try: # r = _virginmedia_tivo.getRecordings() # if not bool(r): status = httpStatusFailure else: status = httpStatusSuccess # args['result'] = logPass args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status # if not isinstance(r, bool): response.body = r # return response # except Exception as e: status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def jsonify(obj, status=200): response = HTTPResponse(content_type='application/json') response.body = json.dumps(obj, encoding='latin1') response.status = status return response
def jsonify(body='', status=200): response = HTTPResponse(content_type='application/json') response.body = json.dumps(body) response.status = status return response