async def shutdown(loop=None): loop = loop if loop is not None else asyncio.get_event_loop() pending = cancel_tasks() cprint(f'Cancelling {len(pending)} tasks...', color='yellow') with contextlib.suppress(asyncio.CancelledError): await asyncio.gather(*pending, return_exceptions=False) await asyncio.sleep(0)
async def post_join_pk(self, post_data: dict, account: Optional[Account] = None): if account is None or account.banned: return url = 'https://api.live.bilibili.com/xlive/lottery-interface/v2/pk/join' headers = self.web_headers.copy() cookies = account.web_cookies.copy() for _ in range(3): response = await self.rl_session.post(url, headers=headers, cookies=cookies, data=post_data) try: response.raise_for_status() js = await response.json() if 0 == js['code']: return js elif '访问被拒绝' == js.get('message'): account.banned = True account.cprint(f'访问被拒绝', color='purple') return None elif '领取过' in js.get('message'): account.cprint(f'已领取', color='purple') return None else: return None except (aiohttp.ClientPayloadError, aiohttp.ClientResponseError) as exc: cprint(f'aiohttp ClientError: {exc}', color='red')
def importdb(conf, dbfile, passwd, passphrase): if PasswdManager.verbose: cprint('Reading and decrypting database', color='blue') g = Giltzarrapo().readEncrypted(conf['dbfile']).decrypt( passwd, conf['privkey'], passphrase) if PasswdManager.verbose: print(cprepare('Reading plain exported file :', color='blue'), cprepare(dbfile, color='lblue')) content = InternalPasswdManager.readfile(dbfile) header_fields = ['service', 'user', 'password'] old_header, lines = content[0].split('\t'), [ l.split('\t') for l in content[1:] ] line_template = '{}\n'.format('\t'.join([ ('{}' if h in header_fields else ' ') for h in old_header ])) if PasswdManager.verbose: print(cprepare('Inserting rows in', color='blue'), cprepare(conf['dbfile'].split('/')[-1], color='lblue'), cprepare('database', color='blue')) for l in lines: InternalPasswdManager.append(g, line_template.format(*l)) if PasswdManager.verbose: cprint('Saving modified database', color='blue') g.encrypt(passwd, conf['pubkey']).save(conf['dbfile'])
def process_login(self): accounts = [ Account(data_file, self.yaml) for data_file in self.account_files ] self.accounts = accounts wait = False for acc in accounts: if not acc.usable and acc.username and acc.password: l = Login(acc, output_file=acc.input_file, yaml=self.yaml) try: cprint(f'{acc.input_file!r}: Logging in...', color='green') l.login() acc.reload() acc.cprint(f'登录成功', color='green') if wait: time.sleep(5) except LoginException as exc: acc.cprint(f'登录失败 - {exc}', error=True) wait = True elif acc.usable: msg = (f'{acc.input_file!r}: cookies读取成功') acc.cprint(f'{msg}', color='green') else: msg = (f'登录信息不完整 && cookies未提供. - ' f' {acc.input_file!r} Skipped.') cprint(f'{msg}', color='yellow')
async def post(self, url, params=None, headers=None, cookies=None, data=None, rate_limited: bool = True): if rate_limited == True: session = self.rl_session else: session = self.session err = None for _ in range(3): # fire request try: response = await session.post(url, params=params, headers=headers, cookies=cookies, data=data, ssl=False) response.raise_for_status() r_json = await response.json(content_type=None) return r_json except aiohttp.ClientError as exc: err = exc cprint(f'aiohttp ClientError: {exc}', color='red') if err: raise HttpError(f'Request failed: {err} @url {url!r}')
def create(dbname, passwd, passphrase, databases_path, keys_path): if PasswdManager.verbose: print(cprepare('Creating', color='blue'), cprepare(dbname, color='lblue'), cprepare('database', color='blue')) g = Giltzarrapo() InternalPasswdManager.append( g, 'passranoid_database:v1.1\tpassranoid_interface:v1.2\tpassranoid_config:v1\n' ) g.status = 'plain' if PasswdManager.verbose: cprint('Generating rsa key pair', color='blue') privkey, pubkey = Giltzarrapo.generateRSApair(passphrase, dir=keys_path, name=dbname) if PasswdManager.verbose: print(cprepare('Keys saved at :\n - Privkey :', color='blue'), cprepare(privkey, color='lblue'), cprepare('\n - Pubkey :', color='blue'), cprepare(pubkey, color='lblue')) if PasswdManager.verbose: print( cprepare('Saving database at :', color='blue'), cprepare('{}/{}'.format(databases_path, dbname), color='lblue')) g.encrypt(passwd, pubkey).save('{}/{}'.format(databases_path, dbname))
def usable(self): usable = False try: usable = self.web_cookies and all( [cookie for cookie in self.web_cookies.values()]) except AttributeError: cprint(f'AttributeError in account.py', error=True) return usable
def print_time_elapsed(self): elapsed = days_to_date(self.time_elapsed) years = elapsed[0] months = elapsed[1] days = elapsed[2] cprint('It has been %s year(s), %s month(s), and %s day(s) since you began your search. ' % (years, months, days)) return 0
def list_room_contents(self, room): object_dic = None for e in self.rooms_desc: if e.lower() == room.lower(): object_dic = self.rooms_objs[e] for obj in object_dic: cprint('\t' + obj)
async def get_area_of_room(roomid: int): response = await Bilibili().request_check_live_info(roomid) if response is None: return if response['code'] == 0: return response['data']['parent_area_id'] else: cprint(f'Get area of room status code {response["code"]}', color='red')
def changedbpass(conf, newpasswd, passwd, passphrase): if PasswdManager.verbose: cprint('Reading and decrypting database', color='blue') g = Giltzarrapo().readEncrypted(conf['dbfile']).decrypt( passwd, conf['privkey'], passphrase) if PasswdManager.verbose: cprint('Encrypting database with the new password', color='blue') g.encrypt(newpasswd, conf['pubkey']).save(conf['dbfile'])
async def get_all_rooms_on_page(page:int, page_size:int = 99, popularity_over:int = 50): response = await Bilibili().request_check_area(0, page=page, page_size=page_size) if response['code'] != 0: cprint(f'Status code in get_all_rooms_on_page ' f'{response["code"]} {response["message"]}', color='red') raise RuntimeError('Status code nonzero') for room_info in response['data']['list']: if room_info['online'] > popularity_over: yield room_info['roomid']
def verifyauth(conf, passwd, passphrase): if PasswdManager.verbose: cprint('Verifying database credentials', color='blue') try: g = Giltzarrapo().readEncrypted(conf['dbfile']).decrypt( passwd, conf['privkey'], passphrase) g.encrypt(passwd, conf['pubkey']).save(conf['dbfile']) except: return False if PasswdManager.verbose: cprint('Successfully verification', color='green') return True
def on_raffle(self, data): t = '' if data['type'] == 'guard': t = 'guard' elif data['type'] == 'pk': t = 'pk' elif data['type'] == 'storm': t = 'storm' else: t = 'gift' self.emitter and self.emitter.emit(t, data) cprint(f'{data["id"]:<13} @{data["roomid"]:<12} {data["name"]}', color='cyan')
def holidays_passed(self, time_elapsed): time = self.date had_christmas = False had_birthday = False had_new_year = False had_valentines = False while time_elapsed != 0: time += timedelta(1) if time.month == self.christmas[1] and time.day == self.christmas[0]: had_christmas = True elif time.month == self.birthday[1] and time.day == self.birthday[0]: had_birthday = True elif time.month == self.new_year[1] and time.day == self.new_year[0]: had_new_year = True elif time.month == self.valentines[1] and time.day == self.valentines[0]: had_valentines = True time_elapsed -= 1 if had_birthday: cprint('Your birthday has passed. ', 0.15) self.birthdays_had += 1 if had_christmas: cprint('Christmas has passed. ', 0.15) if had_new_year: cprint('A new year has come. ', 0.15) if had_valentines: cprint("Valentine's has passed. ", 0.15) return 0
def exportdb(conf, dbfile, passwd, passphrase): if PasswdManager.verbose: cprint('Reading and decrypting database', color='blue') g = Giltzarrapo().readEncrypted(conf['dbfile']).decrypt( passwd, conf['privkey'], passphrase) if PasswdManager.verbose: cprint('Fetching rows', color='blue') header = '\t'.join(['service', 'user', 'password']) lines = [l for i, l in InternalPasswdManager.getlines(g, '*')] if len(lines) == 0: return False if PasswdManager.verbose: print(cprepare('Saving plain database rows at :', color='blue'), cprepare(dbfile, color='lblue')) InternalPasswdManager.savefile(header=header, lines=lines, file=dbfile) return True
def reload(self): data_file = utils.resolve_to_cwd(self.input_file) try: with open(data_file, mode='r', encoding='UTF-8') as iofile: store = self.yaml.load(iofile) self.username = store.get('user').get('username') self.password = store.get('user').get('password') self.web_cookies = store.get('web') self.app_cookies = store.get('app') try: self.uid = self.web_cookies.get('DedeUserID') except AttributeError: pass except FileNotFoundError: msg = (f'File {self.input_file!r} not found. Skipped') cprint(f'{msg}', error=True) except (TypeError, AttributeError): pass
async def connect(self): cls = self.__class__ url = self.server["url"] or f'ws://{self.server["address"]}:{self.server["port"]}' async with websockets.connect(url) as ws: self.connected = True self.ws = ws accepted = False try: await ws.send(self.handshake) cprint(f'Established connection with [ {ws.remote_address} ]', color='green') accepted = True while accepted and ws.open: data = await ws.recv() body = self.deserialize(data) self.on_raffle(body) await ws.close() await ws.wait_closed() self.accepted = False except websockets.ConnectionClosed: if accepted: cprint(f'Lost connection: [ {ws.remote_address} ]', color='red') self.again = True except IndexError: pass except Exception as exc: cprint(f'{type(exc)}: {exc}', error=True) self.again = False finally: self.connected = False
def remove(conf, index, passwd, passphrase): if PasswdManager.verbose: cprint('Reading and decrypting database', color='blue') g = Giltzarrapo().readEncrypted(conf['dbfile']).decrypt( passwd, conf['privkey'], passphrase) if PasswdManager.verbose: cprint('Removing matching rows', color='blue') if index == '*': removerows = [ l[1].encode('utf-8') for l in InternalPasswdManager.getlines(g, '*') ] else: try: removerows = InternalPasswdManager.getlines( g, '*')[index][1].encode('utf-8') except IndexError: return False InternalPasswdManager.remove(g, removerows) if PasswdManager.verbose: cprint('Saving modified database', color='blue') g.encrypt(passwd, conf['pubkey']).save(conf['dbfile']) return True
def changedbkey(conf, newpassphrase, passwd, passphrase): if PasswdManager.verbose: cprint('Reading and decrypting database', color='blue') g = Giltzarrapo().readEncrypted(conf['dbfile']).decrypt( passwd, conf['privkey'], passphrase) if PasswdManager.verbose: cprint('Generating rsa key pair', color='blue') keys_path, keyname = '/'.join( conf['privkey'].split('/')[:-1]), conf['privkey'].split('/')[-1] os.rename(conf['privkey'], '{}/.old.{}'.format(keys_path, keyname)) os.rename(conf['pubkey'], '{}/.old.{}.pub'.format(keys_path, keyname)) privkey, pubkey = Giltzarrapo.generateRSApair(newpassphrase, dir=keys_path, name=keyname) if PasswdManager.verbose: print( cprepare('Old keys moved to :\n - Privkey :', color='blue'), cprepare('{}/.old.{}'.format(keys_path, keyname), color='lblue'), cprepare('\n - Pubkey :', color='blue'), cprepare('{}/.old.{}.pub'.format(keys_path, keyname), color='lblue')) if PasswdManager.verbose: print(cprepare('New keys saved at :\n - Privkey :', color='blue'), cprepare(privkey, color='lblue'), cprepare('\n - Pubkey :', color='blue'), cprepare(pubkey, color='lblue')) if PasswdManager.verbose: cprint('Encrypting database with the new key pair', color='blue') g.encrypt(passwd, pubkey).save(conf['dbfile'])
def login(username, password): response = login_simple(username, password) # raise errors if response.status_code != 200: raise LoginException(f'LoginError: ' + response.status_code) r_json = response.json() if r_json['code'] != 0: cprint(r_json['message'], color='red') cprint('登录失败(返回值非0)', color='red') cprint('解决方法:重启程序再试(建议仅重试一次)', color='green') raise LoginException(f'LoginError') # handle cookies cookies = {} cookie_source = [cookie for cookie in r_json['data']['cookie_info']['cookies']] for cookie in cookie_source: cookies[cookie['name']] = cookie['value'] # handle tokens tokens = {} token_source = { key:value for key,value in r_json['data']['token_info'].items() } tokens.update(token_source) return { 'app': tokens, 'web': cookies, }
async def run(self): while self.again and self.server != None: try: done, pending = await asyncio.wait( [ self.timeout(), self.connect(), ], loop=self.loop, return_when=asyncio.FIRST_EXCEPTION, ) try: for task in done: if task.exception(): raise task.exception() if not self.accepted: msg = (f'ConnectionRefused: Password mismatch') cprint(f'{msg}', error=True) sys.exit(1) except (ConnectionRefusedError, TimeoutError, OSError): await self.on_refused() except websockets.InvalidMessage: pass except NoAvailableServer: cprint(f'NoAvailableServer: Stop connecting.', error=True) self.again = False self.server = None finally: for task in pending: try: task.cancel() await task except Exception: pass
def list(conf, passwd, passphrase): if PasswdManager.verbose: cprint('Reading and decrypting database', color='blue') g = Giltzarrapo().readEncrypted(conf['dbfile']).decrypt( passwd, conf['privkey'], passphrase) if PasswdManager.verbose: cprint('Fetching rows', color='blue') lines = InternalPasswdManager.getlines(g, '*') if PasswdManager.verbose: cprint('Refreshing database', color='blue') g.encrypt(passwd, conf['pubkey']).save(conf['dbfile']) return lines
def version(conf, passwd, passphrase): if PasswdManager.verbose: cprint('Reading and decrypting database', color='blue') g = Giltzarrapo().readEncrypted(conf['dbfile']).decrypt( passwd, conf['privkey'], passphrase) if PasswdManager.verbose: cprint('Fetching database version', color='blue') version = InternalPasswdManager.getversion(g) if PasswdManager.verbose: cprint('Refreshing database', color='blue') g.encrypt(passwd, conf['pubkey']).save(conf['dbfile']) return version
def introduce_room_contents(self, room): desc = None object_dic = None for e in self.rooms_desc: if e.lower() == room.lower(): desc = self.rooms_desc[e] # print desc object_dic = self.rooms_objs[e] cprint(desc) cprint('You see the following: ') for obj in object_dic: cprint('\t' + obj) return object_dic
def insert(conf, service, user, spasswd, passwd, passphrase): if PasswdManager.verbose: cprint('Reading and decrypting database', color='blue') g = Giltzarrapo().readEncrypted(conf['dbfile']).decrypt( passwd, conf['privkey'], passphrase) if PasswdManager.verbose: cprint('Inserting new row', color='blue') if spasswd == '': spasswd = PasswdManager.passgen() InternalPasswdManager.append( g, '{}\t{}\t{}\n'.format(service, user, spasswd)) if PasswdManager.verbose: ctable(header=['service', 'user', 'password'], data=[[service, user, spasswd]], header_color='blue', rows_color='lblue') if PasswdManager.verbose: cprint('Saving modified database', color='blue') g.encrypt(passwd, conf['pubkey']).save(conf['dbfile'])
def change_date_dialogue(days): if days > 1: cprint("%s days have passed." % days) else: cprint("One day has passed.")
def inspect_detailed(self): cprint(string=("ID: " + self.name), t=0.12) cprint(string='. . . . . ', t=0.30) sleep(0.2) return self.header + '\n' + self.desc_detailed + '\n' + self.footer
def inspect_vague(self): cprint(string=("OBJ-ID: " + self.name), t=0.12) cprint(string='. . . . . ', t=0.30) sleep(0.2) return self.header + '\n' + self.desc_vague
def error(text): cprint(text, color='red')
def print_date(self): cprint('It is currently the year %s, day %s of month %s.' % (self.date.year, self.date.day, self.date.month), 0.02) return 0
async def on_refused(self): msg = (f'ConnectionRefused: Server may be down. ') self.server = self.next_server() msg += f'(Switching to {self.server["address"]})' cprint(f'{msg}', color='yellow')
def cprint(self, *args, color='default', **kwargs): prefix = f'[{self.uid}]' data = ' '.join(args) cprint(f'{prefix:<13} {data}', color=color, **kwargs)
except: break else: command, args = command.split(' ')[0], command.split(' ')[1:] try: if command == 'create': create_args = cm.handle(command, args) if create_args != False: PasswdManager.create(*create_args) elif command == 'import': import_args = cm.handle(command, args) if import_args != False: PasswdManager.importdb(*import_args) elif command == 'passgen': passgen_args = cm.handle(command, args) if passgen_args != False: newpasswd = PasswdManager.passgen(*passgen_args) cprint('Generated password : '******'blue', end="") cprint(newpasswd, color='lblue') elif command == 'clear': clear() elif command == 'help': print_help() elif command == 'use': verify_args = cm.handle(command, args) if verify_args != False: success = PasswdManager.verifyauth(*verify_args) if not success: cprint('Wrong password or/and passphrase', color='red') else: cm.set_auth(*verify_args) elif command == 'insert' or command == 'add': insert_args = cm.handle('insert', args)
import sys from giltzarrapo import Giltzarrapo from printer import cprint, ecprint from datetime import datetime as dt passph = '123' passwd = 'abc' num_process = 3 sb = None if '-e' in sys.argv: #RSA KEYS cprint('Generando claves...', color='cyan', end='\r') s = dt.now() Giltzarrapo.generateRSApair(passphrase=passph) e = dt.now() ecprint(['Generacion de claves ', str(e - s)], color=['cyan', 'yellow'], template='{} : {}') #ENCRYPT g = Giltzarrapo(n_processes=num_process) #read cprint('Leyendo fichero...', color='cyan', end='\r') s = dt.now() g.readPlain('testfile.txt') e = dt.now() ecprint(['Lectura de fichero ', str(e - s)], color=['cyan', 'yellow'], template='{} : {}') #encrypt