async def index_route(request): if request.path in STATICS: return web.FileResponse(os.path.join(DIST_PATH, request.path)) return web.FileResponse(INDEX_PATH)
async def serve_file(request: web.Request) -> web.FileResponse: """Serve file from disk.""" if cache_headers: return web.FileResponse(path, headers=CACHE_HEADERS) return web.FileResponse(path)
async def serve_file(request): """Serve file from disk.""" return web.FileResponse(path, headers=CACHE_HEADERS)
async def favicon(request): return web.FileResponse("static/favicon.ico")
async def index(request): return web.FileResponse('./templates/index.html')
async def index(_): return web.FileResponse(STATIC_PATH + '/index.html')
async def index(request): return web.FileResponse('./web/index.html')
async def download(request): path_ = os.path.join(path, request.match_info.get('path')) if os.path.isfile(path_): return web.FileResponse(path_) else: return web.Response(status=404)
async def http_handler(request): if request.rel_url.path == "/": return web.FileResponse("index.html") else: return web.FileResponse("imgs/" + request.rel_url.path[1:])
async def index(r): f = r.app['config']['path']['frontend_dir'] / 'index.html' return web.FileResponse(f)
async def index(self, request: web.Request) -> web.FileResponse: path = str(self._root / 'static' / 'index.html') return web.FileResponse(path)
def index(request): return web.FileResponse('ui/dist/metube/index.html')
async def index(request: web.Request) -> web.StreamResponse: return web.FileResponse('./static/index.html')
async def index_handler(request: web.Request): return web.FileResponse('client/dist/index.html')
async def archive_get_routing(request: web.Request) -> web.StreamResponse: if (GIT_ARCHIVER_ACCESS_KEY and request.headers.get('Authorization', '') != 'Bearer %s' % GIT_ARCHIVER_ACCESS_KEY): return web.HTTPUnauthorized() try: repo = request.query['repo'].strip() clone_options = request.query.get('clone_options', '').strip() disk_quota = int( request.query.get('disk_quota', GIT_ARCHIVER_MAX_DISK_QUOTA)) except Exception: return web.HTTPBadRequest( text='Failed to parse all required parameters') if not (0 < disk_quota <= GIT_ARCHIVER_MAX_DISK_QUOTA): return web.HTTPBadRequest(text='Invalid `disk_quota` parameter') loop = asyncio.get_event_loop() with tempfile.NamedTemporaryFile('w', dir=GIT_ARCHIVER_ARCHIVE_VOLUME_PATH, encoding='utf-8') as run_sh_file: archive_name = '%s.zip' % uuid.uuid4().hex run_sh_file.write( WORKER_CMD_TEMPLATE.format(repo=repo, clone_options=clone_options, archive_filename='/output_mnt/%s' % archive_name)) run_sh_file.flush() archive_host_filename = os.path.join(GIT_ARCHIVER_ARCHIVE_VOLUME_PATH, archive_name) worker_container = None try: async with concurrent_job_semaphore: worker_container = await loop.run_in_executor( thread_executor, functools.partial( docker_client.containers.create, GIT_ARCHIVER_DOCKER_WORKER_IMAGE, ['bash', '/run.sh'], mounts=[ docker.types.Mount('/run.sh', run_sh_file.name, type='bind', read_only=True), docker.types.Mount( '/output_mnt', GIT_ARCHIVER_ARCHIVE_VOLUME_PATH, type='bind'), docker.types.Mount('/tmpfs_mnt', '', type='tmpfs', tmpfs_size=disk_quota) ], user=os.getuid() # type: ignore )) await loop.run_in_executor(thread_executor, worker_container.start) worker_result = await loop.run_in_executor( thread_executor, functools.partial(worker_container.wait, timeout=GIT_ARCHIVER_TIMEOUT)) worker_logs = await loop.run_in_executor( thread_executor, worker_container.logs) worker_logs = worker_logs.decode('utf-8') if worker_result['StatusCode'] != 0: return web.HTTPBadRequest( text= 'Worker is terminated with non-zero status code\n===\n%s' % worker_logs) if not os.path.exists(archive_host_filename): return web.HTTPBadRequest( text='Archive file is not created\n===\n%s' % worker_logs) resp = web.FileResponse(archive_host_filename, headers={ 'Content-Disposition': 'attachment; filename="%s"' % archive_name }) await resp.prepare(request) # TODO: dirty hack to prevent double calling of `FileResponse.prepare()` async def _dummy_prepare(request): return None resp.prepare = _dummy_prepare # type: ignore # From here, `archive_host_filename` doesn't need to be accessbiel anymore return resp except asyncio.CancelledError: logger.debug('The request is cancelled') raise except Exception: logger.exception('Failed to archive git repo') return web.HTTPServerError(text='Unexpected error is occured') finally: if worker_container is not None: await loop.run_in_executor( thread_executor, functools.partial(worker_container.remove, force=True)) if os.path.exists(archive_host_filename): os.unlink(archive_host_filename)
async def main(request): return web.FileResponse(os.path.join(STATIC_DIR, 'index.html'))
async def get(self, request): """Retrieve API error log.""" if not request["hass_user"].is_admin: raise Unauthorized() return web.FileResponse(request.app["hass"].data[DATA_LOGGING])
def maker(*args, **kwargs): ret = web.FileResponse(*args, **kwargs) if request.param == 'fallback': ret._sendfile = ret._sendfile_fallback return ret
async def root(_): return web.FileResponse('haxball/static/index.html')
def index_handler(self, request): return web.FileResponse('./web/index.html')
async def png(self, request): headers = {'content-type': 'image/png'} return web.FileResponse('./web_app/assets/apple-touch-icon.png')
async def handle(request): return web.FileResponse(FILENAME)
def serve_widgetfile(request): filepath = os.path.join(au.get_modules_dir(), 'webviewerwidgets', request.match_info['module_dir'], request.match_info['filename']) if os.path.exists(filepath): return web.FileResponse(filepath)
def get_panel(request): """Return file response with panel.""" return web.FileResponse(panel)
async def download(self, request): name = request.headers.get('file') file_path, headers = await self.find_file(name) if file_path: return web.FileResponse(path=file_path, headers=headers) return web.HTTPNotFound(body='File not found')
async def get_model(request): model_name = request.match_info.get("model_name") return web.FileResponse( path=os.path.join("models", app["bpmn_models"][model_name].model_path))
async def index(_): """Serve frontend files.""" return web.FileResponse(os.path.join(STATIC_FOLDER_PATH, 'index.html'))
async def _handler( self, request: web.Request) -> Union[web.Response, web.FileResponse]: """ Super simple HTTP handler. Parameters ---------- request : web.Request AIOHTTP request object. """ if request.method == 'GET': if request.path == '/match': self.logger.debug( f'{request.remote} accessed {self.IP}:{self.port}/match') return web.FileResponse('./match_config.json') elif request.path == '/map-veto': self.logger.debug( f'{request.remote} accessed {self.IP}:{self.port}/map-veto' ) self.map_veto_image_path = self.create_new_veto_filepath() response = {'path': self.map_veto_image_path} return web.json_response(response) elif request.path == self.map_veto_image_path: self.logger.debug( f'{request.remote} accessed {self.IP}:{self.port}/{self.map_veto_image_path}' ) return web.FileResponse('./result.png') else: self.logger.debug( f'{request.remote} accessed {self.IP}:{self.port}{request.path}' ) if os.path.isfile(f'./{request.path}.json'): self.logger.info('File Found') return web.FileResponse(f'./{request.path}.json') else: self.logger.error('Invalid Request, File not Found') return WebServer._http_error_handler('file not found') # or "Authorization" elif request.method == 'POST': try: get5_event = await request.json() except JSONDecodeError: self.logger.warning( f'{request.remote} sent a invalid json POST ') return WebServer._http_error_handler('json-body') # TODO: Create Checks for the JSON server = None for csgo_server in self.csgo_servers: if socket.gethostbyname( csgo_server.server_address) == request.remote: server = csgo_server break if server is not None: self.logger.debug( f'ServerID={server.id} ({request.remote})=\n {pprint.pformat(get5_event)}' ) if get5_event['event'] == 'knife_start': score_embed = discord.Embed() score_embed.add_field(name=f'0', value=f'{server.team_names[0]}', inline=True) score_embed.add_field(name=f'0', value=f'{server.team_names[1]}', inline=True) gotv = server.get_gotv() if gotv is None: score_embed.add_field(name='GOTV', value='Not Configured', inline=False) else: score_embed.add_field( name='GOTV', value=f'connect {server.server_address}:{gotv}', inline=False) score_embed.set_footer(text="🟢 Live") await server.score_message.edit(embed=score_embed) elif get5_event['event'] == 'round_end': server.update_team_scores([ get5_event["params"]["team1_score"], get5_event["params"]["team2_score"] ]) score_embed = discord.Embed() score_embed.add_field( name=f'{get5_event["params"]["team1_score"]}', value=f'{server.team_names[0]}', inline=True) score_embed.add_field( name=f'{get5_event["params"]["team2_score"]}', value=f'{server.team_names[1]}', inline=True) gotv = server.get_gotv() if gotv is None: score_embed.add_field(name='GOTV', value='Not Configured', inline=False) else: score_embed.add_field( name='GOTV', value=f'connect {server.server_address}:{gotv}', inline=False) score_embed.set_footer(text="🟢 Live") await server.score_message.edit(embed=score_embed) if get5_event['event'] == 'series_end' or get5_event[ 'event'] == 'series_cancel' or get5_event[ 'event'] == 'map_end': if get5_event['event'] == 'series_end': await server.score_message.edit(content='Game Over') elif get5_event['event'] == 'series_cancel': self.logger.info( f'ServerID={server.id} | Admin Cancelled Match') await server.score_message.edit( content='Game Cancelled by Admin') # Temporary fix, Get5 breaks on a series cancel unless map changes valve.rcon.execute( (server.server_address, server.server_port), server.RCON_password, 'sm_map de_mirage') score_embed: discord.Embed = server.score_message.embeds[0] score_embed.set_footer(text='🟥 Ended') await server.score_message.edit(embed=score_embed) if os.path.exists(f'./{get5_event["matchid"]}.json'): os.remove(f'./{get5_event["matchid"]}.json') self.logger.debug( f'Deleted {get5_event["matchid"]}.json') else: self.logger.error( f'Could not delete {get5_event["matchid"]}.json, file does not exist' ) if self.bot.cogs['CSGO'].pug.enabled: for player in server.players: try: await player.move_to( channel=server.channels[0], reason=f'Game Over') except discord.HTTPException: traceback.print_exc() print(f'Unable to move {player}') await server.channels[1].delete(reason='Game Over') await server.channels[2].delete(reason='Game Over') server.make_available() self.csgo_servers.remove(server) else: # Used to decline any requests what doesn't match what our # API expects. self.logger.warning(f'{request.remote} sent an invalid request.') return WebServer._http_error_handler("request-type") return WebServer._http_error_handler()
async def serve_file(request): """Serve file from disk.""" return web.FileResponse(path)
async def fn(_): return web.FileResponse(path)