def logout(self): Config.save_token("") exit_handler() self.sh_screen.hide() self.rh_screen.hide() self.login_screen.show() pass
def login(self, email, password): self.app.log.info("Login to system") try: resp = requests.post(self.url("/auth/login"), data={ 'email': email, 'password': password }, headers={"Accept": "application/json"}) if resp.status_code == 200 or resp.status_code == 201: result = resp.json() self.bearer = result['data']['plainTextToken'] Config.save_token(self.bearer) user = self.get("/user") if user: # self.app.log.debug("User info: %s" % user) self.user = user return True elif resp.status_code == 422: self.app.log.error("Login incorrect", None, True) else: self.app.log.error( "Error: %s\n%s" % (resp.status_code, resp.reason), None, True, lambda: self.app.timer.start(5000)) return False except: self.app.log.info("Connection error") return False
def silence_upload(endpoint, data, callback=None, return_value=None): if Api.bearer is None: return False m = MultipartEncoder(fields=data) if callback is not None: m = MultipartEncoderMonitor(m, callback) try: bearer = Config.load_token() resp = requests.post(Api.apiUrl + endpoint, data=m, headers={ "Content-Type": m.content_type, "Accept": "application/json", "Authorization": "Bearer " + bearer }) if return_value: return_value.value = resp return resp except: print("Failed", endpoint, data) return False pass
def curl_upload(endpoint, file, progress=None, read_function=None): url = Api.apiUrl + endpoint # upload = list() '''data['other_files'] = "" for key in data: if key == "run_file" or re.search("other_files", key): content_type = mime.from_file(data[key]) upload.append((key, (pycurl.FORM_FILE, data[key], pycurl.FORM_FILENAME, os.path.basename(data[key]), pycurl.FORM_CONTENTTYPE, content_type ))) else: if key == "run_file": upload.append((key, os.path.basename(data[key]))) else: upload.append((key, data[key])) ''' # content_type = mime.from_file(file.filename) # upload.append(('file', (pycurl.FORM_FILE, file.filename, pycurl.FORM_FILENAME, os.path.basename(file.filename), pycurl.FORM_CONTENTTYPE, content_type ))) # print(upload) # initialize py curl c = pycurl.Curl() if read_function: c.setopt( pycurl.READFUNCTION, FileReader(open(file.filename, "rb"), read_function).read_callback) c.setopt(pycurl.INFILESIZE, os.path.getsize(file.filename)) c.setopt(pycurl.VERBOSE, 0) c.setopt(pycurl.UPLOAD, 1) c.setopt(pycurl.URL, url) c.setopt(pycurl.NOPROGRESS, 0) bearer = Config.load_token() c.setopt( pycurl.HTTPHEADER, ["Accept: application/json", "Authorization: Bearer " + bearer]) if progress: c.setopt(pycurl.XFERINFOFUNCTION, progress) c.setopt(pycurl.PROGRESSFUNCTION, progress) c.perform() # this kicks off the pycurl module with all options set. c.close() return c
def static_get(endpoint, params=None): if Api.bearer is None: return False try: bearer = Config.load_token() resp = requests.get(Api.apiUrl + endpoint, params=params, headers={ "Accept": "application/json", "Authorization": "Bearer " + bearer }) return resp.json() except: return False
def __init__(self, app): self.app = app self.bearer = Config.load_token() pass
class Api: apiUrl = "https://calomni.com/api" bearer = Config.load_token() user = {} def __init__(self, app): self.app = app self.bearer = Config.load_token() pass def url(self, endpoint): return self.apiUrl + endpoint def login_bearer(self): self.app.log.info("Login to system") user = self.get("/user") if user: self.app.log.debug("User info: %s" % user) self.user = user return self.user return False '''Login to the api''' def login(self, email, password): self.app.log.info("Login to system") try: resp = requests.post(self.url("/auth/login"), data={ 'email': email, 'password': password }, headers={"Accept": "application/json"}) if resp.status_code == 200 or resp.status_code == 201: result = resp.json() self.bearer = result['data']['plainTextToken'] Config.save_token(self.bearer) user = self.get("/user") if user: # self.app.log.debug("User info: %s" % user) self.user = user return True elif resp.status_code == 422: self.app.log.error("Login incorrect", None, True) else: self.app.log.error( "Error: %s\n%s" % (resp.status_code, resp.reason), None, True, lambda: self.app.timer.start(5000)) return False except: self.app.log.info("Connection error") return False '''Logout''' def logout(self): try: self.post(self.url("/auth/logout")) self.bearer = None return True except: self.app.log.info("Connection error") return False def back_to_login(self): self.app.sh_screen.hide() self.app.rh_screen.hide() self.app.login_screen.show() '''Inspector''' def response(self, resp): # Success if resp.status_code == 200 or resp.status_code == 201: result = resp.json() # print(result) if 'status' in result: if result['status']: if "message" in result and result["message"]: self.app.log.info(result['message'], None, True) return result['data'] else: self.show_error(result['message']) else: self.app.log.debug(result) self.show_error("Invalid data received") # Bad request elif resp.status_code == 400: result = resp.json() self.show_error(result["message"]) # Unauthenticated elif resp.status_code == 401: self.show_error("Session expired! Please login again", self.back_to_login) # Everything else else: self.app.log.debug(resp.json()) self.show_error("Error: %s\n%s" % (resp.status_code, resp.reason)) return False def show_error(self, msg, callback=None): self.app.log.error(msg, None, True, callback) '''get request''' def get(self, endpoint, params=None): if self.bearer is None: self.show_error("Session expired! Please login again", self.back_to_login) return False try: resp = requests.get(self.url(endpoint), params=params, headers={ "Accept": "application/json", "Authorization": "Bearer " + self.bearer }) return self.response(resp) except: self.show_error("Connection error") return False '''put request''' def put(self, endpoint, data=None, files=None): if self.bearer is None: return False try: resp = requests.put(self.url(endpoint), data=data, headers={ "Accept": "application/json", "Authorization": "Bearer " + self.bearer }) return self.response(resp) except: self.show_error("Connection error") return False '''post request''' def post(self, endpoint, data=None, files=None): if self.bearer is None: return False try: resp = requests.post(self.url(endpoint), data=data, files=files, headers={ "Accept": "application/json", "Authorization": "Bearer " + self.bearer }) return self.response(resp) except: self.show_error("Connection error") return False '''upload''' def upload(self, endpoint, data, callback=None): if self.bearer is None: return False m = MultipartEncoder(fields=data) if callback is not None: m = MultipartEncoderMonitor(m, callback) try: resp = requests.post(self.url(endpoint), data=m, headers={ "Content-Type": m.content_type, "Accept": "application/json", "Authorization": "Bearer " + self.bearer }) return self.response(resp) except: self.show_error("Connection error") return False @staticmethod def silence_upload(endpoint, data, callback=None, return_value=None): if Api.bearer is None: return False m = MultipartEncoder(fields=data) if callback is not None: m = MultipartEncoderMonitor(m, callback) try: bearer = Config.load_token() resp = requests.post(Api.apiUrl + endpoint, data=m, headers={ "Content-Type": m.content_type, "Accept": "application/json", "Authorization": "Bearer " + bearer }) if return_value: return_value.value = resp return resp except: print("Failed", endpoint, data) return False pass @staticmethod def static_get(endpoint, params=None): if Api.bearer is None: return False try: bearer = Config.load_token() resp = requests.get(Api.apiUrl + endpoint, params=params, headers={ "Accept": "application/json", "Authorization": "Bearer " + bearer }) return resp.json() except: return False '''delete request''' def delete(self, endpoint): if self.bearer is None: return False try: resp = requests.delete(self.url(endpoint), headers={ "Accept": "application/json", "Authorization": "Bearer " + self.bearer }) return self.response(resp) except: self.show_error("Connection error") return False @staticmethod def curl_upload(endpoint, file, progress=None, read_function=None): url = Api.apiUrl + endpoint # upload = list() '''data['other_files'] = "" for key in data: if key == "run_file" or re.search("other_files", key): content_type = mime.from_file(data[key]) upload.append((key, (pycurl.FORM_FILE, data[key], pycurl.FORM_FILENAME, os.path.basename(data[key]), pycurl.FORM_CONTENTTYPE, content_type ))) else: if key == "run_file": upload.append((key, os.path.basename(data[key]))) else: upload.append((key, data[key])) ''' # content_type = mime.from_file(file.filename) # upload.append(('file', (pycurl.FORM_FILE, file.filename, pycurl.FORM_FILENAME, os.path.basename(file.filename), pycurl.FORM_CONTENTTYPE, content_type ))) # print(upload) # initialize py curl c = pycurl.Curl() if read_function: c.setopt( pycurl.READFUNCTION, FileReader(open(file.filename, "rb"), read_function).read_callback) c.setopt(pycurl.INFILESIZE, os.path.getsize(file.filename)) c.setopt(pycurl.VERBOSE, 0) c.setopt(pycurl.UPLOAD, 1) c.setopt(pycurl.URL, url) c.setopt(pycurl.NOPROGRESS, 0) bearer = Config.load_token() c.setopt( pycurl.HTTPHEADER, ["Accept: application/json", "Authorization: Bearer " + bearer]) if progress: c.setopt(pycurl.XFERINFOFUNCTION, progress) c.setopt(pycurl.PROGRESSFUNCTION, progress) c.perform() # this kicks off the pycurl module with all options set. c.close() return c
class FanConfig: config = None logconsole = False logger = None loggername = None dbg = False gpio = None disablefan = False interval = None fanstartlevel = None temp_thresholds = None variable_speeds = None constant_speed = None fan_cooldown_interval = None fan_cooldown_time = None def __init__(self, configfile, appname): self.config = Config(configfile) self.logfile = self.config.get_value_bool(False, "general", "logfile") self.logconsole = self.config.get_value_bool(False, "general", "logconsole") self.loggername = self.config.get_value_string(appname, True, "general", "loggername") self.disablefan = self.config.get_value_bool(False, "hardware", "disablefan") gpio = self.config.get_value_int(-1, "hardware", "pwmgpio") if gpio != -1: if gpio < 2 or gpio > 27: gpio = -1 if gpio == -1 and self.disablefan is False: raise Exception("PWM-GPIO-Port is invalid") self.gpio = gpio logpath = Path(get_current_workingdir()) if self.logfile: logpath = logpath.joinpath("log", self.loggername + ".log") self.logger = EasyLogger( self.logconsole, str(logpath) if self.logfile is True else None, self.loggername) profile = self.config.select_profile() if profile is None: raise Exception("No profile selected or found") temp_thresholds = None profile_temp_thresholds = self.config.get_profile_value( "temp_thresholds") if is_sequence( profile_temp_thresholds) and len(profile_temp_thresholds) > 0: temp_thresholds = profile_temp_thresholds if temp_thresholds is None: self.temp_thresholds = parse_sequence_str("[54,59,74,80]", lambda x: int(x)) else: self.temp_thresholds = temp_thresholds self.interval = self.config.get_profile_value_int(5, "interval") self.fanstartlevel = self.config.get_profile_value_int( 2, "fanstartlevel") fcd = self.config.get_profile_value("fancooldown") if not string_is_empty(fcd): pos_sec = fcd.find("sec") pos_min = fcd.find("min") pos_hrs = fcd.find("hrs") if pos_sec > -1: self.fan_cooldown_time = int(fcd[0:pos_sec]) elif pos_min > -1: self.fan_cooldown_time = int(fcd[0:pos_min]) * 60 elif pos_hrs > -1: self.fan_cooldown_time = int(fcd[0:pos_hrs]) * 3600 else: self.fan_cooldown_interval = int(fcd) elif is_integer(fcd): self.fan_cooldown_interval = fcd else: self.fan_cooldown_time = 10 self.constant_speed = self.config.get_profile_value("constant_speed") self.variable_speeds = self.config.get_profile_value("variable_speeds") dbg = self.config.get_profile_value("debug") self.dbg = dbg if is_boolean(dbg) else False def dbgwrite(self, msg, *args, **kwargs): if self.dbg is True and self.logger is not None: self.logger.info(msg, *args, **kwargs)