派生自 projectDept/qhighschool

胡仁荣
2023-09-11 8c1ac419031d562152ec86437215193c20c909b7
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
package com.qxueyou.scc.stucontroller;
 
import java.util.*;
import java.util.concurrent.TimeUnit;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qxueyou.scc.base.dao.CommonDAO;
import com.qxueyou.scc.base.model.Pager;
import com.qxueyou.scc.config.IpUtils;
import com.qxueyou.scc.sdk.MTCloud;
import com.qxueyou.scc.teach.live.model.AccessLog;
import com.qxueyou.scc.teach.live.utils.RedisCache;
import com.qxueyou.scc.teach.student.model.StuStudent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import com.qxueyou.scc.admin.classes.model.ClsClass;
import com.qxueyou.scc.admin.classes.service.IClassService;
import com.qxueyou.scc.base.model.Result;
import com.qxueyou.scc.base.util.ClientUtils;
import com.qxueyou.scc.base.util.CollectionUtils;
import com.qxueyou.scc.base.util.QBeanUtils;
import com.qxueyou.scc.teach.live.dao.MediaLiveDAO;
import com.qxueyou.scc.teach.live.model.MediaVideoLive;
import com.qxueyou.scc.teach.live.service.IMediaLiveService;
 
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
 
import javax.servlet.http.HttpServletRequest;
 
@Slf4j
@Api(tags="直播接口-学员端")
@RestController
@CrossOrigin
@RequestMapping(value = "/stu/live")
public class StuLiveController {
    
    @Autowired
    IClassService classService;
    
    @Autowired
    IMediaLiveService liveService;
    
    @Autowired
    MediaLiveDAO dao;
 
    @Autowired
    RedisCache redisCache;
 
    @Autowired
    CommonDAO commonDAO;
    
    private final static short[] PUBLIC_LIVE_STATUS = new short[] {
            MediaVideoLive.STATUS_LIVE_LIVE,MediaVideoLive.STATUS_LIVE_PAUSE,
            MediaVideoLive.STATUS_LIVE_STOP,MediaVideoLive.STATUS_LIVE_REVIEW
    };
    
    /**
     * 获取直播列表
     * @param classId 班级id
     * @return
     */
    @ApiOperation(value = "获取直播列表", notes = "")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "classId", value = "班级id", required = true, paramType="query", dataType = "String"),
        @ApiImplicitParam(name = "status", value = "直播状态(2正在直播,5直播中的暂停状态,9停止直播,3回放)", required = true, paramType="query", dataType = "String"),
    })
    @GetMapping(value = "list")
    public Result list(String classId, Short status) {
        short[] _status = null;
        if(status == null || status == 0) {
            _status = PUBLIC_LIVE_STATUS;
        }else {
            _status = new short[]{status};
        }
        
        List<String> liveIds = getLiveIdLst(StringUtils.isEmpty(classId)?ClientUtils.getClassId():classId);
 
        List<MediaVideoLive> lives = liveService.readByStatus(liveIds,_status);
        
        List<Map<String,Object>> lst =QBeanUtils.listBean2ListMap(lives, CollectionUtils.newStringMap(
                "creator","creator",
                "startTime","startTime",
                "endTime","endTime",
                "updateTime","lastUpdateTime",
                "videoLiveId","videoLiveId",
                "name","name",
                "status","status",
                "hlsPullUrl","hlsPullUrl",
                "previewImgUrl","imgPath"
                ));
        
        //添加聊天室id
        if(lst!=null && lst.size()>0){
            for(Map<String,Object> map:lst) {
                map.put("chatroomId", dao.getChatRoomId((String)map.get("videoLiveId")));
            }    
        }
        
        return new Result(true, "success", CollectionUtils.newObjectMap("liveCount", lst==null?0:lst.size(), "liveLst",lst));
    }
 
    /**
     * 获取直播id
     * @param classId
     * @return
     */
    private List<String> getLiveIdLst(String classId) {
        List<String> liveIds = new ArrayList<String>(5);
 
        //获取班级列表及班级所在直播列表
        if(StringUtils.isNotEmpty(classId)) {
            liveIds = dao.getClassLives(classId);
        }else { //查询学员所在的全部班级
            List<ClsClass> clsLst = classService.listMyClass();
            Set<String> ids = new HashSet<String>();
            for(ClsClass cls:clsLst) {
                ids.addAll(dao.getClassLives(cls.getClassId()));
            }
            liveIds.addAll(ids);
        }
        return liveIds;
    }
    
    /**
     * 查看直播明细
     * @param couresId 直播id
     * @return
     */
    @GetMapping(value = "view")
    public Result view(String couresId, String userId, String userName, String logId, HttpServletRequest request) throws Exception {
        String redisLiveUrl = redisCache.getCacheObject("LIVE_URL" + userId);
        AccessLog accessLog=new AccessLog();
        if(StringUtils.isEmpty(logId)){
            String ip = IpUtils.getIpAddr(request);
            String cityInfo = null;
            try {
                cityInfo = IpUtils.getCityInfo(ip);
            } catch (Exception e) {
                log.error("获取ip归属地信息失败!");
            }
            accessLog.setCourseId(couresId);
            accessLog.setEnterTime(new Date());
            accessLog.setType("guangxi");
            accessLog.setName(userName);
            accessLog.setIp(ip);
            accessLog.setIpAttribution(cityInfo);
            accessLog.setCreateTime(new Date());
            accessLog.setUpdateTime(new Date());
            commonDAO.save(accessLog);
        }
        if (!StringUtils.isEmpty(redisLiveUrl)){
            return new Result(true, "success",CollectionUtils.newObjectMap("url",redisLiveUrl,"log",accessLog.getLogId()));
        }
        MTCloud client = new MTCloud();
        String userRole = null;
        HashMap<Object,Object> options = new HashMap<Object, Object>();
        if(userId.equals("")){
            userId= randomId();
        }
        if(userName.equals("") || userName==null){
            userName= "游客";
            userRole=MTCloud.ROLE_GUEST;
        }else {
            userRole=MTCloud.ROLE_USER;
        }
        String res = client.courseAccess(couresId,userId,userName,userRole, 10000, options);
 
        JSONObject jsonObject = JSON.parseObject(res);
 
        if(jsonObject.getString("code").equals("0")){
            JSONObject data = jsonObject.getJSONObject("data");
            String liveUrl = (String) data.get("liveUrl");
            StringBuffer redisLiveKey = new StringBuffer("LIVE_URL");
            redisLiveKey.append(userId);
            redisCache.setCacheObject(redisLiveKey.toString(),liveUrl,5, TimeUnit.MINUTES);
            return new Result(true, "success",CollectionUtils.newObjectMap("url",liveUrl,"log",accessLog.getLogId()));
        }
 
        return new Result(false, jsonObject.getString("msg"));
    }
 
    @ApiOperation(value = "离开路演直播间")
    @GetMapping(value = "leaveRoadShow")
    public Result enterIntoRoadShow(String logId)  {
//        System.out.println(logId);
        if(!StringUtils.isEmpty(logId)){
            StringBuffer hql=new StringBuffer("from AccessLog where logId=?");
            List<Object> args = CollectionUtils.newList(logId);
            AccessLog accessLogs = commonDAO.findUnique(hql.toString(), args, AccessLog.class);
//            System.out.println(accessLogs);
            accessLogs.setLeaveTime(new Date());
            accessLogs.setUpdateTime(new Date());
            commonDAO.update(accessLogs);
            return new Result(true,"退出成功");
        }
        return new Result(false,"logId不能为空");
    }
 
 
    public  String randomId() {
            Random random=new Random();
            String str="";
            for (int i = 0; i <12; i++) {
                if(i==0){
                    //首位不能为0且数字取值区间为 [1,9]
                    str+=(random.nextInt(9)+1);
                }else{
                    //其余位的数字的取值区间为 [0,9]
                    str+=random.nextInt(10);
                }
            }
            return str;
        }
 
 
}