Skip to content

Commit

Permalink
feat: 增加offline_event_record表, 完成好友互发消息
Browse files Browse the repository at this point in the history
  • Loading branch information
leewei0923 committed Nov 25, 2022
1 parent b74b3cd commit f06ecff
Show file tree
Hide file tree
Showing 10 changed files with 358 additions and 10 deletions.
10 changes: 9 additions & 1 deletion src/comm/database/mysql.providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { getConfig } from '../../utils/index';
import { ttalk_user } from 'src/ttalk/entities/ttalk.entity.mysql';
import { ttalk_user_concat } from 'src/ttalk/entities/user_concat.entity.mysql';
import { ttalk_online } from 'src/ttalk/entities/online.entity.mysql';
import { message_record } from 'src/ttalk/entities/message_record.entity.mysql';
import { offline_events_record } from 'src/ttalk/entities/offline_events_record.entity.mysql';

/**
* Mysql 数据库
Expand All @@ -19,7 +21,13 @@ const MYSQL_DATABASE_CONFIG = {
// entities: [
// path.join(__dirname, `dist/**/*.${MYSQL_CONFIG.entities}.entity{.ts,.js}`),
// ],
entities: [ttalk_user, ttalk_user_concat, ttalk_online],
entities: [
ttalk_user,
ttalk_user_concat,
ttalk_online,
message_record,
offline_events_record,
],
};

const MYSQL_DATA_SOURCE = new DataSource(MYSQL_DATABASE_CONFIG);
Expand Down
35 changes: 35 additions & 0 deletions src/ttalk/dto/message.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty } from 'class-validator';

export class SaveMessageDto {
@ApiProperty({ example: '' })
@IsNotEmpty()
user_account: string;

@IsNotEmpty()
friend_account: string;

@IsNotEmpty()
mood_state: string;

@IsNotEmpty()
message_style: string;

@IsNotEmpty()
message: string;

@IsNotEmpty()
read_flag: boolean;
}

export class updateFlagDto {
@ApiProperty({ example: '' })
@IsNotEmpty()
id: string[] | string;

@IsNotEmpty()
user_account: string;

@IsNotEmpty()
friend_account: string;
}
31 changes: 31 additions & 0 deletions src/ttalk/entities/message_record.entity.mysql.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { PrimaryGeneratedColumn, Column, Entity } from 'typeorm';

@Entity()
export class message_record {
@PrimaryGeneratedColumn()
id: number;

@Column()
message_id: string;

@Column()
user_account: string;

@Column()
friend_account: string;

@Column()
mood_state: string;

@Column()
message: string;

@Column()
create_time: string;

@Column()
message_style: string;

@Column()
read_flag: boolean;
}
25 changes: 25 additions & 0 deletions src/ttalk/entities/offline_events_record.entity.mysql.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { PrimaryGeneratedColumn, Column, Entity } from 'typeorm';

@Entity()
export class offline_events_record {
@PrimaryGeneratedColumn()
id: number;

@Column()
user_account: string;

@Column()
friend_account: string;

@Column()
event_type: string;

@Column()
create_time: string;

@Column()
update_time: string;

@Column()
end_flag: boolean;
}
159 changes: 150 additions & 9 deletions src/ttalk/events.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ import { ttalk_online } from './entities/online.entity.mysql';
import { ttalk_user } from './entities/ttalk.entity.mysql';
import { ttalk_user_concat } from './entities/user_concat.entity.mysql';
import { addFriendType } from 'src/types';
import { SaveMessageDto } from './dto/message.dto';
import { message_record } from './entities/message_record.entity.mysql';
import { offline_events_record } from './entities/offline_events_record.entity.mysql';
import { OfflineEventsName } from './types';
import { nanoid } from 'nanoid';

@WebSocketGateway(3102, { cors: true })
export class EventsGateway {
Expand All @@ -21,6 +26,10 @@ export class EventsGateway {
private TTalkUserConcatRepository: Repository<ttalk_user_concat>,
@Inject('TTALK_ONLINE_REPOSITORY')
private TTalkOnlineRepository: Repository<ttalk_online>,
@Inject('MESSAGE_RECORD_REPOSITORY')
private MessageRecordRepository: Repository<message_record>,
@Inject('OFFLINE_EVENTS_RECORD_REPOSITORY')
private EventRecordRepository: Repository<offline_events_record>,
) {}

@WebSocketServer() server: Server;
Expand Down Expand Up @@ -165,22 +174,38 @@ export class EventsGateway {
friends: friend[0],
user: userRes[0],
});
} else {
// 离线状态下添加好友的事件存储
this.offlineEventsSave(
user_account,
friend_account,
OfflineEventsName.APPLY,
);
}
} else if (type === 'accept') {
// 更新联系人身份关系
const query = `UPDATE ttalk_user_concat SET friend_flag = true WHERE user_account = '${friend_account}' AND friend_account = '${user_account}'`;
this.TTalkUserConcatRepository.query(query);

// 查找基础信息
const userRes: any = await this.TTalkUserRepository.query(
`SELECT id, social, ip, nickname, motto , account, avatar, bird_date, add_time, update_time FROM ttalk_user WHERE account = '${user_account}'`,
);
if (online) {
// 查找基础信息
const userRes: any = await this.TTalkUserRepository.query(
`SELECT id, social, ip, nickname, motto , account, avatar, bird_date, add_time, update_time FROM ttalk_user WHERE account = '${user_account}'`,
);

this.server.to(online.online_id).emit('addFriend', {
type: 'accept',
friends: { friend_account: user_account },
user: userRes[0],
});
this.server.to(online.online_id).emit('addFriend', {
type: 'accept',
friends: { friend_account: user_account },
user: userRes[0],
});
} else {
// 离线状态下的事件存储
this.offlineEventsSave(
user_account,
friend_account,
OfflineEventsName.ACCEPT,
);
}
}
return '';
}
Expand Down Expand Up @@ -217,4 +242,120 @@ export class EventsGateway {
} else {
}
}

/**
* 收到消息,发送给接收方
*/
@SubscribeMessage('messaging')
async handleMessing(client: Socket, payload: SaveMessageDto) {
const {
user_account,
friend_account,
message,
mood_state,
message_style,
read_flag,
} = payload;
const curDate = dayjs().format('YYYY-MM-DD HH:mm');
const message_id = nanoid();

// 先查询是否在线,在线将信息存入数据库,然后把信息发送给朋友
// 离线状态,保存数据,将信息存入离线记录

// 自己给自己发送的消息只保存处理
if (user_account !== friend_account) {
const onlineFriendRes = await this.TTalkOnlineRepository.find({
where: {
account: friend_account,
onlineFlag: true,
},
});

if (onlineFriendRes.length > 0) {
for (let i = 0; i < onlineFriendRes.length; i++) {
const to_friend_message = {
user_account: payload.friend_account,
friend_account: payload.user_account,
message: payload.message,
mood_state: payload.mood_state,
message_style: payload.message_style,
read_flag: payload.read_flag,
message_id,
create_time: curDate,
update_time: curDate,
};

this.server
.to(onlineFriendRes[i].online_id)
.emit('messaging', to_friend_message);
}
} else {
// 离线信息存储
this.offlineEventsSave(
user_account,
friend_account,
OfflineEventsName.MESSAGING,
);
}
}

// 将信息存入数据库
this.MessageRecordRepository.save({
message_id,
user_account,
friend_account,
mood_state,
message_style,
message,
read_flag,
create_time: curDate,
});
}

/**
* 用于离线事件存储
* @param user_account 发送方
* @param friend_account 接收方
* @param event 事件类型
* @param end_flag 事件结束标志
*/
private offlineEventsSave(
user_account: string,
friend_account: string,
event: OfflineEventsName,
end_flag?: boolean,
) {
const curDate = dayjs().format('YYYY-MM-DD HH:mm');

this.EventRecordRepository.findOne({
where: {
user_account,
friend_account,
end_flag: false,
event_type: event,
},
}).then((res) => {
// 传入end_flag 不需要执行后续的程序
if (typeof end_flag === 'boolean') {
const queryCode = `UPDATE offline_events_record SET end_flag = ${end_flag} where user_account = '${res.user_account}' AND friend_account = '${res.friend_account}' AND id = '${res.id}'`;
this.EventRecordRepository.query(queryCode);

return;
}

// 如果查找到已经存在的消息,更新update否则更新时间
if (typeof res !== 'object') {
this.EventRecordRepository.save({
user_account,
friend_account,
event_type: event,
create_time: curDate,
update_time: curDate,
});
} else {
const queryCode = `UPDATE offline_events_record SET update_time = ${curDate} where user_account = '${res.user_account}' AND friend_account = '${res.friend_account}' AND id = '${res.id}'`;
this.EventRecordRepository.query(queryCode);
}
});
}
}
20 changes: 20 additions & 0 deletions src/ttalk/talk.providers.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { message_record } from './entities/message_record.entity.mysql';
import { offline_events_record } from './entities/offline_events_record.entity.mysql';
import { ttalk_online } from './entities/online.entity.mysql';
import { ttalk_user } from './entities/ttalk.entity.mysql';
import { ttalk_user_concat } from './entities/user_concat.entity.mysql';
Expand Down Expand Up @@ -28,3 +30,21 @@ export const TTalkOnlineProviders = [
inject: ['MYSQL_DATA_SOURCE'],
},
];

export const MessageRecordProviders = [
{
provide: 'MESSAGE_RECORD_REPOSITORY',
useFactory: async (AppDataSource) =>
await AppDataSource.getRepository(message_record),
inject: ['MYSQL_DATA_SOURCE'],
},
];

export const OfflineEventsProviders = [
{
provide: 'OFFLINE_EVENTS_RECORD_REPOSITORY',
useFactory: async (AppDataSource) =>
await AppDataSource.getRepository(offline_events_record),
inject: ['MYSQL_DATA_SOURCE'],
},
];
18 changes: 18 additions & 0 deletions src/ttalk/ttalk.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { TtalkService } from './ttalk.service';
import { UpdateDto } from './dto/update.dto';
import { AuthGuard } from '@nestjs/passport';
import { AddFriendDto, checkOnlineDto, getAndUpdateDto } from './dto/ttalk.dto';
import { SaveMessageDto, updateFlagDto } from './dto/message.dto';

@Controller('/server/ttalk')
export class TtalkController {
Expand Down Expand Up @@ -117,4 +118,21 @@ export class TtalkController {
getAndUpdateUserIfo(@Body() data: getAndUpdateDto) {
return this.ttalkService.getAndUpdateAccountInfo(data);
}

/** 消息存储 */
@UseGuards(AuthGuard('jwt'))
@Post('/saveNewMessage')
saveNewMessage(@Body() data: SaveMessageDto) {
return this.ttalkService.saveFriendMessage(data);
}

/**
* 更新阅读状态
*/
/** 获取消息存储 */
@UseGuards(AuthGuard('jwt'))
@Post('/updateMessageFlag')
updateMessageFlag(@Body() data: updateFlagDto) {
return this.ttalkService.updateReadFlag(data);
}
}
4 changes: 4 additions & 0 deletions src/ttalk/ttalk.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { Module } from '@nestjs/common';
import { TtalkService } from './ttalk.service';
import { TtalkController } from './ttalk.controller';
import {
MessageRecordProviders,
OfflineEventsProviders,
TTalkOnlineProviders,
TTalkUserConcatProviders,
TTalkUserProviders,
Expand All @@ -18,6 +20,8 @@ import { EventsGateway } from './events.gateway';
...TTalkUserProviders,
...TTalkUserConcatProviders,
...TTalkOnlineProviders,
...MessageRecordProviders,
...OfflineEventsProviders,
EventsGateway,
],
})
Expand Down
Loading

0 comments on commit f06ecff

Please sign in to comment.