async def fbgraph_query(self, resource, extra_params={}, credentials=None, version_segment=API_3_3): """ graph.facebook.com/debug_token? input_token={token-to-inspect} &access_token={app-token-or-admin-token} """ params = {} if credentials is None: params['access_token'] = self.access_token if credentials: params['access_token'] = credentials.get('access_token') params.update(extra_params) async with aiohttp.ClientSession() as session: url = f'https://graph.facebook.com/{version_segment}' + resource logger.debug(f'quering {url}', params=params) async with session.get(url, params=params) as response: if response.status == 200: return await response.json() logger.error('fbgraph_query error', status=response.status, text=(await response.text()))
async def chech(p, params): asyncio.sleep(random()*1) check = Prodict(success=0, region=p.cityRu) check.update({k: p[k] for k in copyattrs}) try: state.myiter() async with aiohttp.ClientSession() as chs: proxy_auth = aiohttp.BasicAuth(p.user, p.password) hostport = f"http://{p.host.strip()}:{p.port}" async with chs.get(test_url, proxy=hostport, proxy_auth=proxy_auth, timeout=10) as pr: check.responseCode = pr.status if pr.status == 200: check.success = 1 check.contentSize = len(await pr.text()) async with chs.get(check_ip, proxy=hostport, proxy_auth=proxy_auth, timeout=10) as ip_r: if ip_r.status == 200: check.extIp = (await ip_r.text()).strip() state.succ() except ClientConnectorError: logger.warn('connection error: %s:%s', p.host, p.port) except asyncio.TimeoutError: logger.warn('asyncio timeout') except TimeoutError: logger.warn('timeout') except Exception: logger.exception('check err') await asyncio.sleep(1) try: async with aiohttp.ClientSession() as ss: async with ss.post(params.notify, json=check, timeout=10) as wh_r: if wh_r.status != 200: logger.error('webhook failed') except Exception: logger.exception('sending webhook err')
async def do_query(url, params, json=None): method = 'post' if json else 'get' async with aiohttp.ClientSession() as session: async with session.request(method, url, params=params, json=json) as resp: resp_data = await resp.json() if resp.status == 200: logger.debug('resp data', rd=resp_data, code=resp.status) return resp_data else: logger.error('wrong response', rd=resp_data, code=resp.status)
async def get_actual_server_status(): query = """ SELECT MAX(dateTime) as last_point FROM events FORMAT JSON """ try: res = await ch.select(query) # datetime.timedelta(hours=3) - поправка на Москву curr_date_in_ch = dateutil.parser.parse(json.loads(res)['data'][0]['last_point']) + datetime.timedelta(hours=3) return curr_date_in_ch except Exception as ex: logger.error('CH exception: {}'.format(ex)) return None
async def common_stat(**params): where = stat_queries.events_where() query = stat_queries.groups(where) + stat_queries.FMT_JSON try: async with timeout(1): stat_groups = await ch.select(query) if stat_groups: return ujson.loads(stat_groups)['data'] except asyncio.TimeoutError: logger.error('stat get error') except asyncio.CancelledError: pass return []
async def worker(): logger.info('isolve_status_bot has been started') # Get current webhook status webhook = await bot.get_webhook_info() logger.error(f'Old webhook: {webhook}') # If URL is bad if webhook.url != WEBHOOK_URL: # If URL doesnt match current - remove webhook if not webhook.url: await bot.delete_webhook() # Set new URL for webhook await bot.set_webhook(WEBHOOK_URL) await status_checker()
async def clean_worker(self): while True: # Remove expired services try: await asyncio.sleep(5) await self.resolve_docstatus_all() await self.check_regs_changed() except ConnectionRefusedError: logger.error('Redis connection refused') except asyncio.CancelledError: logger.warn('Asyncio cancelled') break except Exception: logger.exception('state initialize') await asyncio.sleep(1)
async def reader(): url = 'https://bolt.rstat.org/public/dg-lessons/100stripusers.log' async with aiohttp.ClientSession() as session: async with session.get(url) as res: if res.status == 200: while True: data = await res.content.read(102400) if not data: break yield data # async for block in res.content.read(102400): # yield block else: text = res.text() logger.error(f'request error', s=res.status, t=text, h=res.headers)
async def redirback(uid, data, **params): """ """ logger.debug('fb login', u=uid, d=data, p=params) code = data.get('code') redir_state = data.get('state') if not code: return response.error('Code is absent') if not redir_state: return response.error('Invalid state') credentials = await client.exchange_code(code) if not credentials: return response.error('Couldn\'t get credentials') me = await client.me(credentials) if not me: return response.error('Couldn\'t get user info (me)') token_debug = await client.debug_token(credentials.get('access_token')) logger.debug('debug token; me resp', debresp=token_debug, meresp=me) stored_data = await id_get_redir_data(redir_state) if not stored_data or not stored_data.get('redir_data'): logger.warn('absent redir state', uid=uid, data=data) redir_data = stored_data.get('redir_data') source_sids = redir_data.get('sids') if not source_sids: logger.error('Invalid state contents', state=redir_data) return response.error('Invalid state contents') base_vars = { 'ctime': msec(), 'source': 'fbauth', 'event_id': params.get('id') } fb_params = {'access_token': credentials.get('access_token'), **base_vars} logger.debug('redir data', r=redir_data) source_sids_with_params = [( v, { **base_vars }, ) for k, v in source_sids.items()] uid_id = ( 'uid', uid, ) uid_id_with_params = ( uid_id, base_vars, ) fb_id = ( 'fb', me.get('id'), ) fb_id_with_params = ( fb_id, fb_params, ) additional_ids = [uid_id_with_params, fb_id_with_params] # save fb-to-phone,tg await id_update(fb_id, source_sids_with_params) # save uid-to-fb-tg-phone uid_sids = [*source_sids_with_params, fb_id_with_params] logger.debug('uid sids', uid_id=uid_id, usids=uid_sids) await id_update(uid_id, uid_sids) # save phone-to-uid,fb if source_sids.get('phone'): await id_update(source_sids['phone'], additional_ids) profile = await id_lookup(source_sids['phone']) logger.debug('new profile', profile) if source_sids.get('tg'): await bot_chat_event(sid_chat=source_sids['tg'], name='fblogin', data=me) return response.redirect(cfg.urls.alena_success.url)