Commit d86f39d0 authored by 杨培's avatar 杨培

重新整理了课程发布与修改流程,将共用部分建立Form类,前端共用组件化,等等

parent 6814a5f6
......@@ -12,7 +12,7 @@ use Qiniu\Storage\UploadManager;
use Yii;
use yii\base\Model;
class AttachUploadForm extends Model
class AttachUpload extends Model
{
const SESS_PREFIX = 'attachpool_';
......
......@@ -169,7 +169,7 @@ class Course extends \yii\db\ActiveRecord
if ($count > 0) {
$return['data'] = self::find()
->select('id,user_id,price,name,intro,preview_pic,recommend,play_count,comment_count,favorite_count,created_at')
->where($cond)->limit($num)->offset($offset)->with('teachers')->asArray()->all();
->where($cond)->orderBy(['id'=>SORT_DESC])->limit($num)->offset($offset)->with('teachers')->asArray()->all();
}
return $return;
......
......@@ -37,4 +37,44 @@ class CourseTeacher extends \yii\db\ActiveRecord
return array_column($list, 'teacher_id');
}
public static function removeRelations($courseId, $teacherIds)
{
self::deleteAll([
'and',
['course_id'=>$courseId],
['in', 'teacher_id', $teacherIds]
]);
//self::find()->where(['cousre_id'=>$courseId])->andWhere(['in', 'teacher_id', $teacherIds])
}
/**
* 自动处理新的讲师列表
*
* 对比并移除老的讲师与课程关系,添加新的关系
*
* @param int $courseId
* @param array $newTeacherIds
*/
public static function autoSaveRelations($courseId, $newTeacherIds)
{
$old = self::getTeachersIdsByCourseId($courseId);
$del = array_diff($old, $newTeacherIds);
$new = array_diff($newTeacherIds, $old);
$new && self::saveRelations($courseId, $new);
$del && self::removeRelations($courseId, $del);
}
public static function saveRelations($courseId, $teacherIds)
{
//保存讲师与课程关联数据
foreach ($teacherIds as $teacherId) {
$ct = new self();
$ct->course_id = $courseId;
$ct->teacher_id = $teacherId;
$ct->save();
}
}
}
......@@ -16,7 +16,7 @@ use yii\db\ActiveRecord;
* @property string $name
* @property integer $status
* @property string $size
* @property string $time
* @property int $time
* @property string $format
* @property integer $created_at
* @property integer $updated_at
......
......@@ -2,16 +2,17 @@
namespace frontend\controllers;
use common\libs\Utils;
use common\models\AttachUploadForm;
use common\models\AttachUpload;
use common\models\Course;
use common\models\CourseTeacher;
use common\models\Courseware;
use common\models\Teacher;
use common\models\UploadPools;
use frontend\components\ClassesFilter;
use Qiniu\Storage\BucketManager;
use frontend\models\CoursePublishForm;
use Yii;
use yii\filters\AccessControl;
use yii\web\BadRequestHttpException;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\web\UploadedFile;
......@@ -97,7 +98,12 @@ class MyCourseController extends \yii\web\Controller
$lesson = Courseware::findOne(['course_id'=>$course->id]);
$teacherIds = CourseTeacher::getTeachersIdsByCourseId($course->id);
$thumbToken = '';
/* @var \common\components\Qiniu $qiniu */
$qiniu = Yii::$app->qiniu;
//图片上传Token
$imgPath = 'preview/' . $qiniu->generateRandomFilePath('$(min)$(sec)$(ext)', 12);
$thumbToken = $qiniu->getUploadToken('public', $imgPath);
return $this->render('edit', compact('course', 'lesson', 'teacherIds', 'thumbToken'));
}
......@@ -107,147 +113,131 @@ class MyCourseController extends \yii\web\Controller
*/
public function actionSubmit()
{
$request = Yii::$app->request;
$userId = Yii::$app->user->identity->getId();
$classId = $this->classStatus['id'];
//验证临时ID
$tmpId = $request->post('tmp');
$form = new CoursePublishForm(true);
$form->class_id = $classId;
$form->user_id = $userId;
$form->load(Yii::$app->request->post());
if (!$tmpId || !preg_match('/^\w{20}$/i', $tmpId)) {
Utils::ajaxResponse(false, '参数错误');
return;
if (!$form->validate()) {
Utils::ajaxResponse(false, Utils::fetchErrorFirst($form->errors));
}
//课程数据
$courseData = [
'user_id' => $userId,
'class_id' => $classId
];
foreach (['name', 'teacher', 'price', 'free_time', 'intro', 'preview'=>'preview_pic', 'recommend'] as $postKey => $key) {
is_int($postKey) && $postKey = $key;
$courseData[$key] = $request->post($postKey);
}
$course = new Course();
$course->load($courseData);
//检查预览图是否存在
$previewFile = UploadPools::getFileInfo($courseData['preview_pic']);
$course->preview_pic = $form->preview['key'];
if ($previewFile) {
$course->preview_pic = $previewFile['key'];
} else {
Utils::ajaxResponse(false, '预览图不存在');
return;
foreach (['class_id', 'user_id', 'name', 'price', 'free_time', 'intro', 'recommend'] as $attr) {
$course->$attr = $form->$attr;
}
//验证课程数据
if (!$course->validate()) {
Utils::ajaxResponse(false, join('<br>', Utils::fetchErrors($course->errors)));
return;
Utils::ajaxResponse(false, Utils::fetchErrorFirst($course->errors));
}
//过滤已拥有的讲师列表
$teacherIds = $request->post('teacher', []);
$teacherIds = Teacher::filterOwnTeacherIds($classId, $teacherIds);
//课件数据
$vuid = $request->post('vuid');
$cwData = [
'user_id' => $userId,
'course_id' => 0,
'name' => $vuid, //视频的 uuid
'size' => 0,
'time' => 0,
'format' => ''
];
$courseware = new Courseware();
$courseware->user_id = $userId;
$courseware->course_id = 0;
$courseware->name = $form->vuid['key']; //视频文件uuid
//处理视频信息
$videoFile = UploadPools::getFileInfo($vuid);
if ($videoFile) {
/**
* @var $qiniu \common\components\Qiniu;
*/
$qiniu = Yii::$app->qiniu;
$bucket = $qiniu->getStorageConfig($videoFile['storage'], 'bucket');
$auth = $qiniu->getAuthInstance();
$bucketMgr = new BucketManager($auth);
list($ret, $err) = $bucketMgr->stat($bucket, $videoFile['key']);
if ($err !== null) {
Utils::ajaxResponse(false, $err->message());
return;
} else {
$cwData['size'] = $ret['fsize'];
}
//读取视频信息
$avUrl = $auth->privateDownloadUrl($videoFile['url'].'?avinfo');
$response = (new \GuzzleHttp\Client())->get($avUrl);
$avInfo = $response->getBody();
if ($avInfo) {
$avInfo = \GuzzleHttp\json_decode($avInfo, true);
} else {
Utils::ajaxResponse(false, '读取视频信息失败');
return;
}
//list($video, $audio) = $avInfo['streams'];
//$format = $avInfo['format'];
$cwData['name'] = $videoFile['key'];
$cwData['time'] = round($avInfo['format']['duration']);
$cwData['format'] = pathinfo($videoFile['key'], PATHINFO_EXTENSION);
} else {
Utils::ajaxResponse(false, '视频文件不存在');
return;
}
//视频信息
$videoInfo = CoursePublishForm::getVerifyVideoInfo($form->vuid);
$courseware->size = $videoInfo['file']['fsize'];
$courseware->time = round($videoInfo['av']['format']['duration']);
$courseware->format = pathinfo($form->vuid['key'], PATHINFO_EXTENSION);
//list($video, $audio) = $avInfo['streams'];
//$format = $avInfo['format'];
//验证课件数据
$courseware = new Courseware();
$courseware->load($cwData);
if (!$courseware->validate()) {
Utils::ajaxResponse(false, join('<br>', Utils::fetchErrors($courseware->errors)));
return;
Utils::ajaxResponse(false, Utils::fetchErrorFirst($courseware->errors));
}
//保存课程数据
if (!$course->save()) {
Utils::ajaxResponse(false, '课程保存失败');
return;
Utils::ajaxResponse(false, Utils::fetchErrorFirst($course->errors));
}
//保存课件数据
$courseware->course_id = $course->id;
if (!$courseware->save()) {
Utils::ajaxResponse(false, '课件保存失败');
return;
Utils::ajaxResponse(false, Utils::fetchErrorFirst($courseware->errors));
}
//保存讲师与课程关联数据
foreach ($teacherIds as $teacherId) {
$ct = new CourseTeacher();
$ct->course_id = $course->id;
$ct->teacher_id = $teacherId;
$ct->save();
CourseTeacher::saveRelations($course->id, $form->teacher);
//认领文件与附件
UploadPools::claimFile($form->vuid['uuid']);
UploadPools::claimFile($form->preview['uuid']);
AttachUpload::claimTmpAttachs($form->tmp, 'course:'.$course->id);
Utils::ajaxResponse(true, null, ['course_id'=>$course->id]);
}
/**
* 修改课程信息
*
* @throws BadRequestHttpException
* @throws ForbiddenHttpException
* @throws \yii\base\ExitException
*/
public function actionSave()
{
$userId = Yii::$app->user->identity->getId();
$classId = $this->classStatus['id'];
$form = new CoursePublishForm();
$form->class_id = $classId;
$form->user_id = $userId;
$form->load(Yii::$app->request->post());
if (!$form->validate()) {
Utils::ajaxResponse(false, Utils::fetchErrorFirst($form->errors));
}
if (empty($form->id)) {
throw new BadRequestHttpException();
}
$course = Course::findOne($form->id);
if (!$course || $course->user_id != $userId) {
throw new ForbiddenHttpException();
}
//修改课程数据
$course->name = $form->name;
$course->price = $form->price;
$course->free_time = $form->free_time;
$course->intro = $form->intro;
$course->recommend = $form->recommend;
$form->preview && $course->preview_pic = $form->preview['key'];
//验证课程数据
if (!$course->validate()) {
Utils::ajaxResponse(false, Utils::fetchErrorFirst($course->errors));
}
//认领文件
UploadPools::claimFile($vuid);
UploadPools::claimFile($courseData['preview_pic']);
//保存课程数据
if (!$course->save()) {
Utils::ajaxResponse(false, '课程保存失败');
}
//保存讲师与课程关联数据
CourseTeacher::autoSaveRelations($course->id, $form->teacher);
//保存附件关联
AttachUploadForm::claimTmpAttachs($tmpId, 'course:'.$course->id);
//认领文件与附件
UploadPools::claimFile($course->preview_pic);
AttachUpload::claimTmpAttachs($form->tmp, 'course:'.$course->id);
Utils::ajaxResponse(true, '', ['course_id'=>$course->id]);
Utils::ajaxResponse(true, null, ['course_id'=>$course->id]);
}
/**
......@@ -291,7 +281,7 @@ class MyCourseController extends \yii\web\Controller
$response->format = Response::FORMAT_JSON;
//暂存到本地
$model = new AttachUploadForm();
$model = new AttachUpload();
//if (!Yii::$app->request->isPost) {
// return ['success'=>false, 'msg'=>'请求方式错误'];
......
......@@ -10,7 +10,6 @@ use frontend\assets\AppAsset;
$this->title = '编辑课程信息';
//AppAsset::addScript($this, '@web/assets/single-lib/plupload/plupload.full.min.js');
AppAsset::addScript($this, '@web/assets/course_edit.js');
AppAsset::addCss($this, '@web/assets/css/course_publish.css');
?>
......@@ -56,6 +55,7 @@ AppAsset::addCss($this, '@web/assets/css/course_publish.css');
<div class="cls-part">
<div class="tit">缩略图 <small>建议尺寸:900像素 * 500像素</small></div>
<thumb-upload uptoken="<?=$thumbToken?>"></thumb-upload>
<img src="<?=\Yii::$app->qiniu->getUrl('public', $course->preview_pic)?>-s.preview" />
</div>
<div class="cls-part p-b-20">
......@@ -67,6 +67,7 @@ AppAsset::addCss($this, '@web/assets/css/course_publish.css');
</div>
</div>
<input type="hidden" name="id" value="<?=$course->id?>" />
<input type="hidden" name="tmp" value="{{tmp}}" />
<input type="hidden" name="vuid" value="@orig" v-model="vuid" />
<input type="hidden" name="preview" value="@orig" v-model="previewKey" />
......
......@@ -82,10 +82,17 @@ var vm = new Vue({
var data = $(form).serialize();
var idx = layer.msg("正在提交..", {icon:16, shade: [0.2,'#000'], time:0});
$.post("/my-course/submit", data, function(t) {
$.post("/my-course/save", data, function(t) {
layer.close(idx);
if (t.status) {
location.replace("/my-course/result?id=" + t.data.course_id + "&action=publish");
layer.msg('成功修改课程信息。', {
time: 2000,
icon: 1,
end: function() {
location.href = "/my-course/";
},
shade:[0.2,'#000']
});
} else {
layer.alert(t.message, {icon:5, title:"提示"});
}
......
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