def __init__(self, device, mod, timeout=5000): self.timeout = timeout if isinstance(device, Device): self.device = device else: self.device = connect_device(device) self.logger = createlogger(mod) self.log_path = create_folder() self.config = GetConfigs("common") self.product = Configs("common").get("product", "Info") self.appconfig = AppConfig("appinfo", self.product) self.appconfig.set_section(mod) self.adb = self.device.server.adb self.suc_times = 0 try: self.mod_cfg = GetConfigs(mod) self.test_times = 0 self.dicttesttimes = self.mod_cfg.get_test_times() if mod == "Email": for i in self.dicttesttimes: self.test_times += int(self.dicttesttimes[i]) if i <> 'opentimes': self.test_times += int(self.dicttesttimes[i]) elif mod == "Message": for i in self.dicttesttimes: self.test_times += int(self.dicttesttimes[i]) if i == 'opentimes': self.test_times += int(self.dicttesttimes[i]) * 3 else: for test_time in self.dicttesttimes: self.test_times += int(self.dicttesttimes[test_time]) self.logger.info("Trace Total Times " + str(self.test_times)) except: pass
def post(self): parse = reqparse.RequestParser() parse.add_argument('file', type=werkzeug.datastructures.FileStorage, location='files', help='File is required', required=True) args = parse.parse_args() f = args['file'] filename = str(uuid.uuid4()) + '_' + f.filename filepath = os.path.join(AppConfig.get_file_storage_path(), filename) f.save(filepath) with open(filepath, 'rb') as f: filetype = magic.from_buffer(f.read(), mime=True) f.close() if filetype in ALLOWED_FILE_TYPES: return { 'status': { 'code': 200, 'message': 'api successful' }, 'rsp': { 'filename': filename } } else: f.close() os.remove(filepath) return { 'status': { 'code': 400, 'message': 'unsupported file type' } }, 400
def __init__(self, device,mod,timeout = 5000): self.timeout = timeout if isinstance(device, Device): self.device = device else: self.device = connect_device(device) self.logger = createlogger(mod) self.log_path = create_folder() self.config = GetConfigs("common") self.product = Configs("common").get("product","Info") self.appconfig = AppConfig("appinfo",self.product) self.appconfig.set_section(mod) self.adb = self.device.server.adb self.suc_times = 0 try: self.mod_cfg = GetConfigs(mod) self.test_times = 0 self.dicttesttimes = self.mod_cfg.get_test_times() if mod == "Email": for i in self.dicttesttimes: self.test_times += int(self.dicttesttimes[i]) if i <> 'opentimes': self.test_times += int(self.dicttesttimes[i]) elif mod == "Message": for i in self.dicttesttimes: self.test_times += int(self.dicttesttimes[i]) if i == 'opentimes': self.test_times += int(self.dicttesttimes[i])*3 else: for test_time in self.dicttesttimes: self.test_times += int(self.dicttesttimes[test_time]) self.logger.info("Trace Total Times " + str(self.test_times)) except: pass
def check_if_token_is_valid(decrypted_token): jti = decrypted_token['jti'] logging.debug('verifying token [%s] in redis-store' % (jti)) try: revoked_store = redis.StrictRedis(host=AppConfig.get_redis_hostname(), port=AppConfig.get_redis_port(), db=0, decode_responses=True) entry = revoked_store.get(jti) logging.debug('token found %r' % (entry)) if entry is None: return True if entry: return False return True except Exception as e: logging.error('connection redis failed with :%s' % (e))
def get(self): parse = reqparse.RequestParser() parse.add_argument('filename', type=str, location='args', help='Filename is required', required=True) args = parse.parse_args() filename = args['filename'] filepath = os.path.join(AppConfig.get_file_storage_path(), filename) if (os.path.exists(filepath)): result = send_file(filepath, as_attachment=True) result.headers["x-suggested-filename"] = filename return result else: return {'status': {'code': 400, 'message': 'file not found'}}, 400
def is_user_registered(user): db = g.db_client[AppConfig.get_database_name()] users = db.users try: result = users.find_one({ "username": user.username, "role": user.role }) if result is not None: return True else: return False except ConnectionFailure as e: logging.error("db insert failed: " + str(e)) return False return True
def register(user): if UserServiceProviderRepositories.is_user_registered(user): logging.debug( 'username [%s] with role [%s] already registered, cannot complete registration process' % (user.username, user.role)) return False, None user.app_key = str(uuid.uuid4()) user.app_secret = str(uuid.uuid4()) db = g.db_client[AppConfig.get_database_name()] users = db.users try: result = users.insert_one(user.to_dict()) except ConnectionFailure as e: logging.error("db insert failed: " + str(e)) return False, None return True, user
def register(user): if UserAdminRepositories.is_user_registered(user): logging.debug( 'username [%s] with role [%s] already registered, cannot complete registration process' % (user.username, user.role)) return False salt = bcrypt.gensalt() hashed = bcrypt.hashpw(user.password.encode('utf-8'), salt) user.salt = salt user.password = hashed db = g.db_client[AppConfig.get_database_name()] users = db.users try: result = users.insert_one(user.to_dict(with_password=True)) except ConnectionFailure as e: logging.error("db insert failed: " + str(e)) return False return True
def match(user): db = g.db_client[AppConfig.get_database_name()] users = db.users try: result = users.find_one({ "username": user.username, "role": user.role }) if result is not None and bcrypt.checkpw( user.password.encode('utf-8'), result['password']): logging.debug('username [%s] with role [%s] is verified' % (user.username, user.role)) else: logging.debug( 'username [%s] with role [%s] could not be verified' % (user.username, user.role)) return False except ConnectionFailure as e: logging.error("db insert failed: " + str(e)) return False return True
def match(user): db = g.db_client[AppConfig.get_database_name()] users = db.users try: result = users.find_one({ "app_key": user.app_key, "app_secret": user.app_secret }) if result is not None and result['app_key'] == user.app_key: logging.debug( 'username [%s] with app_key [%s] logged-in successfully' % (result['username'], result['app_key'])) return True, result else: logging.debug( 'app_key [%s] with app_secret [%s] could not be verified' % (user.app_key, user.app_secret)) return False, None except ConnectionFailure as e: logging.error("db insert failed: " + str(e)) return False, None return False, None
def __init__(self, device, mod): self.product = Configs("common").get("product", "Info") self.device = connect_device(device) self.appconfig = AppConfig("appinfo") self.logger = createlogger(mod) self.camera = Camera(self.device, "media_camera") self.record = Recorder(self.device, "media_recorder") #self.browser = Browser(self.device,"media_browser") self.chrome = Chrome(self.device, "media_chrome") if self.product == "Sprints": self.music = PlayMusic(self.device, "media_music") else: self.music = Music(self.device, "media_music") self.suc_times = 0 self.mod_cfg = GetConfigs(mod) self.test_times = 0 self.dicttesttimes = self.mod_cfg.get_test_times() for i in self.dicttesttimes: self.test_times += int(self.dicttesttimes[i]) if i.upper() in ('VIDEOTIMES', 'RECORDER', 'PHOTOTIMES'): self.test_times += int(self.dicttesttimes[i]) * 2 self.logger.info('Trace Total Times ' + str(self.test_times))
from flask_restful import fields, marshal_with, reqparse, Resource from flask_jwt_extended import (jwt_required, create_access_token, create_refresh_token, jwt_required, jwt_refresh_token_required, get_jwt_identity, get_raw_jwt) import werkzeug from flask import send_file import os import logging import uuid import magic from configs import AppConfig ALLOWED_FILE_TYPES = AppConfig.get_supported_upload_file_types() parser = reqparse.RequestParser(bundle_errors=True) class FileUploadResource(Resource): @jwt_required def post(self): parse = reqparse.RequestParser() parse.add_argument('file', type=werkzeug.datastructures.FileStorage, location='files', help='File is required', required=True) args = parse.parse_args() f = args['file'] filename = str(uuid.uuid4()) + '_' + f.filename filepath = os.path.join(AppConfig.get_file_storage_path(), filename) f.save(filepath)
class Common(object): """Provide common functions for all scripts.""" def __init__(self, device, mod, timeout=5000): self.timeout = timeout if isinstance(device, Device): self.device = device else: self.device = connect_device(device) self.logger = createlogger(mod) self.log_path = create_folder() self.config = GetConfigs("common") self.product = Configs("common").get("product", "Info") self.appconfig = AppConfig("appinfo", self.product) self.appconfig.set_section(mod) self.adb = self.device.server.adb self.suc_times = 0 try: self.mod_cfg = GetConfigs(mod) self.test_times = 0 self.dicttesttimes = self.mod_cfg.get_test_times() if mod == "Email": for i in self.dicttesttimes: self.test_times += int(self.dicttesttimes[i]) if i <> 'opentimes': self.test_times += int(self.dicttesttimes[i]) elif mod == "Message": for i in self.dicttesttimes: self.test_times += int(self.dicttesttimes[i]) if i == 'opentimes': self.test_times += int(self.dicttesttimes[i]) * 3 else: for test_time in self.dicttesttimes: self.test_times += int(self.dicttesttimes[test_time]) self.logger.info("Trace Total Times " + str(self.test_times)) except: pass def device(self): return self.device def save_fail_img(self, newimg=None): """save fail image to log path. argv: The picture want to save as failed image. """ path = (self.log_path + "\\" + datetime.now().strftime('%Y-%m-%d-%H-%M-%S') + ".png") if newimg is None: self.logger.debug("Take snapshot.") newimg = self.device.screenshot(path) if newimg is None: self.logger.warning("newimg is None.") return False self.logger.error("Fail: %s" % (path)) return True def get_file_num(self, path, format): """get number of file with specified format. """ content = self.adb.shell("ls " + path) num = content.count(format) self.logger.debug("%s file num is %d." % (format, num)) return num def start_activity(self, packet, activity): data = self.device.server.adb.shell("am start -n %s/%s" % (packet, activity)) if data.find("Error") > -1: self.logger.error("Fail: %s/%s" % (packet, activity)) return False return True def start_app(self, name, b_desk=True): '''Call/People/ALL APPS/Messaging/Browser''' self.logger.debug("start app:%s" % (name)) self.device.press.home() if b_desk and self.device(text=name).wait.exists(timeout=2000): self.device(text=name).click() return True elif b_desk and self.device(description=name).exists: self.device(text=name).click() return True elif self.device(description="ALL APPS").exists: self.device(description="ALL APPS").click() self.device().fling.horiz.toBeginning() for loop in range(5): if self.device(description=name).exists: self.device(description=name).click() return True elif self.device(text=name).exists: self.device(text=name).click() return True self.device().fling.horiz.forward() elif self.device(description="Apps").exists: self.device(description="Apps").click() self.device().fling.horiz.toBeginning() for loop in range(5): if self.device(description=name).exists: self.device(description=name).click() return True self.device().fling.horiz.forward() return False def back_to_all_apps(self): """back_to_home. """ for loop in range(4): self.device.press.back() if self.device(text="ALL APPS").wait.exists(timeout=2000): return True elif self.device(text="exit").exists: self.device(text="exit").click() elif self.device(text="Quit").exists: self.device(text="Quit").click() self.device.press.back() def start_all_app(self, num=3): '''Call/People/ALL APPS/Messaging/Browser''' self.logger.debug("start all app") if self.device(description="ALL APPS").exists: self.device(description="ALL APPS").click() elif self.device(description="Apps").exists: self.device(description="Apps").click() self.device().fling.horiz.toBeginning() self.device().fling.horiz.toBeginning() for i in range(num): for j in range( self.device(className="android.widget.TextView").count - 2): if self.device( resourceId= "com.tct.launcher:id/apps_customize_pane_content" ).child(index=0).child(index=i).exists: self.device( resourceId= "com.tct.launcher:id/apps_customize_pane_content" ).child(index=0).child(index=i).child(index=j).click() self.device(text="ALL APPS").wait.gone(timeout=20000) self.back_to_all_apps() self.device().fling.horiz.forward() # for loop in range(5): # if self.device(description=name).exists: # self.device(description=name).click() # return True # self.device().fling.horiz.forward() return False def select_menu_item(self, stritem): self.device.press.menu() self.device.delay(1) self.device(text=stritem).click() self.device.delay(2) def _is_connected(self, type): temp_type = type if type == "ALL": temp_type = "LTE" for i in range(5): if self.adb.get_data_service_state() == temp_type: break self.device.delay(5) else: self.logger.warning("Cannot get %s service." % (type)) self.device.press.back() return False for i in range(5): if self.adb.get_data_connected_status(): return True self.device.delay(5) else: self.logger.warning("Cannot connect %s data." % (type)) self.device.press.back() return False def switch_network(self, type=None): """switch network to specified type. argv: (str)type -- the type of network. """ self.logger.debug("Switch network to %s." % (type)) self.start_activity(self.appconfig("RadioInfo", "package"), self.appconfig("RadioInfo", "activity")) self.device.delay(2) network_type = self.appconfig("RadioInfo", type) print network_type self.device(scrollable=True).scroll.to( text=self.appconfig("RadioInfo", "set")) if self.device(resourceId=self.appconfig.id( "RadioInfo", "id_network")).wait.exists(timeout=2000): self.device(resourceId=self.appconfig.id("RadioInfo", "id_network")).click() self.device(scrollable=True).scroll.to(text=network_type) self.device.delay(1) self.device(text=network_type).click() self._is_connected(type) self.back_to_home() def back_to_home(self): """back_to_home. """ for loop in range(4): self.device.press.back() self.device.delay(1) if self.device(text="Quit").exists: self.device(text="Quit").click() self.device.press.home() def is_playing_video(self): """check if video is playing or not. """ data = self.device.server.adb.shell("dumpsys media.player") if not data: return None if "AudioTrack" in data: self.logger.debug("The video is playing now") return True else: self.logger.debug("The video is not playing.") return False
import time import urllib2 from util import Console from configs import AppConfig config_path = "/config/hvac_switch.cfg" Console.WriteLine("") Console.WriteLine("#######################################################") Console.WriteLine("#######################################################") app_config = None with open(config_path, 'r') as content_file: j = json.loads(content_file.read()) app_config = AppConfig(j) Console.WriteLine("[{0}] Taking control of gpios", datetime.today().strftime("%Y-%m-%d %H:%M:%S")) GPIO.setmode(GPIO.BCM) GPIO.setup(app_config.pin_on, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(app_config.pin_off, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) while True: input_green = GPIO.input(app_config.pin_on) if input_green == True: Console.WriteLine("[{0}] Button ON Pressed", datetime.today().strftime("%Y-%m-%d %H:%M:%S")) urllib2.urlopen(app_config.base_url + "/hvac/on/" + app_config.api_key + "/").read()
def before_request_func(): g.db_client = MongoClient(AppConfig.get_database_uri()) g.face_recognition = face_recognition
from datetime import timedelta from flask import Flask, jsonify, session, g from flask.blueprints import Blueprint from flask_cors import CORS from flask_jwt_extended import (JWTManager, create_access_token, create_refresh_token, get_jti, jwt_refresh_token_required, get_jwt_identity, jwt_required, get_raw_jwt) from configs import AppConfig import routes import logging from pymongo import MongoClient server = Flask(__name__) server.config['JWT_SECRET_KEY'] = AppConfig.get_jwt_secret_key() server.config['PROPAGATE_EXCEPTIONS'] = True server.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta( minutes=AppConfig.get_jwt_access_token_expiry_in_mins()) server.config['JWT_REFRESH_TOKEN_EXPIRES'] = timedelta( days=AppConfig.get_jwt_refresh_token_expiry_in_days()) server.config['JWT_BLACKLIST_ENABLED'] = True server.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access', 'refresh'] jwt = JWTManager(server) @server.before_request def before_request_func(): g.db_client = MongoClient(AppConfig.get_database_uri()) g.face_recognition = face_recognition
def post(self): args = login_parser.parse_args() user = UserServiceProvider(args, ignore_username=True) user.role = user.get_role() status, service_provider = UserServiceProviderRepositories.match(user) if status: logging.debug( 'username [%s] app_key [%s] with role [%s] is now logged-in successfully' % (service_provider['username'], user.app_key, user.role)) access_token = create_access_token({ 'role': user.role, 'username': service_provider['username'], 'app_key': user.app_key }) refresh_token = create_access_token({ 'role': user.role, 'username': service_provider['username'], 'app_key': user.app_key }) access_jti = get_jti(encoded_token=access_token) refresh_jti = get_jti(encoded_token=refresh_token) try: revoked_store = redis.StrictRedis( host=AppConfig.get_redis_hostname(), port=AppConfig.get_redis_port(), db=0, decode_responses=True) revoked_store.set( access_jti, 'true', timedelta(minutes=AppConfig. get_jwt_access_token_expiry_in_mins()) * 1.2) revoked_store.set( refresh_jti, 'true', timedelta( days=AppConfig.get_jwt_refresh_token_expiry_in_days()) * 1.2) except Exception as e: logging.error( 'connection redis failed with :%s, cannot login user' % (e)) logging.error('username [%s] with role [%s] is not logged-in' % (service_provider['username'], user.role)) return API.response( STATUS_CODES.ERROR_LOGIN_FAILED_SYSTEM_ERROR, {}) res = { 'access_token': access_token, 'refresh_token': refresh_token } return API.response(STATUS_CODES.SUCCESS_USER_LOGGED_IN, res) else: logging.error('app_key [%s] with role [%s] is not logged-in' % (user.app_key, user.role)) return API.response(STATUS_CODES.ERROR_USER_LOGIN, {})
from flask import Flask, jsonify from flask.blueprints import Blueprint from flask_cors import CORS from flask_jwt_extended import ( JWTManager, create_access_token, create_refresh_token, get_jti, jwt_refresh_token_required, get_jwt_identity, jwt_required, get_raw_jwt ) import routes import logging import os from configs import AppConfig server = Flask(__name__) server.config['JWT_SECRET_KEY'] = AppConfig.get_jwt_secret_key() server.config['PROPAGATE_EXCEPTIONS'] = True server.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(minutes=AppConfig.get_jwt_access_token_expiry_in_mins()) server.config['JWT_REFRESH_TOKEN_EXPIRES'] = timedelta(days=AppConfig.get_jwt_refresh_token_expiry_in_days()) server.config['JWT_BLACKLIST_ENABLED'] = True server.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access', 'refresh'] jwt = JWTManager(server) @jwt.user_claims_loader def add_claims_to_access_token(identity): return { 'username': identity['username'], 'role': identity['role'] }
class Common(object): """Provide common functions for all scripts.""" def __init__(self, device,mod,timeout = 5000): self.timeout = timeout if isinstance(device, Device): self.device = device else: self.device = connect_device(device) self.logger = createlogger(mod) self.log_path = create_folder() self.config = GetConfigs("common") self.product = Configs("common").get("product","Info") self.appconfig = AppConfig("appinfo",self.product) self.appconfig.set_section(mod) self.adb = self.device.server.adb self.suc_times = 0 try: self.mod_cfg = GetConfigs(mod) self.test_times = 0 self.dicttesttimes = self.mod_cfg.get_test_times() if mod == "Email": for i in self.dicttesttimes: self.test_times += int(self.dicttesttimes[i]) if i <> 'opentimes': self.test_times += int(self.dicttesttimes[i]) elif mod == "Message": for i in self.dicttesttimes: self.test_times += int(self.dicttesttimes[i]) if i == 'opentimes': self.test_times += int(self.dicttesttimes[i])*3 else: for test_time in self.dicttesttimes: self.test_times += int(self.dicttesttimes[test_time]) self.logger.info("Trace Total Times " + str(self.test_times)) except: pass def device(self): return self.device def save_fail_img(self, newimg = None): """save fail image to log path. argv: The picture want to save as failed image. """ path = (self.log_path + "\\" +datetime.now().strftime('%Y-%m-%d-%H-%M-%S') + ".png") if newimg is None: self.logger.debug("Take snapshot.") newimg = self.device.screenshot(path) if newimg is None: self.logger.warning("newimg is None.") return False self.logger.error("Fail: %s" %(path)) return True def get_file_num(self, path, format): """get number of file with specified format. """ content = self.adb.shell("ls " + path) num = content.count(format) self.logger.debug("%s file num is %d." % (format,num)) return num def start_activity(self,packet,activity): data = self.device.server.adb.shell("am start -n %s/%s"%(packet,activity)) if data.find("Error")>-1: self.logger.error("Fail: %s/%s" %(packet,activity)) return False return True def start_app(self,name,b_desk=True): '''Call/People/ALL APPS/Messaging/Browser''' self.logger.debug("start app:%s" %(name)) self.device.press.home() if b_desk and self.device(text=name).wait.exists(timeout = 2000): self.device(text=name).click() return True elif b_desk and self.device(description=name).exists: self.device(text=name).click() return True elif self.device(description="ALL APPS").exists: self.device(description="ALL APPS").click() self.device().fling.horiz.toBeginning() for loop in range(5): if self.device(description=name).exists: self.device(description=name).click() return True elif self.device(text=name).exists: self.device(text=name).click() return True self.device().fling.horiz.forward() elif self.device(description="Apps").exists: self.device(description="Apps").click() self.device().fling.horiz.toBeginning() for loop in range(5): if self.device(description=name).exists: self.device(description=name).click() return True self.device().fling.horiz.forward() return False def back_to_all_apps(self): """back_to_home. """ for loop in range(4): self.device.press.back() if self.device(text = "ALL APPS").wait.exists(timeout = 2000): return True elif self.device(text = "exit").exists: self.device(text = "exit").click() elif self.device(text = "Quit").exists: self.device(text = "Quit").click() self.device.press.back() def start_all_app(self,num=3): '''Call/People/ALL APPS/Messaging/Browser''' self.logger.debug("start all app") if self.device(description="ALL APPS").exists: self.device(description="ALL APPS").click() elif self.device(description="Apps").exists: self.device(description="Apps").click() self.device().fling.horiz.toBeginning() self.device().fling.horiz.toBeginning() for i in range(num): for j in range(self.device(className="android.widget.TextView").count-2): if self.device(resourceId="com.tct.launcher:id/apps_customize_pane_content").child(index = 0).child(index = i).exists: self.device(resourceId="com.tct.launcher:id/apps_customize_pane_content").child(index = 0).child(index = i).child(index = j).click() self.device(text = "ALL APPS").wait.gone(timeout = 20000) self.back_to_all_apps() self.device().fling.horiz.forward() # for loop in range(5): # if self.device(description=name).exists: # self.device(description=name).click() # return True # self.device().fling.horiz.forward() return False def select_menu_item(self, stritem): self.device.press.menu() self.device.delay(1) self.device(text=stritem).click() self.device.delay(2) def _is_connected(self,type): temp_type = type if type == "ALL": temp_type = "LTE" for i in range(5): if self.adb.get_data_service_state() == temp_type: break self.device.delay(5) else: self.logger.warning("Cannot get %s service." % (type)) self.device.press.back() return False for i in range(5): if self.adb.get_data_connected_status(): return True self.device.delay(5) else: self.logger.warning("Cannot connect %s data." % (type)) self.device.press.back() return False def switch_network(self,type = None): """switch network to specified type. argv: (str)type -- the type of network. """ self.logger.debug("Switch network to %s." % (type)) self.start_activity(self.appconfig("RadioInfo","package"),self.appconfig("RadioInfo","activity")) self.device.delay(2) network_type = self.appconfig("RadioInfo",type) print network_type self.device(scrollable=True).scroll.to(text=self.appconfig("RadioInfo","set")) if self.device(resourceId=self.appconfig.id("RadioInfo","id_network")).wait.exists(timeout = 2000): self.device(resourceId=self.appconfig.id("RadioInfo","id_network")).click() self.device(scrollable=True).scroll.to(text=network_type) self.device.delay(1) self.device(text=network_type).click() self._is_connected(type) self.back_to_home() def back_to_home(self): """back_to_home. """ for loop in range(4): self.device.press.back() self.device.delay(1) if self.device(text = "Quit").exists: self.device(text = "Quit").click() self.device.press.home() def is_playing_video(self): """check if video is playing or not. """ data = self.device.server.adb.shell("dumpsys media.player") if not data: return None if "AudioTrack" in data: self.logger.debug("The video is playing now") return True else: self.logger.debug("The video is not playing.") return False