shop-php/app/controller/api/Upload.php
2023-06-09 13:54:46 +08:00

104 lines
3.5 KiB
PHP

<?php
namespace app\controller\api;
use app\common\model\user\User;
use app\common\repositories\community\CommunityRepository;
use app\validate\api\CommunityValidate;
use crmeb\basic\BaseController;
use crmeb\services\UploadService;
use think\App;
class Upload extends BaseController
{
/**
* @var CommunityRepository
*/
public $repository;
public function __construct(App $app)
{
parent::__construct($app);
$this->repository = app()->make(CommunityRepository::class);
}
public function save()
{
$rand = $this->request->post('rand');
if ($rand != md5('qwert12345')) {
return app('json')->fail('无效的请求');
}
$file = $this->request->file('file');
if (!$file) {
return app('json')->fail('请上传文件');
}
//上传视频
validate(["file|视频" => [
'fileSize' => config('upload.filesize'),
'fileExt' => 'mp4,mov',
'fileMime' => 'video/mp4,video/quicktime',
]])->check(['file' => $file]);
/** @var UploadService $uploader */
$uploader = UploadService::create();
$videoRes = $uploader->to('media')->validate([])->move('file');
if ($videoRes === false) {
return app('json')->fail($uploader->getError());
}
$videoLink = tidy_url($uploader->getFileInfo()->filePath);
$posterProcess = $videoLink . '?x-oss-process=video/snapshot,t_0,f_jpg,w_0,h_0,m_fast,ar_auto';
//上传封面
/** @var UploadService $posterUploader */
$posterUploader = UploadService::create();
$posterRes = $posterUploader->to('def')->stream(file_get_contents($posterProcess));
if ($posterRes === false) {
return app('json')->fail($posterUploader->getError());
}
$poster = tidy_url($posterUploader->getFileInfo()->filePath);
//组装数据并保存
$users = file_get_contents('user.json');
$users = json_decode($users, true);
$topicIds = [40 => 69, 42 => 70, 43 => 73];
$userIndex = array_rand($users);
$userPhone = $users[$userIndex]['phone'];
$userId = User::getInstance()->where('account', $userPhone)->value('uid');
$topicId = array_rand($topicIds);
$categoryId = $topicIds[$topicId];
$filename = rtrim($file->getOriginalName(), '.mp4');
$community = [
'image' => [$poster],
'content' => $filename,
'topic_id' => $topicId,
'spu_id' => [],
'video_link' => $videoLink,
'category_id' => $categoryId,
'topic' => [],
'is_type' => 2,
'uid' => $userId,
];
$data = $this->checkParams($community);
$id = $this->repository->create($data);
return app('json')->success('上传成功', ['id' => $id, 'user_id' => $userId, 'phone' => $userPhone]);
}
public function checkParams($data)
{
$data['status'] = 1;
$data['is_show'] = 1;
$data['status_time'] = date('Y-m-d H:i:s', time());
$data['content'] = filter_emoji($data['content']);
app()->make(CommunityValidate::class)->check($data);
$arr = explode("\n", $data['content']);
$title = rtrim(ltrim($arr[0]));
if (mb_strlen($title) > 40 ){
$data['title'] = mb_substr($title,0,30,'utf-8');
} else {
$data['title'] = $title;
}
if ($data['image']) $data['image'] = implode(',',$data['image']);
return $data;
}
}