SaveController.class.php 19 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
<?php
/**
 * 直播室保存
 * Created by PhpStorm.
 * User: zhoutao
 * Date: 2018/1/8
 * Time: 下午3:58
 */

namespace Apicp\Controller\Room;

use Com\IM\TimRestAPI;
use Com\PackageValidate;
use Common\Common\AttachOperation;
use Common\Common\Constant;
use Common\Model\CronModel;
use Common\Model\RoleModel;
use Common\Service\CronService;
use Common\Service\ImService;
use Common\Service\MainService;
use Common\Service\MsgLogService;
use Common\Service\RangeService;
use Common\Service\StudioService;
use VcySDK\Cron;
use VcySDK\Service;

/**
 * Class SaveController
 * @package Apicp\Controller\Room
 * @property MainService $mainServ
 */
class SaveController extends AbstractController
{
    /**
     * 是更新操作
     * @var bool
     */
    protected $isUpdate = false;

    protected $mainServ = null;

    /**
     * 可见范围所有人员数组
     * @var array
     */
    protected $rangeAllArray = [];

    public function __construct() {
        parent::__construct();

        // 无需登录
        $this->_require_login = false;

    }

    public function index()
    {
        // 获取数据
        $postData = $this->getParams();
        // 把讲师放入参与范围
        $postData['range']['uids'][] = $postData['lecturer'];

        $this->mainServ = new MainService();
        $this->mainServ->start_trans();
        try {
            // 获取可见范围内的人员数据
            $this->rangeAllArray = $this->rangeAll($postData);
            // 所有观看人数
            $postData['range_total'] = count($this->rangeAllArray);

            if (!empty($postData['lm_id'])) {
                $this->isUpdate = true;
                // 更新直播活动
                $mainDetail = $this->mainServ->updateLiveActivity($postData);
            } else {
                // 判断是否还有一条直播活动
                $hasAnotherLive = $this->mainServ->get_by_conds(['live_status' => Constant::LIVE_STATUS_PUBLISHED]);
                if (!empty($hasAnotherLive)) {
                    E('_ERR_ONLY_ONE_LIVE_EVENT_CAN_BE_PLAYED_AT_THE_SAME_TIME');
                }
                // 判断开始时间
                if ($postData['start_time'] <= MILLI_TIME) {
                    E(L('_ERR_PARAMS_NON_COMPLIANT', ['name' => '开始时间', 'why' => '不得早于当前时间']));
                }

                // 固定为讲师角色
                $postData['type'] = Constant::LIVE_ROLE_TYPE_LECTURER;
                // 新增直播活动
                $postData['lm_id'] = $this->mainServ->newLiveActivity($postData);
            }

            // 获取推流名称和地址
            $studioServ = new StudioService();
            list($this->_result['stream_url'], $this->_result['stream_name']) =
                $studioServ->liveNameAndUrlByLmId($postData);

            // 处理更多设置
            $this->dealWithModeSetting($postData, $mainDetail);

            // 处理聊天群组
            $this->createChatRoom($postData['lm_id']);

            $this->mainServ->commit();
        } catch (\Exception $e) {
            $this->mainServ->rollback();
            E($e->getCode() . ':' . $e->getMessage());
        }

        /**
         * 附件处理 start
         */

        $attach_serv = new AttachOperation();

        $at_ids = [];
        if ($postData['pic']) {
            // 封面图
            $at_ids[] = $postData['pic'];
        }
        // 内容中的附件
        $desc_atids = $attach_serv->match_at_ids($postData['desc']);
        $at_ids = array_merge($at_ids, $desc_atids);

        if (!$this->isUpdate) {
            // 新增
            $attach_serv->insert_attach(
                APP_DIR,
                'main',
                $postData['lm_id'],
                ['attach_ids' => $at_ids]
            );

        } else {
            // 编辑
            $attach_serv->update_attach(
                APP_DIR,
                'main',
                $postData['lm_id'],
                ['attach_ids' => $at_ids]
            );
        }

        /**
         * 附件处理 end
         */

        $this->_result['lm_id'] = $postData['lm_id'];
        return true;
    }

    /**
     * 处理 "更多设置"
     * @param       $data
     * @param array $mainDetail
     * @return bool
     */
    private function dealWithModeSetting($data, $mainDetail = [])
    {
        // 是否发布 (发布时推送消息提醒)
        if ($data['live_status'] != Constant::LIVE_STATUS_PUBLISHED) {
            return true;
        }

        // 获取范围对象与上次的差异
        $msgLogServ = new MsgLogService();
        $diffRangeUids = $msgLogServ->sendMsgRangeDiffUids(
            $data['lm_id'],
            $this->rangeAllArray,
            $data['range']['is_all'] == Constant::RANGE_IS_ALL_TRUE
        );

        // 更新
        if ($this->isUpdate) {
            // 进行中
            if (MILLI_TIME >= $mainDetail['start_time']) {
                return true;
            }

            // 发布时推送消息提醒 开启 并且有差异范围对象
            if (isset($data['notice_posting']) &&
                    !empty($diffRangeUids) &&
                    $data['notice_posting'] == Constant::NOTICE_POSTING_TRUE) {
                $data['uids'] = $diffRangeUids;
                // 直播地址
                $msgLogServ->sendMsg($data, $msgLogServ::MSG_LIVE_PUBLISH);
            }

            // 有变更 直播开始前 (分钟)推送消息提醒
            $cronServ = new CronService();
            $cronSdk = new Cron(Service::instance());
            if (isset($data['notice_will_start']) && isset($data['start_time'])) {
                $cronDetail = $cronServ->get_by_conds([
                    'lm_id' => $data['lm_id'],
                    'type' => CronModel::TYPE_LIVE_WILL_START
                ]);
                // 直播开始前 (分钟)推送消息提醒 有变更
                // 并且 为零
                if ($data['notice_will_start'] != $mainDetail['notice_will_start'] &&
                        $data['notice_will_start'] == 0 &&
                        isset($cronDetail['cron_id'])) {
                    // 删除
                    $cronSdk->delete($cronDetail['cron_id']);
                }
                // 直播开始前 (分钟)推送消息提醒 有变更 或者 开始时间有变更 (不能和上面判断合并)
                elseif (($data['notice_will_start'] != $mainDetail['notice_will_start'] ||
                            $data['start_time'] != $mainDetail['start_time']) &&
                            $data['notice_will_start'] != 0) {
                    if (isset($cronDetail['cron_id'])) {
                        // 更新
                        $pushTime = $data['start_time'] - $data['notice_will_start'] * 60 * 1000;
                        $cronSdk->update([
                            'crId' => $cronDetail['cron_id'],
                            'crCron' => rgmdate((String)$pushTime, 's i G j n ? Y'),
                        ]);
                    // 新建
                    } else {
                        $this->createCron(
                            $data['lm_id'],
                            'live_notice_will_start',
                            CronModel::TYPE_LIVE_WILL_START,
                            $data['start_time'] - $data['notice_will_start'] * 60 * 1000
                        );
                    }
                }
            }

            // 直播开始时推送消息
            if (isset($data['notice_start'])) {
                $cronDetail = $cronServ->get_by_conds([
                    'lm_id' => $data['lm_id'],
                    'type' => CronModel::TYPE_LIVE_START
                ]);
                // 有变更
                if ($data['notice_start'] != $mainDetail['notice_start']) {
                    if ($data['notice_start'] == Constant::NOTICE_START_FALSE) {
                        if (isset($cronDetail['cron_id'])) {
                            // 删除
                            $cronSdk->delete($cronDetail['cron_id']);
                        }
                    } else {
                        if (isset($cronDetail['cron_id'])) {
                            // 更新
                            $cronSdk->update([
                                'crId' => $cronDetail['cron_id'],
                                'crCron' => rgmdate((String)$data['notice_start'], 's i G j n ? Y'),
                            ]);
                        } else {
                            // 新建
                            $this->createCron(
                                $data['lm_id'],
                                'live_notice_start',
                                CronModel::TYPE_LIVE_START,
                                $data['start_time']
                            );
                        }
                    }
                }
            }

            // 推荐变更
            if (isset($data['recomend']) && $data['recomend'] != $mainDetail['recomend']) {
                $this->mainServ->openOrCloseRecommender(
                    $data,
                    $this->formatRangeData($data),
                    $data['recomend'] == Constant::RECOMEND_TRUE
                );
            }
        } else {
            // 新建
            // 发布时推送消息提醒
            if (isset($data['notice_posting']) && $data['notice_posting'] == Constant::NOTICE_POSTING_TRUE) {
                $data['uids'] = $diffRangeUids;
                // 直播地址
                $msgLogServ->sendMsg($data, $msgLogServ::MSG_LIVE_PUBLISH);
            }

            // 直播开始前 (分钟)推送消息提醒
            if (isset($data['notice_will_start']) && $data['notice_will_start'] > 0) {
                // 直播开始前 推送消息的时间点
                $this->createCron(
                    $data['lm_id'],
                    'live_notice_will_start',
                    CronModel::TYPE_LIVE_WILL_START,
                    $data['start_time'] - $data['notice_will_start'] * 60 * 1000
                );
            }

            // 直播开始时推送消息
            if (isset($data['notice_start']) && $data['notice_start'] == Constant::NOTICE_START_TRUE) {
                $this->createCron(
                    $data['lm_id'],
                    'live_notice_start',
                    CronModel::TYPE_LIVE_START,
                    $data['start_time']
                );
            }

            if (isset($data['recomend']) && $data['recomend'] == Constant::RECOMEND_TRUE) {
                // 移动端首页推荐
                $this->mainServ->openOrCloseRecommender($data, $this->formatRangeData($data));
            }
        }

        return true;
    }

    /**
     * 获取并验证提交数据
     * @return array
     */
    private function getParams()
    {
        return (new PackageValidate([
            'name' => 'require|max:' . Constant::MAIN_NAME_MAX,
            'start_time' => 'require',
            // 0 < 预计时长 <= 24 (小时)
            'estimated_duration' => 'require|integer|gt:0|elt:' . 24 * 60,
            'desc' => 'require',
            'notice_will_start' => 'integer',
            'notice_posting' => 'in:' . implode(',', Constant::NOTICE_POSTING_LIST),
            'notice_start' => 'in:' . implode(',', Constant::NOTICE_START_LIST),
            'recomend' => 'in:' . implode(',', Constant::RECOMEND_LIST),
            'live_status' => 'in:' . implode(',', Constant::LIVE_STATUS_LIST),
            'range' => 'require',
            // 讲师
            'lecturer' => 'require',
            'lecturer_title' => 'max:' . RoleModel::TITLE_MAX,
            'lecturer_desc' => 'max:' . RoleModel::DESC_MAX,
            'lecturer_pwd' => 'require|length:' . RoleModel::PASSWORD_LENGTH,
        ], [
            'name.require' => L('_ERR_PARAMS_CAN_NOT_EMPTY', ['name' => '名称']),
            'name.max' => L('_ERR_PARAMS_MAX_LENGTH', ['name' => '名称', 'length' => Constant::MAIN_NAME_MAX]),
            'start_time.require' => L('_ERR_PARAMS_CAN_NOT_EMPTY', ['name' => '开始时间']),
            'estimated_duration.require' => L('_ERR_PARAMS_CAN_NOT_EMPTY', ['name' => '预计时长']),
            'estimated_duration.integer' => L('_ERR_PARAMS_NON_COMPLIANT', ['name' => '预计时长', 'why' => '仅能输入正整数']),
            'estimated_duration.gt' => L('_ERR_PARAMS_NON_COMPLIANT', ['name' => '预计时长', 'why' => '仅能输入正整数']),
            'estimated_duration.elt' => L('_ERR_PARAMS_NON_COMPLIANT', ['name' => '预计时长', 'why' => '不能超过24小时']),
            'desc.require' => L('_ERR_PARAMS_CAN_NOT_EMPTY', ['name' => '简介']),
            'notice_will_start.integer' => L('_ERR_PARAMS_NON_COMPLIANT', [
                'name' => '直播开始前(分钟)推送消息提醒',
                'why' => '整数',
            ]),
            'notice_posting.in' => L('_ERR_PARAMS_NON_COMPLIANT', [
                'name' => '发布时推送消息提醒',
                'why' => '应在' . implode(',', Constant::NOTICE_POSTING_LIST) . '范围内',
            ]),
            'notice_start.in' => L('_ERR_PARAMS_NON_COMPLIANT', [
                'name' => '直播开始时推送消息提醒',
                'why' => '应在' . implode(',', Constant::NOTICE_START_LIST) . '范围内',
            ]),
            'recomend.in' => L('_ERR_PARAMS_NON_COMPLIANT', [
                'name' => '移动端首页推荐',
                'why' => '应在' . implode(',', Constant::RECOMEND_LIST) . '范围内',
            ]),
            'live_status.in' => L('_ERR_PARAMS_NON_COMPLIANT', [
                'name' => '直播状态',
                'why' => '应在' . implode(',', Constant::LIVE_STATUS_LIST) . '范围内',
            ]),
            'range.require' => L('_ERR_PARAMS_CAN_NOT_EMPTY', ['name' => '目标对象']),
            'lecturer.require' => L('_ERR_PARAMS_CAN_NOT_EMPTY', ['name' => '讲师']),
            'lecturer_title.max' => L('_ERR_PARAMS_MAX_LENGTH', [
                'name' => '讲师头衔',
                'length' => RoleModel::TITLE_MAX,
            ]),
            'lecturer_desc.max' => L('_ERR_PARAMS_MAX_LENGTH', [
                'name' => '讲师简介',
                'length' => RoleModel::DESC_MAX,
            ]),
            'lecturer_pwd.require' => L('_ERR_PARAMS_CAN_NOT_EMPTY', ['name' => '讲师密令']),
            'lecturer_pwd.length' => L('_ERR_PARAMS_NON_COMPLIANT', [
                'name' => '讲师密令',
                'why' => '讲师密令不合法',
            ]),
        ], [
            'lm_id',
            'name',
            'start_time',
            'estimated_duration',
            'desc',
            'pic',
            'notice_posting',
            'notice_will_start',
            'notice_start',
            'recomend',
            'live_status',
            // 目标对象
            'range',
            // 讲师
            'lecturer',
            'lecturer_title',
            'lecturer_desc',
            'lecturer_pwd',
        ]))->postData;
    }

    /**
     * 创建计划任务并保存
     * @param $lmId
     * @param $remark
     * @param $type
     * @param $time
     * @return bool
     */
    private function createCron($lmId, $remark, $type, $time)
    {
        $cronSdk = new Cron(Service::instance());
        $cronServ = new CronService();

        // 建立 Job 发送消息
        $cronResult = $cronSdk->add([
            'crRemark' => $remark,
            'crType' => Cron::CR_TYPE_CALLBACK,
            'crParams' => json_encode([
                'lm_id' => $lmId,
                'type' => $type,
            ]),
            'crMethod' => 'POST',
            // 回调地址
            'crReqUrl' => oaUrl('Frontend/Callback/PushMsg/Index'),
            'crTimes' => 1,
            'crCron' => rgmdate((String)$time, 's i G j n ? Y'),
            'crMonitorExecution' => $cronSdk::CR_MONITOR_EXECUTION_FALSE,
            'crDescription' => '直播开始时推送消息提醒',
        ]);
        if (empty($cronResult['crId'])) {
            E(L('_ERR_CRON_OPTION_FAILED', ['option' => '创建']));
        }
        // 记录计划任务
        $cronServ->insert([
            'lm_id' => $lmId,
            'cron_id' => $cronResult['crId'],
            'type' => $type
        ]);

        return true;
    }

    /**
     * 处理聊天室
     * @param $lmId
     * @return bool
     */
    private function createChatRoom($lmId)
    {
        if ($this->isUpdate) {
            return true;
        }

        // 创建群组
        $timRestApi = new TimRestAPI();
        $chatRoomResult = $timRestApi->group_create_group2(
            // 类型
            'ChatRoom',
            // 名称
            'yuanquan_chat_room_' . $lmId,
            // 群主
            '',
            [
                // 简介
                'introduction' => null,
                // 群公告
                'notification' => null,
                // 群头像url地址
                'face_url' => null,
                // 群成员最大数量
                'max_member_num' => 500,
            ],
            // 初始群成员列表
            []
        );
        if ($chatRoomResult['ErrorCode'] != 0) {
            \Think\Log::record('处理聊天室失败:::' . $chatRoomResult['ErrorCode'] . ':::' . $chatRoomResult['ErrorInfo']);
            E(L('_ERR_CREATE_IM_CHATROOM_FAILED', ['error' => $chatRoomResult['ErrorInfo']]));
        }

        // 保存聊天室关联
        $imServ = new ImService();
        $imServ->insert([
            'lm_id' => $lmId,
            'group_id' => $chatRoomResult['GroupId']
        ]);

        return true;
    }

    /**
     * 格式化权限数据
     * @return array
     */
    private function formatRangeData($data)
    {
        $right = [];
        // 非全公司
        if (Constant::RANGE_IS_ALL_TRUE != $data['range']['is_all']) {
            foreach (['uids', 'dp_ids', 'job_ids', 'role_ids', 'tag_ids'] as $type) {
                if (!empty($data['range'][$type])) {
                    $right[$type] = $data['range'][$type];
                }
            }
        } else {
            $right['is_all'] = Constant::RANGE_IS_ALL_TRUE;
        }

        return $right;
    }

    /**
     * 获取可观看总人数
     * @param $data
     * @return array
     */
    private function rangeAll($data)
    {
        if (isset($data['range']['is_all']) &&
            $data['range']['is_all'] == Constant::RANGE_IS_ALL_TRUE) {
            $range[Constant::RANGE_TYPE_ALL] = Constant::RANGE_TYPE_ALL;
        } else {
            $rangeType = [
                'dp_ids' => Constant::RANGE_TYPE_DEPARTMENT,
                'uids' => Constant::RANGE_TYPE_USER,
                'job_ids' => Constant::RANGE_TYPE_JOB,
                'role_ids' => Constant::RANGE_TYPE_ROLE,
                'tag_ids' => Constant::RANGE_TYPE_TAG
            ];
            foreach ($rangeType as $type => $const) {
                if (isset($data['range'][$type])) {
                    $range[$const] = $data['range'][$type];
                }
            }
        }

        $rangeServ = new RangeService();
        return $rangeServ->getUidsByRange($range);
    }
}