From c3098e03e4c696156dde98a98b8e360868a4173e Mon Sep 17 00:00:00 2001 From: Brian Martin Date: Thu, 30 May 2019 06:55:15 -0400 Subject: [PATCH] Format with black Formatting code with black - pipenv update --- Pipfile.lock | 6 +- bumper/__init__.py | 608 ++++++++++++++++++++------------------- bumper/confserver.py | 420 +++++++++++++-------------- bumper/mqttserver.py | 101 ++++--- bumper/xmppserver.py | 181 +++++++----- start_bumper.py | 45 ++- tests/test_bumper.py | 7 +- tests/test_confserver.py | 36 ++- 8 files changed, 741 insertions(+), 663 deletions(-) diff --git a/Pipfile.lock b/Pipfile.lock index a824b67..1f64b3a 100644 --- a/Pipfile.lock +++ b/Pipfile.lock @@ -333,11 +333,11 @@ }, "pbr": { "hashes": [ - "sha256:6901995b9b686cb90cceba67a0f6d4d14ae003cd59bc12beb61549bdfbe3bc89", - "sha256:d950c64aeea5456bbd147468382a5bb77fe692c13c9f00f0219814ce5b642755" + "sha256:0ce920b865091450bbcd452b35cf6d6eb8a6d9ce13ad2210d6e77557f85cf32b", + "sha256:93d2dc6ee0c9af4dbc70bc1251d0e545a9910ca8863774761f92716dece400b6" ], "index": "pypi", - "version": "==5.2.0" + "version": "==5.2.1" }, "pylint": { "hashes": [ diff --git a/bumper/__init__.py b/bumper/__init__.py index e2ffaaa..f742275 100644 --- a/bumper/__init__.py +++ b/bumper/__init__.py @@ -25,9 +25,11 @@ token_validity_seconds = 3600 # 1 hour db = None # Logs -os.makedirs("logs", exist_ok=True) #Ensure logs directory exists or create +os.makedirs("logs", exist_ok=True) # Ensure logs directory exists or create # Set format for all logs -logformat = logging.Formatter("[%(asctime)s] :: %(levelname)s :: %(name)s :: %(module)s :: %(funcName)s :: %(lineno)d :: %(message)s") +logformat = logging.Formatter( + "[%(asctime)s] :: %(levelname)s :: %(name)s :: %(module)s :: %(funcName)s :: %(lineno)d :: %(message)s" +) bumperlog = logging.getLogger("bumper") bumper_rotate = RotatingFileHandler("logs/bumper.log", maxBytes=5000000, backupCount=5) @@ -37,28 +39,36 @@ bumperlog.addHandler(bumper_rotate) # bumperlog.setLevel(logging.INFO) confserverlog = logging.getLogger("confserver") -conf_rotate = RotatingFileHandler("logs/confserver.log", maxBytes=5000000, backupCount=5) +conf_rotate = RotatingFileHandler( + "logs/confserver.log", maxBytes=5000000, backupCount=5 +) conf_rotate.setFormatter(logformat) confserverlog.addHandler(conf_rotate) # Override the logging level # confserverlog.setLevel(logging.INFO) mqttserverlog = logging.getLogger("mqttserver") -mqtt_rotate = RotatingFileHandler("logs/mqttserver.log", maxBytes=5000000, backupCount=5) +mqtt_rotate = RotatingFileHandler( + "logs/mqttserver.log", maxBytes=5000000, backupCount=5 +) mqtt_rotate.setFormatter(logformat) mqttserverlog.addHandler(mqtt_rotate) # Override the logging level # mqttserverlog.setLevel(logging.INFO) helperbotlog = logging.getLogger("helperbot") -helperbot_rotate = RotatingFileHandler("logs/helperbot.log", maxBytes=5000000, backupCount=5) +helperbot_rotate = RotatingFileHandler( + "logs/helperbot.log", maxBytes=5000000, backupCount=5 +) helperbot_rotate.setFormatter(logformat) helperbotlog.addHandler(helperbot_rotate) # Override the logging level # helperbotlog.setLevel(logging.INFO) xmppserverlog = logging.getLogger("xmppserver") -xmpp_rotate = RotatingFileHandler("logs/xmppserver.log", maxBytes=5000000, backupCount=5) +xmpp_rotate = RotatingFileHandler( + "logs/xmppserver.log", maxBytes=5000000, backupCount=5 +) xmpp_rotate.setFormatter(logformat) xmppserverlog.addHandler(xmpp_rotate) # Override the logging level @@ -80,13 +90,18 @@ def db_file(): def os_db_path(): - if platform.system() == "Windows": - os.makedirs(os.getenv("APPDATA"), exist_ok=True) #Ensure db_path directory exists or create - return os.path.join(os.getenv("APPDATA"), "bumper.db") + if platform.system() == "Windows": + os.makedirs( + os.getenv("APPDATA"), exist_ok=True + ) # Ensure db_path directory exists or create + return os.path.join(os.getenv("APPDATA"), "bumper.db") else: - os.makedirs(os.path.expanduser("~/.config"), exist_ok=True) #Ensure db_path directory exists or create + os.makedirs( + os.path.expanduser("~/.config"), exist_ok=True + ) # Ensure db_path directory exists or create return os.path.expanduser("~/.config/bumper.db") + def db_get(): try: # Will create the database if it doesn't exist @@ -99,8 +114,7 @@ def db_get(): db.table("tokens", cache_size=0) return db - - + except json.decoder.JSONDecodeError as jerr: bumperlog.error("JsonErr: {} - Doc: {}".format(jerr.msg, jerr.doc)) @@ -284,297 +298,293 @@ class VacBotDevice(object): } def toJSON(self): - return json.dumps(self, default=lambda o: o.__dict__, - sort_keys=False)#, indent=4) + return json.dumps( + self, default=lambda o: o.__dict__, sort_keys=False + ) # , indent=4) -class GlobalVacBotDevice(VacBotDevice): #EcoVacs Home + +class GlobalVacBotDevice(VacBotDevice): # EcoVacs Home UILogicId = "" ota = True - updateInfo = { - "changeLog": "", - "needUpdate": False - } + updateInfo = {"changeLog": "", "needUpdate": False} icon = "" deviceName = "" - -#EcoVacs Home Product IOT Map - 2019-05-20 -#https://portal-ww.ecouser.net/api/pim/product/getProductIotMap + +# EcoVacs Home Product IOT Map - 2019-05-20 +# https://portal-ww.ecouser.net/api/pim/product/getProductIotMap EcoVacsHomeProducts = [ - { - "classid": "dl8fht", - "product": { - "UILogicId": "D_600", - "_id": "5acb0fa87c295c0001876ecf", - "icon": "5acc32067c295c0001876eea", - "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5acc32067c295c0001876eea", - "materialNo": "702-0000-0170", - "name": "DEEBOT 600 Series", - "ota": False, - "supportType": { - "alexa": True, - "assistant": True, - "share": True, - "tmjl": False - } - } + { + "classid": "dl8fht", + "product": { + "UILogicId": "D_600", + "_id": "5acb0fa87c295c0001876ecf", + "icon": "5acc32067c295c0001876eea", + "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5acc32067c295c0001876eea", + "materialNo": "702-0000-0170", + "name": "DEEBOT 600 Series", + "ota": False, + "supportType": { + "alexa": True, + "assistant": True, + "share": True, + "tmjl": False, + }, }, - { - "classid": "02uwxm", - "product": { - "UILogicId": "D_OZMO_SLIM10", - "_id": "5ae1481e7ccd1a0001e1f69e", - "icon": "5b1dddc48bc45700014035a1", - "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5b1dddc48bc45700014035a1", - "materialNo": "110-1715-0201", - "name": "DEEBOT OZMO Slim10 Series", - "ota": False, - "supportType": { - "alexa": True, - "assistant": True, - "share": True, - "tmjl": False - } - } + }, + { + "classid": "02uwxm", + "product": { + "UILogicId": "D_OZMO_SLIM10", + "_id": "5ae1481e7ccd1a0001e1f69e", + "icon": "5b1dddc48bc45700014035a1", + "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5b1dddc48bc45700014035a1", + "materialNo": "110-1715-0201", + "name": "DEEBOT OZMO Slim10 Series", + "ota": False, + "supportType": { + "alexa": True, + "assistant": True, + "share": True, + "tmjl": False, + }, }, - { - "classid": "y79a7u", - "product": { - "UILogicId": "D_OZMO_900", - "_id": "5b04c0227ccd1a0001e1f6a8", - "icon": "5b04c0217ccd1a0001e1f6a7", - "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5b04c0217ccd1a0001e1f6a7", - "materialNo": "110-1810-0101", - "name": "DEEBOT OZMO 900 Series", - "ota": True, - "supportType": { - "alexa": True, - "assistant": True, - "share": True, - "tmjl": False - } - } + }, + { + "classid": "y79a7u", + "product": { + "UILogicId": "D_OZMO_900", + "_id": "5b04c0227ccd1a0001e1f6a8", + "icon": "5b04c0217ccd1a0001e1f6a7", + "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5b04c0217ccd1a0001e1f6a7", + "materialNo": "110-1810-0101", + "name": "DEEBOT OZMO 900 Series", + "ota": True, + "supportType": { + "alexa": True, + "assistant": True, + "share": True, + "tmjl": False, + }, }, - { - "classid": "jr3pqa", - "product": { - "UILogicId": "D_700", - "_id": "5b43077b8bc457000140363e", - "icon": "5b5ac4cc8d5a56000111e769", - "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5b5ac4cc8d5a56000111e769", - "materialNo": "702-0000-0202", - "name": "DEEBOT 711", - "ota": True, - "supportType": { - "alexa": True, - "assistant": True, - "share": True, - "tmjl": False - } - } + }, + { + "classid": "jr3pqa", + "product": { + "UILogicId": "D_700", + "_id": "5b43077b8bc457000140363e", + "icon": "5b5ac4cc8d5a56000111e769", + "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5b5ac4cc8d5a56000111e769", + "materialNo": "702-0000-0202", + "name": "DEEBOT 711", + "ota": True, + "supportType": { + "alexa": True, + "assistant": True, + "share": True, + "tmjl": False, + }, }, - { - "classid": "uv242z", - "product": { - "UILogicId": "D_700", - "_id": "5b5149b4ac0b87000148c128", - "icon": "5b5ac4e45f21100001882bb9", - "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5b5ac4e45f21100001882bb9", - "materialNo": "702-0000-0205", - "name": "DEEBOT 710", - "ota": True, - "supportType": { - "alexa": True, - "assistant": True, - "share": True, - "tmjl": False - } - } + }, + { + "classid": "uv242z", + "product": { + "UILogicId": "D_700", + "_id": "5b5149b4ac0b87000148c128", + "icon": "5b5ac4e45f21100001882bb9", + "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5b5ac4e45f21100001882bb9", + "materialNo": "702-0000-0205", + "name": "DEEBOT 710", + "ota": True, + "supportType": { + "alexa": True, + "assistant": True, + "share": True, + "tmjl": False, + }, }, - { - "classid": "ls1ok3", - "product": { - "UILogicId": "D_900", - "_id": "5b6561060506b100015c8868", - "icon": "5ba4a2cb6c2f120001c32839", - "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5ba4a2cb6c2f120001c32839", - "materialNo": "110-1711-0201", - "name": "DEEBOT 900 Series", - "ota": True, - "supportType": { - "alexa": True, - "assistant": True, - "share": True, - "tmjl": False - } - } + }, + { + "classid": "ls1ok3", + "product": { + "UILogicId": "D_900", + "_id": "5b6561060506b100015c8868", + "icon": "5ba4a2cb6c2f120001c32839", + "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5ba4a2cb6c2f120001c32839", + "materialNo": "110-1711-0201", + "name": "DEEBOT 900 Series", + "ota": True, + "supportType": { + "alexa": True, + "assistant": True, + "share": True, + "tmjl": False, + }, }, - { - "classid": "eyi9jv", - "product": { - "UILogicId": "D_700", - "_id": "5b7b65f364e1680001a08b54", - "icon": "5b7b65f176f7f10001e9a0c2", - "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5b7b65f176f7f10001e9a0c2", - "materialNo": "715", - "name": "DEEBOT 715", - "ota": True, - "supportType": { - "alexa": True, - "assistant": True, - "share": True, - "tmjl": False - } - } + }, + { + "classid": "eyi9jv", + "product": { + "UILogicId": "D_700", + "_id": "5b7b65f364e1680001a08b54", + "icon": "5b7b65f176f7f10001e9a0c2", + "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5b7b65f176f7f10001e9a0c2", + "materialNo": "715", + "name": "DEEBOT 715", + "ota": True, + "supportType": { + "alexa": True, + "assistant": True, + "share": True, + "tmjl": False, + }, }, - { - "classid": "4zfacv", - "product": { - "UILogicId": "DN_2G", - "_id": "5bf2596f23244a00013f2f13", - "icon": "5c778731280fda0001770ba0", - "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5c778731280fda0001770ba0", - "materialNo": "910", - "name": "DEEBOT 910", - "ota": True, - "supportType": { - "alexa": True, - "assistant": True, - "share": True, - "tmjl": False - } - } + }, + { + "classid": "4zfacv", + "product": { + "UILogicId": "DN_2G", + "_id": "5bf2596f23244a00013f2f13", + "icon": "5c778731280fda0001770ba0", + "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5c778731280fda0001770ba0", + "materialNo": "910", + "name": "DEEBOT 910", + "ota": True, + "supportType": { + "alexa": True, + "assistant": True, + "share": True, + "tmjl": False, + }, }, - { - "classid": "vi829v", - "product": { - "UILogicId": "DX_5G", - "_id": "5c19a8f3a1e6ee0001782247", - "icon": "5c9c7995e9e9270001354ab4", - "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5c9c7995e9e9270001354ab4", - "materialNo": "920", - "name": "DEEBOT OZMO 920 Series", - "ota": True, - "supportType": { - "alexa": True, - "assistant": True, - "share": True, - "tmjl": False - } - } + }, + { + "classid": "vi829v", + "product": { + "UILogicId": "DX_5G", + "_id": "5c19a8f3a1e6ee0001782247", + "icon": "5c9c7995e9e9270001354ab4", + "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5c9c7995e9e9270001354ab4", + "materialNo": "920", + "name": "DEEBOT OZMO 920 Series", + "ota": True, + "supportType": { + "alexa": True, + "assistant": True, + "share": True, + "tmjl": False, + }, }, - { - "classid": "gd4uut", - "product": { - "UILogicId": "DR_935G", - "_id": "5bc8189d68142800016a6937", - "icon": "5c7384767b93c700013f12e7", - "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5c7384767b93c700013f12e7", - "materialNo": "960", - "name": "DEEBOT OZMO 960", - "ota": True, - "supportType": { - "alexa": True, - "assistant": True, - "share": False, - "tmjl": False - } - } + }, + { + "classid": "gd4uut", + "product": { + "UILogicId": "DR_935G", + "_id": "5bc8189d68142800016a6937", + "icon": "5c7384767b93c700013f12e7", + "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5c7384767b93c700013f12e7", + "materialNo": "960", + "name": "DEEBOT OZMO 960", + "ota": True, + "supportType": { + "alexa": True, + "assistant": True, + "share": False, + "tmjl": False, + }, }, - { - "classid": "9akc61", - "product": { - "UILogicId": "D_500", - "_id": "5c763f8263023c0001e7f855", - "icon": "5c932067280fda0001770d7f", - "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5c932067280fda0001770d7f", - "materialNo": "D505", - "name": "DEEBOT 505", - "ota": False, - "supportType": { - "alexa": True, - "assistant": True, - "share": True, - "tmjl": False - } - } + }, + { + "classid": "9akc61", + "product": { + "UILogicId": "D_500", + "_id": "5c763f8263023c0001e7f855", + "icon": "5c932067280fda0001770d7f", + "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5c932067280fda0001770d7f", + "materialNo": "D505", + "name": "DEEBOT 505", + "ota": False, + "supportType": { + "alexa": True, + "assistant": True, + "share": True, + "tmjl": False, + }, }, - { - "classid": "r8ead0", - "product": { - "UILogicId": "D_500", - "_id": "5c763f63280fda0001770b88", - "icon": "5c93204b63023c0001e7faa7", - "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5c93204b63023c0001e7faa7", - "materialNo": "D502", - "name": "DEEBOT 502", - "ota": False, - "supportType": { - "alexa": True, - "assistant": True, - "share": True, - "tmjl": False - } - } + }, + { + "classid": "r8ead0", + "product": { + "UILogicId": "D_500", + "_id": "5c763f63280fda0001770b88", + "icon": "5c93204b63023c0001e7faa7", + "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5c93204b63023c0001e7faa7", + "materialNo": "D502", + "name": "DEEBOT 502", + "ota": False, + "supportType": { + "alexa": True, + "assistant": True, + "share": True, + "tmjl": False, + }, }, - { - "classid": "emzppx", - "product": { - "UILogicId": "D_500", - "_id": "5c763f35280fda0001770b84", - "icon": "5c931fef280fda0001770d7e", - "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5c931fef280fda0001770d7e", - "materialNo": "D501", - "name": "DEEBOT 501", - "ota": False, - "supportType": { - "alexa": True, - "assistant": True, - "share": True, - "tmjl": False - } - } + }, + { + "classid": "emzppx", + "product": { + "UILogicId": "D_500", + "_id": "5c763f35280fda0001770b84", + "icon": "5c931fef280fda0001770d7e", + "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5c931fef280fda0001770d7e", + "materialNo": "D501", + "name": "DEEBOT 501", + "ota": False, + "supportType": { + "alexa": True, + "assistant": True, + "share": True, + "tmjl": False, + }, }, - { - "classid": "vsc5ia", - "product": { - "UILogicId": "D_500", - "_id": "5c763eba280fda0001770b81", - "icon": "5c874326280fda0001770d2a", - "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5c874326280fda0001770d2a", - "materialNo": "D500", - "name": "DEEBOT 500", - "ota": False, - "supportType": { - "alexa": True, - "assistant": True, - "share": True, - "tmjl": False - } - } + }, + { + "classid": "vsc5ia", + "product": { + "UILogicId": "D_500", + "_id": "5c763eba280fda0001770b81", + "icon": "5c874326280fda0001770d2a", + "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5c874326280fda0001770d2a", + "materialNo": "D500", + "name": "DEEBOT 500", + "ota": False, + "supportType": { + "alexa": True, + "assistant": True, + "share": True, + "tmjl": False, + }, }, - { - "classid": "aqdd5p", - "product": { - "UILogicId": "D_900", - "_id": "5cb7cfba179839000114d762", - "icon": "5cb7cfbab72c4d00010e5fc7", - "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5cb7cfbab72c4d00010e5fc7", - "materialNo": "110-1711-0001", - "name": "DEEBOT DE55", - "ota": True, - "supportType": { - "alexa": False, - "assistant": False, - "share": False, - "tmjl": False - } - } - } - ] - - - + }, + { + "classid": "aqdd5p", + "product": { + "UILogicId": "D_900", + "_id": "5cb7cfba179839000114d762", + "icon": "5cb7cfbab72c4d00010e5fc7", + "iconUrl": "https://portal-ww.ecouser.net/api/pim/file/get/5cb7cfbab72c4d00010e5fc7", + "materialNo": "110-1711-0001", + "name": "DEEBOT DE55", + "ota": True, + "supportType": { + "alexa": False, + "assistant": False, + "share": False, + "tmjl": False, + }, + }, + }, +] class VacBotClient(object): @@ -616,19 +626,20 @@ def check_authcode(uid, authcode): return False + def loginByItToken(authcode): bumperlog.debug("Checking for authcode: {}".format(authcode)) tokens = db_get().table("tokens") tmpauth = tokens.get( (Query().authcode == authcode) - #& ( # Match authcode + # & ( # Match authcode # (Query().userid == uid.replace("fuid_", "")) # | (Query().userid == "fuid_{}".format(uid)) - #) # Userid with or without fuid_ + # ) # Userid with or without fuid_ ) if tmpauth: - return {"token":tmpauth["token"], "userid":tmpauth["userid"]} - + return {"token": tmpauth["token"], "userid": tmpauth["userid"]} + return {} @@ -665,10 +676,12 @@ def bot_add(sn, did, devclass, resource, company): newbot.company = company bot = bot_get(did) - if not bot: # Not existing bot in database - if not devclass == "" or "@" not in sn or "tmp" not in sn: # try to prevent bad additions to the bot list + if not bot: # Not existing bot in database + if ( + not devclass == "" or "@" not in sn or "tmp" not in sn + ): # try to prevent bad additions to the bot list bumperlog.info( - "Adding new bot with SN: {} DID: {}".format(newbot.name, newbot.did) + "Adding new bot with SN: {} DID: {}".format(newbot.name, newbot.did) ) bot_full_upsert(newbot.asdict()) @@ -685,14 +698,15 @@ def bot_get(did): return bots.get(Bot.did == did) -def bot_toEcoVacsHome_JSON(bot): #EcoVacs Home - for botprod in EcoVacsHomeProducts: - if botprod["classid"] == bot["class"]: - bot["UILogicId"] = botprod["product"]["UILogicId"] - bot["ota"] = botprod["product"]["ota"] - bot["icon"] = botprod["product"]["iconUrl"] - return json.dumps(bot, default=lambda o: o.__dict__, - sort_keys=False)#, indent=4) +def bot_toEcoVacsHome_JSON(bot): # EcoVacs Home + for botprod in EcoVacsHomeProducts: + if botprod["classid"] == bot["class"]: + bot["UILogicId"] = botprod["product"]["UILogicId"] + bot["ota"] = botprod["product"]["ota"] + bot["icon"] = botprod["product"]["iconUrl"] + return json.dumps( + bot, default=lambda o: o.__dict__, sort_keys=False + ) # , indent=4) def bot_full_upsert(vacbot): diff --git a/bumper/confserver.py b/bumper/confserver.py index d18cf6f..91895aa 100644 --- a/bumper/confserver.py +++ b/bumper/confserver.py @@ -31,7 +31,10 @@ class aiohttp_filter(logging.Filter): confserverlog = logging.getLogger("confserver") -logging.getLogger("aiohttp.access").addFilter(aiohttp_filter()) #Add logging filter above to aiohttp.access +logging.getLogger("aiohttp.access").addFilter( + aiohttp_filter() +) # Add logging filter above to aiohttp.access + class EcoVacs_Login: accessToken = "" @@ -41,13 +44,16 @@ class EcoVacs_Login: username = "" def toJSON(self): - return json.dumps(self, default=lambda o: o.__dict__, - sort_keys=False)#, indent=4) - + return json.dumps( + self, default=lambda o: o.__dict__, sort_keys=False + ) # , indent=4) + + class EcoVacsHome_Login(EcoVacs_Login): loginName = "" mobile = "" - ucUid = "" + ucUid = "" + class ConfServer: def __init__(self, address, usessl=False, helperbot=None): @@ -72,10 +78,10 @@ class ConfServer: "/{apiversion}/private/{country}/{language}/{devid}/{apptype}/{appversion}/{devtype}/{aid}/user/checkLogin", self.handle_login, ), - web.get( #EcoVacs Home GetUserAccountInfo + web.get( # EcoVacs Home GetUserAccountInfo "/{apiversion}/private/{country}/{language}/{devid}/{apptype}/{appversion}/{devtype}/{aid}/user/getUserAccountInfo", self.handle_getUserAccountInfo, - ), + ), web.get( "/{apiversion}/private/{country}/{language}/{devid}/{apptype}/{appversion}/{devtype}/{aid}/user/logout", self.handle_logout, @@ -84,15 +90,14 @@ class ConfServer: "/{apiversion}/private/{country}/{language}/{devid}/{apptype}/{appversion}/{devtype}/{aid}/user/getAuthCode", self.handle_getAuthCode, ), - web.get( #EcoVacs Home GetAuthCode - "/{apiversion}/{apptype}/auth/getAuthCode", - self.handle_getAuthCode + web.get( # EcoVacs Home GetAuthCode + "/{apiversion}/{apptype}/auth/getAuthCode", self.handle_getAuthCode ), web.get( "/{apiversion}/private/{country}/{language}/{devid}/{apptype}/{appversion}/{devtype}/{aid}/user/checkAgreement", self.handle_checkAgreement, ), - web.get( #EcoVacs Home CheckAgreement + web.get( # EcoVacs Home CheckAgreement "/{apiversion}/private/{country}/{language}/{devid}/{apptype}/{appversion}/{devtype}/{aid}/user/checkAgreementBatch", self.handle_checkAgreement, ), @@ -100,56 +105,57 @@ class ConfServer: "/{apiversion}/private/{country}/{language}/{devid}/{apptype}/{appversion}/{devtype}/{aid}/common/checkVersion", self.handle_checkVersion, ), - web.get( #EcoVacs Home CheckAPPVersion + web.get( # EcoVacs Home CheckAPPVersion "/{apiversion}/private/{country}/{language}/{devid}/{apptype}/{appversion}/{devtype}/{aid}/common/checkAPPVersion", self.handle_checkAPPVersion, ), - web.get( #EcoVacs Home Upload Device Info + web.get( # EcoVacs Home Upload Device Info "/{apiversion}/private/{country}/{language}/{devid}/{apptype}/{appversion}/{devtype}/{aid}/common/uploadDeviceInfo", self.handle_uploadDeviceInfo, - ), - web.get( #EcoVacs Home GetAdByPositionType + ), + web.get( # EcoVacs Home GetAdByPositionType "/{apiversion}/private/{country}/{language}/{devid}/{apptype}/{appversion}/{devtype}/{aid}/ad/getAdByPositionType", self.handle_getAdByPositionType, - ), - web.get( #EcoVacs Home Get Boot Screen + ), + web.get( # EcoVacs Home Get Boot Screen "/{apiversion}/private/{country}/{language}/{devid}/{apptype}/{appversion}/{devtype}/{aid}/ad/getBootScreen", self.handle_getBootScreen, - ), - web.get( #EcoVacs Home message hasUnreadMsg + ), + web.get( # EcoVacs Home message hasUnreadMsg "/{apiversion}/private/{country}/{language}/{devid}/{apptype}/{appversion}/{devtype}/{aid}/message/hasUnreadMsg", self.handle_hasUnreadMessage, - ), - web.get( #EcoVacs Home neng message hasUnreadMsg - "/api/neng/message/hasUnreadMsg", - self.handle_neng_hasUnreadMessage, - ), - web.get( #EcoVacs Home message getMsgList + ), + web.get( # EcoVacs Home neng message hasUnreadMsg + "/api/neng/message/hasUnreadMsg", self.handle_neng_hasUnreadMessage + ), + web.get( # EcoVacs Home message getMsgList "/{apiversion}/private/{country}/{language}/{devid}/{apptype}/{appversion}/{devtype}/{aid}/message/getMsgList", self.handle_getMsgList, - ), - web.get( #EcoVacs Home common getSystemReminder + ), + web.get( # EcoVacs Home common getSystemReminder "/{apiversion}/private/{country}/{language}/{devid}/{apptype}/{appversion}/{devtype}/{aid}/common/getSystemReminder", self.handle_getSystemReminder, - ), - web.get( #EcoVacs Home shop getCnWapShopConfig + ), + web.get( # EcoVacs Home shop getCnWapShopConfig "/{apiversion}/private/{country}/{language}/{devid}/{apptype}/{appversion}/{devtype}/{aid}/shop/getCnWapShopConfig", self.handle_getCnWapShopConfig, - ), + ), web.get( "/{apiversion}/private/{country}/{language}/{devid}/{apptype}/{appversion}/{devtype}/{aid}/campaign/homePageAlert", self.handle_homePageAlert, ), web.post("/api/users/user.do", self.handle_usersapi), web.get("/api/users/user.do", self.handle_usersapi), - web.post("/api/appsvr/app.do", self.handle_appsvr_api), #EcoVacs Home - web.get("/api/appsvr/app.do", self.handle_appsvr_api), #EcoVacs Home + web.post("/api/appsvr/app.do", self.handle_appsvr_api), # EcoVacs Home + web.get("/api/appsvr/app.do", self.handle_appsvr_api), # EcoVacs Home web.post( "/api/pim/product/getProductIotMap", self.handle_getProductIotMap ), - web.post("/api/lg/log.do", self.handle_lg_log), #EcoVacs Home + web.post("/api/lg/log.do", self.handle_lg_log), # EcoVacs Home web.post("/api/iot/devmanager.do", self.handle_devmanager_botcommand), - web.post("/api/dim/devmanager.do", self.handle_dim_devmanager), #EcoVacs Home + web.post( + "/api/dim/devmanager.do", self.handle_dim_devmanager + ), # EcoVacs Home web.post("/lookup.do", self.handle_lookup), ] ) @@ -158,7 +164,9 @@ class ConfServer: async def start_server(self): try: - confserverlog.info("Starting ConfServer at {}:{}".format(self.address[0], self.address[1])) + confserverlog.info( + "Starting ConfServer at {}:{}".format(self.address[0], self.address[1]) + ) runner = web.AppRunner(self.app) await runner.setup() @@ -213,15 +221,17 @@ class ConfServer: not user_devid == "" ): # Performing basic "auth" using devid, super insecure user = bumper.user_by_deviceid(user_devid) - if "checkLogin" in request.path: + if "checkLogin" in request.path: self.check_token( apptype, countrycode, user, request.query["accessToken"] ) - else: - if "global_" in apptype: #EcoVacs Home + else: + if "global_" in apptype: # EcoVacs Home login_details = EcoVacsHome_Login() login_details.ucUid = "fuid_{}".format(user["userid"]) - login_details.loginName = "fusername_{}".format(user["userid"]) + login_details.loginName = "fusername_{}".format( + user["userid"] + ) login_details.mobile = None else: @@ -239,19 +249,19 @@ class ConfServer: body = { "code": bumper.RETURN_API_SUCCESS, "data": json.loads(login_details.toJSON()), - #{ + # { # "accessToken": self.generate_token(tmpuser), # Generate a token # "country": countrycode, # "email": "null@null.com", # "uid": "fuid_{}".format(tmpuser["userid"]), # "username": "fusername_{}".format(tmpuser["userid"]), - #}, + # }, "msg": "操作成功", "time": bumper.get_milli_time( datetime.utcnow().timestamp() ), } - + return web.json_response(body) body = { @@ -277,8 +287,8 @@ class ConfServer: countrycode = request.match_info.get("country", "us") apptype = request.match_info.get("apptype", "") user = bumper.user_by_deviceid(user_devid) - - if "global_" in apptype: #EcoVacs Home + + if "global_" in apptype: # EcoVacs Home login_details = EcoVacsHome_Login() login_details.ucUid = "fuid_{}".format(user["userid"]) login_details.loginName = "fusername_{}".format(user["userid"]) @@ -289,21 +299,20 @@ class ConfServer: login_details.uid = "fuid_{}".format(user["userid"]) login_details.username = "fusername_{}".format(user["userid"]) login_details.country = countrycode - login_details.email = "null@null.com" - + login_details.email = "null@null.com" + body = { "code": bumper.RETURN_API_SUCCESS, - "data": - { - "email": login_details.email, - "hasMobile": "N", - "hasPassword": "Y", - "uid": login_details.uid, - "userName": login_details.username, - "obfuscatedMobile": None, - "mobile": None, - "loginName": login_details.loginName - }, + "data": { + "email": login_details.email, + "hasMobile": "N", + "hasPassword": "Y", + "uid": login_details.uid, + "userName": login_details.username, + "obfuscatedMobile": None, + "mobile": None, + "loginName": login_details.loginName, + }, "msg": "操作成功", "time": bumper.get_milli_time(datetime.utcnow().timestamp()), } @@ -311,13 +320,12 @@ class ConfServer: except Exception as e: confserverlog.exception("{}".format(e)) - def check_token(self, apptype, countrycode, user, token): try: if bumper.check_token(user["userid"], token): - - if "global_" in apptype: #EcoVacs Home + + if "global_" in apptype: # EcoVacs Home login_details = EcoVacsHome_Login() login_details.ucUid = "fuid_{}".format(user["userid"]) login_details.loginName = "fusername_{}".format(user["userid"]) @@ -329,18 +337,18 @@ class ConfServer: login_details.uid = "fuid_{}".format(user["userid"]) login_details.username = "fusername_{}".format(user["userid"]) login_details.country = countrycode - login_details.email = "null@null.com" - + login_details.email = "null@null.com" + body = { "code": bumper.RETURN_API_SUCCESS, "data": json.loads(login_details.toJSON()), - #{ + # { # "accessToken": self.generate_token(tmpuser), # Generate a token # "country": countrycode, # "email": "null@null.com", # "uid": "fuid_{}".format(tmpuser["userid"]), # "username": "fusername_{}".format(tmpuser["userid"]), - #}, + # }, "msg": "操作成功", "time": bumper.get_milli_time(datetime.utcnow().timestamp()), } @@ -354,27 +362,27 @@ class ConfServer: "time": bumper.get_milli_time(datetime.utcnow().timestamp()), } return web.json_response(body) - + except Exception as e: - confserverlog.exception("{}".format(e)) + confserverlog.exception("{}".format(e)) def generate_token(self, user): try: tmpaccesstoken = uuid.uuid4().hex bumper.user_add_token(user["userid"], tmpaccesstoken) return tmpaccesstoken - + except Exception as e: - confserverlog.exception("{}".format(e)) + confserverlog.exception("{}".format(e)) def generate_authcode(self, user, countrycode, token): - try: + try: tmpauthcode = "{}_{}".format(countrycode, uuid.uuid4().hex) bumper.user_add_authcode(user["userid"], token, tmpauthcode) return tmpauthcode - + except Exception as e: - confserverlog.exception("{}".format(e)) + confserverlog.exception("{}".format(e)) def _auth_any(self, devid, apptype, country, request): try: @@ -385,7 +393,7 @@ class ConfServer: if user: # Default to user 0 tmpuser = user - if "global_" in apptype: #EcoVacs Home + if "global_" in apptype: # EcoVacs Home login_details = EcoVacsHome_Login() login_details.ucUid = "fuid_{}".format(tmpuser["userid"]) login_details.loginName = "fusername_{}".format(tmpuser["userid"]) @@ -397,12 +405,12 @@ class ConfServer: login_details.uid = "fuid_{}".format(tmpuser["userid"]) login_details.username = "fusername_{}".format(tmpuser["userid"]) login_details.country = countrycode - login_details.email = "null@null.com" + login_details.email = "null@null.com" bumper.user_add_device(tmpuser["userid"], user_devid) else: bumper.user_add("tmpuser") # Add a new user tmpuser = bumper.user_get("tmpuser") - if "global_" in apptype: #EcoVacs Home + if "global_" in apptype: # EcoVacs Home login_details = EcoVacsHome_Login() login_details.ucUid = "fuid_{}".format(tmpuser["userid"]) login_details.loginName = "fusername_{}".format(tmpuser["userid"]) @@ -414,7 +422,7 @@ class ConfServer: login_details.uid = "fuid_{}".format(tmpuser["userid"]) login_details.username = "fusername_{}".format(tmpuser["userid"]) login_details.country = countrycode - login_details.email = "null@null.com" + login_details.email = "null@null.com" bumper.user_add_device(tmpuser["userid"], user_devid) for bot in bots: # Add all bots to the user @@ -430,18 +438,17 @@ class ConfServer: # Deactivate old tokens and authcodes bumper.user_revoke_expired_tokens(tmpuser["userid"]) - body = { "code": bumper.RETURN_API_SUCCESS, "data": json.loads(login_details.toJSON()), - #{ + # { # "accessToken": self.generate_token(tmpuser), # Generate a token # "country": countrycode, # "email": "null@null.com", # "uid": "fuid_{}".format(tmpuser["userid"]), # "username": "fusername_{}".format(tmpuser["userid"]), - #}, + # }, "msg": "操作成功", "time": bumper.get_milli_time(datetime.utcnow().timestamp()), } @@ -477,10 +484,10 @@ class ConfServer: async def handle_getAuthCode(self, request): try: - apptype = request.match_info.get("apptype", "") - user_devid = request.match_info.get("devid", "") #Ecovacs + apptype = request.match_info.get("apptype", "") + user_devid = request.match_info.get("devid", "") # Ecovacs if user_devid == "": - user_devid = request.query["deviceId"] #Ecovacs Home + user_devid = request.query["deviceId"] # Ecovacs Home if not user_devid == "": user = bumper.user_by_deviceid(user_devid) @@ -502,17 +509,17 @@ class ConfServer: authcode = token["authcode"] if "global" in apptype: body = { - "code": bumper.RETURN_API_SUCCESS, - "data": { - "authCode": authcode, - "ecovacsUid": request.query["uid"], - }, - "msg": "操作成功", - "success": True, - "time": bumper.get_milli_time( - datetime.utcnow().timestamp() - ), - } + "code": bumper.RETURN_API_SUCCESS, + "data": { + "authCode": authcode, + "ecovacsUid": request.query["uid"], + }, + "msg": "操作成功", + "success": True, + "time": bumper.get_milli_time( + datetime.utcnow().timestamp() + ), + } else: body = { "code": bumper.RETURN_API_SUCCESS, @@ -561,7 +568,7 @@ class ConfServer: except Exception as e: confserverlog.exception("{}".format(e)) - async def handle_checkAPPVersion(self, request): #EcoVacs Home + async def handle_checkAPPVersion(self, request): # EcoVacs Home try: body = { "code": bumper.RETURN_API_SUCCESS, @@ -584,13 +591,13 @@ class ConfServer: return web.json_response(body) except Exception as e: - confserverlog.exception("{}".format(e)) - - async def handle_uploadDeviceInfo(self, request): #EcoVacs Home + confserverlog.exception("{}".format(e)) + + async def handle_uploadDeviceInfo(self, request): # EcoVacs Home try: body = { "code": bumper.RETURN_API_SUCCESS, - "data": None, + "data": None, "msg": "操作成功", "success": True, "time": bumper.get_milli_time(datetime.utcnow().timestamp()), @@ -599,13 +606,13 @@ class ConfServer: return web.json_response(body) except Exception as e: - confserverlog.exception("{}".format(e)) + confserverlog.exception("{}".format(e)) - async def handle_getAdByPositionType(self, request): #EcoVacs Home + async def handle_getAdByPositionType(self, request): # EcoVacs Home try: body = { "code": bumper.RETURN_API_SUCCESS, - "data": None, + "data": None, "msg": "操作成功", "success": True, "time": bumper.get_milli_time(datetime.utcnow().timestamp()), @@ -614,13 +621,13 @@ class ConfServer: return web.json_response(body) except Exception as e: - confserverlog.exception("{}".format(e)) + confserverlog.exception("{}".format(e)) - async def handle_getBootScreen(self, request): #EcoVacs Home + async def handle_getBootScreen(self, request): # EcoVacs Home try: body = { "code": bumper.RETURN_API_SUCCESS, - "data": None, + "data": None, "msg": "操作成功", "success": True, "time": bumper.get_milli_time(datetime.utcnow().timestamp()), @@ -629,13 +636,13 @@ class ConfServer: return web.json_response(body) except Exception as e: - confserverlog.exception("{}".format(e)) + confserverlog.exception("{}".format(e)) - async def handle_hasUnreadMessage(self, request): #EcoVacs Home + async def handle_hasUnreadMessage(self, request): # EcoVacs Home try: body = { "code": bumper.RETURN_API_SUCCESS, - "data": "N", + "data": "N", "msg": "操作成功", "success": True, "time": bumper.get_milli_time(datetime.utcnow().timestamp()), @@ -644,32 +651,22 @@ class ConfServer: return web.json_response(body) except Exception as e: - confserverlog.exception("{}".format(e)) + confserverlog.exception("{}".format(e)) - - async def handle_neng_hasUnreadMessage(self, request): #EcoVacs Home + async def handle_neng_hasUnreadMessage(self, request): # EcoVacs Home try: - body = { - "code": 0, - "data": { - "hasUnRead": True - }, - } + body = {"code": 0, "data": {"hasUnRead": True}} return web.json_response(body) except Exception as e: - confserverlog.exception("{}".format(e)) + confserverlog.exception("{}".format(e)) - - async def handle_getMsgList(self, request): #EcoVacs Home + async def handle_getMsgList(self, request): # EcoVacs Home try: body = { "code": bumper.RETURN_API_SUCCESS, - "data": { - "hasNextPage": 0, - "items": [] - }, + "data": {"hasNextPage": 0, "items": []}, "msg": "操作成功", "success": True, "time": bumper.get_milli_time(datetime.utcnow().timestamp()), @@ -678,9 +675,9 @@ class ConfServer: return web.json_response(body) except Exception as e: - confserverlog.exception("{}".format(e)) + confserverlog.exception("{}".format(e)) - async def handle_getCnWapShopConfig(self, request): #EcoVacs Home + async def handle_getCnWapShopConfig(self, request): # EcoVacs Home try: body = { "code": bumper.RETURN_API_SUCCESS, @@ -688,8 +685,8 @@ class ConfServer: "myShopShowFlag": "N", "myShopUrl": "", "shopIndexShowFlag": "N", - "shopIndexUrl": "" - }, + "shopIndexUrl": "", + }, "msg": "操作成功", "success": True, "time": bumper.get_milli_time(datetime.utcnow().timestamp()), @@ -698,23 +695,20 @@ class ConfServer: return web.json_response(body) except Exception as e: - confserverlog.exception("{}".format(e)) + confserverlog.exception("{}".format(e)) - async def handle_getSystemReminder(self, request): #EcoVacs Home + async def handle_getSystemReminder(self, request): # EcoVacs Home try: body = { "code": bumper.RETURN_API_SUCCESS, - "data": - { - "iosGradeTime": { - "iodGradeFlag": "N" - }, + "data": { + "iosGradeTime": {"iodGradeFlag": "N"}, "openNotification": { "openNotificationContent": None, "openNotificationFlag": "N", - "openNotificationTitle": None - } - }, + "openNotificationTitle": None, + }, + }, "msg": "操作成功", "success": True, "time": bumper.get_milli_time(datetime.utcnow().timestamp()), @@ -723,7 +717,7 @@ class ConfServer: return web.json_response(body) except Exception as e: - confserverlog.exception("{}".format(e)) + confserverlog.exception("{}".format(e)) async def handle_checkAgreement(self, request): try: @@ -736,16 +730,16 @@ class ConfServer: "force": "N", "id": "20180804040641_7d746faf18b8cb22a50d145598fe4c90", "type": "USER", - "url": "https://bumper.ecovacs.com/content/agreement?id=20180804040641_7d746faf18b8cb22a50d145598fe4c90&language=EN", #"https://gl-us-wap.ecovacs.com/content/agreement?id=20180804040641_7d746faf18b8cb22a50d145598fe4c90&language=EN - "version": "1.01" + "url": "https://bumper.ecovacs.com/content/agreement?id=20180804040641_7d746faf18b8cb22a50d145598fe4c90&language=EN", # "https://gl-us-wap.ecovacs.com/content/agreement?id=20180804040641_7d746faf18b8cb22a50d145598fe4c90&language=EN + "version": "1.01", }, { "force": "N", "id": "20180804040245_4e7c56dfb7ebd3b81b1f2747d0859fac", "type": "PRIVACY", - "url": "https://bumper.ecovacs.com/content/agreement?id=20180804040245_4e7c56dfb7ebd3b81b1f2747d0859fac&language=EN", #"https://gl-us-wap.ecovacs.com/content/agreement?id=20180804040245_4e7c56dfb7ebd3b81b1f2747d0859fac&language=EN" - "version": "1.01" - } + "url": "https://bumper.ecovacs.com/content/agreement?id=20180804040245_4e7c56dfb7ebd3b81b1f2747d0859fac&language=EN", # "https://gl-us-wap.ecovacs.com/content/agreement?id=20180804040245_4e7c56dfb7ebd3b81b1f2747d0859fac&language=EN" + "version": "1.01", + }, ], "msg": "操作成功", "success": True, @@ -886,18 +880,18 @@ class ConfServer: srvip = socket.gethostbyname(socket.gethostname()) srvport = 5223 confserverlog.info( - "Reporting FindBest-EcoMsgNew Server to Bot as: {}:{}".format(srvip, srvport) + "Reporting FindBest-EcoMsgNew Server to Bot as: {}:{}".format( + srvip, srvport + ) ) - body = { - "result": "ok", - "ip": srvip, - "port": srvport, - } + body = {"result": "ok", "ip": srvip, "port": srvport} elif service == "EcoUpdate": - srvip = "47.88.66.164" #EcoVacs Server + srvip = "47.88.66.164" # EcoVacs Server srvport = 8005 confserverlog.info( - "Reporting FindBest-EcoUpdate Server to Bot as: {}:{}".format(srvip, srvport) + "Reporting FindBest-EcoUpdate Server to Bot as: {}:{}".format( + srvip, srvport + ) ) body = {"result": "ok", "ip": srvip, "port": srvport} @@ -911,9 +905,9 @@ class ConfServer: "token": postbody["token"], "userId": postbody["userId"], } - else: #EcoVacs Home LoginByITToken + else: # EcoVacs Home LoginByITToken loginToken = bumper.loginByItToken(postbody["token"]) - if not loginToken == {}: + if not loginToken == {}: body = { "resource": postbody["resource"], "result": "ok", @@ -923,7 +917,6 @@ class ConfServer: } else: body = {"result": "fail", "todo": "result"} - elif todo == "GetDeviceList": body = { @@ -957,8 +950,6 @@ class ConfServer: body = {"result": "fail", "todo": "result"} return web.json_response(body) - - async def handle_appsvr_api(self, request): if not request.method == "GET": # Skip GET for now try: @@ -973,22 +964,24 @@ class ConfServer: todo = postbody["todo"] - if todo == "GetGlobalDeviceList": #EcoVacs Home + if todo == "GetGlobalDeviceList": # EcoVacs Home bots = bumper.db_get().table("bots").all() botlist = [] for bot in bots: if bot["class"] != "": b = bumper.bot_toEcoVacsHome_JSON(bot) - if not b is None: #Happens if the bot isn't on the EcoVacs Home list + if ( + not b is None + ): # Happens if the bot isn't on the EcoVacs Home list botlist.append(json.loads(b)) - + body = { - "code": 0, + "code": 0, "devices": botlist, "ret": "ok", "todo": "result", } - + confserverlog.debug( "\r\n POST: {} \r\n Response: {}".format(postbody, body) ) @@ -1000,8 +993,7 @@ class ConfServer: # Return fail for GET body = {"result": "fail", "todo": "result"} - return web.json_response(body) - + return web.json_response(body) async def handle_lookup(self, request): try: @@ -1023,7 +1015,9 @@ class ConfServer: srvip = socket.gethostbyname(socket.gethostname()) srvport = 5223 confserverlog.info( - "Reporting FindBest-EcoMsgNew Server to Bot as: {}:{}".format(srvip, srvport) + "Reporting FindBest-EcoMsgNew Server to Bot as: {}:{}".format( + srvip, srvport + ) ) msgserver = {"ip": srvip, "port": srvport, "result": "ok"} msgserver = json.dumps(msgserver) @@ -1047,11 +1041,10 @@ class ConfServer: except Exception as e: confserverlog.exception("{}".format(e)) - - async def handle_lg_log(self, request): #EcoVacs Home + async def handle_lg_log(self, request): # EcoVacs Home try: json_body = json.loads(await request.text()) - + randomid = "".join(random.sample(string.ascii_letters, 6)) did = json_body["did"] @@ -1060,8 +1053,8 @@ class ConfServer: if not "cmdName" in json_body: if "td" in json_body: json_body["cmdName"] = json_body["td"] - #json_body["td"] = "q" - + # json_body["td"] = "q" + if not "toId" in json_body: json_body["toId"] = did @@ -1078,39 +1071,31 @@ class ConfServer: json_body["payload"] = "" if json_body["td"] == "GetCleanLogs": json_body["td"] = "q" - json_body["payload"] = '' #" - + json_body["payload"] = '' # " if did != "": bot = bumper.bot_get(did) if bot["company"] == "eco-ng" and bot["mqtt_connection"] == True: body = "" retcmd = await self.helperbot.send_command(json_body, randomid) - confserverlog.debug( - "Send Bot - {}".format(json_body) - ) - confserverlog.debug( - "Bot Response - {}".format(body) - ) + confserverlog.debug("Send Bot - {}".format(json_body)) + confserverlog.debug("Bot Response - {}".format(body)) logs = [] logsroot = ET.fromstring(retcmd["resp"]) if logsroot.attrib["ret"] == "ok": cleanlogs = logsroot.getchildren() for l in cleanlogs: - logs.append(l.attrib) - + logs.append(l.attrib) + body = { - "ret": "ok", - #"logs": logs, #TODO: Doesn't parse correctly, new protocol & server side processing - "logs": [] - } - + "ret": "ok", + # "logs": logs, #TODO: Doesn't parse correctly, new protocol & server side processing + "logs": [], + } + else: - body = { - "ret": "ok", - "logs": [], - } - + body = {"ret": "ok", "logs": []} + confserverlog.debug( "\r\n POST: {} \r\n Response: {}".format(json_body, body) ) @@ -1125,7 +1110,6 @@ class ConfServer: ) body = {"id": randomid, "errno": bumper.ERR_COMMON, "ret": "fail"} return web.json_response(body) - except Exception as e: confserverlog.exception("{}".format(e)) @@ -1133,23 +1117,19 @@ class ConfServer: async def handle_devmanager_botcommand(self, request): try: json_body = json.loads(await request.text()) - + randomid = "".join(random.sample(string.ascii_letters, 6)) did = "" - if "toId" in json_body: # Its a command - did = json_body["toId"] + if "toId" in json_body: # Its a command + did = json_body["toId"] if did != "": bot = bumper.bot_get(did) if bot["company"] == "eco-ng" and bot["mqtt_connection"] == True: retcmd = await self.helperbot.send_command(json_body, randomid) body = retcmd - confserverlog.debug( - "Send Bot - {}".format(json_body) - ) - confserverlog.debug( - "Bot Response - {}".format(body) - ) + confserverlog.debug("Send Bot - {}".format(json_body)) + confserverlog.debug("Bot Response - {}".format(body)) return web.json_response(body) else: # No response, send error back @@ -1158,43 +1138,43 @@ class ConfServer: json_body["toId"] ) ) - body = {"id": randomid, "errno": 500, "ret": "fail", "debug": "wait for response timed out"} + body = { + "id": randomid, + "errno": 500, + "ret": "fail", + "debug": "wait for response timed out", + } return web.json_response(body) - + else: if "td" in json_body: # Seen when doing initial wifi config if json_body["td"] == "PollSCResult": body = {"ret": "ok"} return web.json_response(body) - - if json_body["td"] == "HasUnreadMsg": #EcoVacs Home - body = {"ret":"ok","unRead":False} + + if json_body["td"] == "HasUnreadMsg": # EcoVacs Home + body = {"ret": "ok", "unRead": False} return web.json_response(body) except Exception as e: confserverlog.exception("{}".format(e)) - - async def handle_dim_devmanager(self, request): #Used in EcoVacs Home App + async def handle_dim_devmanager(self, request): # Used in EcoVacs Home App try: json_body = json.loads(await request.text()) - + randomid = "".join(random.sample(string.ascii_letters, 6)) did = "" - if "toId" in json_body: # Its a command - did = json_body["toId"] + if "toId" in json_body: # Its a command + did = json_body["toId"] if did != "": bot = bumper.bot_get(did) if bot["company"] == "eco-ng" and bot["mqtt_connection"] == True: retcmd = await self.helperbot.send_command(json_body, randomid) body = retcmd - confserverlog.debug( - "Send Bot - {}".format(json_body) - ) - confserverlog.debug( - "Bot Response - {}".format(body) - ) + confserverlog.debug("Send Bot - {}".format(json_body)) + confserverlog.debug("Bot Response - {}".format(body)) return web.json_response(body) else: # No response, send error back @@ -1205,19 +1185,19 @@ class ConfServer: ) body = {"id": randomid, "errno": bumper.ERR_COMMON, "ret": "fail"} return web.json_response(body) - + else: if "td" in json_body: # Seen when doing initial wifi config if json_body["td"] == "PollSCResult": body = {"ret": "ok"} return web.json_response(body) - - if json_body["td"] == "HasUnreadMsg": #EcoVacs Home - body = {"ret":"ok","unRead":False} + + if json_body["td"] == "HasUnreadMsg": # EcoVacs Home + body = {"ret": "ok", "unRead": False} return web.json_response(body) except Exception as e: - confserverlog.exception("{}".format(e)) + confserverlog.exception("{}".format(e)) async def disconnect(self): try: @@ -1226,7 +1206,7 @@ class ConfServer: self.confthread.join() else: await self.app.shutdown() - + except Exception as e: confserverlog.exception("{}".format(e)) diff --git a/bumper/mqttserver.py b/bumper/mqttserver.py index 6515c54..83c3c9e 100644 --- a/bumper/mqttserver.py +++ b/bumper/mqttserver.py @@ -34,10 +34,7 @@ class MQTTHelperBot: Client = MQTTClient() - def __init__( - self, - address - ): + def __init__(self, address): self.address = address self.client_id = "helper1@bumper/helper1" self.command_responses = [] @@ -62,7 +59,7 @@ class MQTTHelperBot: ] ) asyncio.create_task(self.get_msg()) - + except Exception as e: helperbotlog.exception("{}".format(e)) @@ -71,8 +68,12 @@ class MQTTHelperBot: message = await self.Client.deliver_message() if str(message.topic).split("/")[6] == "helper1": - #Response to command - helperbotlog.debug("Received Response - Topic: {} - Message: {}".format(message.topic, str(message.data.decode("utf-8")))) + # Response to command + helperbotlog.debug( + "Received Response - Topic: {} - Message: {}".format( + message.topic, str(message.data.decode("utf-8")) + ) + ) self.command_responses.append( { "time": time.time(), @@ -81,13 +82,25 @@ class MQTTHelperBot: } ) elif str(message.topic).split("/")[3] == "helper1": - #Helperbot sending command - helperbotlog.debug("Send Command - Topic: {} - Message: {}".format(message.topic, str(message.data.decode("utf-8")))) + # Helperbot sending command + helperbotlog.debug( + "Send Command - Topic: {} - Message: {}".format( + message.topic, str(message.data.decode("utf-8")) + ) + ) elif str(message.topic).split("/")[1] == "atr": - #Broadcast message received on atr - helperbotlog.debug("Received Broadcast - Topic: {} - Message: {}".format(message.topic, str(message.data.decode("utf-8")))) + # Broadcast message received on atr + helperbotlog.debug( + "Received Broadcast - Topic: {} - Message: {}".format( + message.topic, str(message.data.decode("utf-8")) + ) + ) else: - helperbotlog.debug("Received Message - Topic: {} - Message: {}".format(message.topic, str(message.data.decode("utf-8")))) + helperbotlog.debug( + "Received Message - Topic: {} - Message: {}".format( + message.topic, str(message.data.decode("utf-8")) + ) + ) # Cleanup "expired messages" > 60 seconds from time for msg in self.command_responses: @@ -95,17 +108,20 @@ class MQTTHelperBot: datetime.fromtimestamp(msg["time"]) + timedelta(seconds=10) ).timestamp() if time.time() > expire_time: - helperbotlog.debug("Pruning Message Time: {}, MsgTime: {}, MsgTime+60: {}".format(time.time(), msg['time'], expire_time)) + helperbotlog.debug( + "Pruning Message Time: {}, MsgTime: {}, MsgTime+60: {}".format( + time.time(), msg["time"], expire_time + ) + ) self.command_responses.remove(msg) - async def wait_for_resp(self, requestid): try: t_end = (datetime.now() + timedelta(seconds=10)).timestamp() while time.time() < t_end: - await asyncio.sleep(0.1) + await asyncio.sleep(0.1) if len(self.command_responses) > 0: for msg in self.command_responses: topic = str(msg["topic"]).split("/") @@ -115,17 +131,32 @@ class MQTTHelperBot: resppayload = json.loads(msg["payload"]) else: resppayload = str(msg["payload"]) - resp = {"id": requestid, "ret": "ok", "resp": resppayload} + resp = {"id": requestid, "ret": "ok", "resp": resppayload} self.command_responses.remove(msg) return resp - return {"id": requestid, "errno": 500, "ret": "fail", "debug": "wait for response timed out"} + return { + "id": requestid, + "errno": 500, + "ret": "fail", + "debug": "wait for response timed out", + } except asyncio.CancelledError as e: helperbotlog.debug("wait_for_resp cancelled by asyncio") - return {"id": requestid, "errno": 500, "ret": "fail", "debug": "wait for response timed out"} + return { + "id": requestid, + "errno": 500, + "ret": "fail", + "debug": "wait for response timed out", + } except Exception as e: helperbotlog.exception("{}".format(e)) - return {"id": requestid, "errno": 500, "ret": "fail", "debug": "wait for response timed out"} + return { + "id": requestid, + "errno": 500, + "ret": "fail", + "debug": "wait for response timed out", + } async def send_command(self, cmdjson, requestid): try: @@ -154,11 +185,13 @@ class MQTTHelperBot: class MQTTServer: - default_config = {} + default_config = {} async def broker_coro(self): try: - mqttserverlog.info("Starting MQTT Server at {}:{}".format(self.address[0], self.address[1])) + mqttserverlog.info( + "Starting MQTT Server at {}:{}".format(self.address[0], self.address[1]) + ) broker = hbmqtt.broker.Broker(config=self.default_config) await broker.start() @@ -174,13 +207,9 @@ class MQTTServer: except Exception as e: mqttserverlog.exception("{}".format(e)) exit(1) - - def __init__( - self, - address - ): - try: + def __init__(self, address): + try: self.mqttserverthread = None self.address = address @@ -211,7 +240,7 @@ class MQTTServer: ), "plugins": ["bumper"], # No plugins == no auth }, - "topic-check": {"enabled": False}, + "topic-check": {"enabled": False}, } except Exception as e: @@ -253,9 +282,9 @@ class BumperMQTTServer_Plugin: client_id = session.client_id didsplit = str(client_id).split("@") - if not ( # if ecouser or bumper aren't in details it is a bot - "ecouser" in didsplit[1] - or "bumper" in didsplit[1]): + if not ( # if ecouser or bumper aren't in details it is a bot + "ecouser" in didsplit[1] or "bumper" in didsplit[1] + ): tmpbotdetail = str(didsplit[1]).split("/") bumper.bot_add( username, @@ -264,7 +293,7 @@ class BumperMQTTServer_Plugin: tmpbotdetail[1], "eco-ng", ) - + mqttserverlog.debug( "new bot authenticated SN: {} DID: {}".format( username, didsplit[0] @@ -298,7 +327,9 @@ class BumperMQTTServer_Plugin: authenticated = False except Exception as e: - mqttserverlog.exception("Session: {} - {}".format((kwargs.get("session", None)),e)) + mqttserverlog.exception( + "Session: {} - {}".format((kwargs.get("session", None)), e) + ) authenticated = False return authenticated @@ -312,7 +343,7 @@ class BumperMQTTServer_Plugin: bumper.bot_set_mqtt(bot["did"], True) return - #clientuserid = didsplit[0] + # clientuserid = didsplit[0] clientresource = didsplit[1].split("/")[1] client = bumper.client_get(clientresource) if client: @@ -330,7 +361,7 @@ class BumperMQTTServer_Plugin: if bot: bumper.bot_set_mqtt(bot["did"], False) - #clientuserid = didsplit[0] + # clientuserid = didsplit[0] clientresource = didsplit[1].split("/")[1] client = bumper.client_get(clientresource) if client: diff --git a/bumper/xmppserver.py b/bumper/xmppserver.py index e2d637c..f012f6f 100644 --- a/bumper/xmppserver.py +++ b/bumper/xmppserver.py @@ -9,11 +9,12 @@ import asyncio, functools xmppserverlog = logging.getLogger("xmppserver") -class XMPPServer(): - server_id = "ecouser.net" + +class XMPPServer: + server_id = "ecouser.net" clients = [] exit_flag = False - + def __init__(self, address): # Initialize bot server self.address = address @@ -45,6 +46,7 @@ class XMPPServer(): except Exception as e: xmppserverlog.error("{}".format(e)) + class XMPPServer_Protocol(asyncio.Protocol): client_id = None exit_flag = False @@ -55,8 +57,10 @@ class XMPPServer_Protocol(asyncio.Protocol): aclient = None def connection_made(self, transport): - if self.aclient: #Existing client... upgrading to TLS - xmppserverlog.debug("Upgraded connection for {}".format(self.aclient.address)) + if self.aclient: # Existing client... upgrading to TLS + xmppserverlog.debug( + "Upgraded connection for {}".format(self.aclient.address) + ) self.aclient.transport = transport else: aclient = XMPPAsyncClient(transport) @@ -65,15 +69,20 @@ class XMPPServer_Protocol(asyncio.Protocol): self.aclient.state = getattr(aclient, "CONNECT") xmppserverlog.debug("New Connection from {}".format(aclient.address)) - def connection_lost(self, error): XMPPServer.clients.remove(self.aclient) self.aclient._set_state("DISCONNECT") - xmppserverlog.debug("End Connection for ({}:{} | {})".format(self.aclient.address[0], self.aclient.address[1], self.aclient.bumper_jid)) + xmppserverlog.debug( + "End Connection for ({}:{} | {})".format( + self.aclient.address[0], + self.aclient.address[1], + self.aclient.bumper_jid, + ) + ) def data_received(self, data): self.aclient._parse_data(data) - + class XMPPAsyncClient: IDLE = 0 @@ -103,10 +112,14 @@ class XMPPAsyncClient: def send(self, command): try: if self.log_sent_message: - xmppserverlog.debug("send to ({}:{} | {}) - {}".format(self.address[0], self.address[1], self.bumper_jid, command)) - + xmppserverlog.debug( + "send to ({}:{} | {}) - {}".format( + self.address[0], self.address[1], self.bumper_jid, command + ) + ) + self.transport.write(command.encode()) - + except Exception as e: xmppserverlog.exception("{}".format(e)) @@ -145,7 +158,11 @@ class XMPPAsyncClient: ) ) - xmppserverlog.debug("({}:{} | {}) state: {}".format(self.address[0],self.address[1],self.bumper_jid, state)) + xmppserverlog.debug( + "({}:{} | {}) state: {}".format( + self.address[0], self.address[1], self.bumper_jid, state + ) + ) self.state = new_state @@ -166,24 +183,24 @@ class XMPPAsyncClient: ) ) return - + if "disco#items" in data: # Return not-implemented for disco#items self.send( ''.format( - xml.get("id") - )) + xml.get("id") + ) + ) return if "disco#info" in data: - # Return not-implemented for disco#info - self.send( - ''.format( + # Return not-implemented for disco#info + self.send( + ''.format( xml.get("id") - ) - ) - return - + ) + ) + return if xml.get("type") == "set": if ( @@ -247,34 +264,34 @@ class XMPPAsyncClient: pingto = xml.get("to") pingfrom = self.bumper_jid if not "from" in xml.attrib: - xml.attrib["from"] = "{}".format(pingfrom) + xml.attrib["from"] = "{}".format(pingfrom) pingstring = ET.tostring(xml).decode("utf-8") # clean up string to remove namespaces added by ET pingstring = pingstring.replace("xmlns:ns0=", "xmlns=") pingstring = pingstring.replace("ns0:", "") pingstring = pingstring.replace('iq xmlns="urn:xmpp:ping"', "iq") pingstring = pingstring.replace("PLAIN' + 'PLAIN' ) - + else: # Already using TLS send authentication support for iq-auth (fallback) and SASL self.send( - 'PLAIN' + 'PLAIN' ) else: @@ -415,7 +434,7 @@ class XMPPAsyncClient: XMPPServer.server_id ) ) - + self.send( '' ) @@ -435,30 +454,37 @@ class XMPPAsyncClient: except Exception as e: xmppserverlog.exception("{}".format(e)) - async def _handle_starttls(self, data): try: if self.TLSUpgraded == False: - self.TLSUpgraded = True #Set TLSUpgraded true to prevent further attempts to upgrade connection - xmppserverlog.debug("Upgrading connection with STARTTLS for {}:{}".format(self.address[0],self.address[1])) - self.send("") #send process to client + self.TLSUpgraded = ( + True + ) # Set TLSUpgraded true to prevent further attempts to upgrade connection + xmppserverlog.debug( + "Upgrading connection with STARTTLS for {}:{}".format( + self.address[0], self.address[1] + ) + ) + self.send( + "" + ) # send process to client # After proceed the connection should be upgraded to TLS loop = asyncio.get_event_loop() transport = self.transport protocol = self.transport.get_protocol() - + ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ssl_ctx.load_cert_chain(bumper.server_cert, bumper.server_key) ssl_ctx.load_verify_locations(cafile=bumper.ca_cert) - new_transport = await loop.start_tls(transport , protocol, ssl_ctx, server_side=True) + new_transport = await loop.start_tls( + transport, protocol, ssl_ctx, server_side=True + ) protocol.connection_made(new_transport) - - + except Exception as e: xmppserverlog.exception("{}".format(e)) - def _handle_iq_auth(self, data): try: @@ -500,7 +526,7 @@ class XMPPAsyncClient: self.clientresource = aitem.text resource = self.clientresource - if self.devclass: # if there is a devclass it is a bot + if self.devclass: # if there is a devclass it is a bot bumper.bot_add("", self.uid, "", resource, "eco-legacy") xmppserverlog.debug("bot authenticated {}".format(self.uid)) @@ -525,9 +551,7 @@ class XMPPAsyncClient: self._set_state("INIT") # Successful auth - self.send( - ''.format(xml.get("id")) - ) + self.send(''.format(xml.get("id"))) else: # Failed auth @@ -571,8 +595,8 @@ class XMPPAsyncClient: if len(saslauth) > 2: authcode = saslauth[2] - - if self.devclass: # if there is a devclass it is a bot + + if self.devclass: # if there is a devclass it is a bot bumper.bot_add(self.uid, self.uid, self.devclass, "atom", "eco-legacy") self.type = self.BOT xmppserverlog.debug("bot authenticated {}".format(self.uid)) @@ -631,7 +655,11 @@ class XMPPAsyncClient: self.bumper_jid = "{}@{}.ecorobot.net/atom".format( self.uid, self.devclass ) - xmppserverlog.debug("new bot ({}:{} | {})".format(self.address[0],self.address[1], self.bumper_jid)) + xmppserverlog.debug( + "new bot ({}:{} | {})".format( + self.address[0], self.address[1], self.bumper_jid + ) + ) res = '{}'.format( xml.get("id"), self.bumper_jid ) @@ -641,14 +669,22 @@ class XMPPAsyncClient: self.bumper_jid = "{}@{}/{}".format( self.uid, XMPPServer.server_id, self.clientresource ) - xmppserverlog.debug("new client ({}:{} | {})".format(self.address[0],self.address[1], self.bumper_jid)) + xmppserverlog.debug( + "new client ({}:{} | {})".format( + self.address[0], self.address[1], self.bumper_jid + ) + ) res = '{}'.format( xml.get("id"), self.bumper_jid ) else: self.name = "XMPP_Client_{}_{}".format(self.uid, self.address) self.bumper_jid = "{}@{}".format(self.uid, XMPPServer.server_id) - xmppserverlog.debug("new client ({}:{} | {})".format(self.address[0],self.address[1], self.bumper_jid)) + xmppserverlog.debug( + "new client ({}:{} | {})".format( + self.address[0], self.address[1], self.bumper_jid + ) + ) res = '{}'.format( xml.get("id"), self.bumper_jid ) @@ -662,10 +698,9 @@ class XMPPAsyncClient: def _handle_session(self, xml): try: res = ''.format(xml.get("id")) - self._set_state("READY") + self._set_state("READY") self.send(res) - asyncio.Task(self.schedule_ping(30)) - + asyncio.Task(self.schedule_ping(30)) except Exception as e: xmppserverlog.exception("{}".format(e)) @@ -675,7 +710,9 @@ class XMPPAsyncClient: if len(xml) and xml[0].tag == "status": xmppserverlog.debug( - "bot presence {} ".format(ET.tostring(xml, encoding="utf-8").decode("utf-8")) + "bot presence {} ".format( + ET.tostring(xml, encoding="utf-8").decode("utf-8") + ) ) # Most likely a bot, possibly hello world in text @@ -683,8 +720,6 @@ class XMPPAsyncClient: self.send( ' dummy '.format(self.bumper_jid) ) - - # If it is a BOT, send extras if self.type == self.BOT: @@ -695,19 +730,20 @@ class XMPPAsyncClient: ) ) - - else: xmppserverlog.debug( - "client presence - {} ".format(ET.tostring(xml, encoding="utf-8").decode("utf-8")) + "client presence - {} ".format( + ET.tostring(xml, encoding="utf-8").decode("utf-8") + ) ) - + if xml.get("type") == "available": xmppserverlog.debug( "client presence available - {} ".format( - ET.tostring(xml, encoding="utf-8").decode("utf-8")) + ET.tostring(xml, encoding="utf-8").decode("utf-8") + ) ) - + # Send dummy return self.send( ' dummy '.format(self.bumper_jid) @@ -715,8 +751,9 @@ class XMPPAsyncClient: elif xml.get("type") == "unavailable": xmppserverlog.debug( "client presence unavailable (DISCONNECT) - {} ".format( - ET.tostring(xml, encoding="utf-8").decode("utf-8")) - ) + ET.tostring(xml, encoding="utf-8").decode("utf-8") + ) + ) self._set_state("DISCONNECT") else: @@ -756,7 +793,9 @@ class XMPPAsyncClient: if self.log_incoming_data: xmppserverlog.debug( "from ({}:{} | {}) - {}".format( - self.address[0],self.address[1],self.bumper_jid, + self.address[0], + self.address[1], + self.bumper_jid, str( ET.tostring(item, encoding="utf-8").decode( "utf-8" diff --git a/start_bumper.py b/start_bumper.py index 0ddf4f0..4ec5414 100644 --- a/start_bumper.py +++ b/start_bumper.py @@ -6,7 +6,8 @@ import sys, socket import time import platform import os -#os.environ['PYTHONASYNCIODEBUG'] = '1' # Uncomment to enable ASYNCIODEBUG + +# os.environ['PYTHONASYNCIODEBUG'] = '1' # Uncomment to enable ASYNCIODEBUG import asyncio @@ -15,41 +16,39 @@ async def main(): loop = asyncio.get_event_loop() except: loop = asyncio.new_event_loop() - + args = sys.argv listen_host = "" - + if len(args) > 0: if "--debug" in args: logging.basicConfig( level=logging.DEBUG, format="[%(asctime)s] :: %(levelname)s :: %(name)s :: %(module)s :: %(funcName)s :: %(lineno)d :: %(message)s", ) - loop.set_debug(True) # Set asyncio loop to debug - #logging.getLogger("asyncio").setLevel(logging.DEBUG) # Show debug asyncio logs (disabled in init, uncomment for debugging asyncio) + loop.set_debug(True) # Set asyncio loop to debug + # logging.getLogger("asyncio").setLevel(logging.DEBUG) # Show debug asyncio logs (disabled in init, uncomment for debugging asyncio) else: logging.basicConfig( level=logging.INFO, format="[%(asctime)s] :: %(levelname)s :: %(name)s :: %(message)s", ) - - if "--listen" in args: + + if "--listen" in args: listen_host = args[args.index("--listen") + 1] - + if listen_host == "": if platform.system() == "Darwin": # If a Mac, use 0.0.0.0 for listening listen_host = "0.0.0.0" else: - listen_host = socket.gethostbyname(socket.gethostname()) + listen_host = socket.gethostbyname(socket.gethostname()) conf_address_443 = (listen_host, 443) conf_address_8007 = (listen_host, 8007) xmpp_address = (listen_host, 5223) mqtt_address = (listen_host, 8883) - xmpp_server = bumper.XMPPServer( - xmpp_address - ) + xmpp_server = bumper.XMPPServer(xmpp_address) mqtt_server = bumper.MQTTServer(mqtt_address) mqtt_helperbot = bumper.MQTTHelperBot(mqtt_address) conf_server = bumper.ConfServer( @@ -62,23 +61,23 @@ async def main(): try: # Start web servers - conf_server.confserver_app() + conf_server.confserver_app() asyncio.create_task(conf_server.start_server()) - + conf_server_2.confserver_app() asyncio.create_task(conf_server_2.start_server()) - + # Start MQTT Server asyncio.create_task(mqtt_server.broker_coro()) - + # Start MQTT Helperbot asyncio.create_task(mqtt_helperbot.start_helper_bot()) - + # Start XMPP Server asyncio.create_task(xmpp_server.start_async_server()) - + maintain = asyncio.create_task(maintenance_tasks()) - await maintain #Keeps the loop running until this exits + await maintain # Keeps the loop running until this exits finally: # Cleanup and close tasks/loop @@ -86,19 +85,19 @@ async def main(): task.cancel() loop.close() + async def maintenance_tasks(): while True: - await asyncio.sleep(30) # Sleep 30 seconds + await asyncio.sleep(30) # Sleep 30 seconds bumper.revoke_expired_tokens() - + if __name__ == "__main__": try: asyncio.run(main()) - + except KeyboardInterrupt: bumper.bumperlog.info("Keyboard Interrupt!") pass finally: bumper.bumperlog.info("Bumper Exiting!") - diff --git a/tests/test_bumper.py b/tests/test_bumper.py index d0f213c..a6cbb03 100644 --- a/tests/test_bumper.py +++ b/tests/test_bumper.py @@ -180,5 +180,8 @@ def test_client_db(): bumper.client_set_xmpp("resource_123", False) assert_false( bumper.client_get("resource_123")["xmpp_connection"] - ) # Test that xmpp was set False for client - assert_equals(len(bumper.get_disconnected_xmpp_clients()), 1) # Test len of connected xmpp clients is 1 \ No newline at end of file + ) # Test that xmpp was set False for client + assert_equals( + len(bumper.get_disconnected_xmpp_clients()), 1 + ) # Test len of connected xmpp clients is 1 + diff --git a/tests/test_confserver.py b/tests/test_confserver.py index b7a4849..4fd9a2a 100644 --- a/tests/test_confserver.py +++ b/tests/test_confserver.py @@ -12,14 +12,15 @@ confserver = bumper.ConfServer("127.0.0.1:11111", False, mock.MagicMock) confserver.confserver_app() app = confserver.app + def async_return(result): f = asyncio.Future() f.set_result(result) - return f + return f + def test_disconnect(): - - async def test_disconnect_async(): + async def test_disconnect_async(): await confserver.disconnect() loop = asyncio.get_event_loop() @@ -513,6 +514,7 @@ def test_postLookup(): client.close() ) # Close test server after all tests are done + def test_devmgr(): if os.path.exists("tests/tmp.db"): os.remove("tests/tmp.db") # Remove existing db @@ -536,7 +538,7 @@ def test_devmgr(): if jsonresp["ret"] == "ok": assert jsonresp["resp"] else: - assert jsonresp["errno"] + assert jsonresp["errno"] else: assert jsonresp @@ -549,23 +551,33 @@ def test_devmgr(): bumper.bot_add("sn_1234", "did_1234", "dev_1234", "res_1234", "eco-ng") bumper.bot_set_mqtt("did_1234", True) postbody = {"toId": "did_1234"} - + # Test return get status - command_getstatus_resp = { "id": "resp_1234", "resp": "", "ret": "ok" } - confserver.helperbot.send_command = mock.MagicMock(return_value=async_return(command_getstatus_resp)) - # Test + command_getstatus_resp = { + "id": "resp_1234", + "resp": "", + "ret": "ok", + } + confserver.helperbot.send_command = mock.MagicMock( + return_value=async_return(command_getstatus_resp) + ) + # Test loop.run_until_complete(test_devmanager(postbody, command=True)) # Test return fail timeout command_timeout_resp = {"id": "resp_1234", "errno": "timeout", "ret": "fail"} - confserver.helperbot.send_command = mock.MagicMock(return_value=async_return(command_timeout_resp)) - # Test + confserver.helperbot.send_command = mock.MagicMock( + return_value=async_return(command_timeout_resp) + ) + # Test loop.run_until_complete(test_devmanager(postbody, command=True)) # Set bot not on mqtt bumper.bot_set_mqtt("did_1234", False) - confserver.helperbot.send_command = mock.MagicMock(return_value=async_return(command_getstatus_resp)) - # Test + confserver.helperbot.send_command = mock.MagicMock( + return_value=async_return(command_getstatus_resp) + ) + # Test loop.run_until_complete(test_devmanager(postbody, command=True)) loop.run_until_complete(