Return a converted MP3 file.

@param Request  $request  PSR-7 request
@param Response $response PSR-7 response

@return Response HTTP response
499655
private function getConvertedAudioResponse(Request $request, Response $response)
    {
        $from = $request->getQueryParam('from');
        $to = $request->getQueryParam('to');

        $response = $response->withHeader(
            'Content-Disposition',
            'attachment; filename="'.
            $this->video->getFileNameWithExtension('mp3').'"'
        );
        $response = $response->withHeader('Content-Type', 'audio/mpeg');

        if ($request->isGet() || $request->isPost()) {
            try {
                $process = $this->video->getAudioStream($from, $to);
            } catch (Exception $e) {
                // Fallback to default format.
                $this->video = $this->video->withFormat($this->defaultFormat);
                $process = $this->video->getAudioStream($from, $to);
            }
            $response = $response->withBody(new Stream($process));
        }

        return $response;
    }
135372
public function doFilter(Request $request, Response $response)
    {
        if ((int) $request->get('error') === 1) {
            return
                $response
                    ->withStatusCode(404)
                    ->write('error')
            ;
        }
    }
1088042
public function parse( Request $request, Response $response )
    {
        $error = parent::parse( $request, $response );

        if ( $error )
        {
            return $error;
        }

        $body = json_decode( $request->getContent() );

        if ( empty( $body ) )
        {
            return self::PARSE;
        }

        if ( empty( $body->method ) || ! isset( $body->params ) )
        {
            return self::INVALID_REQUEST;
        }

        $this->id       = $body->id;
        $this->method   = $body->method;
        $this->params   = $body->params;

        return null;
    }
1002079
protected function createPsr7Response(Response $response)
    {
        return new PsrResponse(
            $response->getStatusCode(),
            $response->headers->all(),
            $response->getContent(),
            $response->getProtocolVersion()
        );
    }
967311
protected function _createPsr7Request(Request $request, Connection $connection)
    {
        $req = new Psr7\Request(
            $request->getMethod(),
            $this->_getActionPath($request),
            $connection->hasConfig('headers') && \is_array($connection->getConfig('headers'))
                ? $connection->getConfig('headers')
                : []
        );

        $data = $request->getData();
        if (!empty($data) || '0' === $data) {
            if (Request::GET == $req->getMethod()) {
                $req = $req->withMethod(Request::POST);
            }

            if ($this->hasParam('postWithRequestBody') && true == $this->getParam('postWithRequestBody')) {
                $request->setMethod(Request::POST);
                $req = $req->withMethod(Request::POST);
            }

            $req = $req->withBody(
                Psr7\stream_for(\is_array($data)
                    ? JSON::stringify($data, JSON_UNESCAPED_UNICODE)
                    : $data
                )
            );
        }

        return $req;
    }
910027
public function handleRequest(Request $request, Response $response) {
		if ($this->static_enable) {
			$request->uri = $request->server['request_uri'];
			$uri = $request->server['request_uri'];
			if (strpos($uri, $this->static_prefix) === 0) {
				$uri = substr($uri, strlen($this->static_prefix));
			}
			$path = realpath($this->static_dir . $uri);
			if ($path !== false && strpos($path, $this->static_dir) === 0) {
				if ($this->executeInterceptor('before', $request, $response) !== null) {
					$request->end();
					$response->end();
					unset($request, $response);
					return;
				}
				$response->mimeType(pathinfo($path, PATHINFO_EXTENSION));
				$response->sendfile($path);
				$this->executeInterceptor('after', $request, $response);
				$request->end();
				$response->end();
				unset($request, $response);
				return;
			}
		}
		$this->router->parse($request);
		if ($this->executeInterceptor('before', $request, $response) !== null) {
			$request->end();
			$response->end();
			unset($request, $response);
			return;
		}
		$this->dispatch($request, $response);
	}
329567
public function parse( Request $request, Response $response )
    {
        $error = parent::parse( $request, $response );

        if ( $error )
        {
            return $error;
        }

        $method = null;
        $params = xmlrpc_decode_request(
            $request->getContent(),
            $method,
            'utf-8'
        );

        if ( ! $params )
        {
            return self::PARSE;
        }

        if ( empty( $method ) || empty( $params ) )
        {
            return self::INVALID_REQUEST;
        }

        $this->method   = $method;
        $this->params   = $params;

        return null;
    }
106115
public function xhrFileUploadAction(Request $request)
    {
        if (!$request->files->has('file')) {
            return new JsonResponse(
                array(
                    'error' => 400,
                    'error_message' => 'File to upload have to be under "file" key.',
                ),
                400
            );
        }
        try {
            return new JsonResponse(
                array('file' => $this->container->get('synapse.media.domain')
                    ->upload($request->files->get('file'))
                    ->normalize(),
                ),
                201
            );
        } catch (UnsupportedFileException $e) {
            return new JsonResponse(
                array(
                    'error' => 400,
                    'error_message' => 'File isnt supported by Synapse.',
                    'error_full_message' => $e->getMessage(),
                ),
                400
            );
        }
    }
162126
public function download(Request $request)
    {
        $disk = $request->get('disk');
        $file = $request->get('file');

        $storage = Storage::disk($disk);

        $fullPath = $storage->getDriver()->getAdapter()->applyPathPrefix($file);

        if (File::isFile($fullPath)) {
            return response()->download($fullPath);
        }

        return response('', 404);
    }
171800
public function onRequest(Request $request, Response $response)
    {
        // Compat fpm server
        $this->_compatFPM($request);

        // 注入全局变量
        $GLOBALS['__$response'] = $response;

        $response->header('Server', 'ePHP/'. $this->version);

        $filename = APP_PATH . '/public'. $_SERVER['PATH_INFO'];

        // !in_array($extname, ['css', 'js', 'png', 'jpg', 'jpeg', 'gif', 'ico'])
        // Try files, otherwise route to app
        if ( !is_file($filename) ) {
            ob_start();
            (new \ePHP\Core\Application())->run();
            $h = ob_get_clean();

            // Fixed output o byte
            // if (strlen($h) === 0) {
            //     $h = ' ';
            // }

            $response->end($h);
        } else {
            $extname = substr($filename, strrpos($filename, '.') + 1);
            if ( isset( $this->contentType[$extname] ) ) {
                $response->header('Content-Type', $this->contentType[$extname]);
            }
            $response->sendfile($filename);
        }

        // 非调试模式，打印访问日志
        $this->printAccessLog();
    }
823456
public static function toResponse($request, $response)
    {
        if ($response instanceof Responsable) {
            $response = $response->toResponse($request);
        }

        if ($response instanceof PsrResponseInterface) {
            $response = (new HttpFoundationFactory)->createResponse($response);
        } elseif ($response instanceof Model && $response->wasRecentlyCreated) {
            $response = new JsonResponse($response, 201);
        } elseif (! $response instanceof SymfonyResponse &&
                   ($response instanceof Arrayable ||
                    $response instanceof Jsonable ||
                    $response instanceof ArrayObject ||
                    $response instanceof JsonSerializable ||
                    is_array($response))) {
            $response = new JsonResponse($response);
        } elseif (! $response instanceof SymfonyResponse) {
            $response = new Response($response);
        }

        if ($response->getStatusCode() === Response::HTTP_NOT_MODIFIED) {
            $response->setNotModified();
        }

        return $response->prepare($request);
    }
1280366
public function sendRequest(Psr7\Request $request)
        {
            $this->lastRequest = $request;

            //try make out request
            try {
                $this->lastResponse = $response = $this->transport->send($request);
            } catch (RequestException $e) {
                return json_encode(['responseCode' => $e->getCode(),'responseBody' => $e->getMessage()]);
            }

            //analyse response code
            try {
                $this->responseCodeAnalyser($response,$request);
            } catch (\Exception $e) {
                return json_encode(['responseCode' => $e->getCode(),'responseBody' => $e->getMessage()]);
            }
            $responseBody = json_decode($response->getBody()->getContents(),true);
            return json_encode(['responseCode' => $response->getStatusCode(),'responseBody' => json_decode($responseBody['data'],true)]);
        }
1267913
public function prepareResponse($request, $response)
    {
        if (! $response instanceof SymfonyResponse) {
            $response = new Response($response);
        }

        return $response->prepare($request);
    }
921454
protected function decodePusherResponse($request, $response)
    {
        if (! $request->input('callback', false)) {
            return json_decode($response, true);
        }

        return response()->json(json_decode($response, true))
                    ->withCallback($request->callback);
    }
739253
public function modifyResponse(Request $request, Response $response)
    {
        if ($this->isCollect() === false) {
            return;
        }

        // if ($this -> created) {
        //     return;
        // }

        $app = $this->app;


        if ($app->runningInConsole() || !$this->isEnabled() || $this->isMyselfRequest()) {
            return $response;
        }

        // Show the Http Response Exception, when available
        if (isset($response->exception)) {
            $this->addThrowable($response->exception);
        }

        /**---------------------------------------------------------
         *   Display config settings
         *---------------------------------------------------------*/

        if ($this->shouldCollect('config', false)) {
            try {
                $configCollector = new ConfigCollector();
                $configCollector->setData($app['config']->all());
                $this->addCollector($configCollector);
            } catch (\Exception $e) {
                $this->addThrowable(
                    new Exception(
                        'Cannot add ConfigCollector to SongshenzongLog: ' . $e->getMessage(),
                        $e->getCode(),
                        $e
                    )
                );
            }
        }


        if ($this->app->bound(SessionManager::class)) {

            /** @var \Illuminate\Session\SessionManager $sessionManager */
            $sessionManager = $app->make(SessionManager::class);
            $httpDriver     = new SymfonyHttpDriver($sessionManager, $response);
            $this->setHttpDriver($httpDriver);

            if ($this->shouldCollect('session') && !$this->hasCollector('session')) {
                try {
                    $this->addCollector(new SessionCollector($sessionManager));
                } catch (\Exception $e) {
                    $this->addThrowable(
                        new Exception(
                            'Cannot add SessionCollector to SongshenzongLog: ' . $e->getMessage(),
                            $e->getCode(),
                            $e
                        )
                    );
                }
            }
        } else {
            $sessionManager = null;
        }


        /**---------------------------------------------------------
         *   Only one can be enabled.
         *---------------------------------------------------------*/
        if ($this->shouldCollect('request', true) && !$this->hasCollector('request')) {
            try {
                $this->addCollector(new RequestCollector($request, $response, $sessionManager));
            } catch (\Exception $e) {
                $this->addThrowable(
                    new Exception(
                        'Cannot add RequestCollector to SongshenzongLog: ' . $e->getMessage(),
                        $e->getCode(),
                        $e
                    )
                );
            }
        }


        /**---------------------------------------------------------
         *   Just collect + store data
         *---------------------------------------------------------*/
        try {
            $this->collect();
        } catch (\Exception $e) {
            $app['log']->error('Songshenzong exception: ' . $e->getMessage());
        }


        return $response;
    }
831211
public function sendFile($path, $request, $response)
    {
        if (empty($path)) {
            $path = __DIR__ . '/Views/index.html';
            if (!$response->sendfile($path)) {
                swoole_async_readfile($path, function ($filename, $content) use ($response) {
                    $response->end($content);
                });
            }

            return Macro::SEND_FILE_200;
        }

        $path = realpath(urldecode($path));
        $root = $this->config['http']['domain'][$this->route->getHost()]['root'] ?? null;

        // 判断文件是否存在
        if (!file_exists($path)) {
            $response->status(404);
            $response->end('');
            return Macro::SEND_FILE_404;
        }

        // 判断文件是否有权限（非root目录不能访问）
        if (empty($root) || strpos($path, $root) === false) {
            $response->status(403);
            $response->end('');
            return Macro::SEND_FILE_403;
        }

        $info      = pathinfo($path);
        $extension = strtolower($info['extension'] ?? '');

        // 判断缓存
        $lastModified = gmdate('D, d M Y H:i:s', filemtime($path)) . ' GMT';
        if (isset($request->header['if-modified-since']) && $request->header['if-modified-since'] == $lastModified) {
            $response->status(304);
            $response->end('');
            return Macro::SEND_FILE_304;
        }

        $normalHeaders = getInstance()->config->get("fileHeader.normal", ['Content-Type: application/octet-stream']);
        $headers       = getInstance()->config->get("fileHeader.$extension", $normalHeaders);

        foreach ($headers as $value) {
            list($hk, $hv) = explode(': ', $value);
            $response->header($hk, $hv);
        }

        $response->header('Last-Modified', $lastModified);
        if (!$response->sendfile($path)) {
            swoole_async_readfile($path, function ($filename, $content) use ($response) {
                $response->end($content);
            });
        }

        return Macro::SEND_FILE_200;
    }
423630
public function uploadAction(Request $request)
    {
        $folderId = $request->get('folder_id', null);

        try {
            $volumeManager = $this->get('phlexible_media_manager.volume_manager');
            $volume = $volumeManager->getByFolderId($folderId);
            $folder = $volume->findFolder($folderId);

            if (empty($folder)) {
                return new ResultResponse(
                    false,
                    'Target folder not found.',
                    [
                        'params' => $request->request->all(),
                        'files' => $request->files->all(),
                    ]
                );
            }

            if (!$request->files->count()) {
                return new ResultResponse(
                    false,
                    'No files received.',
                    [
                        'params' => $request->request->all(),
                        'files' => $request->files->all(),
                    ]
                );
            }

            $uploadHandler = $this->get('phlexible_media_manager.upload.handler');

            $cnt = 0;
            foreach ($request->files->all() as $uploadedFile) {
                /* @var $uploadedFile UploadedFile */

                $file = $uploadHandler->handle($uploadedFile, $folderId, $this->getUser()->getId());

                if ($file) {
                    ++$cnt;

                    $body = 'Filename: '.$uploadedFile->getClientOriginalName().PHP_EOL
                        .'Folder:   '.$folder->getName().PHP_EOL
                        .'Filesize: '.$file->getSize().PHP_EOL
                        .'Filetype: '.$file->getMimeType().PHP_EOL;

                    $message = MediaManagerMessage::create('File "'.$file->getName().'" uploaded.', $body);
                    $this->get('phlexible_message.message_poster')->post($message);
                }
            }

            return new ResultResponse(
                true,
                $cnt.' file(s) uploaded.',
                [
                    'params' => $request->request->all(),
                    'files' => $request->files->all(),
                ]
            );
        } catch (\Exception $e) {
            return new ResultResponse(
                false,
                $e->getMessage(),
                [
                    'params' => $request->request->all(),
                    'files' => $request->files->all(),
                    'trace' => $e->getTraceAsString(),
                    'traceArray' => $e->getTrace(),
                ]
            );
        }
    }