Skip to content

Commit

Permalink
feat: 优化架构
Browse files Browse the repository at this point in the history
  • Loading branch information
galaxy-s10 committed Aug 18, 2023
1 parent 367174e commit 5d18997
Show file tree
Hide file tree
Showing 15 changed files with 320 additions and 241 deletions.
7 changes: 4 additions & 3 deletions src/app/verify.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,10 @@ const frontendWhiteList = [
'/email_user/register', // 注册,这个接口是post的
'/order/pay',
'/wallet/init',
'/live_room/on_publish',
'/live_room/on_play',
'/live_room/on_unpublish',

'/srs/on_publish',
'/srs/on_play',
'/srs/on_unpublish',
'/srs/rtcV1Publish',
'/srs/rtcV1Play',
'/srs/apiV1StreamsDel',
Expand Down
24 changes: 12 additions & 12 deletions src/config/secretTemp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,6 @@ export const TENCENTCLOUD_LIVE = {
Key: '**********', // 鉴权Key,https://console.cloud.tencent.com/live/domainmanage/detail/185429.push.tlivecloud.com?tab=pushConfig
};

export const SERVER_LIVE = {
PushDomain:
PROJECT_ENV === PROJECT_ENV_ENUM.development
? 'rtmp://localhost'
: '**********', // 推流域名
PullDomain:
PROJECT_ENV === PROJECT_ENV_ENUM.development
? 'http://localhost:5001'
: '**********', // 拉流域名
AppName: 'livestream',
};

export const MYSQL_CONFIG = {
docker: {
container: 'billd-live-mysql',
Expand Down Expand Up @@ -145,3 +133,15 @@ export const ALIPAY_LIVE_CONFIG = {
'**********************************************************************************************************************************************************************************************************************',
gateway: '**********',
}; // 支付宝当面付-自然博客直播

export const SERVER_LIVE = {
PushDomain:
PROJECT_ENV === PROJECT_ENV_ENUM.development
? 'rtmp://localhost'
: '**********', // 推流域名
PullDomain:
PROJECT_ENV === PROJECT_ENV_ENUM.development
? `http://localhost:${SRS_CONFIG.docker.port['8080']}` // http://localhost:5001、http://localhost:8000/livestream
: '**********', // 拉流域名
AppName: 'livestream',
};
83 changes: 25 additions & 58 deletions src/config/websocket/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,27 +107,6 @@ async function updateUserJoinedRoom(data: {
}
}

async function updateRoomIsLiveing(data: {
liveRoomId: number;
client_ip?: string;
}) {
try {
const res = await liveRedisController.getAnchorLiving({
liveRoomId: data.liveRoomId,
});
if (res) {
await liveRedisController.setAnchorLiving({
liveRoomId: data.liveRoomId,
socketId: res.value.socketId,
userInfo: res.value.userInfo,
client_ip: data.client_ip,
});
}
} catch (error) {
console.log(error);
}
}

export const wsSocket: { io?: Server } = {
io: undefined,
};
Expand Down Expand Up @@ -212,7 +191,10 @@ export const connectWebSocket = (server) => {
console.log(chalkERROR('roomId为空'));
return;
}
const [liveRoomInfo] = await Promise.all([liveRoomService.find(roomId)]);
const [liveRoomInfo, liveInfo] = await Promise.all([
liveRoomService.find(roomId),
liveService.findByRoomId(roomId),
]);
if (!liveRoomInfo) {
console.log(chalkERROR('liveRoomInfo为空'));
return;
Expand Down Expand Up @@ -244,7 +226,7 @@ export const connectWebSocket = (server) => {
liveUser,
},
});
if (liveRoomInfo.type === LiveRoomTypeEnum.system) {
if (liveRoomInfo.type === LiveRoomTypeEnum.system && liveInfo) {
socketEmit<WsRoomLivingType['data']>({
socket,
msgType: WsMsgTypeEnum.roomLiving,
Expand All @@ -258,33 +240,28 @@ export const connectWebSocket = (server) => {
userInfo: data.user_info,
client_ip: socket.handshake.address,
});
} else if (!liveInfo) {
socketEmit<WsRoomNoLiveType['data']>({
socket,
msgType: WsMsgTypeEnum.roomNoLive,
data: {
live_room: liveRoomInfo,
},
});
} else {
const anchorIsLiving = await liveRedisController.getAnchorLiving({
liveRoomId: data.data.live_room.id!,
socketEmit<WsRoomLivingType['data']>({
socket,
msgType: WsMsgTypeEnum.roomLiving,
data: {
live_room: liveRoomInfo,
},
});
liveRedisController.setUserJoinedRoom({
socketId: socket.id,
joinRoomId: roomId,
userInfo: data.user_info,
client_ip: socket.handshake.address,
});
if (!anchorIsLiving) {
socketEmit<WsRoomNoLiveType['data']>({
socket,
msgType: WsMsgTypeEnum.roomNoLive,
data: {
live_room: liveRoomInfo,
},
});
} else {
socketEmit<WsRoomLivingType['data']>({
socket,
msgType: WsMsgTypeEnum.roomLiving,
data: {
live_room: liveRoomInfo,
},
});
liveRedisController.setUserJoinedRoom({
socketId: socket.id,
joinRoomId: roomId,
userInfo: data.user_info,
client_ip: socket.handshake.address,
});
}
}

socketEmit<WsOtherJoinType['data']>({
Expand Down Expand Up @@ -323,12 +300,6 @@ export const connectWebSocket = (server) => {
socketId: socket.id,
roomId,
});
liveRedisController.setAnchorLiving({
liveRoomId: userLiveRoomInfo.live_room_id!,
socketId: socket.id,
userInfo: data.user_info,
client_ip: socket.handshake.address,
});
});

// 收到用户获取当前在线用户
Expand Down Expand Up @@ -422,10 +393,6 @@ export const connectWebSocket = (server) => {
});
const liveRoomId = res?.value.userInfo?.live_rooms?.[0].id;
if (liveRoomId && res?.value.joinRoomId === liveRoomId) {
updateRoomIsLiveing({
liveRoomId,
client_ip: socket.handshake.address,
});
}
}
);
Expand Down
43 changes: 0 additions & 43 deletions src/controller/live.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,6 @@ import liveService from '@/service/live.service';

class LiveController {
common = {
create: async ({
socket_id,
live_room_id,
user_id,
track_audio,
track_video,
}: ILive) => {
await liveService.create({
socket_id,
live_room_id,
user_id,
track_audio,
track_video,
});
},
getList: async ({
id,
orderBy = 'asc',
Expand Down Expand Up @@ -83,34 +68,6 @@ class LiveController {
await next();
}

async create(ctx: ParameterizedContext, next) {
const hasAuth = await verifyUserAuth(ctx);
if (!hasAuth) {
throw new CustomError(
`权限不足!`,
ALLOW_HTTP_CODE.forbidden,
ALLOW_HTTP_CODE.forbidden
);
}
const {
socket_id,
live_room_id,
user_id,
track_audio,
track_video,
}: ILive = ctx.request.body;
await this.common.create({
socket_id,
live_room_id,
user_id,
track_audio,
track_video,
});
successHandler({ ctx });

await next();
}

delete = async (ctx: ParameterizedContext, next) => {
const hasAuth = await verifyUserAuth(ctx);
if (!hasAuth) {
Expand Down
98 changes: 1 addition & 97 deletions src/controller/liveRoom.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,11 @@ import { authJwt } from '@/app/auth/authJwt';
import { verifyUserAuth } from '@/app/auth/verifyUserAuth';
import successHandler from '@/app/handler/success-handle';
import { SERVER_LIVE } from '@/config/secret';
import { wsSocket } from '@/config/websocket';
import { WsMsgTypeEnum } from '@/config/websocket/constant';
import liveRedisController from '@/config/websocket/live-redis.controller';
import { ALLOW_HTTP_CODE } from '@/constant';
import { IList, ILiveRoom, IRoomLiving } from '@/interface';
import { IList, ILiveRoom } from '@/interface';
import { CustomError } from '@/model/customError.model';
import liveService from '@/service/live.service';
import liveRoomService from '@/service/liveRoom.service';
import userLiveRoomService from '@/service/userLiveRoom.service';
import { chalkERROR } from '@/utils/chalkTip';

import liveController from './live.controller';

class LiveRoomController {
common = {
Expand Down Expand Up @@ -67,95 +60,6 @@ class LiveRoomController {
await next();
}

async onPlay(ctx: ParameterizedContext, next) {
// https://ossrs.net/lts/zh-cn/docs/v5/doc/http-callback#nodejs-koa-example
// code等于数字0表示成功,其他错误码代表失败。
ctx.body = { code: 0, msg: 'room is living' };
await next();
}

onPublish = async (ctx: ParameterizedContext, next) => {
// https://ossrs.net/lts/zh-cn/docs/v5/doc/http-callback#nodejs-koa-example
// code等于数字0表示成功,其他错误码代表失败。
const { body } = ctx.request;
console.log(body, 'on_publish参数');
const reg = /^roomId___(.+)/g;
const roomId = reg.exec(body.stream)?.[1];
if (!roomId) {
ctx.body = { code: 1, msg: 'no live_room' };
} else {
const result = await liveRoomService.findKey(Number(roomId));
const rtmptoken = result?.key;
const params = new URLSearchParams(body.param);
const paramstoken = params.get('token');
const paramstype = params.get('type');
if (rtmptoken !== paramstoken) {
console.log('鉴权失败');
ctx.body = { code: 1, msg: 'on_publish auth fail' };
} else {
if (paramstype) {
await this.common.update({
id: Number(roomId),
type: Number(paramstype),
});
}
const isLiveing = await liveService.findByRoomId(Number(roomId));
if (isLiveing) {
console.log('鉴权成功,但是正在直播,不允许推流');
ctx.body = { code: 1, msg: 'room is living' };
// ctx.body = { code: 0, msg: 'on_publish room is living' };
} else {
console.log('鉴权成功,允许推流');
const [liveRoomInfo] = await Promise.all([
liveRoomService.find(Number(roomId)),
]);
if (!liveRoomInfo) {
console.log(chalkERROR('liveRoomInfo为空'));
return;
}
const roomLivingData: IRoomLiving['data'] = {
live_room: liveRoomInfo,
};
wsSocket.io
?.to(roomId)
.emit(WsMsgTypeEnum.roomLiving, { data: roomLivingData });

const liveRoom = await liveRoomService.find(Number(roomId));
liveController.common.create({
live_room_id: Number(roomId),
user_id: liveRoom?.user_live_room?.user?.id,
socket_id: '-1',
track_audio: 1,
track_video: 1,
});
ctx.body = { code: 0, msg: 'on_publish auth success' };
}
}
}
await next();
};

async onUnpublish(ctx: ParameterizedContext, next) {
// https://ossrs.net/lts/zh-cn/docs/v5/doc/http-callback#nodejs-koa-example
// code等于数字0表示成功,其他错误码代表失败。
const { body } = ctx.request;
console.log(body, 'on_unpublish参数');
const reg = /^roomId___(.+)/g;
const roomId = reg.exec(body.stream)?.[1];
if (!roomId) {
console.log('on_unpublish错误');
ctx.body = { code: 1, msg: 'on_unpublish fail, no is room' };
} else {
console.log('on_unpublish成功');
ctx.body = { code: 0, msg: 'on_unpublish success' };
liveController.common.deleteByLiveRoomId(Number(roomId));
liveRedisController.delAnchorLiving({
liveRoomId: Number(roomId),
});
}
await next();
}

updateKey = async (ctx: ParameterizedContext, next) => {
const { code, userInfo, message } = await authJwt(ctx);
if (userInfo) {
Expand Down
Loading

0 comments on commit 5d18997

Please sign in to comment.