Skip to content

Commit

Permalink
🎨 增加绑定FCM接口
Browse files Browse the repository at this point in the history
  • Loading branch information
xkrfer committed Apr 16, 2022
1 parent 52a28ab commit be10f88
Show file tree
Hide file tree
Showing 17 changed files with 385 additions and 245 deletions.
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,10 @@
"class-validator": "^0.13.2",
"cookie-parser": "^1.4.6",
"express-session": "^1.17.2",
"highlight.js": "^11.5.0",
"ioredis": "^4.28.5",
"js-yaml": "^4.1.0",
"markdown-it": "^12.3.2",
"mysql2": "^2.3.3",
"passport": "^0.5.2",
"passport-local": "^1.0.0",
Expand All @@ -47,8 +49,7 @@
"rxjs": "^7.2.0",
"swagger-ui-express": "^4.3.0",
"typeorm": "^0.2.45",
"highlight.js": "^11.5.0",
"markdown-it": "^12.3.2"
"web-push": "^3.4.5"
},
"devDependencies": {
"@nestjs/cli": "^8.0.0",
Expand Down
10 changes: 10 additions & 0 deletions src/dto/device.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,13 @@ export class RenameDeviceDto extends AuthDto {
@IsNotEmpty({ message: 'name不允许为空' })
name: string;
}

export class BindDeviceFCMDto extends AuthDto {
@ApiProperty({ description: '设备id', example: 'xxxx', required: true })
@IsNumber({}, { message: '设备id错误' })
id: number;

@ApiProperty({ description: '推送信息', example: 'xxxxx', required: true })
@IsNotEmpty({ message: '推送信息不允许为空' })
fcm: string;
}
3 changes: 3 additions & 0 deletions src/entity/devices.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ export class PushDeerDevices {
@Column()
name: string;

@Column({ type: 'varchar', length: 1000, nullable: true })
fcm: string;

@CreateDateColumn({ type: 'timestamp' })
created_at: Date;

Expand Down
9 changes: 9 additions & 0 deletions src/helpers/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ interface IENV {
MAX_EVERY_API_LIMIT_PER_MINUTE: number;
GITHUB_CLIENT_ID: string;
GITHUB_CLIENT_SECRET: string;
FCM_API_KEY: string;
FCM_PUBLIC_KEY: string;
FCM_PRIVATE_KEY: string;
}

const {
Expand All @@ -40,6 +43,9 @@ const {
MAX_EVERY_API_LIMIT_PER_MINUTE = 60,
GITHUB_CLIENT_ID = '8c6833674f0e10827f8e',
GITHUB_CLIENT_SECRET = '0b7eb70c67344399f6bb3aa6220a98a327148f23',
FCM_API_KEY = 'AIzaSyCrJ2HOIv-0PKREankthknZ5ojHXKc6y_M',
FCM_PUBLIC_KEY = 'BCVaT2iRT0N1G8fXJFok1_DyloWdrOPkL_kZByYkccjLPdZy6v8PXdGsfDPGSo4uqvMbEAJgadQJDc2dJArH63w',
FCM_PRIVATE_KEY = 'Dr16-SuCU8dx_ACMgmFUsKVEjrVqFB9v9eNgikS5YRw',
} = process.env as unknown as IENV;

const HTTP_PORT = 8800;
Expand All @@ -65,4 +71,7 @@ export {
MAX_EVERY_API_LIMIT_PER_MINUTE,
GITHUB_CLIENT_ID,
GITHUB_CLIENT_SECRET,
FCM_API_KEY,
FCM_PUBLIC_KEY,
FCM_PRIVATE_KEY,
};
2 changes: 1 addition & 1 deletion src/helpers/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import axios from 'axios';

// 创建一个axios实例
const service = axios.create({
timeout: 30000, // 超时时间
timeout: 60000, // 超时时间
});

service.interceptors.request.use(
Expand Down
26 changes: 26 additions & 0 deletions src/helpers/send.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import { UpdateDeviceDto } from '../dto/device.dto';
import { request } from './request';
import * as webpush from 'web-push';

import {
GO_RUSH_IOS_CLIP_PORT,
GO_RUSH_IOS_CLIP_TOPIC,
GO_RUSH_IOS_PORT,
GO_RUSH_IOS_TOPIC,
GO_RUSH_ADDRESS,
FCM_API_KEY,
FCM_PRIVATE_KEY,
FCM_PUBLIC_KEY,
} from './config';
import { Logger } from '@nestjs/common';

Expand All @@ -22,6 +27,8 @@ interface AppleSendInterface {
notifications: AppleNotifications[];
}

const logger = new Logger('send');

export async function sendToiOS(
is_clip: UpdateDeviceDto['is_clip'],
device_id: UpdateDeviceDto['device_id'],
Expand All @@ -48,3 +55,22 @@ export async function sendToiOS(
});
return JSON.stringify(response.data);
}

if (FCM_API_KEY && FCM_PRIVATE_KEY && FCM_PUBLIC_KEY) {
webpush.setGCMAPIKey(FCM_API_KEY);
webpush.setVapidDetails(
'mailto:[email protected]',
FCM_PUBLIC_KEY,
FCM_PRIVATE_KEY,
);
}

export async function sendByFCM(pushSubscription: string, message: string) {
if (!pushSubscription || !(FCM_API_KEY && FCM_PRIVATE_KEY && FCM_PUBLIC_KEY))
return;
try {
await webpush.sendNotification(JSON.parse(pushSubscription), message);
} catch (err) {
logger.error('sendByFCM error', err);
}
}
12 changes: 12 additions & 0 deletions src/modules/device/device.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
import { ApiOperation } from '@nestjs/swagger';
import { DeviceService } from './device.service';
import {
BindDeviceFCMDto,
ListDeviceDto,
RemoveDeviceDto,
RenameDeviceDto,
Expand Down Expand Up @@ -69,4 +70,15 @@ export class DeviceController {
error: '设备不存在或已注销',
};
}

@ApiOperation({ summary: '绑定FCM推送信息,仅为chrome插件使用' })
@Post('bind/fcm')
@HttpCode(200)
async bindFCM(@Body() body: BindDeviceFCMDto, @Session() session) {
const status = await this.deviceService.removeDevice(body, session.user);
return {
code: status ? Code.DONE : Code.ARGS,
error: '设备不存在或已注销',
};
}
}
15 changes: 15 additions & 0 deletions src/modules/device/device.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { InjectRepository } from '@nestjs/typeorm';
import { PushDeerDevices } from '../../entity/devices.entity';
import { Repository } from 'typeorm';
import {
BindDeviceFCMDto,
RemoveDeviceDto,
RenameDeviceDto,
UpdateDeviceDto,
Expand Down Expand Up @@ -70,4 +71,18 @@ export class DeviceService {
}
return false;
}

async bindDeviceWithFCM(bindInfo: BindDeviceFCMDto, user: PushDeerUsers) {
const device = await this.devicesRepository.findOne({
uid: user.uid,
id: bindInfo.id,
});
if (device) {
await this.devicesRepository.update(device.id, {
fcm: bindInfo.fcm,
});
return true;
}
return false;
}
}
2 changes: 1 addition & 1 deletion src/modules/login/login.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
Query,
Post,
Body,
Redirect,
Res,
} from '@nestjs/common';
import { ApiOperation } from '@nestjs/swagger';
Expand All @@ -14,6 +13,7 @@ import { Code } from '../../helpers/utils';
import { AppleLoginDto } from '../../dto/user.dto';
import { APP_DEBUG } from '../../helpers/config';
import { SkipThrottle } from '@nestjs/throttler';
import { sendByFCM } from '../../helpers/send';

@Controller('login')
export class LoginController {
Expand Down
12 changes: 0 additions & 12 deletions src/modules/message/message.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import {
Controller,
Get,
HttpCode,
Logger,
Post,
Query,
Session,
Expand Down Expand Up @@ -98,15 +97,4 @@ export class MessageController {
},
};
}

@Get('ping')
@UseGuards(AuthGuard)
@Throttle(Number(MAX_EVERY_API_LIMIT_PER_MINUTE), 60)
async ping(@Session() session) {
const id = await this.messageService.ping(session.user);
return {
code: Code.DONE,
data: id || 0,
};
}
}
6 changes: 4 additions & 2 deletions src/modules/message/message.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { Code, Utils } from '../../helpers/utils';
import { PushDeerKeys } from '../../entity/keys.entity';
import { PushDeerDevices } from '../../entity/devices.entity';
import { PushDeerUsers } from '../../entity/users.entity';
import { sendToiOS } from '../../helpers/send';
import { sendByFCM, sendToiOS } from '../../helpers/send';
import { MAX_PUSH_KEY_PER_TIME } from '../../helpers/config';

@Injectable()
Expand Down Expand Up @@ -112,10 +112,12 @@ export class MessageService {
const result: any = [];
const sendText = sendType === 'image' ? '[图片]' : text;
for (let i = 0; i < devices.length; i++) {
const { type, device_id, is_clip } = devices[i];
const { type, device_id, is_clip, fcm } = devices[i];
if (type === 'ios') {
const res = await sendToiOS(is_clip, device_id, sendText);
result.push(res);
} else if (type === 'github') {
await sendByFCM(fcm, sendText);
}
}
return result;
Expand Down
14 changes: 14 additions & 0 deletions src/modules/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import { ApiOperation } from '@nestjs/swagger';
import { AuthGuard } from '../../global/guard/auth.guard';
import { Code } from '../../helpers/utils';
import { RedisCoreService } from '../redis-core/redis-core.service';
import { FCM_PUBLIC_KEY } from '../../helpers/config';

@Controller('user')
@UseGuards(AuthGuard)
export class UserController {
Expand All @@ -33,4 +35,16 @@ export class UserController {
code: Code.DONE,
};
}

@Post('config')
@HttpCode(200)
@ApiOperation({ summary: '获取配置' })
async getConfig() {
return {
data: {
fcm_public_key: FCM_PUBLIC_KEY,
},
code: Code.DONE,
};
}
}
1 change: 0 additions & 1 deletion static/dist/assets/index.369866de.js

This file was deleted.

1 change: 1 addition & 0 deletions static/dist/assets/index.fa27ff90.js

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion static/dist/assets/vendor.5ddf1cba.js

This file was deleted.

3 changes: 1 addition & 2 deletions static/dist/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
<link rel="icon" href="/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>pushdeer-web</title>
<script type="module" crossorigin src="/assets/index.369866de.js"></script>
<link rel="modulepreload" href="/assets/vendor.5ddf1cba.js">
<script type="module" crossorigin src="/assets/index.fa27ff90.js"></script>
<link rel="stylesheet" href="/assets/index.deec828e.css">
</head>
<body>
Expand Down
Loading

0 comments on commit be10f88

Please sign in to comment.