async def cas_readblock(key): if len(key) == 42: key = bytes.fromhex(key) elif len(key) == 28: key = base64.urlsafe_b64decode(key) else: raise exceptions.NotFound() if 'walk' in request.args: async def iterator(blocks): for block in blocks: yield block resp = iterator(current_app.fs.cas.walkblocks(key)) elif 'file' in request.args: try: fp = current_app.fs.cas.file_from_key(key) except IOError: raise exceptions.BadRequest() if not fp: raise exceptions.NotFound() return good_response(fp, download=request.args['file'] == 'download') else: resp = current_app.fs.cas.readblock(key) if resp is None: raise exceptions.NotFound() resp = bytes(resp) return Response(resp, content_type='application/octet-stream')
async def _handle_http(self, adapter: str): request: Request = _request try: data: Dict[str, Any] = await request.get_json() except Exception as e: raise exceptions.BadRequest() if adapter not in self._adapters: logger.warning(f'Unknown adapter {adapter}. ' 'Please register the adapter before use.') raise exceptions.NotFound() BotClass = self._adapters[adapter] headers = {k: v for k, v in request.headers.items(lower=True)} try: self_id = await BotClass.check_permission(self, 'http', headers, data) except RequestDenied as e: raise exceptions.HTTPException(status_code=e.status_code, description=e.reason, name='Request Denied') if self_id in self._clients: logger.warning("There's already a reverse websocket connection," "so the event may be handled twice.") bot = BotClass('http', self_id) asyncio.create_task(bot.handle_message(data)) return Response('', 204)
class GuildConfig(Model): """ Configuration for a guild, for storing information about what the guild configured. :param int guild_id: The guild's id. :param bool xp_enabled: Wheter XP for every message is enabled. :param float xp_multiplier: XP multiplier for every message. :param bool eco_enabled: Wheter economy commands are enabled. :param int muted_role_id: The muted role's id. :param bool do_logging: Whether to do logging. :param int log_channel_id: The logging channel's id. :param bool do_verification: Wheter to do verification. :param str verification_type: The verification's type. :param int verification_channel_id: The verification channel's id. """ guild_id = Column( types.ForeignKey("guilds", "id", sql_type=types.Integer(big=True)), primary_key=True, ) xp_enabled = Column(types.Boolean()) xp_multiplier = Column(types.Real()) eco_enabled = Column(types.Boolean()) muted_role_id = Column(types.Integer(big=True), nullable=True) do_logging = Column(types.Boolean()) log_channel_id = Column(types.Integer(big=True), nullable=True) do_verification = Column(types.Boolean()) verification_type = Column(types.String()) # enum verification_channel_id = Column(types.Integer(big=True), nullable=True) @classmethod async def fetch(cls, guild_id: Union[str, int]) -> Optional["GuildConfig"]: """Fetch a GuildConfig with the given guild ID.""" query = "SELECT * FROM guildconfigs WHERE guild_id = $1" record = await cls.pool.fetchrow(query, int(guild_id)) if record is None: return None return cls(**record) @classmethod async def fetch_or_404( cls, guild_id: Union[str, int]) -> Optional["GuildConfig"]: """ Fetch a guild configuration with the given ID or send a 404 error. :param Union[str, int] guild_id: The guild's id. """ if guild_config := await cls.fetch(guild_id): return guild_config http_status = HTTPStatus.NOT_FOUND http_status.description = ( f"Guild with ID {guild_id} doesn't exist or doesn't have a configuration." ) raise exceptions.NotFound(http_status)
async def view_vhost_page(key='index.html'): fs = request.app.fs bucket = request.host path = os.path.join('/', bucket, key) try: fp = fs.open(path) except FileNotFoundError: if path.endswith('/'): try: path += '/index.html' fp = fs.open(path) except FileNotFoundError: raise exceptions.NotFound() else: raise exceptions.NotFound() headers = {} return good_response(fp, headers=headers)
def get_website_index(fs, path, user=None): if fs.get_path_config(path).get('website'): index_path = os.path.join(path, 'index.html') try: return fs.open(index_path, owner=user or '*') except FileNotFoundError: path = index_path from quart import exceptions raise exceptions.NotFound()
class Guild(Model): """ Guild model for storing information about discord guilds. :param int id: The guilds id. :param str name: The guilds name. :param int owner_id: The guilds owner id. :param Optional[str] icon_hash: The guilds icon hash. """ id = Column(types.Integer(big=True), primary_key=True) name = Column(types.String()) owner_id = Column(types.Integer(big=True)) icon_hash = Column(types.String(), nullable=True) @classmethod async def fetch(cls, id: Union[str, int]) -> Optional["Guild"]: """Fetch a guild with the given ID.""" query = "SELECT * FROM guilds WHERE id = $1" record = await cls.pool.fetchrow(query, int(id)) if record is None: return None return cls(**record) @classmethod async def fetch_or_404(cls, id: Union[str, int]) -> Optional["Guild"]: """ Fetch a guild with the given ID or send a 404 error. :param Union[str, int] guild_id: The guild's id. """ if guild := await cls.fetch(id): return guild http_status = HTTPStatus.NOT_FOUND http_status.description = f"Guild with ID {id} doesn't exist." raise exceptions.NotFound(http_status)
async def _handle_ws_reverse(self, adapter: str): websocket: QuartWebSocket = _websocket if adapter not in self._adapters: logger.warning( f'Unknown adapter {adapter}. Please register the adapter before use.' ) raise exceptions.NotFound() BotClass = self._adapters[adapter] headers = {k: v for k, v in websocket.headers.items(lower=True)} try: self_id = await BotClass.check_permission(self, 'websocket', headers, None) except RequestDenied as e: print(e.reason) raise exceptions.HTTPException(status_code=e.status_code, description=e.reason, name='Request Denied') if self_id in self._clients: logger.warning("There's already a reverse websocket connection," "so the event may be handled twice.") ws = WebSocket(websocket) bot = BotClass('websocket', self_id, websocket=ws) await ws.accept() logger.opt(colors=True).info( f"WebSocket Connection from <y>{adapter.upper()} " f"Bot {self_id}</y> Accepted!") self._bot_connect(bot) try: while not ws.closed: data = await ws.receive() if data is None: continue asyncio.create_task(bot.handle_message(data)) finally: self._bot_disconnect(bot)
async def simple_api(path): path = unquote('/' + path) fs = current_app.fs user = auth.user_from_request(fs, request) username = user['username'] if user else '*' if request.method == 'GET': if path.endswith('/'): enc = JSONEncoder() listiter = fs.listdir(path, owner=username) async def iterator(): for p in listiter: p1 = p.to_dict() del p1['data'] del p1['history_key'] r = (enc.encode(p1) + '\n').encode('utf8') yield r return Response(iterator(), status=200, content_type='application/json') try: rev = request.args.get('rev', None) if rev: rev = int(rev) fp = fs.open(path, owner=username, rev=rev) except (FileNotFoundError, ValueError): raise exceptions.NotFound() except PermissionError: raise exceptions.Forbidden() headers = {} return good_response(fp, headers=headers) elif request.method == 'PUT': ctype = request.headers.get('content-type', '') print('UPLOADING', path, request.headers, ctype) try: with fs.open(path, mode='w', owner=username) as fp: fp.do_hash('md5') fp.content_type = ctype for metakey in request.headers: if metakey.startswith('x-amz-meta-'): metavalue = request.headers[metakey] metakey = metakey[11:] fp.meta[metakey] = metavalue expiration = request.headers.get('Expires', None) if expiration: fp.meta['expiration'] = float(expiration) await aws.read_request(request, fp) except FileNotFoundError: raise exceptions.NotFound() except PermissionError: raise exceptions.Forbidden() return Response(fp.meta['md5']) elif request.method == 'DELETE': try: if fs.delete(path, owner=username): return Response('') else: raise exceptions.NotFound() except PermissionError: raise exceptions.Forbidden() return Response('')