Commit 49c14fe7 authored by 杨培's avatar 杨培

完成课程保存的整个过程(数据验证,文件认领等等)

parent 9b3e9df1
...@@ -54,7 +54,7 @@ class Utils ...@@ -54,7 +54,7 @@ class Utils
foreach ($errors as $k => $v) { foreach ($errors as $k => $v) {
foreach ($v as $msg) { foreach ($v as $msg) {
$msg[] = $msg; $msgs[] = $msg;
} }
} }
......
...@@ -123,5 +123,49 @@ class AttachUploadForm extends Model ...@@ -123,5 +123,49 @@ class AttachUploadForm extends Model
$key = self::SESS_PREFIX.$tmp; $key = self::SESS_PREFIX.$tmp;
return Yii::$app->session->remove($key); return Yii::$app->session->remove($key);
} }
/**
* 认领并绑定指定内容下的所有附件
*
* @param string $tmp
* @param string $bind 绑定归属
* @return int 绑定附件数量
*/
public static function claimTmpAttachs($tmp, $bind)
{
$attachs = self::getTmpAttachs($tmp);
$count = self::claimAttachs($attachs, $bind);
$count > 0 && self::clearTmpAttachs($tmp);
return $count;
}
/**
* 认领并绑定传入的附件数据
*
* @param $attachData
* @return int
*/
protected static function claimAttachs($attachData, $bind)
{
$count = 0;
if ($attachData) {
foreach ($attachData as $uuid) {
$cl = UploadPools::claimFile($uuid);
if ($cl) {
Yii::$app->db->createCommand()->insert('upload_attachments', [
'bind' => $bind,
'key' => $cl['key'],
'filesize' => $cl['filesize'],
'w' => $cl['w'],
'h' => $cl['h']
])->execute();
++$count;
}
}
}
return $count;
}
} }
\ No newline at end of file
...@@ -14,7 +14,6 @@ use yii\redis\ActiveRecord; ...@@ -14,7 +14,6 @@ use yii\redis\ActiveRecord;
* @property integer $user_id * @property integer $user_id
* @property integer $classed_id * @property integer $classed_id
* @property string $name * @property string $name
* @property array $teacher
* @property integer $price * @property integer $price
* @property integer $free_time * @property integer $free_time
* @property string $intro * @property string $intro
...@@ -42,7 +41,7 @@ class Course extends \yii\db\ActiveRecord ...@@ -42,7 +41,7 @@ class Course extends \yii\db\ActiveRecord
$this->name = strip_tags($this->name); $this->name = strip_tags($this->name);
$this->intro = HtmlPurifier::process($this->intro); $this->intro = HtmlPurifier::process($this->intro);
return true; return true;
} }
...@@ -70,12 +69,12 @@ class Course extends \yii\db\ActiveRecord ...@@ -70,12 +69,12 @@ class Course extends \yii\db\ActiveRecord
return [ return [
[['name', 'preview_pic'], 'required'], [['name', 'preview_pic'], 'required'],
['name', 'string', 'length'=>[1,60]], ['name', 'string', 'length'=>[1,60]],
//['teacher', 'exist', 'targetAttribute'=>'teacher_id', 'targetClass'=>CourseTeacher::className(), 'allowArray'=>true], [['user_id', 'class_id'], 'integer'],
['user_id', 'integer'], ['intro', 'string'],
['class_id', 'integer'],
['price', 'integer', 'min'=>0, 'max'=>9999], ['price', 'integer', 'min'=>0, 'max'=>9999],
['free_time', 'integer', 'min'=>0, 'max'=>15], ['free_time', 'integer', 'min'=>0, 'max'=>15],
['recommend', 'boolean'], ['recommend', 'boolean'],
['recommend', 'default', 'value'=>0],
['status', 'in', 'range'=>[0, 1, 2, 3]] ['status', 'in', 'range'=>[0, 1, 2, 3]]
]; ];
} }
......
...@@ -47,7 +47,7 @@ class UploadPools extends ActiveRecord ...@@ -47,7 +47,7 @@ class UploadPools extends ActiveRecord
public function validateSkey($attr, $params) public function validateSkey($attr, $params)
{ {
if (!preg_match('/^\w+:[\w\.\/]+$/', $this->$attr)) { if (!preg_match('#^[\w\-]+\:[\w\-\./]+$#i', $this->$attr)) {
$this->addError($attr, "$attr format is not a validate skey."); $this->addError($attr, "$attr format is not a validate skey.");
} }
} }
...@@ -140,6 +140,7 @@ class UploadPools extends ActiveRecord ...@@ -140,6 +140,7 @@ class UploadPools extends ActiveRecord
*/ */
protected static function claimFileConfirm($file) protected static function claimFileConfirm($file)
{ {
if ($file && $file->status == self::STATUS_UNUSE) { if ($file && $file->status == self::STATUS_UNUSE) {
$file->status = self::STATUS_USED; $file->status = self::STATUS_USED;
$file->save(); $file->save();
......
...@@ -15,7 +15,6 @@ class m161010_075253_upload_attachments_init extends Migration ...@@ -15,7 +15,6 @@ class m161010_075253_upload_attachments_init extends Migration
'filesize' => $this->integer(10)->unsigned()->notNull(), 'filesize' => $this->integer(10)->unsigned()->notNull(),
'w' => $this->smallInteger(5)->unsigned()->defaultValue(0)->comment('图片宽'), 'w' => $this->smallInteger(5)->unsigned()->defaultValue(0)->comment('图片宽'),
'h' => $this->smallInteger(5)->unsigned()->defaultValue(0)->comment('图片高'), 'h' => $this->smallInteger(5)->unsigned()->defaultValue(0)->comment('图片高'),
'`status` tinyint(1) NOT NULL DEFAULT \'0\' COMMENT \'文件状态: 0未认领,1已认领,2已删除(弃用)\'',
'upload_time' => $this->integer(10)->unsigned()->notNull()->comment('上传时间'), 'upload_time' => $this->integer(10)->unsigned()->notNull()->comment('上传时间'),
'PRIMARY KEY (`id`)', 'PRIMARY KEY (`id`)',
'KEY `bind` (`bind`)', 'KEY `bind` (`bind`)',
......
...@@ -46,27 +46,44 @@ class MyCourseController extends \yii\web\Controller ...@@ -46,27 +46,44 @@ class MyCourseController extends \yii\web\Controller
public function actionSubmit() public function actionSubmit()
{ {
$course = new Course();
$courseware = new Courseware();
$courseTeacher = new CourseTeacher();
$request = Yii::$app->request; $request = Yii::$app->request;
$userId = 1; $userId = 1;
$classId = 1; $classId = 1;
//验证临时ID
$tmpId = $request->post('tmp');
if (!$tmpId || !preg_match('/^\w{20}$/i', $tmpId)) {
Utils::ajaxResponse(false, '参数错误');
return;
}
//课程数据 //课程数据
$courseData = [ $courseData = [
'user_id' => $userId, 'user_id' => $userId,
'classed_id' => $classId 'classed_id' => $classId
]; ];
foreach (['name', 'teacher', 'price', 'free_time', 'intro', 'preview_pic', 'recommend'] as $key) { foreach (['name', 'teacher', 'price', 'free_time', 'intro', 'preview'=>'preview_pic', 'recommend'] as $postKey => $key) {
$courseData[$key] = $request->post($key); is_int($postKey) && $postKey = $key;
$courseData[$key] = $request->post($postKey);
} }
$course = new Course();
$course->load($courseData); $course->load($courseData);
//检查预览图是否存在
$previewFile = UploadPools::getFileInfo($courseData['preview_pic']);
if ($previewFile) {
$course->preview_pic = $previewFile['key'];
} else {
Utils::ajaxResponse(false, '预览图不存在');
return;
}
//验证课程数据
if (!$course->validate()) { if (!$course->validate()) {
Utils::ajaxResponse(false, join('<br>', Utils::fetchErrors($course->errors))); Utils::ajaxResponse(false, join('<br>', Utils::fetchErrors($course->errors)));
return; return;
...@@ -78,7 +95,6 @@ class MyCourseController extends \yii\web\Controller ...@@ -78,7 +95,6 @@ class MyCourseController extends \yii\web\Controller
//课件数据 //课件数据
$vuid = $request->post('vuid'); $vuid = $request->post('vuid');
$vuid = '2ade5751-8fae-11e6-a1b1-1242ac110005'; //测试uuid
$cwData = [ $cwData = [
'user_id' => $userId, 'user_id' => $userId,
'course_id' => 0, 'course_id' => 0,
...@@ -88,32 +104,86 @@ class MyCourseController extends \yii\web\Controller ...@@ -88,32 +104,86 @@ class MyCourseController extends \yii\web\Controller
'format' => '' 'format' => ''
]; ];
$video = UploadPools::getFileInfo($vuid); //处理视频信息
$videoFile = UploadPools::getFileInfo($vuid);
if ($videoFile) {
if ($video) { $qiniu = Yii::$app->qiniu;
$bucket = Yii::$app->qiniu->getStorageConfig($video['storage'], 'bucket'); $bucket = $qiniu->getStorageConfig($videoFile['storage'], 'bucket');
$auth = Yii::$app->qiniu->getAuthInstance(); $auth = $qiniu->getAuthInstance();
$bucketMgr = new BucketManager($auth); $bucketMgr = new BucketManager($auth);
list($ret, $err) = $bucketMgr->stat($bucket, $video['key']); list($ret, $err) = $bucketMgr->stat($bucket, $videoFile['key']);
if ($err !== null) { if ($err !== null) {
echo $err->message(); Utils::ajaxResponse(false, $err->message());
return;
} else { } else {
print_r($ret); $cwData['size'] = $ret['fsize'];
} }
}
return; //读取视频信息
$avUrl = $videoFile['url'].'?avinfo';
$response = (new \GuzzleHttp\Client())->get($avUrl);
$courseware->load($cwData); $avInfo = $response->getBody();
if ($avInfo) {
$avInfo = \GuzzleHttp\json_decode($avInfo, true);
} else {
Utils::ajaxResponse(false, '读取视频信息失败');
return;
}
//list($video, $audio) = $avInfo['streams'];
//$format = $avInfo['format'];
if ($courseware->validate()) { $cwData['name'] = $videoFile['key'];
echo 'Success'; $cwData['time'] = round($avInfo['format']['duration']);
$cwData['format'] = pathinfo($videoFile['key'], PATHINFO_EXTENSION);
} else { } else {
print_r($courseware->errors); Utils::ajaxResponse(false, '视频文件不存在');
return;
}
//验证课件数据
$courseware = new Courseware();
$courseware->load($cwData);
if (!$courseware->validate()) {
Utils::ajaxResponse(false, join('<br>', Utils::fetchErrors($courseware->errors)));
return;
} }
//保存课程数据
if (!$course->save()) {
Utils::ajaxResponse(false, '课程保存失败');
return;
}
//保存课件数据
$courseware->course_id = $course->id;
if (!$courseware->save()) {
Utils::ajaxResponse(false, '课件保存失败');
return;
}
//保存讲师与课程关联数据
foreach ($teacherIds as $teacherId) {
$ct = new CourseTeacher();
$ct->course_id = $course->id;
$ct->teacher_id = $teacherId;
$ct->save();
}
//认领文件
UploadPools::claimFile($vuid);
UploadPools::claimFile($courseData['preview_pic']);
//保存附件关联
AttachUploadForm::claimTmpAttachs($tmpId, 'course:'.$course->id);
Utils::ajaxResponse(true, '', ['course_id'=>$course->id]);
} }
/** /**
...@@ -146,9 +216,7 @@ class MyCourseController extends \yii\web\Controller ...@@ -146,9 +216,7 @@ class MyCourseController extends \yii\web\Controller
public function actionTest() public function actionTest()
{ {
$data = AttachUploadForm::getTmpAttachs('dxQ9tE6XyKX2TD6bndgP'); print_r(UploadPools::claimFile('2ade5751-8fae-11e6-a1b1-1242ac110005'));
var_dump($data);
} }
} }
...@@ -77,7 +77,7 @@ AppAsset::addCss($this, '@web/assets/css/course_publish.css'); ...@@ -77,7 +77,7 @@ AppAsset::addCss($this, '@web/assets/css/course_publish.css');
<div class="tit">课程属性</div> <div class="tit">课程属性</div>
<div class="checkbox"> <div class="checkbox">
<label> <label>
<input type="checkbox" name="recommend">推荐课程 <input type="checkbox" name="recommend" value="1">推荐课程
</label> </label>
</div> </div>
</div> </div>
......
...@@ -80,7 +80,7 @@ var vm = new Vue({ ...@@ -80,7 +80,7 @@ var vm = new Vue({
}); });
this.$on("thumb-uploaded", function(name, data) { this.$on("thumb-uploaded", function(name, data) {
self.previewKey = data.key; self.previewKey = data.uuid;
}); });
var validator = $(form).validate({ var validator = $(form).validate({
...@@ -141,8 +141,12 @@ var vm = new Vue({ ...@@ -141,8 +141,12 @@ var vm = new Vue({
submitHandler: function() { submitHandler: function() {
var data = $(form).serialize(); var data = $(form).serialize();
$.post("/my-course/submit", data, function(t) { $.post("/my-course/submit", data, function(t) {
alert(t); if (t.status) {
}); alert("保存成功,请等待审核!");
} else {
alert(t.message);
}
}, "json");
return false; return false;
} }
}); });
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment