<?php

namespace Modules\Common\Http\Controllers\Qiniu;

use Illuminate\Http\Request;
use Modules\Common\Services\Qiniu\QiniuTokenService;
use Qiniu\Auth;

class CallbackController
{
    public function uploadToken(Request $request) {
        $qiniuConfig = config('common.qiniu');

        $auth = new Auth($qiniuConfig['accessKey'], $qiniuConfig['secretKey']);
        $videoEnv = $qiniuConfig['videoEnv'];
        $expires = 7200;
        $policy  = [
            'scope' => $qiniuConfig['bucket'],
            'callbackUrl' => config('common.common.duanjuManageDomain') . '/api/qiniu/upload/callback',
            'callbackBody' => '{"hash":"$(etag)","key":"$(key)", "fname":"$(fname)", "fprefix":"$(fprefix)" ,"duration":"$(avinfo.video.duration)"}',
            'callbackBodyType' => 'application/json',
            'forceSaveKey' => true,
            'saveKey' => 'duanju/'.$videoEnv.'/$(x:video_id)/$(etag)-'.uniqid().'$(ext)',
        ];
        $upToken = $auth->uploadToken($qiniuConfig['bucket'], null, $expires, $policy, true);
        return $upToken;
    }

    public function callback(Request $request) {
        $allInfo = $request->only(['duration', 'fname', 'hash', 'key', 'fprefix']);
        $videoUrl = config('common.qiniu.publicVideoLinkDomain') . DIRECTORY_SEPARATOR . $allInfo['key'];
        $publicVideoUrl = QiniuTokenService::getPrivateSourceDownloadUrl($videoUrl);
        $allInfo['public_video_url'] = $publicVideoUrl;
        $allInfo['url'] = $videoUrl;
        $allInfo['name'] = $allInfo['fprefix'];

        return $allInfo;
    }
}
