def load_censors(self): """Load a list of banned words to scrub from chats.""" try: with open("config/censors.yaml", "r", encoding="utf-8") as censors: self.censors = yaml.safe_load(censors) except Exception: logger.debug("Cannot find censors.yaml")
def load_censors(self): """Load a list of banned words to scrub from chats.""" try: with open('config/censors.yaml', 'r', encoding='utf-8') as censors: self.censors = yaml.safe_load(censors) except: logger.debug('Cannot find censors.yaml')
def postEvent(eventType, data, namespace=None, room=None): if not isinstance(data, dict): return error_response(500, "Message data must be of type dict.") headers = { 'Authorization': 'Bearer {}'.format(app.config.get('SERVICE_TOKEN')), 'Content-Type': 'application/json' } emit = { 'eventType': eventType, 'data': data, 'namespace': namespace, 'room': room, } with app.test_request_context(): url = url_for('message_api.emit_message', _external=True) try: resp = requests.post(url, json=emit, headers=headers) except: logger.debug('Failed to post to url: {}'.format(url)) abort(500) return resp
def decorated_function(*args, **kwargs): if not 'Authorization' in request.headers: response = jsonify(message='Missing authorization header') response.status_code = 401 return response # try parser json web token try: json_web_token = parse_token(request) access_token = get_oauth_token(json_web_token) logger.debug('access_token: %s' % access_token) user = validate_token(access_token) if user is None: response = jsonify(message='Check user token failed') response.status_code = 403 return response return fn(user=user, *args, **kwargs) except DecodeError: response = jsonify(message='Token is invalid') response.status_code = 401 return response except ExpiredSignature: response = jsonify(message='Token has expired') response.status_code = 403 return response
def load_ipranges(self): """Load a list of banned IP ranges.""" try: with open("config/iprange_ban.txt", "r", encoding="utf-8") as ipranges: self.ipRange_bans = ipranges.read().splitlines() except Exception: logger.debug("Cannot find iprange_ban.txt")
def load_iniswaps(self): """Load a list of characters for which INI swapping is allowed.""" try: with open("config/iniswaps.yaml", "r", encoding="utf-8") as iniswaps: self.allowed_iniswaps = yaml.safe_load(iniswaps) except Exception: logger.debug("Cannot find iniswaps.yaml")
def load_iniswaps(self): """Load a list of characters for which INI swapping is allowed.""" try: with open('config/iniswaps.yaml', 'r', encoding='utf-8') as iniswaps: self.allowed_iniswaps = yaml.safe_load(iniswaps) except: logger.debug('Cannot find iniswaps.yaml')
def load_ipranges(self): """Load a list of banned IP ranges.""" try: with open('config/iprange_ban.txt', 'r', encoding='utf-8') as ipranges: self.ipRange_bans = ipranges.read().splitlines() except: logger.debug('Cannot find iprange_ban.txt')
def LOG(*args): message = "" for item in enumerate(args): if isinstance(item[1], (int, long)): message += " " + str(item[1]) else: message += " " + item[1] logger.debug('%s:%s', request.remote_addr, message)
def search_by_query(self, index, query, size): """ Sample of query: {"query": {"match_all": {}}} """ resp = self.es.search(index=index, body=query, size=size) logger.debug("%d documents found" % resp['hits']['total']) return resp
def __load_packages(self) -> None: """ Executes packages on_load method """ order = self.__get_load_order() for package in order: package_instance = package() logger.debug(f"Package load: {str(package_instance)}") package_instance.on_load()
def search_stack(self, q): query = {"query": {"query_string": {"query": q}}} logger.debug('query %s' % query) data = self.search_by_query('stack', query, 2500) list_stack = [] for item in data['hits']['hits']: list_stack.append(item['_source']) return list_stack
def _add_offer( self, action: Add, item_factory: ItemFactory = Provide[AppContainer.items.factory], ) -> None: # Todo: Add taxation items = [self.inventory.get(item_id) for item_id in action.items] self.response.items.del_.extend(item.copy(deep=True) for item in items) self.inventory.remove_items(items) required_items: List[Item] = [] for requirement in action.requirements: # TODO: This will probably cause issues with nested items, create_item function have to be changed required_items_list = item_factory.create_items( requirement.template_id, requirement.count) for item, children in required_items_list: required_items.extend([item, *children]) selling_price_rub = self.flea_market.items_price(required_items) selling_time: timedelta = self.flea_market.selling_time( items, selling_price_rub) logger.debug(f"Requirements cost in rubles: {selling_price_rub}") logger.debug(f"Selling time: {selling_time}") will_sell_in_24_h = selling_time < timedelta(days=1) if will_sell_in_24_h: # "5bdac0b686f7743e1665e09e": "Your {soldItem} {itemCount} items was bought by {buyerNickname}", sent_at = datetime.now() + selling_time message = MailDialogueMessage( dt=int(sent_at.timestamp()), hasRewards=True, uid=TraderType.Ragman.value, type=MailMessageType.FleamarketMessage.value, templateId="5bdac0b686f7743e1665e09e", items=MailMessageItems.from_items(required_items), systemData={ "soldItem": items[0].tpl, "itemCount": str(items[0].upd.StackObjectsCount), "buyerNickname": "Nikita", }, ) self.profile.mail.add_message(message) else: # "5bdac06e86f774296f5a19c5": "The item was not sold", sent_at = datetime.now() + timedelta(days=1) message = MailDialogueMessage( dt=int(sent_at.timestamp() + 5), hasRewards=True, uid=TraderType.Ragman.value, type=MailMessageType.FleamarketMessage.value, templateId="5bdac06e86f774296f5a19c5", items=MailMessageItems.from_items(items), ) self.profile.mail.add_message(message)
def revoke_token(access_token): h = Http() logger.debug('revoking %s' % access_token) resp, cont = h.request( 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token, headers={ 'Host': 'www.googleapis.com', 'Authorization': access_token }) return resp
def build_music_list_ao2(self, music_list): song_list = [] for item in music_list: if 'category' not in item: #skip settings n stuff continue song_list.append(item['category']) for song in item['songs']: if self._is_valid_song_name(song['name']): song_list.append(song['name']) else: logger.debug(f"{song['name']} is not a valid song name") return song_list
def update(self) -> None: self.current_time = int(time.time()) self.time_elapsed = self.current_time - self.metadata["updated_at"] time_generator_worked = self.__update_fuel() skip_time = self.time_elapsed - time_generator_worked logger.debug(f"Generator worked for: {time_generator_worked}") logger.debug(f"Time skipped: {skip_time}") self.__update_production_time(self.time_elapsed, time_generator_worked) self.metadata["updated_at"] = self.current_time
def handleGithubError(error, data={}): status = error.args[0] errorData = error.args[1] resp = { 'data': data, 'error': errorData, } logger.debug( 'Received GitHub Error with Status {status}. Error: {errorData}'. format(status=status, errorData=errorData)) return resp, status
def __import_packages(self) -> None: """ Imports top-level packages in self.packages_dir directory """ for module_path in (d for d in self.packages_dir.glob("*") if d.is_dir()): module_name = ".".join(module_path.relative_to(root_dir).parts) module = importlib.import_module(module_name) if hasattr(module, "Package"): package: Type[PackageBase] = getattr(module, "Package") package.path = module_path logger.debug(f"Package import: {package.Meta.name}") self.register(package)
def build_music_pages_ao1(self, music_list): song_list = [] index = 0 for item in music_list: if 'category' not in item: continue song_list.append('{}#{}'.format(index, item['category'])) index += 1 for song in item['songs']: if self._is_valid_song_name(song['name']): song_list.append('{}#{}'.format(index, song['name'])) index += 1 else: logger.debug(f"{song['name']} is not a valid song name") song_list = [song_list[x:x + 10] for x in range(0, len(song_list), 10)] return song_list
def check_payload(ok, data): if ok: str_code = data['payload']['data']['base64_code'] if ',' not in str_code: logger.debug("Wrong parameter: %s" % data) return False, build_result(APIStatus.BadRequest) base64_code = str_code.split(',')[1] cond1 = is_base64_code(base64_code) if not cond1: logger.debug("Wrong parameter: %s" % data) return False, build_result(APIStatus.BadRequest) return ok, data
async def generate_bots( request: Request, bot_generator: BotGenerator = Depends(Provide[BotContainer.bot_generator]), ) -> TarkovSuccessResponse[List[dict]]: bots: List[dict] = [] request_data: dict = await request.json() logger.debug(request_data) for condition in request_data["conditions"]: bot_limit = condition["Limit"] for _ in range(bot_limit): bot = bot_generator.generate(bot_role="assault") bots.append(bot) return TarkovSuccessResponse(data=bots)
def dispatch(self, request_data: List[dict]) -> DispatcherResponse: self.inventory = self.profile.inventory self.__make_dispatchers() actions: List[dict] = request_data for action in actions: logger.debug(action) for dispatcher in self.dispatchers: try: dispatcher.dispatch(action) break except NotImplementedError: pass else: raise NotImplementedError( f"Action {action} not implemented in any of the dispatchers" ) return self.response
def assign_prop(cls, values: dict) -> dict: # pylint: disable=no-self-argument, no-self-use if values["_type"] != "Item": return values if isinstance(values["_props"], BaseItemProps): return values props = values["_props"] try: model = props_models_map[values["_parent"]] except KeyError as e: raise KeyError( f"Props class for node with id {values['_parent']} was not found" ) from e try: values["_props"] = model.parse_obj(props) except ValidationError as e: logger.debug(values["_id"]) logger.debug(e) raise return values
async def notifierserver_get( profile_id: str, notifier: NotifierService = Depends( Provide[AppContainer.notifier.service]), ) -> PlainTextResponse: for _ in range(90): if notifier.has_notifications(profile_id): notifications = notifier.get_notifications_view(profile_id) logger.debug(f"New notifications for profile {profile_id}") logger.debug(notifications) response = "\n".join([ orjson.dumps(notification).decode("utf8") for notification in notifications ]) logger.debug(f"NotifierService response: {response}") return PlainTextResponse( content=response, media_type="application/json", ) await asyncio.sleep(1) return PlainTextResponse( content=orjson.dumps({ "type": "ping", "eventId": "ping" }), media_type="application/json", )
def __update_offers(self) -> None: """ Clears expired offers and generates new ones until we have desired amount """ self.__clear_expired_offers() now = datetime.now() time_elapsed = now - self.updated_at self.updated_at = now try: keys_to_delete = random.sample(list(self.offers.keys()), k=int(time_elapsed.total_seconds())) except ValueError: keys_to_delete = [] for key in keys_to_delete: del self.offers[key] new_offers_amount: int = self.offers_amount - len(self.offers) new_offers = self.generator.generate_offers(new_offers_amount) logger.debug(f"Generated {len(new_offers)} items!") self.offers.update(new_offers)
def post(self): super().post() self.add_argument('namespace', type=str, required=False, location='json') self.namespace = self.args.get('namespace') self.add_argument('eventType', type=str, required=True, location='json') try: self.event_type = Event_Types(self.args.get('eventType')) except ValueError as e: abort( 400, message= 'Invalid eventType provided: {}. Valid event types include: {}' .format(self.args.get('eventType'), getAllEventTypes())) self.add_argument('room', type=str, required=False, location='json') self.room = self.args.get('room') self.add_argument('data', type=dict, required=True, location='json') self.data = self.args.get('data') logger.debug('Emitting {event_type} to {room}: {data}'.format( event_type=self.event_type.value, room=self.room, data=self.data)) emitEvent(self.event_type.value, self.data, namespace=self.namespace, room=self.room) return
def get_load_order(self) -> PackageTypeList: in_order: PackageTypeList = [] dependency_graph: Dict[PackageType, PackageTypeList] = { pkg: [ self.__get_package_with_name(name) for name in pkg.Meta.dependencies ] for pkg in self.packages } logger.debug(f"Dependency graph: {dependency_graph}") pkg_with_no_deps = [ pkg for pkg, pkg_deps in dependency_graph.items() if not pkg_deps ] logger.debug(f"pkg_with_no_deps: {pkg_with_no_deps}") if not pkg_with_no_deps and dependency_graph: raise NoBasePackageError dependency_graph = { pkg: [d for d in deps if d not in pkg_with_no_deps] for pkg, deps in dependency_graph.items() if pkg not in pkg_with_no_deps } while pkg_with_no_deps: pkg = pkg_with_no_deps.pop() in_order.append(pkg) for package, dependencies in dependency_graph.items(): try: dependencies.remove(pkg) except ValueError: pass if not dependencies: pkg_with_no_deps.append(package) del dependency_graph[package] break if dependency_graph: logger.debug(dependency_graph) for pkg, deps in dependency_graph.items(): raise CycleDependencyError(package=pkg, dependencies=deps) return in_order
def get_urls(source): urls = source['payload']['data']['image_address'] if urls != '': logger.debug("The request data:%s" % urls) return urls
async def log_response_time(request: Request, call_next: Callable) -> Response: start_time = time.time() response = await call_next(request) response_time = round(time.time() - start_time, 3) logger.debug(f"Response time: {response_time}s") return response
def save_document(self, index, document_type, document, id=None): res = self.es.index(index=index, doc_type=document_type, body=document, id=id) logger.debug("Created documento ID %s" % res['_id'])
def google(): access_token_url = 'https://www.googleapis.com/oauth2/v4/token' people_api_url = 'https://www.googleapis.com/oauth2/v3/userinfo' tokeninfo_url = 'https://www.googleapis.com/oauth2/v3/tokeninfo' logger.debug('google request =>') logger.debug(request.json) payload = dict(client_id=request.json['clientId'], redirect_uri=request.json['redirectUri'], client_secret=app.config['GOOGLE_CLIENT_SECRET'], code=request.json['code'], grant_type='authorization_code') logger.debug('Google Payload =>') logger.debug(payload) # Step 2. Exchange authorization code for access token. r = requests.post(access_token_url, data=payload) token = json.loads(r.text) logger.debug('Access Token =>') logger.debug(token) # Step 2. Retrieve information about the current user. # create user if not exists one headers = {'Authorization': 'Bearer {0}'.format(token['access_token'])} r = requests.get(people_api_url, headers=headers) profile = json.loads(r.text) logger.info('Login as => %s' % profile['email']) logger.debug(profile) if security.is_valid_email(profile['email']): # Step 4. Create a new account or return an existing one. r = requests.get('%s?access_token=%s' % (tokeninfo_url, token['access_token'])) token_info = json.loads(r.text) logger.debug('Tokeninfo =>') logger.debug(token_info) # u = User(id=profile['sub'], provider='google', # display_name=profile['name']) # Step 5. Create a new account or return an existing one. payload = { 'sub': profile['sub'], 'iat': datetime.utcnow(), 'exp': token_info['exp'], 'access_token': token['access_token'] } jwt = security.create_token(payload) return jsonify(token=jwt) else: return not_authorized( 403, 'Invalid email domain. Please sign with ciandt.com acccount')