import requests import json class Mw40V: def __init__(self, username, password, encrypt_key, verification_key): self.username = username self.password = password self.encrypt_key = encrypt_key self.verification_key = verification_key self.login_token = None def request(self, method, params, id): if self.login_token is None and method != 'Login': self.login(self.username, self.password) body = { "jsonrpc": "2.0", "method": method, "params": params, "id": id } r = requests.post( f"http://bbox.nomad/jrd/webapi?api={method}", data=json.dumps(body), headers=self.headers(method) ) if 'error' in r.json(): if r.json()['error']['message'] in ['Authentication Failure', 'Request need login']: self.login_token = None self.request(self, method, params, id) else: raise Exception(r.json()['error']) elif 'result' in r.json(): return r.json()['result'] else: return {} def headers(self, method): return { 'Referer': 'http://bbox.nomad/index.html', '_TclRequestVerificationKey': self.verification_key, '_TclRequestVerificationToken': self.encrypt(str(self.login_token)) or "null" } def login(self, user, password): result = self.request( "Login", { "UserName": self.encrypt(user), "Password": self.encrypt(password) }, "1.1" ) if 'token' not in result: raise Exception("Error while login to nomad bbox") self.login_token = result['token'] def connect(self): result = self.request( "Connect", None, "3.2" ) return result def disconnect(self): result = self.request( "DisConnect", None, "3.3" ) return result def encrypt(self, subject): if not str: return "" subject = str(subject) result_list = [] for i, char_i in enumerate(subject): num_char_i = ord(char_i) x = (ord(self.encrypt_key[i % len(self.encrypt_key)]) & 0xf0) \ | ((num_char_i & 0xf) ^ (ord(self.encrypt_key[i % len(self.encrypt_key)]) & 0xf)) y = (ord(self.encrypt_key[i % len(self.encrypt_key)]) & 0xf0) \ | ((num_char_i >> 4) ^ (ord(self.encrypt_key[i % len(self.encrypt_key)]) & 0xf)) result_list.append(chr(x)) result_list.append(chr(y)) return ''.join(result_list)