def GET(self): con = ESL.ESLconnection('127.0.0.1', '8021', 'ClueCon') if not con.connected(): # Unable to connect FreeSWITCH print("Unable to connect FreeSWITCH") web.header('Content-Type', 'application/json','unique=True') raise web.InternalError("{\"message\": \"active call list error\"}") #Sending command to FreeSWITCH print("Sending command to FreeSWITCH for call list") e = con.api("show calls as json") if e: # Found active calls. Prasing and makeing list of call uuid. Sending response 200 - ok with list of call uuids in JSON print("Active calls found") web.header('Content-Type', 'application/json','unique=True') calls_str = json.loads(e.getBody()) arr_call_uuids = [] if calls_str['row_count'] > 0: for call in calls_str['rows']: arr_call_uuids.append(call['call_uuid']) raise web.ok(json.dumps(arr_call_uuids)) else: web.header('Content-Type', 'application/json','unique=True') raise web.InternalError("{\"message\": \"active call list error\"}")
def GET(self): if LoginChecker.loggedIn(): data = {} try: data['consoleFeedback'] = commandSender.formatHDD( web.input().args) outJSON = json.dumps(data) except IOError as e: raise web.InternalError(e.message) except RuntimeError as e: raise web.InternalError(e.message) return outJSON
def POST(self): if not web.data(): # No data. Return 500 - hangup error print("No data found in the request") web.header('Content-Type', 'application/json','unique=True') raise web.InternalError("{\"message\": \"hangup error\"}") else: data = json.loads(web.data()) if not data: # No JSON. Return 500 - hangup error print("No JSON data found in the request") web.header('Content-Type', 'application/json','unique=True') raise web.InternalError("{\"message\": \"hangup error\"}") else: # Fetch uuid from JSON uuid = data["uuid"] if not uuid: # UUID not found in request JSON. Return 500 - hangup error print("UUID not found in JSON") web.header('Content-Type', 'application/json','unique=True') raise web.InternalError("{\"message\": \"hangup error\"}") con = ESL.ESLconnection('127.0.0.1', '8021', 'ClueCon') if not con.connected(): # Unable to connect FreeSWITCH print("Unable to connect FreeSWITCH") web.header('Content-Type', 'application/json','unique=True') raise web.InternalError("{\"message\": \"call error\"}") # Check if mentioned call exists e = con.api(str("uuid_exists "+uuid)) if (e.getBody() != 'true'): # Call does not exists. Return 404 - call not found print("Call not found for call uuid:"+uuid) web.header('Content-Type', 'application/json','unique=True') raise web.notfound("{\"message\": \"call not found\"}") else: # Call found. Sending command for hangup to FreeSWITCH print("Call found. Hanging up..") e = con.api(str("uuid_kill "+uuid)) if (e.getBody().find("OK") != -1): # Call hangup Successfully. Return 202 - ok print("Call hangup sucessfully. Call UUID:"+uuid) web.header('Content-Type', 'application/json','unique=True') raise web.accepted("{\"message\": \"ok\"}") else: # Call hangup failed print("Call hangup failed") web.header('Content-Type', 'application/json','unique=True') raise web.InternalError("{\"message\": \"hangup error\"}")
def GET(self): if LoginChecker.loggedIn(): data = {} try: data['consoleFeedback'] = commandSender.smartTest() outJSON = json.dumps(data) except IOError as e: raise web.InternalError(e.message) except OSError as e: raise web.InternalError(e.message) except AssertionError as e: raise web.Conflict(e.message) return outJSON
def GET(self): if LoginChecker.loggedIn(): # Check status of system try: datetime = commandSender.outputTime() cameraFeedback, cameraBoolean = commandSender.cameraStatus() gpsFeedback, gpsBoolean = commandSender.gpsStatus() internetFeedback, internetBoolean = commandSender.internetStatus( ) extHDDFeedback, hdd0Boolean, hdd0Space, hdd1Boolean, hdd2Boolean, hdd3Boolean, hdd1Space, hdd2Space, hdd3Space = commandSender.hddStatus( ) vpnFeedback, vpnBoolean = commandSender.vpnStatus() # Encode to JSON data = {} data[ 'consoleFeedback'] = constants.systemStatusHeader + datetime + cameraFeedback + extHDDFeedback + internetFeedback + vpnFeedback + gpsFeedback data['cameraStatus'] = cameraBoolean data['gpsStatus'] = gpsBoolean data['internetStatus'] = internetBoolean data['vpnStatus'] = vpnBoolean data['HDD0Status'] = hdd0Boolean data['HDD1Status'] = hdd1Boolean data['HDD2Status'] = hdd2Boolean data['HDD3Status'] = hdd3Boolean data['HDD0Space'] = hdd0Space data['HDD1Space'] = hdd1Space data['HDD2Space'] = hdd2Space data['HDD3Space'] = hdd3Space outJSON = json.dumps(data) except IOError as e: raise web.InternalError(e.message) return outJSON
def POST(self): '''handles post requests to the server''' try: # gets post data data = web.data() # tries to convert data to json (error handled below) json_data = json.loads(data) mode = None # makes sure mode is in the json data if 'mode' in json_data: mode = json_data['mode'] print(f'new mode selected with id: {mode}') # display_controller is added via a add_processor # pylint: disable=no-member if not web.ctx.web_server_only_mode: web.ctx.display_controller.set_mode(mode) # returns the mode that was sent (in full system this will send the new mode) web.header('Access-Control-Allow-Origin', '*') web.header('Content-Type', 'application/json') return '{"mode": "' + mode + '"}' else: print('post request doesn\'t contain new mode') return web.BadRequest() except ValueError: # catches error from json.loads print('data from post request is not valid json') return web.BadRequest() except: print('internal server error') return web.InternalError()
def POST(self): if not web.data(): # No data. Return 500 - call error print("No data found in the request") web.header('Content-Type', 'application/json','unique=True') raise web.InternalError("{\"message\": \"call error\"}") else: data = json.loads(web.data()) if not data: # No JSON. Return 500 - call error print("No JSON data found in the request") web.header('Content-Type', 'application/json','unique=True') raise web.InternalError("{\"message\": \"call error\"}") else: # Fetch destination from JSON destination = data["destination"] print("Destination: "+destination) if not destination: # Destination not found in request JSON. Return 500 - call error web.header('Content-Type', 'application/json','unique=True') raise web.InternalError("{\"message\": \"call error\"}") con = ESL.ESLconnection('127.0.0.1', '8021', 'ClueCon') if not con.connected(): # Unable to connect FreeSWITCH print("Unable to connect FreeSWITCH") web.header('Content-Type', 'application/json','unique=True') raise web.InternalError("{\"message\": \"call error\"}") temp = "{'origination_caller_id_number=3024561011'}user/"+destination+" &playback(http://s3.amazonaws.com/plivocloud/music.mp3)" cmd = str(temp) # Sending command to FreeSWITCH print("Initiating Call.. ") e = con.api("originate", cmd) if e: res = e.getBody() if (res.find("OK") != -1): # Call Successful. Return 201 -ok print("Call Successful") web.header('Content-Type', 'application/json','unique=True') raise web.created("{\"message\": \"ok\"}") else: # Call Failed. Return 500 - call error print("Call Failed") web.header('Content-Type', 'application/json','unique=True') raise web.InternalError("{\"message\": \"call error\"}")
def GET(self): if LoginChecker.loggedIn(): try: data = {'consoleFeedback': commandSender.moveData0()} outJSON = json.dumps(data) except IOError as e: raise web.InternalError(e.message) return outJSON
def GET(self): if LoginChecker.loggedIn(): try: commandSender.removeThumbnail(web.input()) except IOError as e: raise web.InternalError(e.message) return 0
def GET(self): if LoginChecker.loggedIn(): try: data = commandSender.probeHDD() outJSON = json.dumps(data) except IOError as e: raise web.InternalError(e.message) return outJSON
def GET(self): if LoginChecker.loggedIn(): data = {} try: data['consoleFeedback'] = commandSender.hddOff() statusFeedback, data['HDD0Status'], data['HDD0Space'], data[ 'HDD1Status'], data['HDD2Status'], data[ 'HDD3Status'], data['HDD1Space'], data[ 'HDD2Space'], data[ 'HDD3Space'] = commandSender.hddStatus() data['consoleFeedback'] += statusFeedback outJSON = json.dumps(data) except IOError as e: raise web.InternalError(e.message) except RuntimeError as e: raise web.InternalError(e.message) return outJSON
def GET(self): try: logger.debug('Request description: GET request for fetching valve data') SprinklerDB.send_heart_beat(self.product_id) valve_info = get_valve_info(self.valve_id) web.header('Content-Type', 'application/json') logger.info('Request completed. Sending data: %s', valve_info) return json.dumps(valve_info) except Exception as ex: logger.exception("Could not fetch data due to unknown error") raise web.InternalError(ex.message)
def GET(self): if LoginChecker.loggedIn(): data = {} try: data = commandSender.populateConfigBox() outJSON = json.dumps(data) except IOError as e: raise web.InternalError(e.message) return outJSON
def GET(self): if LoginChecker.loggedIn(): data = {} try: data['images'] = commandSender.cfCheck() outJSON = json.dumps(data) except IOError as e: raise web.InternalError(e.message) return outJSON
def GET(self): if LoginChecker.loggedIn(): data = {} try: data['consoleFeedback'] = commandSender.videoCameraOff() outJSON = json.dumps(data) except IOError as e: raise web.InternalError(e.message) return outJSON
def GET(self): if LoginChecker.loggedIn(): data = {} try: data['consoleFeedback'] = commandSender.updateConfigFile( web.input()) outJSON = json.dumps(data) except IOError as e: raise web.InternalError(e.message) return outJSON
def handle_exceptions(ex): message = str(ex) if 'WEBENV' in os.environ and os.environ['WEBENV'] == 'test': pass elif (('WEBENV' in os.environ and os.environ['WEBENV'] == 'development') or ('WEBENV' in web.ctx.env and web.ctx.env['WEBENV'] == 'development')): message = traceback.format_exc(10) print message # to get this in the server logs else: print traceback.format_exc(10) if isinstance(ex, PermissionDenied): web.message = 'Permission Denied' raise web.Forbidden() elif isinstance(ex, IllegalState): # Sometimes we try to explain why illegal state, like # the assessment still has items, can't delete it. # web.message = 'IllegalState {0}'.format(message) # raise web.NotAcceptable() raise web.InternalError('IllegalState {0}'.format(message)) else: raise web.InternalError(message)
def GET(self): if LoginChecker.loggedIn(): data = {} try: data['consoleFeedback'], data[ 'intervalTestResult'] = commandSender.intervalTest() outJSON = json.dumps(data) except IOError as e: raise web.InternalError(e.message) return outJSON
def POST(self): try: logger.debug('Request description: POST request for saving valve data') valve_info = json.loads(web.data()) logger.info('Data to save: %s', valve_info) update_valve_info(self.valve_id, valve_info) logger.info('Request completed successfully') except ValueError as ex: logger.exception("Could not save data as it is invalid") raise web.BadRequest(ex.message) except Exception as ex: logger.exception("Could not save data due to unknown error") raise web.InternalError(ex.message)
def GET(self): if LoginChecker.loggedIn(): data = {} try: data['consoleFeedback'] = commandSender.prevIntervalTest() outJSON = json.dumps(data) except AttributeError as e: raise web.InternalError( 'Latest photo directory (/data0/latest) corrupt or not present.' ) return outJSON
def InternalError(data=None): """<comment-ja> 500 InternalError メソッド 呼出は直接ではなく、web.internalerror を利用してください。 </comment-ja> <comment-en> TODO: English Comment </comment-en> """ if isinstance(data, list): data = "\n".join(data) return web.InternalError(data)
def GET(self): if LoginChecker.loggedIn(): data = {} try: data['consoleFeedback'] = commandSender.cameraOff() statusFeedback, statusBoolean = commandSender.cameraStatus() data['consoleFeedback'] += statusFeedback data['cameraStatus'] = statusBoolean outJSON = json.dumps(data) except IOError as e: raise web.InternalError(e.message) return outJSON
def GET(self, dirpath, filename): file_path = web_path + '/' + dirpath + '/' + filename web.header('Content-Type', 'text/html; charset=utf-8') web.header('Access-Control-Allow-Origin', '*') web.header('Access-Control-Allow-Methods', '*') if os.path.isfile(file_path): try: with open(file_path) as f: return f.read() except Exception as e: print e return web.InternalError() else: print 'the file not exist:', file_path return web.NotFound()
def GET(self): qs = web.input() with open(qs.file, 'r') as f: contents = f.read() expected = crypto.hmac(key, contents) # print 'expected: {}'.format(convert.bytes_to_hex(expected)) actual = convert.hex_to_bytes(qs.signature) is_mac_valid = self._insecure_compare(expected, actual) if not is_mac_valid: raise web.InternalError('Invalid MAC') return 'Valid MAC'
def get_html_text(): if session.has_key(u'client_language'): if session.client_language in html_languages: return dict(html_dictionary[session.client_language]) else: log_to_file(u"ConfigError: Missing language-section for " u"language: " + session.client_language + " in gsmbpasswd-html.conf") raise web.InternalError( message=u"ConfigError: No such available language. " u"Please contact your system administrator.") else: log_to_file( u"Error: The client removed its cookie during an active session") raise web.HTTPError( u"400 Bad request", {u'content-type': u'text/html'}, u"Error: This site requires cookies. Please reload the page " u"and try again.")
def PUT(self, transferId): ''' PUT /transfer/{ID} Updates one transfer. ''' if not transferId: msg = "Cannot PUT to the transfer resource without specifying a valid transfer resource ID in the path transfer/{ID}" web.debug(msg) raise web.BadRequest(msg) try: transferId = int(transferId) except ValueError as e: msg = "Invalid transfer id: " + str(e) web.debug(msg) raise web.BadRequest(msg) try: raw = web.data() if config.audit: web.debug("Request Body: " + str(raw)) parsed = json.loads(raw) transfer = web.storify(parsed) transfer = policy.update(transferId, transfer) return json.dumps(transfer) except TransferNotFound: msg = "Cannot PUT to transfer resource transfer/" + str( transferId) + ". Resource not found." web.debug(msg) raise web.BadRequest(msg) except MalformedTransfer as e: msg = "Bad request body in PUT to transfer/ resource: " + str(e) web.debug(msg) raise web.BadRequest(msg) except NotAllowed as e: msg = "Bad request body in PUT to transfer/ resource: " + str(e) web.debug(msg) raise web.BadRequest(msg) except PolicyError as e: msg = "Internal server error: " + str(e) web.debug(msg) raise web.InternalError(msg)
def GET(self, name): relative_path = web.ctx.fullpath.__str__() if web.store_cache.__contains__(relative_path): print "Avaiable in the cache " return web.store_cache.get(relative_path) else: print "Not in cache , hitting the remote" response = requests.get(web.config['remote'] + relative_path) raw_response = response.text try: response.raise_for_status() except Exception as e: print "Request failed with status code " + str( response.status_code) + " ,hence not caching the request" print e.message return web.InternalError() print "coming here" web.store_cache[relative_path] = raw_response web.store_cache.sync() return raw_response
def convertfrom(self, value, tag, mimetype): if mimetype == 'application/xml': element = self.db.elementFromXML(value) if element.tagName != tag: raise web.BadRequest( "Bad request, toplevel XML tag %s does not match final XPath element %s" % (element.tagName, tag)) return element elif mimetype == 'application/x-www-form-urlencoded': # xxxjack here comes a special case, and I don't like it. # if the url-encoded data contains exactly one element and its name is the same as the # tag name we don't encode. if type(value) == type({}) and len(value) == 1 and tag in value: value = value[tag] element = self.db.elementFromTagAndData(tag, value) return element elif mimetype == 'application/json': try: valueDict = json.loads(value) except ValueError: raise web.BadRequest( "No JSON object could be decoded from body") if not isinstance(valueDict, dict): raise web.BadRequest( "Bad request, JSON toplevel object must be object") # xxxjack here comes a special case, and I don't like it. # if the JSON dictionary contains exactly one element and its name is the same as the # tag name we don't encode. if len(valueDict) == 1 and tag in valueDict: element = self.db.elementFromTagAndData(tag, valueDict[tag]) else: element = self.db.elementFromTagAndData(tag, valueDict) return element elif mimetype == 'text/plain': element = self.db.elementFromTagAndData(tag, value) return element else: raise web.InternalError("Conversion from %s not implemented" % mimetype)
def GET(self): if not GLOBALS['session']['loggedin']: raise web.Forbidden() web.header('Content-type', 'text/plain') web.header('Transfer-Encoding', 'chunked') sessionid = GLOBALS['session']['loggedin']['sessionid'] offset = 0 c = 0 try: for courses in memrise.whatistudy(sessionid): yield json.dumps({ "content": GLOBALS['prender'].ajax_dashboard(courses, offset)['__body__'] }) + '$' offset += len(courses) # Take this opportunity to sync courses in session for course in courses: data = {} for k in [ 'num_things', 'learned', 'review', 'ignored', 'percent_complete' ]: data[k] = course[k] c += 1 except HTTPError as e: if e.response.status_code == 403: raise web.Forbidden() else: raise web.NotFound() except Exception as e: print(e) raise web.InternalError()
def generate_http_response(self, status_code, data=None, exc_cls=None, exc_msg=None): if status_code == HTTP_STATUS_CODE.OK: if data: raise web.OK(data=json.dumps(data), headers={}) else: raise web.OK() elif status_code == HTTP_STATUS_CODE.Created: raise web.Created() elif status_code == HTTP_STATUS_CODE.Accepted: raise web.Accepted() elif status_code == HTTP_STATUS_CODE.BadRequest: raise web.BadRequest( message=self.generate_message(exc_cls, exc_msg)) elif status_code == HTTP_STATUS_CODE.Unauthorized: raise web.Unauthorized( message=self.generate_message(exc_cls, exc_msg)) elif status_code == HTTP_STATUS_CODE.Forbidden: raise web.Forbidden( message=self.generate_message(exc_cls, exc_msg)) elif status_code == HTTP_STATUS_CODE.NotFound: raise web.NotFound(message=self.generate_message(exc_cls, exc_msg)) elif status_code == HTTP_STATUS_CODE.Conflict: raise web.Conflict(message=self.generate_message(exc_cls, exc_msg)) elif status_code == HTTP_STATUS_CODE.InternalError: raise web.InternalError( message=self.generate_message(exc_cls, exc_msg)) else: if data: raise web.HTTPError(status_code, data=json.dumps(data)) else: raise web.HTTPError(status_code)