Compare commits

...

10 Commits

Author SHA1 Message Date
liufumingren
f5095cb0ee first commit 2026-05-02 19:08:46 +08:00
iamtsm
c46d009e59 feat: v0.05-release
feat: 支持企业开放注册通道
feat: 优化后台管理tab默认选中
feat: 支持指定pm2进程日志路径
feat: 优化请求异常处理
fix: 修复通过分享加入群聊消息错误
fix: 修复浏览器通知失效
fix: 修复画板变量作用域
fix: 修复频道公开开关变更不及时
2025-06-21 21:53:32 +08:00
iamtsm
0f59746e47 feat: update pm2 config 2025-06-15 09:40:20 +08:00
iamtsm
3bd2d8f401 fix: 修复频道备注名称为空默认展示问题 2025-06-13 23:22:01 +08:00
iamtsm
1415e3084a feat: 支持共享剪贴板/优化部署流程/文档更新 2025-06-13 23:22:01 +08:00
https://blog.iamtsm.cn
2c7f2211ea
Merge pull request #4 from freebughao/main
feat: 增加了env中配置redis db 的选项
2025-06-09 15:33:48 +08:00
bughao
8b556319b7 feat: 增加了env中配置redis db 的选项 2025-06-09 15:32:37 +08:00
iamtsm
cfdbc273a7 feat: add LICENSE #2 2025-06-06 20:36:49 +08:00
iamtsm
749cdf1b58 feat: v0.02-release 2025-06-05 09:30:54 +08:00
iamtsm
92efa2b408 feat: update README.md 2025-02-12 17:52:18 +08:00
439 changed files with 56647 additions and 25334 deletions

6
.gitignore vendored
View File

@ -32,8 +32,12 @@ node_modules
dist/
system-dist/
web-dist/
tmp/
.VSCodeCounter/
electron-dist/
.idea/

27
DISCLAIMER.md Normal file
View File

@ -0,0 +1,27 @@
# 免责声明
1.1 如使用本演示网站/开源项目,即表示您已同意本条款。我们 (开源项目维护团队) 始终在不断更改和改进我们的服务。我们可能会增加或删除功能,也可能暂停或彻底停止某项服务。您可以随时停止使用我们的服务,我们也可以随时对我们的服务增加新的限制。
1.2 该网站/开源项目的使用者在使用本演示网站/开源项目前,应仔细阅读以下条款并同意遵守。使用本演示网站/开源项目将被视为对本免责协议的接受和遵守。
## 演示网站/开源项目的性质
2.1 本演示网站/开源项目旨在帮助大家学习webrtc,提供一个学习/演示demo环境,和基础功能代码入门教学
2.2 本演示网站/开源项目提供的服务旨在为用户提供数据传输功能演示,包括但不限于文件传输、直播、音视频通话、远程屏幕共享、聊天等功能的演示。
2.3 使用者应理解,本演示网站/开源项目仅提供技术支持演示,不对数据传输的准确性、及时性、完整性、安全性或合法性负责。使用者应自行承担使用本演示网站/开源项目的风险。
## 使用者责任
3.1 使用者应承担使用本演示网站/开源项目的全部责任和风险。对于使用者通过本演示网站/开源项目进行的任何操作、行为或后果,本演示网站/开源项目不承担任何责任。
3.2 使用者不得利用本演示网站/开源项目进行任何违法、侵权、威胁、诽谤、骚扰、破坏性或其他不当行为。若使用者违反上述规定,本演示网站/开源项目有权立即终止或限制使用者的访问权限。
3.3 本演示网站使用者严禁上传违法违规内容,包括但不限于:色情低俗、政治敏感、、暴力、恶意软件、诈骗、贩卖公民隐私,上传上述内容将永久封禁账号或 IP 地址,并可能承担承担刑事责任
## 免责条款
4.1 本演示网站/开源项目不对任何由于使用本演示网站/开源项目而引起的任何直接、间接、附带、特殊、惩罚性或后续的损害承担责任,包括但不限于利润损失、商业中断、计算机系统故障、数据丢失或其他经济损失。
4.2 本演示网站/开源项目不对任何第三方通过本演示网站/开源项目发布、提供或传输的任何内容的准确性、合法性、安全性或可靠性负责。
## 免责声明的范围
本免责协议适用于使用本演示网站/开源项目的所有用户,无论其身份或目的。该免责协议的内容适用于因使用本演示网站/开源项目而产生的一切事项,包括但不限于使用本演示网站/开源项目的内容、服务或信息所引起的任何纠纷、损失或损害。

View File

@ -1,6 +1,6 @@
MIT License
Copyright (c) 2024 tl-open-source
Copyright (c) 2025 iamtsm
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@ -1,27 +0,0 @@
![TL-RTC-APP Logo](web-v2-res/image/tlrtcapp-logo.svg)
### 安装步骤
1. 克隆仓库:
```bash
git clone https://github.com/tl-open-source/tl-rtc-app.git
```
2. 进入项目目录:
```bash
cd tl-rtc-app
```
3. 安装依赖:
```bash
npm install
```
### 使用说明
1. 启动应用:
```bash
npm start
```
2. 打开浏览器并访问 `http://localhost:9096`。
### 许可证
该项目根据 MIT 许可证授权。有关详细信息,请参阅 [LICENSE](LICENSE) 文件。

73
README_ZH.md Normal file
View File

@ -0,0 +1,73 @@
英文: [README.md](README.md)
<p align="center">
<img src="web-res/image/tlrtcapp-logo.svg" alt="TL-RTC-APP Logo">
</p>
<p align="center">
<img src="web-res/image/channel-chat.png" alt="TL-RTC-APP Channel Chat">
</p>
### 安装步骤
1. 前提条件
```bash
确保已安装 Node.js (v16+) 和 npm,mysql(5.7+), redis(4.0+)。
```
2. 克隆仓库:
```bash
git clone https://github.com/tl-open-source/tl-rtc-app.git
```
3. 进入项目目录:
```bash
cd tl-rtc-app
```
4. 安装依赖:
```bash
npm install
```
5. 安装pm2:
```bash
npm install pm2 -g
```
6. 启动服务:
```bash
npm run http
```
或者 (如需体验音视频/屏幕共享/直播等功能):
```bash
npm run https
```
7. 打包前端资源:
```bash
gulp default
```
### 使用说明
1. 打开浏览器并访问 `http://localhost:9096` (默认)。
2. 通过管理端应用进行IM应用管理 `http://localhost:9098/system.html` (默认)。
### 许可证
该项目根据 MIT 许可证授权。有关详细信息,请参阅 [LICENSE](LICENSE) 文件。
### 免责声明
有关详细信息,请参阅 [DISCLAIMER](DISCLAIMER) 文件。

View File

@ -1,5 +1,7 @@
const path = require("path");
const dotEnv = require("dotenv");
const fs = require("fs");
const { exec } = require("child_process");
/**
* 从.env文件中加载环境变量
@ -44,23 +46,68 @@ const get_env_config = function () {
value = value === 'true'
}
//openai keys转换为数组
if(key === 'openai_keys'){
value = value.split(',')
}
//企业微信通知 keys转换为数组
if(key === 'notify_qiwei_normal' || key === 'notify_qiwei_error'){
value = value.split(',')
}
defaultConfJson[key] = value
})
return defaultConfJson
}
/**
* 设置环境变量
* @param {*} key 配置项的键名(不含 tl_rtc_app_ 前缀)
* @param {*} value 配置项的新值
*/
const set_env_config = function (key, value) {
// 构建完整的环境变量名
const fullKey = `tl_rtc_app_${key}`;
// 获取 .env 文件路径
const envFilePath = path.resolve(__dirname, "../tlrtcapp.env");
try {
// 读取 .env 文件内容
let envContent = fs.readFileSync(envFilePath, 'utf8');
// 准备正则表达式,匹配键值对
const regex = new RegExp(`^${fullKey}=.*$`, 'm');
// 检查键是否存在
if (regex.test(envContent)) {
// 如果键存在,则替换其值
envContent = envContent.replace(regex, `${fullKey}=${value}`);
} else {
// 如果键不存在,则在文件末尾添加
console.error(`Config not found: ${fullKey}`);
return {
success: false,
message: `Config not found: ${fullKey}`
}
}
// 写入更新后的内容
fs.writeFileSync(envFilePath, envContent, 'utf8');
// 更新当前进程中的环境变量
process.env[fullKey] = value;
console.log(`Config updated: ${fullKey}=${value}`);
return {
success: true,
message: `Config updated: ${fullKey}=${value}`
}
} catch (error) {
console.error(`Failed to update config ${fullKey}:`, error)
return {
success: false,
message: `Failed to update config ${fullKey}: ${error}`
}
}
}
module.exports = {
get_env_config,
load_env_config
load_env_config,
set_env_config,
}

1
conf/skin/dark.js Normal file

File diff suppressed because one or more lines are too long

1
conf/skin/light.js Normal file

File diff suppressed because one or more lines are too long

5
gulp-obfuscator.js Normal file
View File

@ -0,0 +1,5 @@
module.exports = {
replaceVarsMap: {
"tl-rtc-app-": "TL-RTC-APP-SDK-",
},
};

View File

@ -1,5 +1,8 @@
'use strict';
const {
replaceVarsMap
} = require('./gulp-obfuscator');
const pkg = require('./package.json');
const gulp = require('gulp');
@ -43,15 +46,19 @@ const argv = minimist(process.argv.slice(2), {
});
// 输出目录
const dest = ({
dist: './dist'
const web_dest = ({
dist: './web-dist'
}[argv.dest || 'dist'] || argv.dest) + (argv.vs ? '/' + pkg.version : '');
const system_dest = ({
dist: './system-dist'
}[argv.dist || 'dist'] || argv.dist) + (argv.vs ? '/' + pkg.version : '');
// lib-entry-sdk.min.js
const entry_js = () => {
const web_entry_js = () => {
return gulp.src([
'./web-v2-res/js/tl_rtc_entry.js',
'./web-res/js/tl_rtc_entry.js',
])
.pipe(babel())
.pipe(uglifyEs({
@ -63,6 +70,12 @@ const entry_js = () => {
}))
.pipe(replace(' ', ''))
.pipe(replace('\n', ''))
.pipe(replace(
new RegExp(Object.keys(replaceVarsMap).join('|'), 'g'),
function(matched) {
return replaceVarsMap[matched];
}
))
.pipe(replace(
'lib-basic-sdk.min.js', 'lib-basic-sdk.min.' + fileVersion + '.js'
))
@ -74,7 +87,7 @@ const entry_js = () => {
))
.pipe(concat('lib-entry-sdk.min.' + fileVersion + '.js', { newLine: ' ' }))
.pipe(header.apply(null, config.comment))
.pipe(gulp.dest(dest))
.pipe(gulp.dest(web_dest))
.pipe(gzip({
append: true,
gzipOptions: {
@ -82,14 +95,13 @@ const entry_js = () => {
memLevel: 9
}
}))
.pipe(gulp.dest(dest));
.pipe(gulp.dest(web_dest));
};
// lib-basic-sdk.min.js
const basic_js = () => {
const web_basic_js = () => {
return gulp.src([
'./web-v2-res/js/basic/*.js',
'./web-res/js/basic/*.js',
])
.pipe(babel())
.pipe(uglifyEs({
@ -101,9 +113,15 @@ const basic_js = () => {
}))
.pipe(replace(' ', ''))
.pipe(replace('\n', ''))
.pipe(replace(
new RegExp(Object.keys(replaceVarsMap).join('|'), 'g'),
function(matched) {
return replaceVarsMap[matched];
}
))
.pipe(concat('lib-basic-sdk.min.' + fileVersion + '.js', { newLine: ';' }))
.pipe(header.apply(null, config.comment))
.pipe(gulp.dest(dest))
.pipe(gulp.dest(web_dest))
.pipe(gzip({
append: true,
gzipOptions: {
@ -111,14 +129,13 @@ const basic_js = () => {
memLevel: 9
}
}))
.pipe(gulp.dest(dest));
.pipe(gulp.dest(web_dest));
};
// lib-component-sdk.min.js
const component_js = () => {
const web_component_js = () => {
return gulp.src([
'./web-v2-res/js/component/*.js',
'./web-res/js/component/*.js',
])
.pipe(babel())
.pipe(uglifyEs({
@ -130,9 +147,15 @@ const component_js = () => {
}))
.pipe(replace(' ', ''))
.pipe(replace('\n', ''))
.pipe(replace(
new RegExp(Object.keys(replaceVarsMap).join('|'), 'g'),
function(matched) {
return replaceVarsMap[matched];
}
))
.pipe(concat('lib-component-sdk.min.' + fileVersion + '.js', { newLine: ' ' }))
.pipe(header.apply(null, config.comment))
.pipe(gulp.dest(dest))
.pipe(gulp.dest(web_dest))
.pipe(gzip({
append: true,
gzipOptions: {
@ -140,64 +163,77 @@ const component_js = () => {
memLevel: 9
}
}))
.pipe(gulp.dest(dest));
.pipe(gulp.dest(web_dest));
};
// lib-module-sdk.min.js
const module_js = () => {
const web_module_js = () => {
return gulp.src([
// sidebar模块
'./web-v2-res/js/module/sidebar/logo.js',
'./web-v2-res/js/module/sidebar/tool.js',
'./web-v2-res/js/module/sidebar/bottom.js',
'./web-v2-res/js/module/sidebar/sidebar.js',
'./web-res/js/module/sidebar/hovertips.js',
'./web-res/js/module/sidebar/logo.js',
'./web-res/js/module/sidebar/tool.js',
'./web-res/js/module/sidebar/bottom.js',
'./web-res/js/module/sidebar/sidebar.js',
// channel模块
'./web-v2-res/js/module/channel/top.js',
'./web-v2-res/js/module/channel/list.js',
'./web-v2-res/js/module/channel/channel.js',
'./web-res/js/module/channel/top.js',
'./web-res/js/module/channel/list.js',
'./web-res/js/module/channel/channel.js',
// channel-content模块
'./web-v2-res/js/module/channel/content/body.js',
'./web-v2-res/js/module/channel/content/more.js',
'./web-v2-res/js/module/channel/content/invite.js',
'./web-v2-res/js/module/channel/content/tool.js',
'./web-v2-res/js/module/channel/content/textarea.js',
'./web-v2-res/js/module/channel/content.js',
'./web-res/js/module/channel/content/search.js',
'./web-res/js/module/channel/content/body.js',
'./web-res/js/module/channel/content/more.js',
'./web-res/js/module/channel/content/invite.js',
'./web-res/js/module/channel/content/tool.js',
'./web-res/js/module/channel/content/textarea.js',
'./web-res/js/module/channel/content.js',
// login模块
'./web-v2-res/js/module/login/mobile.js',
'./web-v2-res/js/module/login/list.js',
'./web-v2-res/js/module/login/login.js',
'./web-res/js/module/login/mobile.js',
'./web-res/js/module/login/list.js',
'./web-res/js/module/login/login.js',
// login-content模块
'./web-v2-res/js/module/login/content/mobile.js',
'./web-v2-res/js/module/login/content/account.js',
'./web-v2-res/js/module/login/content/email.js',
'./web-v2-res/js/module/login/content.js',
'./web-res/js/module/login/content/account.js',
'./web-res/js/module/login/content/email.js',
'./web-res/js/module/login/content.js',
// contact模块
'./web-v2-res/js/module/contact/list.js',
'./web-v2-res/js/module/contact/top.js',
'./web-v2-res/js/module/contact/contact.js',
'./web-res/js/module/contact/list.js',
'./web-res/js/module/contact/top.js',
'./web-res/js/module/contact/contact.js',
// contact-content模块
'./web-v2-res/js/module/contact/content/group.js',
'./web-v2-res/js/module/contact/content/apply.js',
'./web-v2-res/js/module/contact/content/friend.js',
'./web-v2-res/js/module/contact/content/search.js',
'./web-v2-res/js/module/contact/content.js',
'./web-res/js/module/contact/content/group.js',
'./web-res/js/module/contact/content/apply_user.js',
'./web-res/js/module/contact/content/apply_group.js',
'./web-res/js/module/contact/content/friend.js',
'./web-res/js/module/contact/content/search_user.js',
'./web-res/js/module/contact/content/search_group.js',
'./web-res/js/module/contact/content.js',
//cut_paste模块
'./web-res/js/module/cut_paste/top.js',
'./web-res/js/module/cut_paste/list.js',
'./web-res/js/module/cut_paste/cut_paste.js',
// cut_paste-content模块
'./web-res/js/module/cut_paste/content.js',
//setting模块
'./web-v2-res/js/module/setting/list.js',
'./web-v2-res/js/module/setting/setting.js',
'./web-res/js/module/setting/list.js',
'./web-res/js/module/setting/setting.js',
//setting-content模块
'./web-v2-res/js/module/setting/content/account.js',
'./web-v2-res/js/module/setting/content/other.js',
'./web-v2-res/js/module/setting/content.js',
'./web-res/js/module/setting/content/normal.js',
'./web-res/js/module/setting/content/account.js',
'./web-res/js/module/setting/content/message.js',
'./web-res/js/module/setting/content/skin.js',
'./web-res/js/module/setting/content/other.js',
'./web-res/js/module/setting/content.js',
//blank模块
'./web-v2-res/js/module/blank/content.js',
'./web-res/js/module/blank/content.js',
//主模块
'./web-v2-res/js/tl_rtc_app.js',
'./web-res/js/tl_rtc_app.js',
])
.pipe(babel())
.pipe(uglifyEs({
@ -209,9 +245,15 @@ const module_js = () => {
}))
.pipe(replace(' ', ''))
.pipe(replace('\n', ''))
.pipe(replace(
new RegExp(Object.keys(replaceVarsMap).join('|'), 'g'),
function(matched) {
return replaceVarsMap[matched];
}
))
.pipe(concat('lib-module-sdk.min.' + fileVersion + '.js', { newLine: ' ' }))
.pipe(header.apply(null, config.comment))
.pipe(gulp.dest(dest))
.pipe(gulp.dest(web_dest))
.pipe(gzip({
append: true,
gzipOptions: {
@ -219,29 +261,34 @@ const module_js = () => {
memLevel: 9
}
}))
.pipe(gulp.dest(dest));
.pipe(gulp.dest(web_dest));
};
// js
const js = gulp.parallel(
basic_js, entry_js, component_js, module_js
);
// css
const css = () => {
// lib-css-sdk.min.css
const web_css = () => {
return gulp.src([
'./web-v2-res/css/comm.css',
'./web-v2-res/css/pc.css',
'./web-v2-res/css/ipad.css',
'./web-v2-res/css/mobile.css',
'./web-v2-res/css/max.css',
'./web-v2-res/css/max-mobile.css',
// 基础
'./web-res/css/pc.css',
// 组件样式
'./web-res/css/*/*.css',
// 媒体查询样式
'./web-res/css/max.css',
'./web-res/css/ipad.css',
'./web-res/css/max-mobile.css',
'./web-res/css/mobile.css',
])
.pipe(cleanCSS())
.pipe(replace(
new RegExp(Object.keys(replaceVarsMap).join('|'), 'g'),
function(matched) {
return replaceVarsMap[matched];
}
))
.pipe(concat('lib-css-sdk.min.' + fileVersion + '.css', { newLine: '\n' }))
.pipe(header.apply(null, config.comment))
.pipe(gulp.dest(dest))
.pipe(gulp.dest(web_dest))
.pipe(gzip({
append: true,
gzipOptions: {
@ -249,15 +296,20 @@ const css = () => {
memLevel: 9
}
}))
.pipe(gulp.dest(dest));
.pipe(gulp.dest(web_dest));
};
// html
const html = () => {
const web_html = () => {
return gulp.src([
'./web-v2-res/*.{html,json}',
'./web-res/*.html',
])
.pipe(replace(
new RegExp(Object.keys(replaceVarsMap).join('|'), 'g'),
function(matched) {
return replaceVarsMap[matched];
}
))
.pipe(replace(
'lib-entry-sdk.min.js', 'lib-entry-sdk.min.' + fileVersion + '.js'
))
@ -277,7 +329,7 @@ const html = () => {
collapseWhitespace: true,
removeComments: true,
}))
.pipe(gulp.dest(dest))
.pipe(gulp.dest(web_dest))
.pipe(gzip({
append: true,
gzipOptions: {
@ -285,16 +337,15 @@ const html = () => {
memLevel: 9
}
}))
.pipe(gulp.dest(dest));
.pipe(gulp.dest(web_dest));
};
// image
const image = () => {
const web_image = () => {
return gulp.src([
'./web-v2-res/image/*.{eot,svg,ttf,woff,woff2,png,jpg,gif,jpeg,mp3}',
'./web-v2-res/image/example/*.{eot,svg,ttf,woff,woff2,png,jpg,gif,jpeg,mp3}',
'./web-res/image/*.{eot,svg,ttf,woff,woff2,png,jpg,gif,jpeg,mp3}',
])
.pipe(gulp.dest(dest + '/image'))
.pipe(gulp.dest(web_dest + '/image'))
.pipe(gzip({
append: true,
gzipOptions: {
@ -302,15 +353,21 @@ const image = () => {
memLevel: 9
}
}))
.pipe(gulp.dest(dest + '/image'));
.pipe(gulp.dest(web_dest + '/image'))
};
// statics
const statics = () => {
const web_statics = () => {
return gulp.src([
'./web-v2-res/static/**/*.*',
'./web-res/static/**/*.*',
])
.pipe(gulp.dest(dest + '/static'))
.pipe(replace(
new RegExp(Object.keys(replaceVarsMap).join('|'), 'g'),
function(matched) {
return replaceVarsMap[matched];
}
))
.pipe(gulp.dest(web_dest + '/static'))
.pipe(gzip({
append: true,
gzipOptions: {
@ -318,30 +375,300 @@ const statics = () => {
memLevel: 9
}
}))
.pipe(gulp.dest(dest + '/static'));
.pipe(gulp.dest(web_dest + '/static'))
};
// clean
const clean = cb => {
return del([dest], {
/**********************************************以上为产品端前端资源*************************************************/
// lib-css-sdk.min.css
const system_web_css = () => {
return gulp.src([
// 基础
'./web-res/css/pc.css',
// 组件样式
'./web-res/css/*/*.css',
// 媒体查询样式
'./web-res/css/max.css',
'./web-res/css/ipad.css',
'./web-res/css/max-mobile.css',
'./web-res/css/mobile.css',
])
.pipe(cleanCSS())
.pipe(replace(
new RegExp(Object.keys(replaceVarsMap).join('|'), 'g'),
function(matched) {
return replaceVarsMap[matched];
}
))
.pipe(concat('lib-css-sdk.min.' + fileVersion + '.css', { newLine: '\n' }))
.pipe(header.apply(null, config.comment))
.pipe(gulp.dest(system_dest))
.pipe(gzip({
append: true,
gzipOptions: {
level: 9,
memLevel: 9
}
}))
.pipe(gulp.dest(system_dest));
};
// lib-basic-sdk.min.js
const system_web_basic_js = () => {
return gulp.src([
'./web-res/js/basic/*.js',
])
.pipe(babel())
.pipe(uglifyEs({
mangle: true,
compress: true,
output: {
ascii_only: true
},
}))
.pipe(replace(' ', ''))
.pipe(replace('\n', ''))
.pipe(replace(
new RegExp(Object.keys(replaceVarsMap).join('|'), 'g'),
function(matched) {
return replaceVarsMap[matched];
}
))
.pipe(concat('lib-basic-sdk.min.' + fileVersion + '.js', { newLine: ';' }))
.pipe(header.apply(null, config.comment))
.pipe(gulp.dest(system_dest))
.pipe(gzip({
append: true,
gzipOptions: {
level: 9,
memLevel: 9
}
}))
.pipe(gulp.dest(system_dest));
};
// lib-component-sdk.min.js
const system_web_component_js = () => {
return gulp.src([
'./web-res/js/component/*.js',
])
.pipe(babel())
.pipe(uglifyEs({
mangle: true,
compress: true,
output: {
ascii_only: true
},
}))
.pipe(replace(' ', ''))
.pipe(replace('\n', ''))
.pipe(replace(
new RegExp(Object.keys(replaceVarsMap).join('|'), 'g'),
function(matched) {
return replaceVarsMap[matched];
}
))
.pipe(concat('lib-component-sdk.min.' + fileVersion + '.js', { newLine: ' ' }))
.pipe(header.apply(null, config.comment))
.pipe(gulp.dest(system_dest))
.pipe(gzip({
append: true,
gzipOptions: {
level: 9,
memLevel: 9
}
}))
.pipe(gulp.dest(system_dest));
};
// lib-system-sdk.min.js
const system_js = () => {
return gulp.src([
'./system-res/js/*.js',
'./system-res/js/component/*.js',
])
.pipe(babel())
.pipe(uglifyEs({
mangle: true,
compress: true,
output: {
ascii_only: true
},
}))
.pipe(replace(' ', ''))
.pipe(replace('\n', ''))
.pipe(replace(
new RegExp(Object.keys(replaceVarsMap).join('|'), 'g'),
function(matched) {
return replaceVarsMap[matched];
}
))
.pipe(replace(
'lib-basic-sdk.min.js', 'lib-basic-sdk.min.' + fileVersion + '.js'
))
.pipe(replace(
'lib-component-sdk.min.js', 'lib-component-sdk.min.' + fileVersion + '.js'
))
.pipe(concat('lib-system-sdk.min.' + fileVersion + ".js", { newLine: ';' }))
.pipe(header.apply(null, config.comment))
.pipe(gulp.dest(system_dest))
.pipe(gzip({
append: true,
gzipOptions: {
level: 9,
memLevel: 9
}
}))
.pipe(gulp.dest(system_dest));
};
// lib-system-sdk.min.css
const system_css = () => {
return gulp.src([
'./system-res/css/*.css',
'./system-res/css/component/*.css',
])
.pipe(cleanCSS())
.pipe(replace(
new RegExp(Object.keys(replaceVarsMap).join('|'), 'g'),
function(matched) {
return replaceVarsMap[matched];
}
))
.pipe(concat('lib-system-sdk.min.' + fileVersion + '.css', { newLine: '\n' }))
.pipe(header.apply(null, config.comment))
.pipe(gulp.dest(system_dest))
.pipe(gzip({
append: true,
gzipOptions: {
level: 9,
memLevel: 9
}
}))
.pipe(gulp.dest(system_dest));
};
// system html
const system_html = () => {
return gulp.src([
'./system-res/system.html',
])
.pipe(replace(
new RegExp(Object.keys(replaceVarsMap).join('|'), 'g'),
function(matched) {
return replaceVarsMap[matched];
}
))
.pipe(replace(
'lib-system-sdk.min.js', 'lib-system-sdk.min.' + fileVersion + '.js'
))
.pipe(replace(
'lib-system-sdk.min.css', 'lib-system-sdk.min.' + fileVersion + '.css'
))
.pipe(replace(
'lib-css-sdk.min.css', 'lib-css-sdk.min.' + fileVersion + '.css'
))
.pipe(gulpHtmlmin({
collapseWhitespace: true,
removeComments: true,
}))
.pipe(gulp.dest(system_dest))
.pipe(gzip({
append: true,
gzipOptions: {
level: 9,
memLevel: 9
}
}))
.pipe(gulp.dest(system_dest));
};
// system image
const system_image = () => {
return gulp.src([
'./system-res/image/*.{eot,svg,ttf,woff,woff2,png,jpg,gif,jpeg,mp3}',
])
.pipe(gulp.dest(system_dest + '/image'))
.pipe(gzip({
append: true,
gzipOptions: {
level: 9,
memLevel: 9
}
}))
.pipe(gulp.dest(system_dest + '/image'))
};
// system statics
const system_statics = () => {
return gulp.src([
'./system-res/static/**/*.*',
])
.pipe(replace(
new RegExp(Object.keys(replaceVarsMap).join('|'), 'g'),
function(matched) {
return replaceVarsMap[matched];
}
))
.pipe(gulp.dest(system_dest + '/static'))
.pipe(gzip({
append: true,
gzipOptions: {
level: 9,
memLevel: 9
}
}))
.pipe(gulp.dest(system_dest + '/static'))
};
/**********************************************以上为管理端前端资源*************************************************/
const cleanWeb = cb => {
return del([web_dest], {
force: true
});
};
const defaultTask = gulp.series(clean, gulp.parallel(
basic_js, entry_js, component_js, module_js, css, html, image, statics
const cleanSystem = cb => {
return del([system_dest], {
force: true
});
}
// 产品端
const webTask = gulp.series(cleanWeb, gulp.parallel(
web_css, web_html, web_image, web_statics,
web_basic_js, web_component_js, web_entry_js, web_module_js,
));
// task
exports.default = gulp.series(clean, gulp.parallel(
js, css, html, image, statics
// 管理端
const systemTask = gulp.series(cleanSystem, gulp.parallel(
// 引入产品端资源
system_web_css, system_web_basic_js, system_web_component_js,
system_image, system_statics, system_html, system_css, system_js,
));
// 监听任务
exports.watch = () => {
gulp.watch('./web-v2-res/js/**', defaultTask);
gulp.watch('./web-v2-res/css/**', defaultTask);
gulp.watch('./web-v2-res/image/**', defaultTask);
gulp.watch('./web-v2-res/static/**', defaultTask);
gulp.watch('./web-v2-res/*.{eot,svg,ttf,woff,woff2,html,json,png,jpg,gif,jpeg,mp3}', defaultTask);
};
// 产品端监听
gulp.watch('./web-res/**', webTask);
// 管理端监听
gulp.watch('./system-res/**', systemTask);
};
// 导出任务
exports.web = webTask;
exports.system = systemTask;
// 默认任务
exports.default = gulp.parallel(webTask, systemTask);

12313
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,13 +1,10 @@
{
"name": "tl-rtc-app",
"version": "0.0.1",
"description": "im chat",
"main": "main.js",
"version": "0.0.5",
"description": "webrtc, p2p, file, video, draw, chat",
"scripts": {
"http-api": "cross-env tl_rtc_app_env_mode=http node tlapi",
"http-socket": "cross-env tl_rtc_app_env_mode=http node tlsocket",
"https-api": "cross-env tl_rtc_app_env_mode=https node tlapi",
"https-socket": "cross-env tl_rtc_app_env_mode=https node tlsocket"
"http": "pm2 start pm2.config.http.json",
"https": "pm2 start pm2.config.https.json"
},
"repository": {
"type": "git",
@ -22,17 +19,15 @@
"@babel/preset-env": "^7.26.0",
"@grpc/grpc-js": "^1.8.0",
"@grpc/proto-loader": "^0.6.0",
"ali-oss": "^6.21.0",
"body-parser": "^1.20.2",
"bull": "^4.16.5",
"concurrently": "^8.2.0",
"cookie-parser": "^1.4.6",
"cos-nodejs-sdk-v5": "^2.14.0",
"cross-env": "^5.2.0",
"del": "^2.2.2",
"dotenv": "^16.3.1",
"express": "^4.17.1",
"glob": "^10.3.1",
"google-protobuf": "^3.0.0",
"gulp": "^4.0.2",
"gulp-babel": "^8.0.0",
"gulp-clean-css": "^4.3.0",
@ -50,12 +45,15 @@
"gulp-rev-all": "^4.0.0",
"gulp-uglify": "^3.0.2",
"gulp-uglify-es": "^3.0.0",
"image-size": "^2.0.1",
"lru-cache": "^10.0.1",
"minimist": "^1.2.5",
"multer": "^1.4.5-lts.1",
"music-metadata": "^7.14.0",
"mysql2": "^2.1.0",
"nodemailer": "^6.9.14",
"nodemailer-smtp-transport": "^2.7.4",
"pm2": "^5.4.3",
"redis": "^4.6.13",
"request": "^2.88.2",
"rollup-plugin-copy": "^3.4.0",

43
pm2.config.http.json Normal file
View File

@ -0,0 +1,43 @@
{
"apps": [
{
"name": "tl-rtc-app-super-api",
"script": "tlsuperapi.js",
"interpreter": "node",
"instances": 1,
"max_memory_restart": "500M",
"env": {
"tl_rtc_app_env_mode": "http"
},
"out_file": "./logs/tl-rtc-app-super-api.log",
"error_file": "./logs/tl-rtc-app-super-api.error.log",
"merge_logs": false
},
{
"name": "tl-rtc-app-api",
"script": "tlapi.js",
"interpreter": "node",
"instances": 1,
"max_memory_restart": "500M",
"env": {
"tl_rtc_app_env_mode": "http"
},
"out_file": "./logs/tl-rtc-app-api.log",
"error_file": "./logs/tl-rtc-app-api.error.log",
"merge_logs": false
},
{
"name": "tl-rtc-app-socket",
"script": "tlsocket.js",
"interpreter": "node",
"instances": 1,
"max_memory_restart": "500M",
"env": {
"tl_rtc_app_env_mode": "http"
},
"out_file": "./logs/tl-rtc-app-socket.log",
"error_file": "./logs/tl-rtc-app-socket.error.log",
"merge_logs": false
}
]
}

43
pm2.config.https.json Normal file
View File

@ -0,0 +1,43 @@
{
"apps": [
{
"name": "tl-rtc-app-super-api",
"script": "tlsuperapi.js",
"interpreter": "node",
"instances": 1,
"max_memory_restart": "500M",
"env": {
"tl_rtc_app_env_mode": "https"
},
"out_file": "./logs/tl-rtc-app-super-api.log",
"error_file": "./logs/tl-rtc-app-super-api.error.log",
"merge_logs": false
},
{
"name": "tl-rtc-app-api",
"script": "tlapi.js",
"interpreter": "node",
"instances": 1,
"max_memory_restart": "500M",
"env": {
"tl_rtc_app_env_mode": "https"
},
"out_file": "./logs/tl-rtc-app-api.log",
"error_file": "./logs/tl-rtc-app-api.error.log",
"merge_logs": false
},
{
"name": "tl-rtc-app-socket",
"script": "tlsocket.js",
"interpreter": "node",
"instances": 1,
"max_memory_restart": "500M",
"env": {
"tl_rtc_app_env_mode": "https"
},
"out_file": "./logs/tl-rtc-app-socket.log",
"error_file": "./logs/tl-rtc-app-socket.error.log",
"merge_logs": false
}
]
}

File diff suppressed because it is too large Load Diff

View File

@ -1,21 +1,21 @@
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess,
setBit
tlResponseNotFound, tlResponseSuccess,
setBit, checkIsId, sanitizeHTML
} = require('../../utils/utils')
const { getAvatarOssUrl } = require('../../utils/oss/oss')
const channelService = require('../../service/channel/tl_channel_service')
const channelChatService = require('../../service/channel/tl_channel_chat_service')
const channelUserService = require('../../service/channel/tl_channel_user_service')
const userSessionService = require('../../service/user/tl_user_session_service')
const userService = require('../../service/user/tl_user_service')
const channelFileService = require('../../service/channel/tl_channel_file_service')
const channelMediaService = require('../../service/channel/tl_channel_media_service')
const userReadBiz = require('../user/user_read_biz')
const { fields: channelChatFields } = require('../../tables/tl_channel_chat')
const { fields: channelUserFields} = require('../../tables/tl_channel_user')
const { fields: userFields } = require('../../tables/tl_user')
const { fields: channelFields } = require('../../tables/tl_channel')
const { fields: channelFileFields } = require('../../tables/tl_channel_file')
const { fields: channelMediaFields } = require('../../tables/tl_channel_media')
const {
Def: TlChannelChatDef,
@ -26,12 +26,16 @@ const {
const {
Def: TlChannelUserDef
} = channelUserFields
const {
Def: TlUserDef
} = userFields
const {
Def: TlChannelDef, Type: TlChannelType
} = channelFields
const {
Type: TlChannelFileType
} = channelFileFields
const {
Type: TlChannelMediaType
} = channelMediaFields
@ -49,11 +53,45 @@ const addFriendChannelChat = async function ({
loginInfo, message, toUserId, toUserName, channelId, atUserId, atUserName
}) {
if (!message) {
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
if(message.length > 8192){
return tlResponseArgsError("消息内容过长")
}
// 防止xss攻击
message = sanitizeHTML(message)
if (!channelId) {
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if(!checkIsId(channelId)){
return tlResponseArgsError("请求参数错误")
}
if(toUserId){
toUserId = parseInt(toUserId)
if(!checkIsId(toUserId)){
return tlResponseArgsError("请求参数错误")
}
}
if(atUserId){
atUserId = parseInt(atUserId)
if(!checkIsId(atUserId)){
return tlResponseArgsError("请求参数错误")
}
}
if(toUserName && toUserName.length > 64){
return tlResponseArgsError("请求参数错误")
}
if(atUserName && atUserName.length > 64){
return tlResponseArgsError("请求参数错误")
}
const {
@ -70,6 +108,22 @@ const addFriendChannelChat = async function ({
return tlResponseNotFound("发送失败,频道不存在")
}
const channelType = channelInfo[TlChannelDef.type]
if(channelType !== TlChannelType.FRIEND){
return tlResponseArgsError("发送失败,频道类型错误")
}
// 当前用户是否存在频道
const channelUserInfo = await channelUserService.getInfoByChannelIdAndUserId({
companyId: loginUserCompanyId,
channelId: channelId,
userId: loginUserId
})
if(Object.keys(channelUserInfo).length == 0){
return tlResponseNotFound("非法操作")
}
// 设置@标志
let flag = 0
if (atUserId && atUserName) {
@ -100,10 +154,10 @@ const addFriendChannelChat = async function ({
])
const friendUser = channelUserList.find(item => item[TlChannelUserDef.userId] !== loginUserId)
if(!friendUser){
return tlResponseNotFound("发送失败,好友不存在")
return tlResponseNotFound("发送失败,对方已经不是您的好友")
}
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
const info = await channelChatService.addFriendChatInfo({
@ -163,11 +217,34 @@ const addGroupChannelChat = async function ({
loginInfo, message, channelId, atUserId, atUserName, atAll
}) {
if (!message) {
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
if(message.length > 8192){
return tlResponseArgsError("消息内容过长")
}
// 防止xss攻击
message = sanitizeHTML(message)
if (!channelId) {
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if(!checkIsId(channelId)){
return tlResponseArgsError("请求参数错误")
}
if(atUserId){
atUserId = parseInt(atUserId)
if(!checkIsId(atUserId)){
return tlResponseArgsError("请求参数错误")
}
}
if(atUserName && atUserName.length > 64){
return tlResponseArgsError("请求参数错误")
}
const {
@ -184,6 +261,22 @@ const addGroupChannelChat = async function ({
return tlResponseNotFound("发送失败,频道不存在")
}
const channelType = channelInfo[TlChannelDef.type]
if(channelType !== TlChannelType.GROUP){
return tlResponseArgsError("发送失败,频道类型错误")
}
// 当前用户是否存在频道
const channelUserInfo = await channelUserService.getInfoByChannelIdAndUserId({
companyId: loginUserCompanyId,
channelId: channelId,
userId: loginUserId
})
if(Object.keys(channelUserInfo).length == 0){
return tlResponseNotFound("非法操作")
}
// 设置@标志
let flag = 0
if (atUserId && atUserName) {
@ -247,140 +340,6 @@ const addGroupChannelChat = async function ({
})
}
/**
* 撤回群组/好友消息
* @param {*} loginInfo
* @param {*} channelId
* @param {*} messageId
* @param {*} messageType
*/
const rollbackChannelChat = async function ({
loginInfo, channelId, messageId, messageType
}) {
const {
loginUserCompanyId, loginUserId, loginUsername,
} = loginInfo
if (!channelId) {
return tlResponseArgsError("请求参数为空")
}
if (!messageId) {
return tlResponseArgsError("请求参数为空")
}
if (!messageType) {
return tlResponseArgsError("请求参数为空")
}
// 频道是否存在
const channelInfo = await channelService.getInfoById({
companyId: loginUserCompanyId,
id: channelId
})
if(Object.keys(channelInfo).length == 0){
return tlResponseNotFound("撤回失败,频道不存在")
}
// 消息是否存在
let messageInfo = {}
if([
TlChannelChatType.FRIEND,
TlChannelChatType.GROUP,
// 不支持撤回系统消息
// TlChannelChatType.SYSTEM,
].includes(messageType)){
messageInfo = await channelChatService.getInfoById({
companyId: loginUserCompanyId,
id: messageId
})
}
if(Object.keys(messageInfo).length == 0){
return tlResponseNotFound("撤回失败,消息不存在")
}
// 不能撤回他人消息
if(messageInfo[TlChannelChatDef.fromUserId] !== loginUserId){
return tlResponseForbidden("撤回失败")
}
// 时间是否超过2分钟
const now = Date.now()
const messageTimeStamp = messageInfo[TlChannelChatDef.messageTimeStamp]
if(now - messageTimeStamp > 2 * 60 * 1000){
return tlResponseForbidden("撤回失败,消息已超过2分钟")
}
// 删除原有消息
let deleteRes = 0
if([
TlChannelChatType.FRIEND,
TlChannelChatType.GROUP,
].includes(messageType)){
deleteRes = await channelChatService.deleteInfoById({
companyId: loginUserCompanyId,
id: messageId
})
}else{
return tlResponseSvrError("撤回失败")
}
if(deleteRes == 0){
return tlResponseSvrError("撤回失败")
}
let rollbackMessage = ''
if([
TlChannelChatType.FRIEND,
TlChannelChatType.GROUP,
].includes(messageType)){
rollbackMessage = `${loginUsername}撤回了一条消息`
}
// 生成撤回系统消息
const rollbackInfo = await channelChatService.addSystemChatnfo({
companyId: loginUserCompanyId,
channelId,
message: '<p>' + rollbackMessage + '</p>',
other: JSON.stringify({
[TlChannelChatOther.ip]: '',
}),
messageTimeStamp: Date.now(),
messageVersion: 'v1',
flag: 0
})
if(Object.keys(rollbackInfo).length == 0){
return tlResponseSvrError("撤回失败")
}
// 更新用户已读消息
const updateUserReadRes = await userReadBiz.updateChannelChatRead({
loginInfo, channelId,
latestReadId: rollbackInfo[TlChannelChatDef.id],
})
if(!updateUserReadRes.success){
return tlResponseSvrError("撤回失败")
}
return tlResponseSuccess("撤回成功", {
id: rollbackInfo[TlChannelChatDef.id],
message: rollbackInfo[TlChannelChatDef.message],
type: rollbackInfo[TlChannelChatDef.type],
createTime: rollbackInfo[TlChannelChatDef.createdAt],
fromUserId: rollbackInfo[TlChannelChatDef.fromUserId],
fromUserName: rollbackInfo[TlChannelChatDef.fromUserName],
hasRead: true,
messageTimeStamp: rollbackInfo[TlChannelChatDef.messageTimeStamp],
messageVersion: rollbackInfo[TlChannelChatDef.messageVersion],
})
}
/**
* 回复好友聊天
* @param {*} loginInfo
@ -399,19 +358,47 @@ const addReplyFriendChannelChat = async function ({
} = loginInfo
if (!message) {
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
if(message.length > 8192){
return tlResponseArgsError("消息内容过长")
}
// 防止xss攻击
message = sanitizeHTML(message)
if (!channelId) {
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if(!checkIsId(channelId)){
return tlResponseArgsError("请求参数错误")
}
if (!messageId) {
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
messageId = parseInt(messageId)
if(!checkIsId(messageId)){
return tlResponseArgsError("请求参数错误")
}
if (!messageType) {
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
if(atUserId){
atUserId = parseInt(atUserId)
if(!checkIsId(atUserId)){
return tlResponseArgsError("请求参数错误")
}
}
if(atUserName && atUserName.length > 64){
return tlResponseArgsError("请求参数错误")
}
// 频道是否存在
@ -423,6 +410,17 @@ const addReplyFriendChannelChat = async function ({
return tlResponseNotFound("发送失败,频道不存在")
}
// 当前用户是否存在频道
const channelUserInfo = await channelUserService.getInfoByChannelIdAndUserId({
companyId: loginUserCompanyId,
channelId: channelId,
userId: loginUserId
})
if(Object.keys(channelUserInfo).length == 0){
return tlResponseNotFound("非法操作")
}
const channelType = channelInfo[TlChannelDef.type]
if(channelType !== TlChannelType.FRIEND){
return tlResponseArgsError("发送失败,频道类型错误")
@ -442,6 +440,22 @@ const addReplyFriendChannelChat = async function ({
id: messageId
})
}else if([
TlChannelFileType.OFFLINE,
TlChannelFileType.P2P,
].includes(messageType)){
messageInfo = await channelFileService.getInfoById({
companyId: loginUserCompanyId,
id: messageId
})
}else if([
TlChannelMediaType.AUDIO,
TlChannelMediaType.VIDEO,
].includes(messageType)){
messageInfo = await channelMediaService.getInfoById({
companyId: loginUserCompanyId,
id: messageId
})
}
if(Object.keys(messageInfo).length == 0){
return tlResponseNotFound("发送失败,回复消息不存在")
@ -502,6 +516,28 @@ const addReplyFriendChannelChat = async function ({
TlChannelChatType.GROUP,
].includes(messageType)){
replyToMessageContent = messageInfo[TlChannelChatDef.message]
}else if([
TlChannelFileType.OFFLINE,
TlChannelFileType.P2P,
].includes(messageType)){
if(messageType == TlChannelFileType.P2P){
replyToMessageContent = "在线文件"
}else if(messageType == TlChannelFileType.OFFLINE){
replyToMessageContent = "离线文件"
}else{
replyToMessageContent = "未知文件消息"
}
}else if([
TlChannelMediaType.VIDEO,
TlChannelMediaType.AUDIO,
].includes(messageType)){
if(messageType == TlChannelMediaType.VIDEO){
replyToMessageContent = "视频通话"
}else if(messageType == TlChannelMediaType.AUDIO){
replyToMessageContent = "语音通话"
}else{
replyToMessageContent = "未知音视频消息"
}
}else{
replyToMessageContent = '未知消息'
}
@ -546,19 +582,47 @@ const addReplyGroupChannelChat = async function ({
} = loginInfo
if (!message) {
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
if(message.length > 8192){
return tlResponseArgsError("消息内容过长")
}
// 防止xss攻击
message = sanitizeHTML(message)
if (!channelId) {
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if(!checkIsId(channelId)){
return tlResponseArgsError("请求参数错误")
}
if (!messageId) {
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
messageId = parseInt(messageId)
if(!checkIsId(messageId)){
return tlResponseArgsError("请求参数错误")
}
if (!messageType) {
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
if(atUserId){
atUserId = parseInt(atUserId)
if(!checkIsId(atUserId)){
return tlResponseArgsError("请求参数错误")
}
}
if(atUserName && atUserName.length > 64){
return tlResponseArgsError("请求参数错误")
}
// 频道是否存在
@ -571,6 +635,17 @@ const addReplyGroupChannelChat = async function ({
return tlResponseNotFound("发送失败,频道不存在")
}
// 当前用户是否存在频道
const channelUserInfo = await channelUserService.getInfoByChannelIdAndUserId({
companyId: loginUserCompanyId,
channelId: channelId,
userId: loginUserId
})
if(Object.keys(channelUserInfo).length == 0){
return tlResponseNotFound("非法操作")
}
const channelType = channelInfo[TlChannelDef.type]
if(channelType !== TlChannelType.GROUP){
return tlResponseArgsError("发送失败,频道类型错误")
@ -589,6 +664,22 @@ const addReplyGroupChannelChat = async function ({
companyId: loginUserCompanyId,
id: messageId
})
}else if([
TlChannelFileType.OFFLINE,
TlChannelFileType.P2P,
].includes(messageType)){
messageInfo = await channelFileService.getInfoById({
companyId: loginUserCompanyId,
id: messageId
})
}else if([
TlChannelMediaType.AUDIO,
TlChannelMediaType.VIDEO,
].includes(messageType)){
messageInfo = await channelMediaService.getInfoById({
companyId: loginUserCompanyId,
id: messageId
})
}
if(Object.keys(messageInfo).length == 0){
@ -652,6 +743,28 @@ const addReplyGroupChannelChat = async function ({
TlChannelChatType.GROUP,
].includes(messageType)){
replyToMessageContent = messageInfo[TlChannelChatDef.message]
}else if([
TlChannelFileType.OFFLINE,
TlChannelFileType.P2P,
].includes(messageType)){
if(messageType == TlChannelFileType.P2P){
replyToMessageContent = "在线文件"
}else if(messageType == TlChannelFileType.OFFLINE){
replyToMessageContent = "离线文件"
}else{
replyToMessageContent = "未知文件消息"
}
}else if([
TlChannelMediaType.VIDEO,
TlChannelMediaType.AUDIO,
].includes(messageType)){
if(messageType == TlChannelMediaType.VIDEO){
replyToMessageContent = "视频通话"
}else if(messageType == TlChannelMediaType.AUDIO){
replyToMessageContent = "语音通话"
}else{
replyToMessageContent = "未知音视频消息"
}
}else{
replyToMessageContent = '未知消息'
}
@ -679,13 +792,10 @@ const addReplyGroupChannelChat = async function ({
}
module.exports = {
addFriendChannelChat,
addGroupChannelChat,
addReplyFriendChannelChat,
addReplyGroupChannelChat,
rollbackChannelChat,
}

View File

@ -0,0 +1,350 @@
const {
tlResponseArgsError, tlResponseSvrError,
tlResponseNotFound, tlResponseSuccess, checkIsId
} = require('../../utils/utils')
const {
getOssUrl
} = require('../../utils/oss/oss')
const channelFileService = require('../../service/channel/tl_channel_file_service')
const channelUserService = require('../../service/channel/tl_channel_user_service')
const cloudFileService = require('../../service/cloud/tl_cloud_file_service')
const userReadBiz = require('../user/user_read_biz')
const { fields: channelFileFields } = require('../../tables/tl_channel_file')
const { fields: channelUserFields} = require('../../tables/tl_channel_user')
const { fields: cloudFileFields } = require('../../tables/tl_cloud_file')
const {
Def: TlChannelFileDef, Type: TlChannelFileType,
Status: TlChannelFileStatus, Other: TlChannelFileOther,
} = channelFileFields
const { Def: TlChannelUserDef } = channelUserFields
const { Def: TlCloudFileDef } = cloudFileFields
/**
* 发送好友频道文件消息
* @param {*} loginInfo
* @param {*} cloudFileId
* @param {*} type
* @param {*} channelId
*/
const addFriendChannelFile = async function ({
loginInfo, cloudFileId, type, channelId
}) {
if (!cloudFileId) {
return tlResponseArgsError("请求参数错误")
}
cloudFileId = parseInt(cloudFileId)
if (!checkIsId(cloudFileId)) {
return tlResponseArgsError("请求参数错误")
}
if (!type) {
return tlResponseArgsError("请求参数错误")
}
if (!channelId) {
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if (!checkIsId(channelId)) {
return tlResponseArgsError("请求参数错误")
}
const {
loginUserCompanyId, loginUserId, loginUsername,
loginUserAvatar
} = loginInfo;
// 发送好友媒体消息,如果没有找到好友,说明可能已被对方删除
const channelUserList = await channelUserService.getListByChannelId({
companyId: loginUserCompanyId,
channelId
}, [
TlChannelUserDef.userId,
TlChannelUserDef.status
])
const friendUser = channelUserList.find(item => item[TlChannelUserDef.userId] !== loginUserId)
if(!friendUser){
return tlResponseNotFound("发送失败,对方已经不是您的好友")
}
// 当前用户是否存在频道
const channelUserInfo = channelUserList.find(item => item[TlChannelUserDef.userId] == loginUserId)
if(!channelUserInfo){
return tlResponseNotFound("非法操作")
}
const info = await channelFileService.addInfo({
companyId: loginUserCompanyId,
channelId,
flag: 0,
type: type,
status: TlChannelFileStatus.INIT,
cloudFileId: cloudFileId,
fromUserId: loginUserId,
fromUserName: loginUsername,
other: JSON.stringify({
[TlChannelFileOther.ip]: '',
}),
messageTimeStamp: Date.now(),
messageVersion: 'v1'
})
if (Object.keys(info).length == 0) {
return tlResponseSvrError("发送失败")
}
// 更新用户已读消息
const updateUserReadRes = await userReadBiz.updateChannelFileRead({
loginInfo, channelId,
latestReadId: info[TlChannelFileDef.id],
})
if(!updateUserReadRes.success){
return tlResponseSvrError("发送失败")
}
const fileType = info[TlChannelFileDef.type]
let message = ""
if(fileType == TlChannelFileType.P2P){
message = "在线文件"
}else if(fileType == TlChannelFileType.OFFLINE){
message = "离线文件"
}
const cloudFile = await cloudFileService.getInfoById({
companyId: loginUserCompanyId,
id: cloudFileId
}, [
TlCloudFileDef.id,
TlCloudFileDef.originFileName,
TlCloudFileDef.fileSize,
TlCloudFileDef.fileUrl,
])
if (!cloudFile) {
return tlResponseSvrError("发送失败")
}
let fileUrl = cloudFile[TlCloudFileDef.fileUrl]
fileUrl = await getOssUrl(fileUrl)
return tlResponseSuccess("发送成功", {
id: info[TlChannelFileDef.id],
message: message,
fromUserName: info[TlChannelFileDef.fromUserName],
type: info[TlChannelFileDef.type],
status: info[TlChannelFileDef.status],
cloudFileId: cloudFileId,
createTime: info[TlChannelFileDef.createdAt],
fromUserId: info[TlChannelFileDef.fromUserId],
fromUserName: info[TlChannelFileDef.fromUserName],
fromUserAvatar: loginUserAvatar,
fileName: cloudFile[TlCloudFileDef.originFileName],
fileSize: cloudFile[TlCloudFileDef.fileSize],
fileUrl,
hasRead: true,
messageTimeStamp: info[TlChannelFileDef.messageTimeStamp],
messageVersion: info[TlChannelFileDef.messageVersion],
})
}
/**
* 发送群聊频道媒体流消息
* @param {*} loginInfo
* @param {*} file
* @param {*} type
* @param {*} other
* @param {*} channelId
*/
const addGroupChannelFile = async function ({
loginInfo, cloudFileId, type, channelId
}) {
if (!cloudFileId) {
return tlResponseArgsError("请求参数错误")
}
cloudFileId = parseInt(cloudFileId)
if (!checkIsId(cloudFileId)) {
return tlResponseArgsError("请求参数错误")
}
if (!type) {
return tlResponseArgsError("请求参数错误")
}
if (!channelId) {
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if (!checkIsId(channelId)) {
return tlResponseArgsError("请求参数错误")
}
const {
loginUserCompanyId, loginUserId, loginUsername,
loginUserAvatar
} = loginInfo;
// 当前用户是否存在频道
const channelUserInfo = await channelUserService.getInfoByChannelIdAndUserId({
companyId: loginUserCompanyId,
channelId: channelId,
userId: loginUserId
})
if(Object.keys(channelUserInfo).length == 0){
return tlResponseNotFound("非法操作")
}
const info = await channelFileService.addInfo({
companyId: loginUserCompanyId,
channelId,
flag: 0,
type: type,
status: TlChannelFileStatus.INIT,
cloudFileId: cloudFileId,
fromUserId: loginUserId,
fromUserName: loginUsername,
other: JSON.stringify({
[TlChannelFileOther.ip]: '',
}),
messageTimeStamp: Date.now(),
messageVersion: 'v1'
})
if (Object.keys(info).length == 0) {
return tlResponseSvrError("发送群聊频道媒体流失败")
}
// 更新用户已读消息
const updateUserReadRes = await userReadBiz.updateChannelFileRead({
loginInfo, channelId,
latestReadId: info[TlChannelFileDef.id],
})
if(!updateUserReadRes.success){
return tlResponseSvrError("发送失败")
}
const fileType = info[TlChannelFileDef.type]
let message = ""
if(fileType == TlChannelFileType.P2P){
message = "在线文件"
}else if(fileType == TlChannelFileType.OFFLINE){
message = "离线文件"
}
const cloudFile = await cloudFileService.getInfoById({
companyId: loginUserCompanyId,
id: cloudFileId
}, [
TlCloudFileDef.id,
TlCloudFileDef.originFileName,
TlCloudFileDef.fileSize,
TlCloudFileDef.fileUrl,
])
if (!cloudFile) {
return tlResponseSvrError("发送失败")
}
let fileUrl = cloudFile[TlCloudFileDef.fileUrl]
fileUrl = await getOssUrl(fileUrl)
return tlResponseSuccess("发送成功", {
id: info[TlChannelFileDef.id],
message: message,
fromUserName: info[TlChannelFileDef.fromUserName],
type: info[TlChannelFileDef.type],
status: info[TlChannelFileDef.status],
cloudFileId: cloudFileId,
createTime: info[TlChannelFileDef.createdAt],
fromUserId: info[TlChannelFileDef.fromUserId],
fromUserName: info[TlChannelFileDef.fromUserName],
fromUserAvatar: loginUserAvatar,
fileName: cloudFile[TlCloudFileDef.originFileName],
fileSize: cloudFile[TlCloudFileDef.fileSize],
fileUrl,
hasRead: true,
messageTimeStamp: info[TlChannelFileDef.messageTimeStamp],
messageVersion: info[TlChannelFileDef.messageVersion],
})
}
/**
* 发送群聊频道离线文件消息
* @param {*} loginInfo
* @param {*} cloudFileId
* @param {*} other
* @param {*} channelId
*/
const addGroupChannelP2PFile = async function ({
loginInfo, cloudFileId, channelId
}) {
return await addGroupChannelFile({
loginInfo, cloudFileId, type: TlChannelFileType.P2P, channelId
})
}
/**
* 发送群聊频道在线文件消息
* @param {*} loginInfo
* @param {*} cloudFileId
* @param {*} other
* @param {*} channelId
*/
const addGroupChannelOfflineFile = async function ({
loginInfo, cloudFileId, channelId
}) {
return await addGroupChannelFile({
loginInfo, cloudFileId, type: TlChannelFileType.OFFLINE, channelId
})
}
/**
* 发送好友频道离线文件消息
* @param {*} loginInfo
* @param {*} cloudFileId
* @param {*} other
* @param {*} channelId
*/
const addFirendChannelP2PFile = async function ({
loginInfo, cloudFileId, channelId
}) {
return await addFriendChannelFile({
loginInfo, cloudFileId, type: TlChannelFileType.P2P, channelId
})
}
/**
* 发送好友频道在线文件消息
* @param {*} loginInfo
* @param {*} cloudFileId
* @param {*} other
* @param {*} channelId
*/
const addFriendChannelOfflineFile = async function ({
loginInfo, cloudFileId, channelId
}) {
return await addFriendChannelFile({
loginInfo, cloudFileId, type: TlChannelFileType.OFFLINE, channelId
})
}
module.exports = {
addFirendChannelP2PFile,
addFriendChannelOfflineFile,
addGroupChannelP2PFile,
addGroupChannelOfflineFile
}

View File

@ -0,0 +1,291 @@
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess, checkIsId
} = require('../../utils/utils')
const channelMediaService = require('../../service/channel/tl_channel_media_service')
const channelUserService = require('../../service/channel/tl_channel_user_service')
const userReadBiz = require('../user/user_read_biz')
const { fields: channelMediaFields } = require('../../tables/tl_channel_media')
const { fields: channelUserFields} = require('../../tables/tl_channel_user')
const {
Def: TlChannelMediaDef, Type: TlChannelMediaType,
Status: TlChannelMediaStatus, Other: TlChannelMediaOther
} = channelMediaFields
const {
Def: TlChannelUserDef
} = channelUserFields
/**
* 发送好友频道媒体流通话消息
* @param {*} loginInfo
* @param {*} media
* @param {*} type
* @param {*} toUserId
* @param {*} toUserName
* @param {*} channelId
*/
const addFriendChannelMedia = async function ({
loginInfo, media, type, channelId
}) {
if (!media) {
return tlResponseArgsError("请求参数错误")
}
if (!type) {
return tlResponseArgsError("请求参数错误")
}
if (!channelId) {
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if (!checkIsId(channelId)) {
return tlResponseArgsError("请求参数错误")
}
const {
loginUserCompanyId, loginUserId, loginUsername,
loginUserAvatar
} = loginInfo;
// 发送好友媒体消息,如果没有找到好友,说明可能已被对方删除
const channelUserList = await channelUserService.getListByChannelId({
companyId: loginUserCompanyId,
channelId
}, [
TlChannelUserDef.userId,
TlChannelUserDef.status
])
const friendUser = channelUserList.find(item => item[TlChannelUserDef.userId] !== loginUserId)
if(!friendUser){
return tlResponseNotFound("发送失败,对方已经不是您的好友")
}
// 当前用户是否存在频道
const channelUserInfo = channelUserList.find(item => item[TlChannelUserDef.userId] == loginUserId)
if(!channelUserInfo){
return tlResponseNotFound("非法操作")
}
const info = await channelMediaService.addInfo({
companyId: loginUserCompanyId,
channelId,
flag: 0,
type: type,
status: TlChannelMediaStatus.INIT,
media: JSON.stringify(media),
fromUserId: loginUserId,
fromUserName: loginUsername,
other: JSON.stringify({
[TlChannelMediaOther.ip]: '',
}),
messageTimeStamp: Date.now(),
messageVersion: 'v1'
})
if (Object.keys(info).length == 0) {
return tlResponseSvrError("发送失败")
}
// 更新用户已读消息
const updateUserReadRes = await userReadBiz.updateChannelMediaRead({
loginInfo, channelId,
latestReadId: info[TlChannelMediaDef.id],
})
if(!updateUserReadRes.success){
return tlResponseSvrError("发送失败")
}
const mediaType = info[TlChannelMediaDef.type]
let message = ""
if(mediaType == TlChannelMediaType.AUDIO){
message = "语音通话"
}else if(mediaType == TlChannelMediaType.VIDEO){
message = "视频通话"
}
return tlResponseSuccess("发送成功", {
id: info[TlChannelMediaDef.id],
media: JSON.parse(info[TlChannelMediaDef.media]),
message: message,
fromUserName: info[TlChannelMediaDef.fromUserName],
type: info[TlChannelMediaDef.type],
status: info[TlChannelMediaDef.status],
createTime: info[TlChannelMediaDef.createdAt],
fromUserId: info[TlChannelMediaDef.fromUserId],
fromUserName: info[TlChannelMediaDef.fromUserName],
fromUserAvatar: loginUserAvatar,
hasRead: true,
messageTimeStamp: info[TlChannelMediaDef.messageTimeStamp],
messageVersion: info[TlChannelMediaDef.messageVersion],
})
}
/**
* 发送好友频道语音通话消息
* @param {*} loginInfo
* @param {*} media
* @param {*} channelId
*/
const addFriendChannelAudio = async function ({
loginInfo, media, channelId
}) {
return await addFriendChannelMedia({
loginInfo, media, type: TlChannelMediaType.AUDIO, channelId
})
}
/**
* 发送好友频道视频通话消息
* @param {*} loginInfo
* @param {*} media
* @param {*} channelId
*/
const addFriendChannelVideo = async function ({
loginInfo, media, channelId
}) {
return await addFriendChannelMedia({
loginInfo, media, type: TlChannelMediaType.VIDEO, channelId
})
}
/**
* 发送群聊频道媒体流消息
* @param {*} loginInfo
* @param {*} media
* @param {*} type
* @param {*} other
* @param {*} channelId
*/
const addGroupChannelMedia = async function ({
loginInfo, media, type, channelId
}) {
if (!media) {
return tlResponseArgsError("请求参数错误")
}
if (!type) {
return tlResponseArgsError("请求参数错误")
}
if (!channelId) {
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if (!checkIsId(channelId)) {
return tlResponseArgsError("请求参数错误")
}
const {
loginUserCompanyId, loginUserId, loginUsername,
loginUserAvatar
} = loginInfo
// 当前用户是否存在频道
const channelUserInfo = await channelUserService.getInfoByChannelIdAndUserId({
companyId: loginUserCompanyId,
channelId: channelId,
userId: loginUserId
})
if(Object.keys(channelUserInfo).length == 0){
return tlResponseNotFound("非法操作")
}
const info = await channelMediaService.addInfo({
companyId: loginUserCompanyId,
channelId,
flag: 0,
type: type,
status: TlChannelMediaStatus.INIT,
media: JSON.stringify(media),
fromUserId: loginUserId,
fromUserName: loginUsername,
other: JSON.stringify({
[TlChannelMediaOther.ip]: '',
}),
messageTimeStamp: Date.now(),
messageVersion: 'v1'
})
if (Object.keys(info).length == 0) {
return tlResponseSvrError("发送失败")
}
// 更新用户已读消息
const updateUserReadRes = await userReadBiz.updateChannelMediaRead({
loginInfo, channelId,
latestReadId: info[TlChannelMediaDef.id],
})
if(!updateUserReadRes.success){
return tlResponseSvrError("发送失败")
}
const mediaType = info[TlChannelMediaDef.type]
let message = ""
if(mediaType == TlChannelMediaType.AUDIO){
message = "语音通话"
}else if(mediaType == TlChannelMediaType.VIDEO){
message = "视频通话"
}
return tlResponseSuccess("发送成功", {
id: info[TlChannelMediaDef.id],
media: JSON.parse(info[TlChannelMediaDef.media]),
message: message,
fromUserName: info[TlChannelMediaDef.fromUserName],
type: info[TlChannelMediaDef.type],
status: info[TlChannelMediaDef.status],
createTime: info[TlChannelMediaDef.createdAt],
fromUserId: info[TlChannelMediaDef.fromUserId],
fromUserName: info[TlChannelMediaDef.fromUserName],
fromUserAvatar: loginUserAvatar,
hasRead: true,
messageTimeStamp: info[TlChannelMediaDef.messageTimeStamp],
messageVersion: info[TlChannelMediaDef.messageVersion],
})
}
/**
* 发送群聊频道语音消息
* @param {*} loginInfo
* @param {*} media
* @param {*} other
* @param {*} channelId
*/
const addGroupChannelAudio = async function ({
loginInfo, media, channelId
}) {
return await addGroupChannelMedia({
loginInfo, media, type: TlChannelMediaType.AUDIO, channelId
})
}
/**
* 发送群聊频道视频消息
* @param {*} loginInfo
* @param {*} media
* @param {*} other
* @param {*} channelId
*/
const addGroupChannelVideo = async function ({
loginInfo, media, channelId
}) {
return await addGroupChannelMedia({
loginInfo, media, type: TlChannelMediaType.VIDEO, channelId
})
}
module.exports = {
addFriendChannelAudio,
addFriendChannelVideo,
addGroupChannelAudio,
addGroupChannelVideo,
}

View File

@ -0,0 +1,161 @@
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess, checkIsId
} = require('../../utils/utils')
const channelNoticeService = require('../../service/channel/tl_channel_notice_service')
const userService = require('../../service/user/tl_user_service')
const channelUserService = require('../../service/channel/tl_channel_user_service')
const { fields: channelNoticeFields } = require('../../tables/tl_channel_notice')
const { fields: userFields } = require('../../tables/tl_user')
const {
Def: TlChannelNoticeDef,
} = channelNoticeFields
const {
Def: TlUserDef,
} = userFields
/**
* 发布频道公告
* @param {*} loginInfo
* @param {*} channelId
* @param {*} content
* @returns
*/
const addNotice = async function({
loginInfo, channelId, content
}){
if(!channelId) {
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if(!checkIsId(channelId)){
return tlResponseArgsError("请求参数错误")
}
if(!content) {
return tlResponseArgsError("请求参数错误")
}
if(content.length > 8096){
return tlResponseArgsError("内容过长")
}
const {
loginUserCompanyId, loginUserId, loginUsername
} = loginInfo
// 当前用户是否存在频道
const channelUserInfo = await channelUserService.getInfoByChannelIdAndUserId({
companyId: loginUserCompanyId,
channelId: channelId,
userId: loginUserId
})
if(Object.keys(channelUserInfo).length == 0){
return tlResponseNotFound("非法操作")
}
const notice = await channelNoticeService.addInfo({
companyId: loginUserCompanyId,
channelId,
userId: loginUserId,
content: content,
})
if(Object.keys(notice).length === 0){
return tlResponseSvrError("发布失败")
}
return tlResponseSuccess("发布成功")
}
/**
* 获取频道通知记录
* @param {*} loginInfo
* @param {*} channelId
*/
const getNoticeList = async function({
loginInfo, channelId
}){
if (!channelId) {
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if(!checkIsId(channelId)){
return tlResponseArgsError("请求参数错误")
}
const {
loginUserCompanyId, loginUserId, loginUsername
} = loginInfo
// 当前用户是否存在频道
const channelUserInfo = await channelUserService.getInfoByChannelIdAndUserId({
companyId: loginUserCompanyId,
channelId: channelId,
userId: loginUserId
})
if(Object.keys(channelUserInfo).length == 0){
return tlResponseNotFound("非法操作")
}
const noticeList = await channelNoticeService.getListByChannelId({
companyId: loginUserCompanyId,
channelId,
}, [
TlChannelNoticeDef.id,
TlChannelNoticeDef.userId,
TlChannelNoticeDef.content,
TlChannelNoticeDef.createdAt,
])
if(!noticeList){
return tlResponseSvrError("获取失败")
}
// 获取用户名称
const userIdList = []
noticeList.forEach(element => {
userIdList.push(element[TlChannelNoticeDef.userId])
});
const userList = await userService.getListByIdList({
companyId: loginUserCompanyId,
idList: userIdList,
}, [
TlUserDef.id,
TlUserDef.name,
])
const userMap = {}
userList.forEach(element => {
userMap[element[TlUserDef.id]] = element[TlUserDef.name]
});
let resultList = []
noticeList.forEach(element => {
const username = userMap[element[TlChannelNoticeDef.userId]]
resultList.push({
id: element[TlChannelNoticeDef.id],
username: username,
content: element[TlChannelNoticeDef.content],
createTime: element[TlChannelNoticeDef.createdAt],
})
});
return tlResponseSuccess("查询成功", resultList)
}
module.exports = {
addNotice,
getNoticeList
}

View File

@ -1,6 +1,6 @@
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess, setBit, checkBit
tlResponseArgsError, tlResponseSvrError,
tlResponseNotFound, tlResponseSuccess, setBit, checkIsId
} = require('../../utils/utils')
const channelService = require('../../service/channel/tl_channel_service')
const channelUserService = require('../../service/channel/tl_channel_user_service')
@ -14,7 +14,7 @@ const { fields: channelChatFields } = require('../../tables/tl_channel_chat')
const { fields: userFields } = require('../../tables/tl_user')
const { fields: userFriendFields } = require('../../tables/tl_user_friend')
const { fields: channelFields } = require('../../tables/tl_channel')
const { getOssUrl, getAvatarOssUrl } = require('../../utils/oss/oss')
const { getAvatarOssUrl } = require('../../utils/oss/oss')
const { Def: TlChannelUserDef, Type: TlChannelUserType, Flag: TlChannelUserFlag } = channelUserFields
const { Def : TlUserDef } = userFields
@ -22,28 +22,46 @@ const { Def: TlUserFriendDef } = userFriendFields
const { Def: TlChannelDef, Type: TlChannelType } = channelFields
const { Def: TlChannelChatDef, Other: TlChannelChatOther } = channelChatFields
/**
* 添加频道用户
* @param {*} loginInfo
* @param {*} channelId
* @param {*} userId
* @param {*} roleId
* @param {*} isShare
* @param {*} isInvite
*/
const addChannelUser = async function({ loginInfo, channelId, userId, roleId }){
const addChannelUser = async function({
loginInfo, channelId, userId, roleId, isShare = false, isInvite = false
}){
if(!channelId){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if(!checkIsId(channelId)){
return tlResponseArgsError("请求参数错误")
}
if(!userId){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
userId = parseInt(userId)
if(!checkIsId(userId)){
return tlResponseArgsError("请求参数错误")
}
if(!roleId){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
roleId = parseInt(roleId)
if(!checkIsId(roleId)){
return tlResponseArgsError("请求参数错误")
}
const {
loginUserCompanyId, loginUserId, loginUsername
loginUserCompanyId, loginUserId, loginUsername, loginUserRoleId
} = loginInfo
const channelInfo = await channelService.getInfoById({
@ -82,11 +100,19 @@ const addChannelUser = async function({ loginInfo, channelId, userId, roleId }){
TlUserDef.name
])
let message = '<p>' + userInfo[TlUserDef.name] + "加入群聊" + '</p>';
if(isInvite){
message = '<p>' + loginUsername + "邀请 " + userInfo[TlUserDef.name] + "加入群聊" + '</p>';
}
if(isShare){
message = '<p>' + userInfo[TlUserDef.name] + "通过" + loginUsername + "的分享加入群聊" + '</p>';
}
// 生成邀请消息
const channelMessage = await channelChatService.addSystemChatnfo({
companyId: loginUserCompanyId,
channelId,
message: '<p>' + loginUsername + "邀请 " + userInfo[TlUserDef.name] + "加入频道" + '</p>',
message: message,
other: JSON.stringify({
[TlChannelChatOther.ip]: '',
}),
@ -114,13 +140,13 @@ const addChannelUser = async function({ loginInfo, channelId, userId, roleId }){
// 更新用户频道角色
await userSessionService.updateUserChannelRoleMap({
userId: loginUserId,
userId,
channelRoleMap: {
[channelId]: roleId
}
})
return tlResponseSuccess("添加频道用户成功")
return tlResponseSuccess("添加成功")
}
/**
@ -132,15 +158,25 @@ const addChannelUser = async function({ loginInfo, channelId, userId, roleId }){
*/
const addChannelUserList = async function({ loginInfo, channelId, userIdList, roleId }){
if(!channelId){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if(!checkIsId(channelId)){
return tlResponseArgsError("请求参数错误")
}
if(!userIdList){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
for (let i = 0; i < userIdList.length; i++){
userIdList[i] = parseInt(userIdList[i])
if(!checkIsId(userIdList[i])){
return tlResponseArgsError("请求参数错误")
}
}
if(userIdList.length == 0){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
if(userIdList.length > 100){
@ -148,13 +184,29 @@ const addChannelUserList = async function({ loginInfo, channelId, userIdList, ro
}
if(!roleId){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
roleId = parseInt(roleId)
if(!checkIsId(roleId)){
return tlResponseArgsError("请求参数错误")
}
const {
loginUserCompanyId, loginUserId, loginUsername
} = loginInfo
// 当前用户是否存在频道
const channelUserInfo = await channelUserService.getInfoByChannelIdAndUserId({
companyId: loginUserCompanyId,
channelId: channelId,
userId: loginUserId
})
if(Object.keys(channelUserInfo).length == 0){
return tlResponseNotFound("非法操作")
}
const channelInfo = await channelService.getInfoById({
companyId: loginUserCompanyId,
id: channelId
@ -203,7 +255,7 @@ const addChannelUserList = async function({ loginInfo, channelId, userIdList, ro
channelId,
message: '<p>' + loginUsername + "邀请 " + userInfoList.map(
item => item[TlUserDef.name]
).join(",") + " 共" + userInfoList.length + "人加入频道" + '</p>',
).join(",") + " 共" + userInfoList.length + "人加入群聊" + '</p>',
other: JSON.stringify({
[TlChannelChatOther.ip]: '',
}),
@ -245,7 +297,7 @@ const addChannelUserList = async function({ loginInfo, channelId, userIdList, ro
}
})
return tlResponseSuccess("添加频道用户成功", {
return tlResponseSuccess("添加成功", {
id: channelMessage[TlChannelChatDef.id],
message: channelMessage[TlChannelChatDef.message],
type: channelMessage[TlChannelChatDef.type],
@ -257,39 +309,6 @@ const addChannelUserList = async function({ loginInfo, channelId, userIdList, ro
})
}
/**
* 分享加入群聊
* @param {*} loginInfo
* @param {*} channelId
*/
const shareJoinGroupChannel = async function({ loginInfo, channelId }){
if(!channelId){
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId, loginUsername
} = loginInfo
const channelInfo = await channelService.getInfoById({
companyId: loginUserCompanyId,
id: channelId
}, [
TlChannelDef.id,
TlChannelDef.type
])
if(Object.keys(channelInfo).length == 0){
return tlResponseArgsError("频道不存在")
}
return addChannelUser({
loginInfo, channelId,
userId: loginUserId,
roleId: TlRoleInner.channel.member.id
})
}
/**
* 添加频道普通身份用户
@ -299,7 +318,7 @@ const shareJoinGroupChannel = async function({ loginInfo, channelId }){
*/
const addChannelUserNormal = async function({ loginInfo, channelId, userId }){
return addChannelUser({
loginInfo, channelId, userId, roleId: TlRoleInner.channel.member.id
loginInfo, channelId, userId, roleId: TlRoleInner.channel.member.id, isInvite: true
})
}
@ -335,7 +354,11 @@ const addChannelUserAdmin = async function({ loginInfo, channelId, userId }){
*/
const deleteChannelUser = async function({ loginInfo, channelUserId }){
if(!channelUserId){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
channelUserId = parseInt(channelUserId)
if(!checkIsId(channelUserId)){
return tlResponseArgsError("请求参数错误")
}
const {
@ -348,10 +371,10 @@ const deleteChannelUser = async function({ loginInfo, channelUserId }){
})
if(info == 0){
return tlResponseSvrError("删除频道用户失败")
return tlResponseSvrError("删除失败")
}
return tlResponseSuccess("删除频道用户成功")
return tlResponseSuccess("删除成功")
}
/**
@ -361,7 +384,11 @@ const deleteChannelUser = async function({ loginInfo, channelUserId }){
*/
const updateChannelUserRoleNormal = async function({ loginInfo, channelUserId }){
if(!channelUserId){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
channelUserId = parseInt(channelUserId)
if(!checkIsId(channelUserId)){
return tlResponseArgsError("请求参数错误")
}
const {
@ -375,7 +402,11 @@ const updateChannelUserRoleNormal = async function({ loginInfo, channelUserId })
roleId: TlRoleInner.channel.member.id,
})
return tlResponseSuccess("修改频道用户成功")
if(Object.keys(info).length == 0){
return tlResponseSvrError("更新失败")
}
return tlResponseSuccess("更新成功")
}
/**
@ -385,7 +416,11 @@ const updateChannelUserRoleNormal = async function({ loginInfo, channelUserId })
*/
const updateChannelUserRoleAdmin = async function({ loginInfo, channelUserId }){
if(!channelUserId){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
channelUserId = parseInt(channelUserId)
if(!checkIsId(channelUserId)){
return tlResponseArgsError("请求参数错误")
}
const {
@ -400,10 +435,10 @@ const updateChannelUserRoleAdmin = async function({ loginInfo, channelUserId }){
})
if(Object.keys(info).length == 0){
return tlResponseSvrError("修改频道用户失败")
return tlResponseSvrError("更新失败")
}
return tlResponseSuccess("修改频道用户成功")
return tlResponseSuccess("更新成功")
}
/**
@ -413,12 +448,27 @@ const updateChannelUserRoleAdmin = async function({ loginInfo, channelUserId }){
*/
const getChannelUserList = async function({ loginInfo, channelId }){
if(!channelId){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if(!checkIsId(channelId)){
return tlResponseArgsError("请求参数错误")
}
const {
loginUserCompanyId, loginUserId
} = loginInfo
// 当前用户是否存在频道
const channelUserInfo = await channelUserService.getInfoByChannelIdAndUserId({
companyId: loginUserCompanyId,
channelId: channelId,
userId: loginUserId
})
if(Object.keys(channelUserInfo).length == 0){
return tlResponseNotFound("非法操作")
}
const channelUserList = await channelUserService.getListByChannelId({
companyId: loginUserCompanyId,
@ -467,7 +517,7 @@ const getChannelUserList = async function({ loginInfo, channelId }){
const userId = channelUser[TlChannelUserDef.userId]
const user = userMap[userId]
if(!user){
return
continue
}
// 获取好友关系名称
@ -478,13 +528,13 @@ const getChannelUserList = async function({ loginInfo, channelId }){
resultList.push({
userId: user[TlUserDef.id],
username: user[TlUserDef.name],
userAvatar: await getOssUrl(user[TlUserDef.avatarUrl]),
userAvatar: await getAvatarOssUrl(user[TlUserDef.avatarUrl]),
friendName: friendName,
userFriendId: userFriendId
})
}
return tlResponseSuccess("获取单个频道用户列表成功", resultList)
return tlResponseSuccess("获取成功", resultList)
}
@ -492,7 +542,7 @@ const getChannelUserList = async function({ loginInfo, channelId }){
* 获取频道列表的用户列表
* @param {*} loginInfo
*/
const getChannelListUserList = async function({loginInfo}){
const getChannelListUserList = async function({ loginInfo }){
const {
loginUserCompanyId, loginUserId
} = loginInfo
@ -554,7 +604,7 @@ const getChannelListUserList = async function({loginInfo}){
const userId = channelUser[TlChannelUserDef.userId]
const user = userMap[userId]
if(!user){
return
continue
}
// 获取好友关系名称
@ -566,7 +616,7 @@ const getChannelListUserList = async function({loginInfo}){
channelUserList.push({
userId: user[TlUserDef.id],
username: user[TlUserDef.name],
userAvatar: await getOssUrl(user[TlUserDef.avatarUrl]),
userAvatar: await getAvatarOssUrl(user[TlUserDef.avatarUrl]),
friendName: friendName,
userFriendId: userFriendId
})
@ -574,7 +624,7 @@ const getChannelListUserList = async function({loginInfo}){
result[channelId] = channelUserList
}
return tlResponseSuccess("获取全部频道用户列表成功", result)
return tlResponseSuccess("获取成功", result)
}
@ -587,7 +637,11 @@ const getChannelListUserList = async function({loginInfo}){
*/
const updateChannelToTop = async function({channelId, top = false, loginInfo}){
if(!channelId){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if(!checkIsId(channelId)){
return tlResponseArgsError("请求参数错误")
}
const {
@ -640,7 +694,11 @@ const updateChannelToTop = async function({channelId, top = false, loginInfo}){
*/
const updateChannelToBlack = async function({channelId, black = false, loginInfo}){
if(!channelId){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if(!checkIsId(channelId)){
return tlResponseArgsError("请求参数错误")
}
const {
@ -690,7 +748,11 @@ const updateChannelToBlack = async function({channelId, black = false, loginInfo
*/
const exitChannel = async function({channelId, loginInfo}){
if(!channelId){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if(!checkIsId(channelId)){
return tlResponseArgsError("请求参数错误")
}
const {
@ -707,16 +769,20 @@ const exitChannel = async function({channelId, loginInfo}){
])
if(Object.keys(channelUserInfo).length == 0){
return tlResponseNotFound("退出频道成功")
return tlResponseNotFound("退出成功")
}
// 删除自己在频道的数据
await channelUserService.deleteInfoById({
const deleteRes = await channelUserService.deleteInfoById({
companyId: loginUserCompanyId,
id: channelUserInfo[TlChannelUserDef.id]
})
return tlResponseSuccess("退出频道成功")
if(deleteRes == 0){
return tlResponseSvrError("退出失败")
}
return tlResponseSuccess("退出成功")
}
@ -731,7 +797,6 @@ module.exports = {
getChannelUserList,
addChannelUserListNormal,
getChannelListUserList,
shareJoinGroupChannel,
updateChannelToTop,
updateChannelToBlack,
exitChannel

View File

@ -0,0 +1,275 @@
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseNotFound, tlResponseSuccess,
checkBit, checkIsId, getImageSize, getAudioInfo
} = require('../../utils/utils')
const {
contactOssKeyParam, serverFileUrlTransfer
} = require('../../utils/oss/oss')
const cloudFileService = require('../../service/cloud/tl_cloud_file_service')
const { fields: TlCloudFileFields } = require('../../tables/tl_cloud_file')
const {
Type: TlCloudFileType, Def: TlCloudFileDef,
Flag: TlCloudFileFlag,
} = TlCloudFileFields
const totalFileSize = 100 * 1024 * 1024
/**
* 上传文件
* @param {*} loginInfo
* @param {*} file
* @param {*} channelId
* @param {*} dirId
* @param {*} fileId
*/
const uploadFile = async function ({ loginInfo, file, channelId, dirId, fileId }) {
if (!file) {
return tlResponseArgsError("文件为空")
}
const {
loginUserCompanyId, loginUserId, loginUsername
} = loginInfo
// 大小
const fileSize = file.size
//最大5M
if (fileSize > 5 * 1024 * 1024){
return tlResponseForbidden("文件最大不能超过5M")
}
// 获取当前登录用户所有文件大小, 最大100M
const userCloudFileSize = await cloudFileService.getListByUserId({
companyId: loginUserCompanyId,
userId: loginUserId,
}, [
TlCloudFileDef.fileSize
])
// 获取回收站文件大小
const userCloudRecycleFileSize = await cloudFileService.getListByUserIdDeleted({
companyId: loginUserCompanyId,
userId: loginUserId,
}, [
TlCloudFileDef.fileSize
])
let totalSize = 0
for(let i = 0; i < userCloudFileSize.length; i++){
totalSize += userCloudFileSize[i][TlCloudFileDef.fileSize]
}
for(let i = 0; i < userCloudRecycleFileSize.length; i++){
totalSize += userCloudRecycleFileSize[i][TlCloudFileDef.fileSize]
}
if(totalSize + fileSize > totalFileSize){
return tlResponseForbidden("当前剩余空间不足")
}
let flag = 0
// 类型
const fileType = file.mimetype
// 源文件名
let fileOriginalName = Buffer.from(file.originalname, 'latin1').toString('utf-8');
// 后缀
const fileExt = fileOriginalName.split('.').pop()
// 生成文件名称
const saveFileName = fileId;
// url - ossKey = /companyId/userId/flag/fileName
const fileUrl = contactOssKeyParam({
companyId: loginUserCompanyId,
userId: loginUserId,
ossFlag: flag,
fileName: saveFileName
})
let other = {}
// 根据后缀和类型判断文件类型
let saveFileType = TlCloudFileType.OTHER
// 图片
if (fileType.indexOf('image') > -1 || [
'jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'ico',
].includes(fileExt)) {
saveFileType = TlCloudFileType.IMAGE
const imageSize = await getImageSize(file.path)
if(imageSize){
other = {
width: imageSize.width,
height: imageSize.height
}
}
}
// 音频
else if (fileType.indexOf('audio') > -1 || [
'mp3', 'wav', 'wma', 'ogg', 'ape', 'flac', 'aac', 'amr',
].includes(fileExt)) {
saveFileType = TlCloudFileType.AUDIO
const audioInfo = await getAudioInfo(file.path)
other = {
channels: audioInfo.format.numberOfChannels,
sampleRate: audioInfo.format.sampleRate,
duration: audioInfo.format.duration
}
}
// 视频
else if (fileType.indexOf('video') > -1 || [
'mp4', 'avi', 'mov', 'wmv', 'rmvb', 'flv', '3gp', 'mkv', 'webp',
].includes(fileExt)) {
saveFileType = TlCloudFileType.VIDEO
other = {
width: file.width,
height: file.height,
duration: file.duration
}
}
// 文档
else if ([
'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'txt',
'html', 'htm', 'css', 'js', 'json', 'xml', 'sql', 'java', 'c', 'cpp', 'h', 'hpp',
'py', 'go', 'php', 'sh', 'bat', 'cmd', 'ini', 'conf', 'log', 'md', 'markdown',
'tsv', 'dat', 'db', 'dbf', 'mdb', 'accdb', 'sqlit', 'db3', 'db2', 'db1',
].includes(fileExt)) {
saveFileType = TlCloudFileType.DOCUMENT
}
// 压缩包
else if ([
'zip', 'rar', '7z', 'tar', 'tgz', 'gz', 'bz2', 'xz', 'lz', 'lzma', 'z',
'iso', 'img', 'bin', 'patch', 'diff',
].includes(fileExt)) {
saveFileType = TlCloudFileType.ZIP
}
// 其他
else {
saveFileType = TlCloudFileType.OTHER
}
dirId = parseInt(dirId) || 0
// 保存文件记录
const result = await cloudFileService.addInfo({
companyId: loginUserCompanyId,
userId: loginUserId,
type: saveFileType,
flag,
originFileName: fileOriginalName,
originFileType: fileType,
fileName: saveFileName,
fileSize,
fileUrl: `${fileUrl}`,
fileId: fileId,
dirId: dirId,
other: JSON.stringify(other)
})
if(Object.keys(result).length === 0){
return tlResponseSvrError("上传失败")
}
return tlResponseSuccess("上传成功", {
cloudFileId: result.id,
fileId: fileId,
})
}
/**
* 下载云服务器本地文件
* @param {*} loginInfo
* @param {*} fileId : 资源库id
* @param {*} key : 文件的key路径
* @returns
*/
const downloadCloudFile = async function ({ loginInfo, fileId, key }) {
if (!fileId && !key) {
return tlResponseArgsError("请求参数错误")
}
if(fileId && !checkIsId(fileId)){
return tlResponseArgsError("请求参数错误")
}
const {
loginUserCompanyId, loginUserId,
} = loginInfo
// 如果传到是fileId,则查询文件信息
if(fileId){
fileId = parseInt(fileId)
const fileInfo = await cloudFileService.getInfoById({
companyId: loginUserCompanyId,
id: fileId
})
if(Object.keys(fileInfo).length === 0){
return tlResponseNotFound("文件不存在")
}
const userId = fileInfo[TlCloudFileDef.userId]
if(userId !== loginUserId){
return tlResponseForbidden("你没有权限下载该文件")
}
const flag = fileInfo[TlCloudFileDef.flag]
const saveToAly = checkBit(flag, TlCloudFileFlag.IS_UPLOAD_ALI)
const saveToTx = checkBit(flag, TlCloudFileFlag.IS_UPLOAD_TX)
const saveToQn = checkBit(flag, TlCloudFileFlag.IS_UPLOAD_QN)
if(saveToAly || saveToTx || saveToQn){
return tlResponseForbidden("当前文件存在OSS中,请使用OSS地址下载")
}
// 服务器路径
const filePath = serverFileUrlTransfer(fileInfo[TlCloudFileDef.fileUrl])
// 检查文件是否存在
if (filePath === '') {
return tlResponseNotFound("文件不存在")
}
// 返回文件流
return tlResponseSuccess("获取成功", filePath)
}
// 如果传到是key,则直接处理
if(key){
// base64解码key
key = Buffer.from(key, 'base64').toString('utf-8')
key = decodeURIComponent(key)
if(!key || key.length === 0){
return tlResponseArgsError("请求参数错误")
}
// 服务器路径
const filePath = serverFileUrlTransfer(key)
// 检查文件是否存在
if (filePath === '') {
return tlResponseNotFound("文件不存在")
}
// 返回文件流
return tlResponseSuccess("获取成功", filePath)
}
}
module.exports = {
uploadFile,
downloadCloudFile,
}

View File

@ -1,14 +1,21 @@
const uuid = require('uuid')
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess
tlResponseNotFound, tlResponseSuccess,
checkBit,
setBit, checkIsId
} = require('../../utils/utils')
const companyService = require('../../service/company/tl_company_service')
const userSessionService = require('../../service/user/tl_user_session_service')
const { inner: TlRoleInner } = require('../../tables/tl_role')
const { fields: TlCompanyFields } = require('../../tables/tl_company')
const {
Def: TlCompanyDef, Flag: TlCompanyFlag
} = TlCompanyFields
/**
* 添加企业
* 添加企业 - 管理员
* @param {*} loginInfo
* @param {*} name
* @param {*} address
@ -18,43 +25,52 @@ const userSessionService = require('../../service/user/tl_user_session_service')
* @param {*} logo
* @param {*} description
*/
const addCompany = async function ({
loginInfo, name, address, phone, email, website, logo, description
const adminAddCompany = async function ({
loginInfo, name, address, phone, email, website, logo, description, openRegister
}) {
const {
loginUserCompanyId, loginUserId, loginUserRoleId
} = loginInfo
if(loginUserRoleId !== TlRoleInner.user.admin.id){
return tlResponseForbidden("非法用户")
}
if(!name){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
if(!address){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
if(!phone){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
if(!email){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
if(!website){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
if(!logo){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
if(!description){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
const {
loginUserCompanyId, loginUserId
} = loginInfo
const code = uuid.v4().replace(/-/g, '')
let flag = 0
if(openRegister !== null && openRegister !== undefined){
flag = setBit(flag, TlCompanyFlag.IS_OPEN_REGISTER, openRegister)
}
const info = await companyService.addInfo({
name,
address,
@ -63,14 +79,128 @@ const addCompany = async function ({
website,
logo,
description,
code
code,
flag
})
if(Object.keys(info).length == 0){
return tlResponseSvrError("添加企业失败")
}
return tlResponseSuccess("添加企业成功", info)
return tlResponseSuccess("添加成功", info)
}
/**
* 更新企业 - 管理员
* @param {*} loginInfo
* @param {*} id
* @param {*} name
* @param {*} address
* @param {*} phone
* @param {*} email
* @param {*} website
* @param {*} logo
* @param {*} description
* @param {*} code
* @param {*} authStatus
* @param {*} expiredStatus
* @param {*} openRegister
*/
const adminUpdateCompany = async function ({
id, loginInfo, name, address, phone, email,
website, logo, description, code, authStatus, expiredStatus, openRegister
}) {
const {
loginUserCompanyId, loginUserId, loginUserRoleId
} = loginInfo
if(loginUserRoleId !== TlRoleInner.user.admin.id){
return tlResponseForbidden("非法用户")
}
if(!id){
return tlResponseArgsError("请求参数错误")
}
if(!name){
return tlResponseArgsError("请求参数错误")
}
if(!address){
return tlResponseArgsError("请求参数错误")
}
if(!phone){
return tlResponseArgsError("请求参数错误")
}
if(!email){
return tlResponseArgsError("请求参数错误")
}
if(!website){
return tlResponseArgsError("请求参数错误")
}
if(!logo){
return tlResponseArgsError("请求参数错误")
}
if(!description){
return tlResponseArgsError("请求参数错误")
}
if(!code){
return tlResponseArgsError("请求参数错误")
}
if(openRegister == undefined || openRegister == null){
return tlResponseArgsError("请求参数错误")
}
const info = await companyService.getInfoById({
id
})
if(Object.keys(info).length == 0){
return tlResponseNotFound("企业不存在")
}
let flag = 0
if(authStatus){
flag = setBit(flag, TlCompanyFlag.IS_PASS_AUTH, true)
}else{
flag = setBit(flag, TlCompanyFlag.IS_PASS_AUTH, false)
}
if(expiredStatus){
flag = setBit(flag, TlCompanyFlag.IS_EXPIRED, true)
}else{
flag = setBit(flag, TlCompanyFlag.IS_EXPIRED, false)
}
flag = setBit(flag, TlCompanyFlag.IS_OPEN_REGISTER, openRegister)
const result = await companyService.updateInfoById({
id: id,
}, {
[TlCompanyDef.name]: name,
[TlCompanyDef.address]: address,
[TlCompanyDef.phone]: phone,
[TlCompanyDef.email]: email,
[TlCompanyDef.website]: website,
[TlCompanyDef.logo]: logo,
[TlCompanyDef.description]: description,
[TlCompanyDef.code]: code,
[TlCompanyDef.flag]: flag
})
if(Object.keys(result).length == 0){
return tlResponseSvrError("更新失败")
}
return tlResponseSuccess("更新成功")
}
@ -78,20 +208,237 @@ const addCompany = async function ({
* 获取企业信息
* @param {*} loginInfo
*/
const getCompanyInfo = async function ({loginInfo}) {
const getCompanyInfo = async function ({
loginInfo
}) {
const {
loginUserCompanyId, loginUserId
loginUserCompanyId, loginUserId, loginUserRoleId
} = loginInfo
if(loginUserRoleId !== TlRoleInner.user.admin.id){
return tlResponseForbidden("非法用户")
}
const info = await companyService.getInfoById({
id: loginUserCompanyId
})
return tlResponseSuccess("获取企业信息成功", info)
return tlResponseSuccess("获取成功", info)
}
/**
* 获取企业列表 - 管理员
* @param {*} loginInfo
* @param {*} page
* @param {*} limit
* @param {*} keyword
* @returns
*/
const adminGetCompanyList = async function ({
loginInfo, page, limit, keyword
}) {
const {
loginUserCompanyId, loginUserId, loginUserRoleId
} = loginInfo
if(loginUserRoleId !== TlRoleInner.user.admin.id){
return tlResponseForbidden("非法用户")
}
if(!page){
return tlResponseArgsError("请求参数错误")
}
if(!limit){
return tlResponseArgsError("请求参数错误")
}
if(!checkIsId(page)){
return tlResponseArgsError("请求参数错误")
}
if(!checkIsId(limit)){
return tlResponseArgsError("请求参数错误")
}
page = parseInt(page)
limit = parseInt(limit)
let list = []
let total = 0
if(keyword == "" || keyword == undefined || keyword == null){
list = await companyService.getListForPage({}, [
TlCompanyDef.id,
TlCompanyDef.name,
TlCompanyDef.address,
TlCompanyDef.phone,
TlCompanyDef.email,
TlCompanyDef.website,
TlCompanyDef.logo,
TlCompanyDef.description,
TlCompanyDef.code,
TlCompanyDef.flag,
TlCompanyDef.createdAt
], page, limit)
total = await companyService.getCount({})
}else{
list = await companyService.getListByKeywordForPage({
keyword: keyword
}, [
TlCompanyDef.id,
TlCompanyDef.name,
TlCompanyDef.address,
TlCompanyDef.phone,
TlCompanyDef.email,
TlCompanyDef.website,
TlCompanyDef.logo,
TlCompanyDef.description,
TlCompanyDef.code,
TlCompanyDef.flag,
TlCompanyDef.createdAt
], page, limit)
total = await companyService.getCountByKeyword({
keyword: keyword
})
}
let resultList = []
for (let i = 0; i < list.length; i++) {
const item = list[i];
let flag = item[TlCompanyDef.flag] || 0
const authStatus = checkBit(flag, TlCompanyFlag.IS_PASS_AUTH)
const expiredStatus = checkBit(flag, TlCompanyFlag.IS_EXPIRED)
const openRegister = checkBit(flag, TlCompanyFlag.IS_OPEN_REGISTER)
resultList.push({
id: item[TlCompanyDef.id],
name: item[TlCompanyDef.name],
address: item[TlCompanyDef.address],
phone: item[TlCompanyDef.phone],
email: item[TlCompanyDef.email],
website: item[TlCompanyDef.website],
logo: item[TlCompanyDef.logo],
description: item[TlCompanyDef.description],
code: item[TlCompanyDef.code],
authStatus,
expiredStatus,
openRegister,
createTime: item[TlCompanyDef.createdAt],
})
}
return tlResponseSuccess("获取成功", {
list: resultList,
count: total
})
}
/**
* 删除企业 - 管理员
* @param {*} loginInfo
* @returns
*/
const adminDeleteCompany = async function ({loginInfo, id}) {
const {
loginUserCompanyId, loginUserId, loginUserRoleId
} = loginInfo
if(loginUserRoleId !== TlRoleInner.user.admin.id){
return tlResponseForbidden("非法用户")
}
if(!id){
return tlResponseArgsError("请求参数错误")
}
const info = await companyService.getInfoById({
id
})
if(Object.keys(info).length == 0){
return tlResponseNotFound("企业不存在")
}
const result = await companyService.deleteInfoById({
id
})
if(result == 0){
return tlResponseNotFound("删除失败")
}
return tlResponseSuccess("删除成功")
}
/**
* 获取企业信息 - 管理员
* @param {*} id
* @param {*} loginInfo
* @returns
*/
const adminGetCompanyInfo = async function ({
id, loginInfo
}) {
const {
loginUserCompanyId, loginUserId, loginUserRoleId
} = loginInfo
if(loginUserRoleId !== TlRoleInner.user.admin.id){
return tlResponseForbidden("非法用户")
}
if(!id){
return tlResponseArgsError("请求参数错误")
}
const info = await companyService.getInfoById({
id
})
if(Object.keys(info).length == 0){
return tlResponseNotFound("企业不存在")
}
let flag = info[TlCompanyDef.flag] || 0
const authStatus = checkBit(flag, TlCompanyFlag.IS_PASS_AUTH)
const expiredStatus = checkBit(flag, TlCompanyFlag.IS_EXPIRED)
const openRegister = checkBit(flag, TlCompanyFlag.IS_OPEN_REGISTER)
return tlResponseSuccess("获取成功", {
id: info[TlCompanyDef.id],
name: info[TlCompanyDef.name],
address: info[TlCompanyDef.address],
phone: info[TlCompanyDef.phone],
email: info[TlCompanyDef.email],
website: info[TlCompanyDef.website],
logo: info[TlCompanyDef.logo],
description: info[TlCompanyDef.description],
code: info[TlCompanyDef.code],
authStatus,
expiredStatus,
openRegister,
createTime: info[TlCompanyDef.createdAt],
})
}
module.exports = {
addCompany,
getCompanyInfo
getCompanyInfo,
adminAddCompany,
adminUpdateCompany,
adminGetCompanyList,
adminDeleteCompany,
adminGetCompanyInfo,
}

View File

@ -1,12 +1,64 @@
const crypto = require("crypto")
const {
checkBit, tlResponseSuccess, tlResponseForbidden
} = require("../../utils/utils");
const { get_env_config, set_env_config } = require("../../../conf/env_config");
const conf = get_env_config()
const companyService = require('../../service/company/tl_company_service')
const userSessionService = require('../../service/user/tl_user_session_service')
const { inner: TlRoleInner } = require('../../tables/tl_role')
const { fields: TlCompanyFields } = require('../../tables/tl_company')
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess
} = require("../../utils/utils");
const {get_env_config} = require("../../../conf/env_config");
const conf = get_env_config()
const crypto = require("crypto")
const userSessionService = require('../../service/user/tl_user_session_service')
Def: TlCompanyDef, Flag: TlCompanyFlag
} = TlCompanyFields
/**
* 获取所有企业邀请码 - 最多返回10个
* @returns
*/
const getAllCompanyInviteCode = async function () {
const companyList = await companyService.getListForPage({}, [
TlCompanyDef.id,
TlCompanyDef.code,
TlCompanyDef.name,
TlCompanyDef.flag
], 1, 10)
const resultList = []
for(let i = 0; i < companyList.length; i++) {
const item = companyList[i];
// 处理每个企业的邀请码
const flag = item[TlCompanyDef.flag] || 0
const code = item[TlCompanyDef.code] || ''
const name = item[TlCompanyDef.name] || ''
// 过滤掉没有邀请码的企业
if(code.length === 0) {
continue
}
const authStatus = checkBit(flag, TlCompanyFlag.IS_PASS_AUTH)
const expiredStatus = checkBit(flag, TlCompanyFlag.IS_EXPIRED)
const openRegister = checkBit(flag, TlCompanyFlag.IS_OPEN_REGISTER)
// 没有通过认证、已过期、未开放注册的企业,不算在内
if(!authStatus && !expiredStatus && !openRegister) {
continue
}
resultList.push({
value: code,
name: name
})
}
return resultList
}
/**
@ -17,6 +69,8 @@ const userSessionService = require('../../service/user/tl_user_session_service')
* @param {*} loginInfo 登录信息
*/
const initData = async function({openTurn, useSecret, ip, token}){
const inviteCodeList = await getAllCompanyInviteCode()
if(!token){
return tlResponseSuccess("获取成功",{
version : conf.version,
@ -24,6 +78,7 @@ const initData = async function({openTurn, useSecret, ip, token}){
rtcConfig: { iceServers: [] },
options: {},
logo : genClientLogo(),
codeList: inviteCodeList
})
}
@ -38,6 +93,7 @@ const initData = async function({openTurn, useSecret, ip, token}){
rtcConfig: { iceServers: [] },
options: {},
logo : genClientLogo(),
codeList: inviteCodeList
})
}
@ -55,6 +111,7 @@ const initData = async function({openTurn, useSecret, ip, token}){
"offerToReceiveVideo": 1
},
logo : genClientLogo(),
codeList: inviteCodeList
})
}
@ -68,6 +125,7 @@ const initData = async function({openTurn, useSecret, ip, token}){
"offerToReceiveVideo": 1
},
logo : genClientLogo(),
codeList: inviteCodeList
})
}
@ -133,6 +191,218 @@ const genTurnServerIceServersConfig = function(withTurn, useSecret, username){
return iceServers;
}
/**
* 获取系统环境配置
* @param {*} loginInfo
*/
const adminGetSystemEnvConfig = async function({
loginInfo
}) {
const {
loginUserCompanyId, loginUserId, loginUserRoleId
} = loginInfo
if(loginUserRoleId !== TlRoleInner.user.admin.id){
return tlResponseForbidden("非法用户")
}
// redis配置
const redisConfig = {
host: conf.redis_host,
port: conf.redis_port,
password: conf.redis_password,
}
// webrtc配置
const webrtcConfig = {
stun_host: conf.webrtc_stun_host,
turn_host: conf.webrtc_turn_host,
turn_username: conf.webrtc_turn_username,
turn_credential: conf.webrtc_turn_credential,
turn_secret: conf.webrtc_turn_secret,
turn_expire: conf.webrtc_turn_expire,
}
// mysql配置
const mysqlConfig = {
host: conf.db_mysql_host,
port: conf.db_mysql_port,
user: conf.db_mysql_user,
password: conf.db_mysql_password,
database: conf.db_mysql_database,
}
// email配置
const emailConfig = {
host: conf.mail_host,
port: conf.mail_port,
user: conf.mail_user,
pass: conf.mail_password,
}
// 配置项定义 - 从前端移到后端
const configDefinitions = {
redis: {
title: 'Redis配置',
configKey: 'redisConfig',
fields: [
{ key: 'host', label: '主机', desc: 'Redis服务器地址', type: 'text' },
{ key: 'port', label: '端口', desc: 'Redis服务器端口', type: 'text' },
{ key: 'password', label: '密码', desc: 'Redis服务器密码', type: 'text' }
]
},
webrtc: {
title: 'WebRTC配置',
configKey: 'webrtcConfig',
fields: [
{ key: 'stun_host', label: 'STUN服务器', desc: 'STUN服务器地址', type: 'text' },
{ key: 'turn_host', label: 'TURN服务器', desc: 'TURN服务器地址', type: 'text' },
{ key: 'turn_username', label: 'TURN用户名', desc: 'TURN服务器用户名', type: 'text' },
{ key: 'turn_credential', label: 'TURN密码', desc: 'TURN服务器密码', type: 'text' },
{ key: 'turn_secret', label: 'TURN密钥', desc: 'TURN服务器密钥', type: 'text' },
{ key: 'turn_expire', label: '过期时间', desc: 'TURN过期时间(秒)', type: 'text' }
]
},
mysql: {
title: 'MySQL配置',
configKey: 'mysqlConfig',
fields: [
{ key: 'host', label: '主机', desc: 'MySQL服务器地址', type: 'text' },
{ key: 'port', label: '端口', desc: 'MySQL服务器端口', type: 'text' },
{ key: 'user', label: '用户名', desc: 'MySQL用户名', type: 'text' },
{ key: 'password', label: '密码', desc: 'MySQL密码', type: 'text' },
{ key: 'database', label: '数据库', desc: 'MySQL数据库名称', type: 'text' }
]
},
email: {
title: '邮件配置',
configKey: 'emailConfig',
fields: [
{ key: 'host', label: 'SMTP服务器', desc: '邮件SMTP服务器地址', type: 'text' },
{ key: 'port', label: 'SMTP端口', desc: '邮件SMTP服务器端口', type: 'text' },
{ key: 'user', label: '邮箱账号', desc: '发送邮件的邮箱账号', type: 'text' },
{ key: 'pass', label: '邮箱密码', desc: '邮箱授权密码', type: 'text' }
]
}
};
return tlResponseSuccess("获取成功", {
redisConfig,
webrtcConfig,
mysqlConfig,
emailConfig,
configDefinitions
})
}
/**
* 设置系统环境配置
* @param {*} loginInfo
* @param {*} redisConfig
* @param {*} webrtcConfig
* @param {*} mysqlConfig
* @param {*} emailConfig
* @returns
*/
const adminSetSystemEnvConfig = async function({
loginInfo,
redisConfig = {},
webrtcConfig = {},
mysqlConfig = {},
emailConfig = {},
}) {
const {
loginUserCompanyId, loginUserId, loginUserRoleId
} = loginInfo
if(loginUserRoleId !== TlRoleInner.user.admin.id){
return tlResponseForbidden("非法用户")
}
// 设置redis配置
if(Object.keys(redisConfig).length > 0) {
if(redisConfig.host !== undefined && redisConfig.host !== null) {
set_env_config("redis_host", redisConfig.host)
}
if(redisConfig.port !== undefined && redisConfig.port !== null) {
redisConfig.port = parseInt(redisConfig.port)
set_env_config("redis_port", redisConfig.port)
}
if(redisConfig.password !== undefined && redisConfig.password !== null) {
set_env_config("redis_password", redisConfig.password)
}
}
// 设置webrtc配置
if(Object.keys(webrtcConfig).length > 0) {
if(webrtcConfig.stun_host !== undefined && webrtcConfig.stun_host !== null) {
set_env_config("webrtc_stun_host", webrtcConfig.stun_host)
}
if(webrtcConfig.turn_host !== undefined && webrtcConfig.turn_host !== null) {
set_env_config("webrtc_turn_host", webrtcConfig.turn_host)
}
if(webrtcConfig.turn_username !== undefined && webrtcConfig.turn_username !== null) {
set_env_config("webrtc_turn_username", webrtcConfig.turn_username)
}
if(webrtcConfig.turn_credential !== undefined && webrtcConfig.turn_credential !== null) {
set_env_config("webrtc_turn_credential", webrtcConfig.turn_credential)
}
if(webrtcConfig.turn_secret !== undefined && webrtcConfig.turn_secret !== null) {
set_env_config("webrtc_turn_secret", webrtcConfig.turn_secret)
}
if(webrtcConfig.turn_expire !== undefined && webrtcConfig.turn_expire !== null) {
webrtcConfig.turn_expire = parseInt(webrtcConfig.turn_expire)
set_env_config("webrtc_turn_expire", webrtcConfig.turn_expire)
}
}
// 设置mysql配置
if(Object.keys(mysqlConfig).length > 0) {
if(mysqlConfig.host !== undefined && mysqlConfig.host !== null) {
set_env_config("db_mysql_host", mysqlConfig.host)
}
if(mysqlConfig.port !== undefined && mysqlConfig.port !== null) {
set_env_config("db_mysql_port", mysqlConfig.port)
}
if(mysqlConfig.user !== undefined && mysqlConfig.user !== null) {
set_env_config("db_mysql_user", mysqlConfig.user)
}
if(mysqlConfig.password !== undefined && mysqlConfig.password !== null) {
set_env_config("db_mysql_password", mysqlConfig.password)
}
if(mysqlConfig.database !== undefined && mysqlConfig.database !== null) {
set_env_config("db_mysql_database", mysqlConfig.database)
}
}
// 设置email配置
if(Object.keys(emailConfig).length > 0) {
if(emailConfig.host !== undefined && emailConfig.host !== null) {
set_env_config("mail_host", emailConfig.host)
}
if(emailConfig.port !== undefined && emailConfig.port !== null) {
emailConfig.port = parseInt(emailConfig.port)
set_env_config("mail_port", emailConfig.port)
}
if(emailConfig.user !== undefined && emailConfig.user !== null) {
set_env_config("mail_user", emailConfig.user)
}
if(emailConfig.pass !== undefined && emailConfig.pass !== null) {
set_env_config("mail_password", emailConfig.pass)
}
}
return tlResponseSuccess("设置完成")
}
module.exports = {
initData
initData,
adminGetSystemEnvConfig,
adminSetSystemEnvConfig
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,273 @@
const { tlConsoleError, tlConsole, tlResponseSuccess, tlResponseSvrError, tlResponseForbidden } = require("../../utils/utils");
const pm2 = require("pm2");
const { inner: TlRoleInner } = require('../../tables/tl_role')
/**
* 连接到PM2
* @returns {Promise<void>} 连接Promise
*/
const connectToPm2 = () => {
return new Promise((resolve, reject) => {
pm2.connect((err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
};
/**
* 停止PM2服务
* @param {string|string[]} services - 服务名称(单个服务名或服务名数组)
* @param {object} loginInfo - 登录信息
* @returns {Promise<object>} 返回执行结果
*/
const adminStopPm2Service = async function ({
services, loginInfo
}) {
const {
loginUserCompanyId, loginUserId, loginUserRoleId
} = loginInfo
if(loginUserRoleId !== TlRoleInner.user.admin.id){
return tlResponseForbidden("非法用户")
}
if (!services) {
return tlResponseSvrError(`Services not specified`);
}
// 将单个服务名转换为数组
const serviceArray = Array.isArray(services) ? services : [services];
if (serviceArray.length === 0) {
return tlResponseSvrError(`Empty services array`);
}
try {
await connectToPm2();
const results = await Promise.all(serviceArray.map(service => {
return new Promise((resolve, reject) => {
pm2.stop(service, (err, proc) => {
if (err) {
reject(err);
} else {
resolve(proc);
}
});
});
}));
// 提取关键信息并格式化返回结果
let proc = results[0][0];
let result = {
name: proc.name,
status: proc.pm2_env.status,
pid: proc.pid,
}
tlConsole(`PM2 services stopped: ${serviceArray.join(', ')}`, result);
pm2.disconnect();
return tlResponseSuccess(`Services stopped: ${serviceArray.join(', ')}`, result);
} catch (error) {
tlConsoleError(`Failed to stop PM2 services: ${error?.message}`);
pm2.disconnect();
return tlResponseSvrError(`Failed to stop PM2 services: ${error?.message}`);
}
};
/**
* 启动PM2服务
* @param {string|string[]} services - 服务名称(单个服务名或服务名数组)
* @param {object} loginInfo - 登录信息
* @returns {Promise<object>} 返回执行结果
*/
const adminStartPm2Service = async function ({
services, loginInfo
}) {
const {
loginUserCompanyId, loginUserId, loginUserRoleId
} = loginInfo
if(loginUserRoleId !== TlRoleInner.user.admin.id){
return tlResponseForbidden("非法用户")
}
if (!services) {
return tlResponseSvrError(`Services not specified`);
}
// 将单个服务名转换为数组
const serviceArray = Array.isArray(services) ? services : [services];
if (serviceArray.length === 0) {
return tlResponseSvrError(`Empty services array`);
}
try {
await connectToPm2();
const results = await Promise.all(serviceArray.map(service => {
return new Promise((resolve, reject) => {
pm2.start(service, (err, proc) => {
if (err) {
reject(err);
} else {
resolve(proc);
}
});
});
}));
// 提取关键信息并格式化返回结果
let proc = results[0][0];
let result = {
name: proc.name,
status: proc.pm2_env.status,
pid: proc.pid,
}
tlConsole(`PM2 services started: ${serviceArray.join(', ')}`, result);
pm2.disconnect();
return tlResponseSuccess(`Services started: ${serviceArray.join(', ')}`, result);
} catch (error) {
tlConsoleError(`Failed to start PM2 services: ${error?.message}`);
pm2.disconnect();
return tlResponseSvrError(`Failed to start PM2 services: ${error?.message}`);
}
};
/**
* 重启PM2服务
* @param {string|string[]} services - 服务名称(单个服务名或服务名数组)
* @param {object} loginInfo - 登录信息
* @returns {Promise<object>} 返回执行结果
*/
const adminReadminStartPm2Service = async function ({
services, loginInfo
}) {
const {
loginUserCompanyId, loginUserId, loginUserRoleId
} = loginInfo
if(loginUserRoleId !== TlRoleInner.user.admin.id){
return tlResponseForbidden("非法用户")
}
if (!services) {
return tlResponseSvrError(`Services not specified`);
}
// 将单个服务名转换为数组
const serviceArray = Array.isArray(services) ? services : [services];
if (serviceArray.length === 0) {
return tlResponseSvrError(`Empty services array`);
}
try {
await connectToPm2();
const results = await Promise.all(serviceArray.map(service => {
return new Promise((resolve, reject) => {
pm2.restart(service, (err, proc) => {
if (err) {
reject(err);
} else {
resolve(proc);
}
});
});
}));
// 提取关键信息并格式化返回结果
let proc = results[0][0];
let result = {
name: proc.name,
status: proc.pm2_env.status,
pid: proc.pid,
}
tlConsole(`PM2 services restarted: ${serviceArray.join(', ')}`, result);
pm2.disconnect();
return tlResponseSuccess(`Services restarted: ${serviceArray.join(', ')}`, result);
} catch (error) {
tlConsoleError(`Failed to restart PM2 services: ${error?.message}`);
pm2.disconnect();
return tlResponseSvrError(`Failed to restart PM2 services: ${error?.message}`);
}
};
/**
* 获取PM2服务状态
* @param {*} loginInfo
* @returns
*/
const adminGetServiceStatus = async function ({
loginInfo
}) {
const {
loginUserCompanyId, loginUserId, loginUserRoleId
} = loginInfo
if(loginUserRoleId !== TlRoleInner.user.admin.id){
return tlResponseForbidden("非法用户")
}
try {
await connectToPm2();
const list = await new Promise((resolve, reject) => {
pm2.list((err, procList) => {
if (err) {
reject(err);
} else {
resolve(procList);
}
});
});
tlConsole(`PM2 service status retrieved`);
pm2.disconnect();
// 提取关键信息并格式化返回结果
let resultList = list.map(proc => ({
name: proc.name,
status: proc.pm2_env.status,
pid: proc.pid,
monit: {
memory: proc.monit.memory,
cpu: proc.monit.cpu
},
}));
// 只保留tl-rtc-app-api和tl-rtc-app-socket服务
resultList = resultList.filter(
proc => proc.name === 'tl-rtc-app-api' ||
proc.name === 'tl-rtc-app-socket'
);
return tlResponseSuccess("PM2服务状态获取成功", {
processList: resultList,
});
} catch (error) {
tlConsoleError(`Failed to get PM2 service status: ${error?.message}`);
pm2.disconnect();
return tlResponseSvrError(`Failed to get PM2 service status: ${error?.message}`);
}
};
module.exports = {
adminStopPm2Service,
adminStartPm2Service,
adminReadminStartPm2Service,
adminGetServiceStatus
}

View File

@ -1,50 +1,66 @@
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess,
tlResponseNotFound, tlResponseSuccess,
setBit, checkBit,
tlConsole
checkIsId
} = require('../../utils/utils')
const channelService = require('../../service/channel/tl_channel_service')
const channelUserService = require('../../service/channel/tl_channel_user_service')
const userService = require('../../service/user/tl_user_service')
const userFriendService = require('../../service/user/tl_user_friend_service')
const userSessionService = require('../../service/user/tl_user_session_service')
const userApplyService = require('../../service/user/tl_user_apply_service')
const userReadService = require('../../service/user/tl_user_read_service')
const userFriendBiz = require('./user_friend_biz')
const userConfigService = require('../../service/user/tl_user_config_service')
const { fields: userFields } = require('../../tables/tl_user')
const { fields: userFriendFields } = require('../../tables/tl_user_friend')
const { fields: userApplyFields } = require('../../tables/tl_user_apply')
const { fields: userReadFields } = require('../../tables/tl_user_read')
const { fields: channelFields } = require('../../tables/tl_channel')
const { fields: userConfigFields } = require('../../tables/tl_user_config')
const { fields: channelUserFields } = require('../../tables/tl_channel_user')
const { inner: TlRoleInner } = require('../../tables/tl_role')
const { getOssUrl } = require('../../utils/oss/oss')
const { addChannelUser } = require('../../biz/channel/channel_user_biz')
const { getAvatarOssUrl } = require('../../utils/oss/oss')
const TlUserDef = userFields.Def
const TlUserFriendDef = userFriendFields.Def
const TlUserFriendType = userFriendFields.FriendType
const TlUserFriendFlag = userFriendFields.Flag
const TlUserFriendStatus = userFriendFields.Status
const TlUserApplyDef = userApplyFields.Def
const TlUserApplyStatus = userApplyFields.Status
const TlUserApplyType = userApplyFields.Type
const TlUserApplyOrigin = userApplyFields.Origin
const TlUserApplyFlag = userApplyFields.Flag
const TlUserReadDef = userReadFields.Def
const TlUserReadType = userReadFields.Type
const TlUserConfingDef = userConfigFields.Def
const TlUserConfingAccount = userConfigFields.Account
const TlChannelDef = channelFields.Def
const TlChannelUserDef = channelUserFields.Def
/**
* 申请添加好友
* @param {*} friendId
* @param {*} origin
* @param {*} remark
* @param {*} loginInfo
*/
const applyAddFriend = async function({ friendId, origin, remark, loginInfo }){
const applyAddFriend = async function({ friendId, remark, loginInfo }){
if(!friendId){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
if(!origin){
return tlResponseArgsError("请求参数为空")
friendId = parseInt(friendId)
if(!checkIsId(friendId)){
return tlResponseArgsError("请求参数不合法")
}
if(remark && remark.length > 64){
return tlResponseArgsError("备注信息过长")
}
const {
@ -105,13 +121,37 @@ const applyAddFriend = async function({ friendId, origin, remark, loginInfo }){
return tlResponseForbidden("对方已经向你发送过申请,请查看申请记录")
}
// 获取用户配置
const userConfigInfo = await userConfigService.getInfoByUserId({
companyId: loginUserCompanyId,
userId: friendId
}, [
TlUserConfingDef.account
])
let accountSettingStr = userConfigInfo[TlUserConfingDef.account]
let accountSetting = {}
try{
accountSetting = JSON.parse(accountSettingStr)
}catch(e){
accountSetting = {}
}
// 是否不接受好友申请
let notAcceptFriendApply = accountSetting[TlUserConfingAccount.notAcceptFriendApply] || false
if(notAcceptFriendApply){
return tlResponseForbidden("对方已关闭好友申请")
}
let flag = 0
flag = setBit(flag, TlUserApplyFlag.IS_APPLY_FRIEND_BY_SEARCH_NAME, true)
// 生成申请记录
const applyInfo = await userApplyService.addInfo({
companyId: loginUserCompanyId,
userId: loginUserId,
targetId: friendId,
origin,
origin: "通过搜索",
remark,
flag,
type: TlUserApplyType.FRIEND,
status: TlUserApplyStatus.WAIT
})
@ -133,7 +173,12 @@ const applyAddFriend = async function({ friendId, origin, remark, loginInfo }){
*/
const passUserFriendApply = async function({ id, loginInfo }){
if(!id){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
id = parseInt(id)
if(!checkIsId(id)){
return tlResponseArgsError("请求参数不合法")
}
const {
@ -150,6 +195,11 @@ const passUserFriendApply = async function({ id, loginInfo }){
return tlResponseNotFound("申请记录不存在")
}
// 如果不是被申请人,不能通过
if(applyInfo[TlUserApplyDef.targetId] != loginUserId){
return tlResponseForbidden("非法操作")
}
const status = applyInfo[TlUserApplyDef.status]
if(status != TlUserApplyStatus.WAIT){
return tlResponseForbidden("申请记录状态不正确")
@ -183,6 +233,26 @@ const passUserFriendApply = async function({ id, loginInfo }){
return initChannelRes
}
const applyFlag = applyInfo[TlUserApplyDef.flag]
const isApplyFriendBySearchName = checkBit(applyFlag, TlUserApplyFlag.IS_APPLY_FRIEND_BY_SEARCH_NAME)
const isApplyFriendBySearchPhone = checkBit(applyFlag, TlUserApplyFlag.IS_APPLY_FRIEND_BY_SEARCH_PHONE)
const isApplyFriendBySearchEmail = checkBit(applyFlag, TlUserApplyFlag.IS_APPLY_FRIEND_BY_SEARCH_EMAIL)
const isApplyByShareLink = checkBit(applyFlag, TlUserApplyFlag.IS_APPLY_FRIEND_BY_INVITE)
let friendFlag = 0
if(isApplyFriendBySearchName){
friendFlag = setBit(friendFlag, TlUserFriendFlag.IS_ADD_BY_SEARCH_NAME, true)
}
if(isApplyFriendBySearchPhone){
friendFlag = setBit(friendFlag, TlUserFriendFlag.IS_ADD_BY_SEARCH_PHONE, true)
}
if(isApplyFriendBySearchEmail){
friendFlag = setBit(friendFlag, TlUserFriendFlag.IS_ADD_BY_SEARCH_EMAIL, true)
}
if(isApplyByShareLink){
friendFlag = setBit(friendFlag, TlUserFriendFlag.IS_ADD_BY_INVITE, true)
}
// 生成双向好友记录
let initUserFriendRes = await userFriendBiz.initUserFriendForPassFriend({
loginUserCompanyId,
@ -190,8 +260,9 @@ const passUserFriendApply = async function({ id, loginInfo }){
loginUsername,
applyUserId,
applyUserName: applyUserInfo[TlUserDef.name],
origin: applyInfo[TlUserApplyDef.origin],
origin: applyInfo[TlUserApplyDef.origin],
remark: applyInfo[TlUserApplyDef.remark],
flag: friendFlag,
channelId: initChannelRes.data.channelId
})
@ -225,7 +296,12 @@ const passUserFriendApply = async function({ id, loginInfo }){
*/
const rejectUserFriendApply = async function({ id, loginInfo }){
if(!id){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
id = parseInt(id)
if(!checkIsId(id)){
return tlResponseArgsError("请求参数不合法")
}
const {
@ -239,13 +315,19 @@ const rejectUserFriendApply = async function({ id, loginInfo }){
TlUserApplyDef.id,
TlUserApplyDef.status,
TlUserApplyDef.type,
TlUserApplyDef.userId
TlUserApplyDef.userId,
TlUserApplyDef.targetId
])
if(Object.keys(applyInfo).length == 0){
return tlResponseNotFound("申请记录不存在")
}
// 如果不是被申请人,不能通过
if(applyInfo[TlUserApplyDef.targetId] != loginUserId){
return tlResponseForbidden("非法操作")
}
const status = applyInfo[TlUserApplyDef.status]
if(status != TlUserApplyStatus.WAIT){
return tlResponseForbidden("申请记录状态不正确")
@ -305,6 +387,7 @@ const getUserFriendApplyListFromSelf = async function({ loginInfo }){
TlUserApplyDef.id,
TlUserApplyDef.targetId,
TlUserApplyDef.origin,
TlUserApplyDef.flag,
TlUserApplyDef.status,
TlUserApplyDef.remark,
TlUserApplyDef.createdAt
@ -349,12 +432,6 @@ const getUserFriendApplyListFromSelf = async function({ loginInfo }){
for(let i = 0; i < applyList.length; i++){
const item = applyList[i]
let originStr = ''
const origin = item[TlUserApplyDef.origin]
if(origin == TlUserApplyOrigin.SEARCH_NAME){
originStr = "搜索用户名添加"
}
const status = item[TlUserApplyDef.status]
let statusStr = ''
if(status == TlUserApplyStatus.PASS){
@ -373,9 +450,9 @@ const getUserFriendApplyListFromSelf = async function({ loginInfo }){
resultList.push({
id : item[TlUserApplyDef.id],
username: userInfo[TlUserDef.name],
userAvatar: await getOssUrl(userInfo[TlUserDef.avatarUrl]),
userAvatar: await getAvatarOssUrl(userInfo[TlUserDef.avatarUrl]),
userApplyRemark: item[TlUserApplyDef.remark],
origin : originStr,
origin : item[TlUserApplyDef.origin],
createTime: item[TlUserApplyDef.createdAt],
status : statusStr,
userCompanyName: loginUserCompanyName,
@ -383,7 +460,7 @@ const getUserFriendApplyListFromSelf = async function({ loginInfo }){
})
}
return tlResponseSuccess("获取我发出的申请记录成功", resultList)
return tlResponseSuccess("获取成功", resultList)
}
/**
@ -404,6 +481,7 @@ const getUserFriendListFromOther = async function({ loginInfo }){
TlUserApplyDef.id,
TlUserApplyDef.userId,
TlUserApplyDef.origin,
TlUserApplyDef.flag,
TlUserApplyDef.status,
TlUserApplyDef.remark,
TlUserApplyDef.createdAt
@ -448,12 +526,6 @@ const getUserFriendListFromOther = async function({ loginInfo }){
for(let i = 0; i < applyList.length; i++){
const item = applyList[i]
let originStr = ''
const origin = item[TlUserApplyDef.origin]
if(origin == TlUserApplyOrigin.SEARCH_NAME){
originStr = "搜索用户名添加"
}
const status = item[TlUserApplyDef.status]
let statusStr = ''
if(status == TlUserApplyStatus.PASS){
@ -472,24 +544,543 @@ const getUserFriendListFromOther = async function({ loginInfo }){
resultList.push({
id : item[TlUserApplyDef.id],
username: userInfo[TlUserDef.name],
userAvatar: await getOssUrl(userInfo[TlUserDef.avatarUrl]),
userAvatar: await getAvatarOssUrl(userInfo[TlUserDef.avatarUrl]),
userApplyRemark: item[TlUserApplyDef.remark],
origin : originStr,
origin : item[TlUserApplyDef.origin],
createTime: item[TlUserApplyDef.createdAt],
status : statusStr,
userCompanyName: loginUserCompanyName,
hasRead: userReadMap.has(item[TlUserApplyDef.id])
})
}
return tlResponseSuccess("获取我收到的申请记录成功", resultList)
return tlResponseSuccess("获取成功", resultList)
}
/**
* 申请加入群聊
* @param {*} channelId
* @param {*} remark
* @param {*} shareUserId
* @param {*} loginInfo
*/
const applyAddGroup = async function({ channelId, remark, shareUserId, loginInfo }){
if(!channelId){
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if(!checkIsId(channelId)){
return tlResponseArgsError("请求参数不合法")
}
if(remark && remark.length > 64){
return tlResponseArgsError("备注信息过长")
}
if(shareUserId){
shareUserId = parseInt(shareUserId)
if(!checkIsId(shareUserId)){
return tlResponseArgsError("请求参数不合法")
}
}
const {
loginUserCompanyId, loginUserId
} = loginInfo
const channelInfo = await channelService.getInfoById({
companyId: loginUserCompanyId,
id: channelId
})
if(Object.keys(channelInfo).length == 0){
return tlResponseNotFound("频道不存在")
}
const channelUserInfo = await channelUserService.getInfoByChannelIdAndUserId({
companyId: loginUserCompanyId,
channelId: channelId,
userId: loginUserId
})
if(Object.keys(channelUserInfo).length > 0){
return tlResponseForbidden("已加入群聊")
}
// 查看自己是否存在待验证的申请记录
let applyHistroryList = await userApplyService.getListByUserIdAndTargetIdAndStatuAndType({
companyId: loginUserCompanyId,
userId: loginUserId,
targetId: channelId,
status: TlUserApplyStatus.WAIT,
type: TlUserApplyType.GROUP
}, [
TlUserApplyDef.id
])
if(applyHistroryList.length > 0){
return tlResponseForbidden("你已经向该群发送过申请,请查看申请记录")
}
let flag = 0
let origin = ''
if(shareUserId){
const shareUserInfo = await userService.getInfoById({
companyId: loginUserCompanyId,
id: shareUserId
}, [
TlUserDef.name
])
flag = setBit(flag, TlUserApplyFlag.IS_APPLY_GROUP_BY_SHARE_LINK, true)
origin = "通过"+shareUserInfo[TlUserDef.name]+"分享"
}else{
flag = setBit(flag, TlUserApplyFlag.IS_APPLY_GROUP_BY_SEARCH_NAME, true)
origin = "通过搜索"
}
// 生成申请记录
const applyInfo = await userApplyService.addInfo({
companyId: loginUserCompanyId,
userId: loginUserId,
targetId: channelId,
origin,
remark,
flag,
type: TlUserApplyType.GROUP,
status: TlUserApplyStatus.WAIT
})
if(Object.keys(applyInfo).length == 0){
return tlResponseSvrError("发送申请失败")
}
return tlResponseSuccess("发送申请成功", {
applyId: applyInfo[TlUserApplyDef.id]
})
}
/**
* 通过用户群聊申请
* @param {*} id
* @param {*} loginInfo
* @returns
*/
const passUserGroupApply = async function({ id, loginInfo }){
if(!id){
return tlResponseArgsError("请求参数错误")
}
id = parseInt(id)
if(!checkIsId(id)){
return tlResponseArgsError("请求参数不合法")
}
const {
loginUserCompanyId, loginUserId
} = loginInfo
// 查询申请记录
const applyInfo = await userApplyService.getInfoById({
companyId: loginUserCompanyId,
id
})
if(Object.keys(applyInfo).length == 0){
return tlResponseNotFound("申请记录不存在")
}
// 如果当前用户不是群聊创建人,不能通过
const channelId = applyInfo[TlUserApplyDef.targetId]
const channelInfo = await channelService.getInfoById({
companyId: loginUserCompanyId,
id: channelId
})
if(Object.keys(channelInfo).length == 0){
return tlResponseNotFound("频道不存在")
}
const channelUserInfo = await channelUserService.getInfoByChannelIdAndUserId({
companyId: loginUserCompanyId,
channelId,
userId: loginUserId
})
if(Object.keys(channelUserInfo).length == 0){
return tlResponseForbidden("非法操作")
}
const channelUserRole = channelUserInfo[TlChannelUserDef.roleId]
if(channelUserRole != TlRoleInner.channel.creator.id){
return tlResponseForbidden("非法操作")
}
const status = applyInfo[TlUserApplyDef.status]
if(status != TlUserApplyStatus.WAIT){
return tlResponseForbidden("申请记录状态不正确")
}
const type = applyInfo[TlUserApplyDef.type]
if(type != TlUserApplyType.GROUP){
return tlResponseForbidden("申请记录类型不正确")
}
// 更新申请记录状态
const updateInfo = await userApplyService.updateInfoById({
companyId: loginUserCompanyId,
id
}, {
[TlUserApplyDef.status]: TlUserApplyStatus.PASS
})
if(Object.keys(updateInfo).length == 0){
return tlResponseSvrError("更新申请记录状态失败")
}
const flag = applyInfo[TlUserApplyDef.flag]
// 生成频道用户
const result = await addChannelUser({
loginInfo, channelId,
userId: applyInfo[TlUserApplyDef.userId],
roleId: TlRoleInner.channel.member.id,
isShare: checkBit(flag, TlUserApplyFlag.IS_APPLY_GROUP_BY_SHARE_LINK)
})
if(!result.success){
return result
}
return tlResponseSuccess("通过申请成功", {
applyId : id,
applyUserId: applyInfo[TlUserApplyDef.userId]
})
}
/**
* 拒绝用户群聊申请
* @param {*} id
* @param {*} loginInfo
* @returns
*/
const rejectUserGroupApply = async function({ id, loginInfo }){
if(!id){
return tlResponseArgsError("请求参数错误")
}
id = parseInt(id)
if(!checkIsId(id)){
return tlResponseArgsError("请求参数不合法")
}
const {
loginUserCompanyId, loginUserId
} = loginInfo
const applyInfo = await userApplyService.getInfoById({
companyId: loginUserCompanyId,
id
})
if(Object.keys(applyInfo).length == 0){
return tlResponseNotFound("申请记录不存在")
}
// 如果当前用户不是群聊创建人,不能通过
const channelId = applyInfo[TlUserApplyDef.targetId]
const channelInfo = await channelService.getInfoById({
companyId: loginUserCompanyId,
id: channelId
})
if(Object.keys(channelInfo).length == 0){
return tlResponseNotFound("频道不存在")
}
const channelUserInfo = await channelUserService.getInfoByChannelIdAndUserId({
companyId: loginUserCompanyId,
channelId,
userId: loginUserId
})
if(Object.keys(channelUserInfo).length == 0){
return tlResponseForbidden("非法操作")
}
const channelUserRole = channelUserInfo[TlChannelUserDef.roleId]
if(channelUserRole != TlRoleInner.channel.creator.id){
return tlResponseForbidden("非法操作")
}
const status = applyInfo[TlUserApplyDef.status]
if(status != TlUserApplyStatus.WAIT){
return tlResponseForbidden("申请记录状态不正确")
}
const type = applyInfo[TlUserApplyDef.type]
if(type != TlUserApplyType.GROUP){
return tlResponseForbidden("申请记录类型不正确")
}
// 更新申请记录状态
const updateInfo = await userApplyService.updateInfoById({
companyId: loginUserCompanyId,
id
}, {
[TlUserApplyDef.status]: TlUserApplyStatus.REJECT
})
if(Object.keys(updateInfo).length == 0){
return tlResponseSvrError("更新申请记录状态失败")
}
return tlResponseSuccess("拒绝申请成功", {
applyId : id,
applyUserId: applyInfo[TlUserApplyDef.userId]
})
}
/**
* 获取我发出的群聊申请记录
* @param {*} loginInfo
*/
const getUserGroupApplyListFromSelf = async function({ loginInfo }){
const {
loginUserCompanyId, loginUserId, loginUserCompanyName
} = loginInfo
const applyList = await userApplyService.getListByUserIdAndType({
companyId: loginUserCompanyId,
userId: loginUserId,
type: TlUserApplyType.GROUP
}, [
TlUserApplyDef.id,
TlUserApplyDef.targetId,
TlUserApplyDef.origin,
TlUserApplyDef.status,
TlUserApplyDef.remark,
TlUserApplyDef.createdAt
])
// 频道信息
let channelIdList = new Set(
applyList.map(item => item[TlUserApplyDef.targetId])
)
let channelInfoList = await channelService.getListByIdList({
companyId: loginUserCompanyId,
idList: [...channelIdList]
}, [
TlChannelDef.id,
TlChannelDef.name,
])
let channelInfoMap = new Map()
channelInfoList.forEach(item => {
channelInfoMap.set(item[TlChannelDef.id], item)
})
// 已读记录
let readList = await userReadService.getListByUserIdTypeList({
companyId: loginUserCompanyId,
userId: loginUserId,
typeList: [
TlUserReadType.GROUP_APPLY,
TlUserReadType.GROUP_APPLY_PASS,
TlUserReadType.GROUP_APPLY_REJECT
]
}, [
TlUserReadDef.recordId
])
let userReadMap = new Map()
readList.forEach(item => {
userReadMap.set(item[TlUserReadDef.recordId], true)
})
let resultList = []
for(let i = 0; i < applyList.length; i++){
const item = applyList[i]
const status = item[TlUserApplyDef.status]
let statusStr = ''
if(status == TlUserApplyStatus.PASS){
statusStr = "已通过申请"
}else if(status == TlUserApplyStatus.REJECT){
statusStr = "已拒绝申请"
}
else if(status == TlUserApplyStatus.WAIT){
statusStr = "等待对方验证"
}
let channelInfo = channelInfoMap.get(item[TlUserApplyDef.targetId])
if(!channelInfo){
channelInfo = {}
}
resultList.push({
id : item[TlUserApplyDef.id],
channelId: channelInfo[TlChannelDef.id],
channelName: channelInfo[TlChannelDef.name],
channelAvatar: "/image/group-default-avatar.png",
channelApplyRemark: item[TlUserApplyDef.remark],
channelCompanyName: loginUserCompanyName,
origin : item[TlUserApplyDef.origin],
createTime: item[TlUserApplyDef.createdAt],
status : statusStr,
hasRead: userReadMap.has(item[TlUserApplyDef.id])
})
}
return tlResponseSuccess("获取成功", resultList)
}
/**
* 获取我收到的群聊申请记录
* @param {*} loginInfo
* @returns
*/
const getUserGroupListFromOther = async function({ loginInfo }){
const {
loginUserCompanyId, loginUserId, loginUserCompanyName
} = loginInfo
// 获取我所在的所有频道
const channelList = await channelUserService.getListByUserIdAndRoleId({
companyId: loginUserCompanyId,
userId: loginUserId,
roleId: TlRoleInner.channel.creator.id
}, [
TlChannelUserDef.channelId
])
if(channelList.length == 0){
return tlResponseSuccess("获取成功", [])
}
let channelIdList = channelList.map(item => item[TlChannelUserDef.channelId])
const applyList = await userApplyService.getListByTargetIdListAndType({
companyId: loginUserCompanyId,
targetIdList: channelIdList,
type: TlUserApplyType.GROUP
}, [
TlUserApplyDef.id,
TlUserApplyDef.userId,
TlUserApplyDef.targetId,
TlUserApplyDef.origin,
TlUserApplyDef.status,
TlUserApplyDef.remark,
TlUserApplyDef.createdAt
])
// 频道信息
let channelInfoList = await channelService.getListByIdList({
companyId: loginUserCompanyId,
idList: [...channelIdList]
}, [
TlChannelDef.id,
TlChannelDef.name,
])
let channelInfoMap = new Map()
channelInfoList.forEach(item => {
channelInfoMap.set(item[TlChannelDef.id], item)
})
// 用户信息
let userIdList = new Set(
applyList.map(item => item[TlUserApplyDef.userId])
)
let userInfoList = await userService.getListByIdList({
companyId: loginUserCompanyId,
idList: [...userIdList]
}, [
TlUserDef.id,
TlUserDef.name,
TlUserDef.avatarUrl
])
let userInfoMap = new Map()
userInfoList.forEach(item => {
userInfoMap.set(item[TlUserDef.id], item)
})
// 已读记录
let readList = await userReadService.getListByUserIdTypeList({
companyId: loginUserCompanyId,
userId: loginUserId,
typeList: [
TlUserReadType.GROUP_APPLY,
TlUserReadType.GROUP_APPLY_PASS,
TlUserReadType.GROUP_APPLY_REJECT
]
}, [
TlUserReadDef.recordId
])
let userReadMap = new Map()
readList.forEach(item => {
userReadMap.set(item[TlUserReadDef.recordId], true)
})
let resultList = []
for(let i = 0; i < applyList.length; i++){
const item = applyList[i]
const status = item[TlUserApplyDef.status]
let statusStr = ''
if(status == TlUserApplyStatus.PASS){
statusStr = "通过申请"
}else if(status == TlUserApplyStatus.REJECT){
statusStr = "拒绝申请"
}else if(status == TlUserApplyStatus.WAIT){
statusStr = "等待我验证"
}
let userInfo = userInfoMap.get(item[TlUserApplyDef.userId])
if(!userInfo){
userInfo = {}
}
let channelInfo = channelInfoMap.get(item[TlUserApplyDef.targetId])
if(!channelInfo){
channelInfo = {}
}
resultList.push({
id : item[TlUserApplyDef.id],
channelId: channelInfo[TlChannelDef.id],
channelName: channelInfo[TlChannelDef.name],
channelAvatar: "/image/group-default-avatar.png",
channelApplyRemark: item[TlUserApplyDef.remark],
channelCompanyName: loginUserCompanyName,
userId: userInfo[TlUserDef.id],
username: userInfo[TlUserDef.name],
userAvatar: await getAvatarOssUrl(userInfo[TlUserDef.avatarUrl]),
origin : item[TlUserApplyDef.origin],
createTime: item[TlUserApplyDef.createdAt],
status : statusStr,
hasRead: userReadMap.has(item[TlUserApplyDef.id])
})
}
return tlResponseSuccess("获取成功", resultList)
}
module.exports = {
applyAddFriend,
passUserFriendApply,
rejectUserFriendApply,
getUserFriendApplyListFromSelf,
getUserFriendListFromOther
getUserFriendListFromOther,
applyAddGroup,
passUserGroupApply,
rejectUserGroupApply,
getUserGroupApplyListFromSelf,
getUserGroupListFromOther
}

View File

@ -1,20 +1,33 @@
const crypto = require('crypto')
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess,
setBit, checkBit, checkIsEmail
tlResponseNotFound, tlResponseSuccess,
checkIsEmail, checkIsId, encryptStr,
tlConsole
} = require('../../utils/utils')
const userService = require('../../service/user/tl_user_service')
const userFriendService = require('../../service/user/tl_user_friend_service')
const userSessionService = require('../../service/user/tl_user_session_service')
const { getAvatarOssUrl } = require('../../utils/oss/oss')
const cloudFileService = require('../../service/cloud/tl_cloud_file_service')
const userConfigService = require('../../service/user/tl_user_config_service')
const companyService = require('../../service/company/tl_company_service')
const { getOssUrl, getAvatarOssUrl } = require('../../utils/oss/oss')
const { fields: userFields } = require('../../tables/tl_user')
const { fields: userFriendFields } = require('../../tables/tl_user_friend')
const { fields: cloudFileFields } = require('../../tables/tl_cloud_file')
const { fields: userConfigFields } = require('../../tables/tl_user_config')
const { inner: TlRoleInner } = require('../../tables/tl_role')
const { fields: companyFields } = require('../../tables/tl_company')
const TlUserDef = userFields.Def
const TlUserFriendDef = userFriendFields.Def
const TlUserFriendStatus = userFriendFields.Status
const TlUserFriendType = userFriendFields.FriendType
const TlCloudFileDef = cloudFileFields.Def
const TlUserConfingDef = userConfigFields.Def
const TlUserConfingAccount = userConfigFields.Account
const TlCompanyDef = companyFields.Def
@ -25,7 +38,11 @@ const TlUserFriendType = userFriendFields.FriendType
*/
const searchUserByName = async function({ name, loginInfo }){
if(!name){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
if(name.length > 20){
return tlResponseArgsError("请求参数过长")
}
const {
@ -70,8 +87,29 @@ const searchUserByName = async function({ name, loginInfo }){
let friendType = userFriendInfo[TlUserFriendDef.friendType]
if(friendType === TlUserFriendType.NORMAL){
friendTypeStr = '普通好友'
}else if(friendType === TlUserFriendType.SPECIAL){
friendTypeStr = '特别关注'
}
}
// 非好友, 检查是否允许被搜索
if(!isFriend){
// 获取用户配置
const userConfigInfo = await userConfigService.getInfoByUserId({
companyId: loginUserCompanyId,
userId: info[TlUserDef.id]
}, [
TlUserConfingDef.account
])
let accountSettingStr = userConfigInfo[TlUserConfingDef.account]
let accountSetting = {}
try{
accountSetting = JSON.parse(accountSettingStr)
}catch(e){
accountSetting = {}
}
// 不允许被搜索
let notAllowSearchAccount = accountSetting[TlUserConfingAccount.notAllowSearchAccount] || false
if(notAllowSearchAccount){
return tlResponseForbidden("私密用户")
}
}
@ -83,11 +121,12 @@ const searchUserByName = async function({ name, loginInfo }){
wechatName: info[TlUserDef.wchatName],
channelId: userFriendInfo[TlUserFriendDef.channelId],
isFriend: isFriend,
isSelf: info[TlUserDef.id] == loginUserId,
remark: userFriendInfo[TlUserFriendDef.remark],
friendType: friendTypeStr
}
return tlResponseSuccess("搜索用户成功", result)
return tlResponseSuccess("搜索成功", result)
}
/**
@ -97,7 +136,12 @@ const searchUserByName = async function({ name, loginInfo }){
*/
const searchUserById = async function({ id, loginInfo }){
if(!id){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
id = parseInt(id)
if(!id){
return tlResponseArgsError("请求参数错误")
}
const {
@ -135,6 +179,29 @@ const searchUserById = async function({ id, loginInfo }){
isFriend = true
}
// 非好友, 检查是否允许被搜索
if(!isFriend){
// 获取用户配置
const userConfigInfo = await userConfigService.getInfoByUserId({
companyId: loginUserCompanyId,
userId: info[TlUserDef.id]
}, [
TlUserConfingDef.account
])
let accountSettingStr = userConfigInfo[TlUserConfingDef.account]
let accountSetting = {}
try{
accountSetting = JSON.parse(accountSettingStr)
}catch(e){
accountSetting = {}
}
// 不允许被搜索
let notAllowSearchAccount = accountSetting[TlUserConfingAccount.notAllowSearchAccount] || false
if(notAllowSearchAccount){
return tlResponseForbidden("私密用户")
}
}
const result = {
userId: info[TlUserDef.id],
username: info[TlUserDef.name],
@ -145,7 +212,70 @@ const searchUserById = async function({ id, loginInfo }){
isFriend: isFriend
}
return tlResponseSuccess("搜索用户成功", result)
return tlResponseSuccess("搜索成功", result)
}
/**
* 更新用户头像
* @param {*} token
* @param {*} loginInfo
* @param {*} cloudFileId
* @returns
*/
const updateUserAvatar = async function({ token, loginInfo, cloudFileId }){
const {
loginUserCompanyId, loginUserId
} = loginInfo
if(!cloudFileId){
return tlResponseArgsError("请求参数错误")
}
cloudFileId = parseInt(cloudFileId)
if(!cloudFileId){
return tlResponseArgsError("请求参数错误")
}
const cloudFileInfo = await cloudFileService.getInfoById({
companyId: loginUserCompanyId,
id: cloudFileId
}, [
TlCloudFileDef.fileUrl,
TlCloudFileDef.userId
])
if(Object.keys(cloudFileInfo).length == 0){
return tlResponseNotFound("更新失败")
}
// 如果文件所属人不是自己, 非法操作
const cloudFileUserId = cloudFileInfo[TlCloudFileDef.userId]
if(cloudFileUserId != loginUserId){
return tlResponseForbidden("非法操作")
}
const result = await userService.updateInfoById({
companyId: loginUserCompanyId,
id: loginUserId,
}, {
[TlUserDef.avatarUrl]: cloudFileInfo[TlCloudFileDef.fileUrl]
})
if(Object.keys(result).length == 0){
return tlResponseSvrError("更新头像失败")
}
let fileUrl = cloudFileInfo[TlCloudFileDef.fileUrl]
fileUrl = await getOssUrl(fileUrl)
// 更新登录态信息
await userSessionService.setUserInfoByToken({
token, info: Object.assign(loginInfo, {
loginUserAvatar: fileUrl
})
})
return tlResponseSuccess("更新头像成功")
}
@ -176,6 +306,10 @@ const bindEmail = async function({ token, loginInfo, email, code }) {
return tlResponseArgsError("邮箱格式不正确")
}
if(email.length > 50){
return tlResponseArgsError("邮箱长度过长")
}
if(email == loginUserEmail){
return tlResponseForbidden("邮箱未更换")
}
@ -226,10 +360,504 @@ const bindEmail = async function({ token, loginInfo, email, code }) {
}
/**
* 更新用户信息 - 管理员
* @param {*} id
* @param {*} companyId
* @param {*} name
* @param {*} email
* @param {*} mobile
* @param {*} avatarUrl
* @param {*} roleId
* @param {*} loginInfo
* @returns
*/
const adminUpdateUser = async function({
id, companyId, name, email, mobile, avatarUrl,
loginInfo
}){
const {
loginUserCompanyId, loginUserId, loginUserRoleId
} = loginInfo
if(loginUserRoleId !== TlRoleInner.user.admin.id){
return tlResponseForbidden("非法用户")
}
if(!id || !name || !companyId){
return tlResponseArgsError("请求参数错误")
}
if(!checkIsId(id)){
return tlResponseArgsError("用户id非法")
}
if(!checkIsId(companyId)){
return tlResponseArgsError("企业id非法")
}
id = parseInt(id)
companyId = parseInt(companyId)
if(name.length > 20){
return tlResponseArgsError("用户名过长")
}
if(email.length > 64){
return tlResponseArgsError("邮箱过长")
}
if(mobile.length > 11){
return tlResponseArgsError("手机号过长")
}
const companyInfo = await companyService.getInfoById({
id: companyId
})
if(Object.keys(companyInfo).length == 0){
return tlResponseNotFound("企业不存在")
}
const info = await userService.getInfoById({
id: id,
companyId
}, [
TlUserDef.id
])
if(Object.keys(info).length == 0){
return tlResponseNotFound("用户不存在")
}
const result = await userService.updateInfoById({
id: id,
companyId
}, {
[TlUserDef.name]: name,
[TlUserDef.email]: email,
[TlUserDef.mobile]: mobile,
[TlUserDef.avatarUrl]: avatarUrl,
})
if(Object.keys(result).length == 0){
return tlResponseSvrError("更新失败")
}
return tlResponseSuccess("更新成功")
}
/**
* 删除用户 - 管理员
* @param {*} companyId
* @param {*} id
* @param {*} loginInfo
* @returns
*/
const adminDeleteUser = async function({ companyId, id, loginInfo }){
const {
loginUserCompanyId, loginUserId, loginUserRoleId
} = loginInfo
if(loginUserRoleId !== TlRoleInner.user.admin.id){
return tlResponseForbidden("非法用户")
}
if(!id){
return tlResponseArgsError("请求参数错误")
}
if(!companyId){
return tlResponseArgsError("请求参数错误")
}
if(!checkIsId(companyId)){
return tlResponseArgsError("企业id非法")
}
if(!checkIsId(id)){
return tlResponseArgsError("用户id非法")
}
companyId = parseInt(companyId)
id = parseInt(id)
const companyInfo = await companyService.getInfoById({
id: companyId
})
if(Object.keys(companyInfo).length == 0){
return tlResponseNotFound("企业不存在")
}
const info = await userService.getInfoById({
id,
companyId
}, [
TlUserDef.id,
TlUserDef.roleId
])
if(Object.keys(info).length == 0){
return tlResponseNotFound("用户不存在")
}
const roleId = info[TlUserDef.roleId]
if(roleId === TlRoleInner.user.admin.id){
return tlResponseForbidden("管理员帐号不允许删除")
}
const result = await userService.deleteInfoById({
id,
companyId
})
console.log("result : ", result)
if(result == 0){
return tlResponseSvrError("删除失败")
}
return tlResponseSuccess("删除成功")
}
/**
* 获取用户列表 - 管理员
* @param {*} keyword
* @param {*} companyId
* @param {*} page
* @param {*} limit
* @param {*} loginInfo
* @returns
**/
const adminGetUserList = async function({ keyword = '', companyId = undefined, page, limit, loginInfo }){
const {
loginUserCompanyId, loginUserId, loginUserRoleId
} = loginInfo
if(loginUserRoleId !== TlRoleInner.user.admin.id){
return tlResponseForbidden("非法用户")
}
if(!page || !limit){
return tlResponseArgsError("请求参数错误")
}
if(!checkIsId(page)){
return tlResponseArgsError("请求参数错误")
}
if(!checkIsId(limit)){
return tlResponseArgsError("请求参数错误")
}
page = parseInt(page)
limit = parseInt(limit)
if(keyword.length > 20){
return tlResponseArgsError("用户名过长")
}
let list = []
let total = 0
if(keyword === '' || keyword === undefined || keyword === null){
list = await userService.getListForPage({
companyId
}, [
TlUserDef.id,
TlUserDef.companyId,
TlUserDef.name,
TlUserDef.email,
TlUserDef.mobile,
TlUserDef.avatarUrl,
TlUserDef.roleId,
TlUserDef.createdAt
], page, limit)
total = await userService.getCount({
})
}else{
list = await userService.getListByKeywordForPage({
keyword, companyId
}, [
TlUserDef.id,
TlUserDef.companyId,
TlUserDef.name,
TlUserDef.email,
TlUserDef.mobile,
TlUserDef.avatarUrl,
TlUserDef.roleId,
TlUserDef.createdAt
], page, limit)
total = await userService.getCountByKeyword({
keyword
})
}
if(list.length == 0){
return tlResponseSuccess("获取成功", {
list: [],
count: 0
})
}
const companyIdList = list.map(item => item[TlUserDef.companyId])
let companyInfoMap = {}
if(companyIdList.length > 0){
const companyList = await companyService.getListByIdList({
idList: companyIdList
}, [
TlCompanyDef.id,
TlCompanyDef.name
])
companyInfoMap = companyList.reduce((acc, cur) => {
acc[cur[TlCompanyDef.id]] = cur
return acc
}, {})
}
let resultList = []
for(let i = 0; i < list.length; i++){
let item = list[i]
let roleId = item[TlUserDef.roleId]
let roleName = ''
if(roleId === TlRoleInner.user.admin.id){
roleName = TlRoleInner.user.admin.name
}else if(roleId === TlRoleInner.user.normal.id){
roleName = TlRoleInner.user.normal.name
}else{
roleName = "未知"
}
let companyId = item[TlUserDef.companyId]
const companyInfo = companyInfoMap[companyId] || {}
let companyName = companyInfo[TlCompanyDef.name] || ''
resultList.push({
companyId: companyId,
companyName: companyName,
id: item[TlUserDef.id],
name: item[TlUserDef.name],
email: item[TlUserDef.email],
mobile: item[TlUserDef.mobile],
avatarUrl: await getAvatarOssUrl(item[TlUserDef.avatarUrl]),
roleName,
roleId,
createTime: item[TlUserDef.createdAt],
})
}
return tlResponseSuccess("获取成功", {
list: resultList,
count: total
})
}
/**
* 获取用户信息 - 管理员
* @param {*} id
* @param {*} companyId
* @param {*} loginInfo
* @returns
*/
const adminGetUserInfo = async function({ id, companyId, loginInfo }){
const {
loginUserCompanyId, loginUserId, loginUserRoleId
} = loginInfo
if(loginUserRoleId !== TlRoleInner.user.admin.id){
return tlResponseForbidden("非法用户")
}
if(!id || !companyId){
return tlResponseArgsError("请求参数错误")
}
if(!checkIsId(id)){
return tlResponseArgsError("用户id非法")
}
if(!checkIsId(companyId)){
return tlResponseArgsError("企业id非法")
}
id = parseInt(id)
companyId = parseInt(companyId)
const companyInfo = await companyService.getInfoById({
id: companyId
}, [
TlCompanyDef.id,
TlCompanyDef.name
])
if(Object.keys(companyInfo).length == 0){
return tlResponseNotFound("企业不存在")
}
const info = await userService.getInfoById({
id,
companyId
}, [
TlUserDef.id,
TlUserDef.companyId,
TlUserDef.name,
TlUserDef.email,
TlUserDef.mobile,
TlUserDef.avatarUrl,
TlUserDef.roleId,
TlUserDef.createdAt
])
if(Object.keys(info).length == 0){
return tlResponseNotFound("用户不存在")
}
let roleId = info[TlUserDef.roleId]
let roleName = ''
if(roleId === TlRoleInner.user.admin.id){
roleName = TlRoleInner.user.admin.name
}else if(roleId === TlRoleInner.user.normal.id){
roleName = TlRoleInner.user.normal.name
}else {
roleName = "未知"
}
const result = {
companyId: info[TlUserDef.companyId],
companyName: companyInfo[TlCompanyDef.name],
id: info[TlUserDef.id],
name: info[TlUserDef.name],
email: info[TlUserDef.email],
mobile: info[TlUserDef.mobile],
avatarUrl: await getAvatarOssUrl(info[TlUserDef.avatarUrl]),
roleName,
roleId,
createTime: info[TlUserDef.createdAt],
}
return tlResponseSuccess("获取成功", result)
}
/**
* 添加用户 - 管理员
* @param {*} companyId
* @param {*} name
* @param {*} password
* @param {*} email
* @param {*} mobile
* @param {*} avatarUrl
* @param {*} roleId
* @param {*} loginInfo
* @returns
*/
const adminAddUser = async function({
companyId, name, password, email, mobile, avatarUrl, roleId,
loginInfo
}){
const {
loginUserCompanyId, loginUserId, loginUserRoleId
} = loginInfo
if(loginUserRoleId !== TlRoleInner.user.admin.id){
return tlResponseForbidden("非法用户")
}
if(!companyId || !name || !password || !roleId){
return tlResponseArgsError("请求参数错误")
}
if(!checkIsId(companyId)){
return tlResponseArgsError("企业id非法")
}
if(!checkIsId(roleId)){
return tlResponseArgsError("角色id非法")
}
companyId = parseInt(companyId)
roleId = parseInt(roleId)
if(name.length > 20){
return tlResponseArgsError("用户名过长")
}
if(password.length > 64){
return tlResponseArgsError("密码过长")
}
if(email && email.length > 64){
return tlResponseArgsError("邮箱过长")
}
if(mobile && mobile.length > 11){
return tlResponseArgsError("手机号过长")
}
if(avatarUrl && avatarUrl.length > 255){
return tlResponseArgsError("头像url过长")
}
const companyInfo = await companyService.getInfoById({
id: companyId
})
if(Object.keys(companyInfo).length == 0){
return tlResponseNotFound("企业不存在")
}
if([
TlRoleInner.user.normal.id,
].indexOf(roleId) === -1){
return tlResponseArgsError("角色id非法")
}
const salt = crypto.randomBytes(16).toString('hex')
const saltPassword = encryptStr({
str: password,
salt: salt
})
tlConsole(name, password, salt, saltPassword)
const result = await userService.addInfo({
companyId,
name,
password,
salt,
roleId,
email: email || '',
mobile: mobile || '',
avatarUrl: avatarUrl || '',
})
if(Object.keys(result).length == 0){
return tlResponseSvrError("添加失败")
}
return tlResponseSuccess("添加用成功")
}
module.exports = {
searchUserByName,
updateUserAvatar,
searchUserById,
bindEmail
bindEmail,
adminUpdateUser,
adminAddUser,
adminDeleteUser,
adminGetUserList,
adminGetUserInfo
}

View File

@ -0,0 +1,317 @@
const {
tlResponseArgsError, tlResponseSvrError,
tlResponseNotFound, tlResponseSuccess, checkIsId
} = require('../../utils/utils')
const userClearService = require('../../service/user/tl_user_clear_service')
const channelService = require('../../service/channel/tl_channel_service')
const channelChatService = require('../../service/channel/tl_channel_chat_service')
const channelFileService = require('../../service/channel/tl_channel_file_service')
const channelMediaService = require('../../service/channel/tl_channel_media_service')
const channelUserService = require('../../service/channel/tl_channel_user_service')
const { fields: userClearDef } = require('../../tables/tl_user_clear')
const { Def: TlUserClearDef, Type: TlUserClearType } = userClearDef
/**
* 更新频道清理记录
* @param {*} loginInfo
* @param {*} channelId
* @param {*} latestClearId
* @param {*} type
*/
const updateChannelUserClear = async function({
loginInfo, channelId, latestClearId, type
}){
if (latestClearId == null || latestClearId == undefined) {
return tlResponseArgsError("请求参数错误")
}
latestClearId = parseInt(latestClearId)
if(!checkIsId(latestClearId)){
return tlResponseArgsError("请求参数错误")
}
if (!channelId) {
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if(!checkIsId(channelId)){
return tlResponseArgsError("请求参数错误")
}
if(!type){
return tlResponseArgsError("请求参数错误")
}
const {
loginUserCompanyId, loginUserId, loginUsername
} = loginInfo
const userClearList = await userClearService.getListByChannelUserId({
companyId: loginUserCompanyId,
userId: loginUserId,
channelId
})
let chatClearRecord = null
let mediaClearRecord = null
let fileClearRecord = null
userClearList.forEach((userClear) => {
if (userClear[TlUserClearDef.type] === TlUserClearType.CHAT) {
chatClearRecord = userClear
}
if (userClear[TlUserClearDef.type] === TlUserClearType.MEDIA) {
mediaClearRecord = userClear
}
if (userClear[TlUserClearDef.type] === TlUserClearType.FILE) {
fileClearRecord = userClear
}
})
// 聊天消息清理记录不存在,新增, 否则更新清理消息最新ID
if(type === TlUserClearType.CHAT){
if(!chatClearRecord || Object.keys(chatClearRecord).length === 0){
chatClearRecord = await userClearService.addInfo({
companyId: loginUserCompanyId,
userId: loginUserId,
channelId,
latestClearId,
type: TlUserClearType.CHAT
})
if(Object.keys(chatClearRecord).length === 0){
return tlResponseSvrError("更新失败")
}
}else{
const clearId = chatClearRecord[TlUserClearDef.id]
if(!clearId){
return tlResponseSvrError("更新失败")
}
// 更新聊天消息清理记录
const updateInfo = await userClearService.updateInfoById({
companyId: loginUserCompanyId,
id: clearId
}, {
[TlUserClearDef.latestClearId]: latestClearId
})
if(Object.keys(updateInfo).length === 0){
return tlResponseSvrError("更新失败")
}
}
}
// 媒体消息清理记录不存在,新增, 否则更新清理消息最新ID
if(type === TlUserClearType.MEDIA){
if(!mediaClearRecord || Object.keys(mediaClearRecord).length === 0){
mediaClearRecord = await userClearService.addInfo({
companyId: loginUserCompanyId,
userId: loginUserId,
channelId,
latestClearId,
type: TlUserClearType.MEDIA
})
if(Object.keys(mediaClearRecord).length === 0){
return tlResponseSvrError("更新失败")
}
}else{
const clearId = mediaClearRecord[TlUserClearDef.id]
if(!clearId){
return tlResponseSvrError("更新失败")
}
// 更新媒体消息清理记录
const updateInfo = await userClearService.updateInfoById({
companyId: loginUserCompanyId,
id: clearId
}, {
[TlUserClearDef.latestClearId]: latestClearId
})
if(Object.keys(updateInfo).length === 0){
return tlResponseSvrError("更新失败")
}
}
}
// 文件消息清理记录不存在,新增, 否则更新清理消息最新ID
if(type === TlUserClearType.FILE){
if(!fileClearRecord || Object.keys(fileClearRecord).length === 0){
fileClearRecord = await userClearService.addInfo({
companyId: loginUserCompanyId,
userId: loginUserId,
channelId,
latestClearId,
type: TlUserClearType.FILE
})
if(Object.keys(fileClearRecord).length === 0){
return tlResponseSvrError("更新失败")
}
}else{
const clearId = fileClearRecord[TlUserClearDef.id]
if(!clearId){
return tlResponseSvrError("更新失败")
}
// 更新文件消息清理记录
const updateInfo = await userClearService.updateInfoById({
companyId: loginUserCompanyId,
id: clearId
}, {
[TlUserClearDef.latestClearId]: latestClearId
})
if(Object.keys(updateInfo).length === 0){
return tlResponseSvrError("更新失败")
}
}
}
return tlResponseSuccess("更新成功")
}
/**
* 更新频道多类型清理记录 (文件/媒体/聊天)
* @param {*} loginInfo
* @param {*} channelId
* @returns
*/
const updateChannelMuiltClear = async function({
loginInfo, channelId
}){
const {
loginUserCompanyId, loginUserId
} = loginInfo
if(!channelId){
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if(!checkIsId(channelId)){
return tlResponseArgsError("请求参数错误")
}
// 频道是否存在
const channel = await channelService.getInfoById({
companyId: loginUserCompanyId,
id: channelId
})
if(Object.keys(channel).length === 0){
return tlResponseNotFound("频道不存在")
}
// 当前用户是否存在频道
const channelUserInfo = await channelUserService.getInfoByChannelIdAndUserId({
companyId: loginUserCompanyId,
channelId: channelId,
userId: loginUserId
})
if(Object.keys(channelUserInfo).length == 0){
return tlResponseNotFound("非法操作")
}
// 找到最新的频道聊天id
const latestChatClearId = await channelChatService.getChannelChatLatestId({
companyId: loginUserCompanyId,
channelId
})
// 找到最新的频道媒体id
const latestMediaClearId = await channelMediaService.getChannelMediaLatestId({
companyId: loginUserCompanyId,
channelId
})
// 找到最新的频道文件id
const latestFileClearId = await channelFileService.getChannelFileLatestId({
companyId: loginUserCompanyId,
channelId
})
const chatResult = await updateChannelUserClear({
loginInfo, channelId, latestClearId: latestChatClearId, type: TlUserClearType.CHAT
});
if (!chatResult.success) {
return chatResult
}
const mediaResult = await updateChannelUserClear({
loginInfo, channelId, latestClearId: latestMediaClearId, type: TlUserClearType.MEDIA
});
if (!mediaResult.success) {
return mediaResult
}
const fileResult = await updateChannelUserClear({
loginInfo, channelId, latestClearId: latestFileClearId, type: TlUserClearType.FILE
});
if (!fileResult.success) {
return fileResult
}
return tlResponseSuccess("清理成功")
}
/**
* 更新频道聊天清理记录
* @param {*} loginInfo
* @param {*} channelId
* @returns
*/
const updateChannelChatClear = async function({
loginInfo, channelId
}){
return await updateChannelUserClear({
loginInfo, channelId, type: TlUserClearType.CHAT
})
}
/**
* 更新频道媒体清理记录
* @param {*} loginInfo
* @param {*} channelId
* @returns
*/
const updateChannelMediaClear = async function({
loginInfo, channelId
}){
return await updateChannelUserClear({
loginInfo, channelId, type: TlUserClearType.MEDIA
})
}
/**
* 更新频道文件清理记录
* @param {*} loginInfo
* @param {*} channelId
* @returns
*/
const updateChannelFileClear = async function({
loginInfo, channelId
}){
return await updateChannelUserClear({
loginInfo, channelId, type: TlUserClearType.FILE
})
}
module.exports = {
updateChannelChatClear,
updateChannelMediaClear,
updateChannelFileClear,
updateChannelMuiltClear,
}

View File

@ -1,10 +1,7 @@
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess,
setBit, checkBit
tlResponseSvrError, tlResponseNotFound, tlResponseSuccess,
} = require('../../utils/utils')
const userConfigService = require('../../service/user/tl_user_config_service')
const userSessionService = require('../../service/user/tl_user_session_service')
const { fields: userConfigFields } = require('../../tables/tl_user_config')
@ -13,6 +10,7 @@ const TlUserConfigAccountDef = userConfigFields.Account
const TlUserConfigSkinDef = userConfigFields.Skin
const TlUserConfigAuthorityDef = userConfigFields.Authority
const TlUserConfigMessageDef = userConfigFields.Message
const TlUserConfigNormalDef = userConfigFields.Normal
const TlUserConfigOtherDef = userConfigFields.Other
@ -68,7 +66,7 @@ const getUserConfigSetting = async function({ loginInfo }){
normal: JSON.parse(userConfigNormal)
}
return tlResponseSuccess("获取设置成功", result)
return tlResponseSuccess("获取成功", result)
}
@ -116,10 +114,10 @@ const updateUserConfigNormal = async function({ loginInfo, normal }){
})
if(Object.keys(result).length == 0){
return tlResponseSvrError("更新设置失败")
return tlResponseSvrError("更新失败")
}
return tlResponseSuccess("更新设置成功")
return tlResponseSuccess("更新成功")
}
@ -167,10 +165,10 @@ const updateUserConfigAccount = async function({ loginInfo, account }){
})
if(Object.keys(result).length == 0){
return tlResponseSvrError("更新设置失败")
return tlResponseSvrError("更新失败")
}
return tlResponseSuccess("更新设置成功")
return tlResponseSuccess("更新成功")
}
@ -218,10 +216,10 @@ const updateUserConfigMessage = async function({ loginInfo, message }){
})
if(Object.keys(result).length == 0){
return tlResponseSvrError("更新设置失败")
return tlResponseSvrError("更新失败")
}
return tlResponseSuccess("更新设置成功")
return tlResponseSuccess("更新成功")
}
/**
@ -268,10 +266,10 @@ const updateUserConfigAuthority = async function({ loginInfo, authority }){
})
if(Object.keys(result).length == 0){
return tlResponseSvrError("更新设置失败")
return tlResponseSvrError("更新失败")
}
return tlResponseSuccess("更新设置成功")
return tlResponseSuccess("更新成功")
}
/**
@ -318,10 +316,10 @@ const updateUserConfigSkin = async function({ loginInfo, skin }){
})
if(Object.keys(result).length == 0){
return tlResponseSvrError("更新设置失败")
return tlResponseSvrError("更新失败")
}
return tlResponseSuccess("更新设置成功")
return tlResponseSuccess("更新成功")
}
@ -369,10 +367,10 @@ const updateUserConfigOther = async function({ loginInfo, other }){
})
if(Object.keys(result).length == 0){
return tlResponseSvrError("更新设置失败")
return tlResponseSvrError("更新失败")
}
return tlResponseSuccess("更新设置成功")
return tlResponseSuccess("更新成功")
}

View File

@ -1,8 +1,6 @@
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess,
setBit, checkBit,
tlConsole
tlResponseNotFound, tlResponseSuccess, checkIsId
} = require('../../utils/utils')
const userFriendService = require('../../service/user/tl_user_friend_service')
const userService = require('../../service/user/tl_user_service')
@ -10,7 +8,7 @@ const userSessionService = require('../../service/user/tl_user_session_service')
const channelService = require('../../service/channel/tl_channel_service')
const channelUserService = require('../../service/channel/tl_channel_user_service')
const channelChatService = require('../../service/channel/tl_channel_chat_service')
const { getOssUrl } = require('../../utils/oss/oss')
const { getAvatarOssUrl } = require('../../utils/oss/oss')
const { fields: userFriendFields } = require('../../tables/tl_user_friend')
const { fields: userFields } = require('../../tables/tl_user')
@ -19,11 +17,14 @@ const { fields: channelUserFields } = require('../../tables/tl_channel_user')
const { inner: TlRoleInner } = require('../../tables/tl_role')
const { fields: channelChatFields } = require('../../tables/tl_channel_chat')
const { Def: TlUserFriendDef, Status: TlUserFriendStatus, FriendType: TlUserFriendType, Origin: TlUserFriendOrigin } = userFriendFields
const {
Def: TlUserFriendDef, Status: TlUserFriendStatus,
FriendType: TlUserFriendType,
} = userFriendFields
const { Def: TlUserDef } = userFields
const { Def: TlChannelDef, Type: TlChannelType } = channelFields
const { Def: TlChannelChatDef, Other: TlChannelChatOther } = channelChatFields
const { Other: TlChannelChatOther } = channelChatFields
const { Def: TlchannelUserDef, Type: TlChannelUserType } = channelUserFields
@ -46,6 +47,7 @@ const getFriendList = async function({ loginInfo }){
TlUserFriendDef.id,
TlUserFriendDef.friendId,
TlUserFriendDef.origin,
TlUserFriendDef.flag,
TlUserFriendDef.createdAt,
TlUserFriendDef.friendType,
TlUserFriendDef.remark,
@ -80,11 +82,6 @@ const getFriendList = async function({ loginInfo }){
let resultList = []
for(let i = 0; i < userFriendList.length; i++){
const item = userFriendList[i]
let originStr = ''
const origin = item[TlUserFriendDef.origin]
if(origin == TlUserFriendOrigin.SEARCH_NAME){
originStr = "搜索用户名添加"
}
const friendId = item[TlUserFriendDef.friendId]
let friendInfo = userInfoMap.get(friendId)
@ -98,13 +95,11 @@ const getFriendList = async function({ loginInfo }){
let friendType = item[TlUserFriendDef.friendType]
if(friendType == TlUserFriendType.NORMAL){
friendTypeStr = '普通好友'
}else if(friendType == TlUserFriendType.SPECIAL){
friendTypeStr = '特别关注'
}
resultList.push({
id : item[TlUserFriendDef.id],
origin : originStr,
origin : item[TlUserFriendDef.origin],
friendType: friendTypeStr,
remark: item[TlUserFriendDef.remark],
createTime: item[TlUserFriendDef.createdAt],
@ -115,11 +110,11 @@ const getFriendList = async function({ loginInfo }){
username: friendInfo[TlUserDef.name],
userEmail: friendInfo[TlUserDef.email],
userMobile: friendInfo[TlUserDef.mobile],
userAvatar: await getOssUrl(friendInfo[TlUserDef.avatarUrl]),
userAvatar: await getAvatarOssUrl(friendInfo[TlUserDef.avatarUrl]),
})
}
return tlResponseSuccess("获取好友列表成功", resultList)
return tlResponseSuccess("获取成功", resultList)
}
@ -130,7 +125,12 @@ const getFriendList = async function({ loginInfo }){
*/
const deleteFriend = async function({ loginInfo, channelId }){
if(!channelId){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if(!checkIsId(channelId)){
return tlResponseArgsError("请求参数错误")
}
const {
@ -148,7 +148,7 @@ const deleteFriend = async function({ loginInfo, channelId }){
])
if(Object.keys(channelUserInfo).length == 0){
return tlResponseNotFound("删除好友成功")
return tlResponseNotFound("非法操作")
}
const channelType = channelUserInfo[TlchannelUserDef.type]
@ -157,11 +157,15 @@ const deleteFriend = async function({ loginInfo, channelId }){
}
// 删除自己在频道的数据
await channelUserService.deleteInfoById({
const deleteRes = await channelUserService.deleteInfoById({
companyId: loginUserCompanyId,
id: channelUserInfo[TlchannelUserDef.id]
})
if(deleteRes === 0){
return tlResponseSvrError("删除失败")
}
// 获取好友关系
const userFriendInfo = await userFriendService.getInfoByChannelIdAndUserId({
companyId: loginUserCompanyId,
@ -172,21 +176,25 @@ const deleteFriend = async function({ loginInfo, channelId }){
])
if(Object.keys(userFriendInfo).length == 0){
return tlResponseNotFound("删除好友成功")
return tlResponseNotFound("删除成功")
}
const userFriendId = userFriendInfo[TlUserFriendDef.id]
if(!userFriendId){
return tlResponseNotFound("删除好友成功")
return tlResponseNotFound("删除成功")
}
// 删除好友关系
await userFriendService.deleteInfoById({
const deleteFriendRes = await userFriendService.deleteInfoById({
companyId: loginUserCompanyId,
id: userFriendId
})
return tlResponseSuccess("删除好友成功")
if(deleteFriendRes === 0){
return tlResponseSvrError("删除失败")
}
return tlResponseSuccess("删除成功")
}
@ -198,11 +206,20 @@ const deleteFriend = async function({ loginInfo, channelId }){
*/
const updateRemark = async function({ loginInfo, channelId, remark }){
if(!channelId){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if(!checkIsId(channelId)){
return tlResponseArgsError("请求参数错误")
}
if(!remark){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
if(remark.length > 20){
return tlResponseArgsError("备注长度不能超过20")
}
const {
@ -223,6 +240,12 @@ const updateRemark = async function({ loginInfo, channelId, remark }){
return tlResponseNotFound("好友不存在")
}
// 当前用户是否存在频道
const channelUserInfo = userFriendList.find(item => item[TlUserFriendDef.userId] == loginUserId)
if(!channelUserInfo){
return tlResponseNotFound("非法操作")
}
const userFriendId = friendInfo[TlUserFriendDef.id]
const info = await userFriendService.updateInfoById({
@ -233,10 +256,10 @@ const updateRemark = async function({ loginInfo, channelId, remark }){
})
if(Object.keys(info).length == 0){
return tlResponseSvrError("修改好友备注失败")
return tlResponseSvrError("更新失败")
}
return tlResponseSuccess("修改好友备注成功")
return tlResponseSuccess("更新成功")
}
/**
@ -247,11 +270,20 @@ const updateRemark = async function({ loginInfo, channelId, remark }){
*/
const updateRename = async function({ loginInfo, channelId, rename }){
if(!channelId){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if(!checkIsId(channelId)){
return tlResponseArgsError("请求参数错误")
}
if(!rename){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
if(rename.length > 20){
return tlResponseArgsError("备注长度不能超过20")
}
const {
@ -272,6 +304,12 @@ const updateRename = async function({ loginInfo, channelId, rename }){
return tlResponseNotFound("好友不存在")
}
// 当前用户是否存在频道
const channelUserInfo = userFriendList.find(item => item[TlUserFriendDef.userId] == loginUserId)
if(!channelUserInfo){
return tlResponseNotFound("非法操作")
}
const userFriendId = friendInfo[TlUserFriendDef.id]
const info = await userFriendService.updateInfoById({
companyId: loginUserCompanyId,
@ -281,10 +319,10 @@ const updateRename = async function({ loginInfo, channelId, rename }){
})
if(Object.keys(info).length == 0){
return tlResponseSvrError("修改好友备注失败")
return tlResponseSvrError("更新失败")
}
return tlResponseSuccess("修改好友备注成功")
return tlResponseSuccess("更新成功")
}
@ -302,6 +340,11 @@ const initChannelForPassFriend = async function({
return tlResponseArgsError("初始化好友频道失败,请求参数为空")
}
applyUserId = parseInt(applyUserId)
if(!checkIsId(applyUserId)){
return tlResponseArgsError("初始化好友频道失败,请求参数错误")
}
// 获取这两个人的用户频道信息
const channelUserList = await channelUserService.getListByTypeUserIdList({
companyId: loginUserCompanyId,
@ -330,7 +373,7 @@ const initChannelForPassFriend = async function({
const existChannelId = loginUserIdChannelIdList.find(item => applyUserIdChannelIdList.includes(item))
// 如果已经存在频道用户数据,直接返回
if(existChannelId){
return tlResponseSuccess("初始化好友频道成功1", { channelId: existChannelId })
return tlResponseSuccess("初始化好友频道成功", { channelId: existChannelId })
}
// 创建新频道
@ -405,7 +448,7 @@ const initChannelForPassFriend = async function({
}
})
return tlResponseSuccess("初始化好友频道成功2", { channelId })
return tlResponseSuccess("初始化好友频道成功", { channelId })
}
@ -418,9 +461,11 @@ const initChannelForPassFriend = async function({
* @param {*} origin
* @param {*} remark
* @param {*} channelId
* @param {*} flag
*/
const initUserFriendForPassFriend = async function({
loginUserCompanyId, loginUserId, loginUsername, applyUserId, applyUserName, origin, remark, channelId
loginUserCompanyId, loginUserId, loginUsername,
applyUserId, applyUserName, origin, remark, channelId, flag
}){
if(!applyUserId){
return tlResponseForbidden("生成好友记录失败,参数错误")
@ -457,6 +502,7 @@ const initUserFriendForPassFriend = async function({
userId: loginUserId,
friendId: applyUserId,
origin: origin,
flag: flag,
remark: remark,
friendType: TlUserFriendType.NORMAL,
status: TlUserFriendStatus.NORMAL,
@ -473,6 +519,7 @@ const initUserFriendForPassFriend = async function({
userId: applyUserId,
friendId: loginUserId,
origin: origin,
flag: flag,
remark: remark,
friendType: TlUserFriendType.NORMAL,
status: TlUserFriendStatus.NORMAL,
@ -487,66 +534,6 @@ const initUserFriendForPassFriend = async function({
return tlResponseSuccess("生成好友记录成功")
}
/**
* 更新好友类型
* @param {*} loginInfo
* @param {*} channelId
* @param {*} special
*/
const updateFriendSpecical = async function({ loginInfo, channelId, special }){
if(!channelId){
return tlResponseArgsError("请求参数为空")
}
if(special === undefined || special === null){
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId
} = loginInfo
// 获取频道用户列表
const userFriendList = await userFriendService.getListByChannelId({
companyId: loginUserCompanyId,
channelId,
}, [
TlUserFriendDef.id,
TlUserFriendDef.userId,
])
const friendInfo = userFriendList.find(item => item[TlUserFriendDef.userId] == loginUserId)
if(!friendInfo){
return tlResponseNotFound("好友不存在")
}
const newFriendType = special ? TlUserFriendType.SPECIAL : TlUserFriendType.NORMAL
const userFriendId = friendInfo[TlUserFriendDef.id]
const info = await userFriendService.updateInfoById({
companyId: loginUserCompanyId,
id: userFriendId,
}, {
[TlUserFriendDef.friendType]: special ? TlUserFriendType.SPECIAL : TlUserFriendType.NORMAL
})
if(Object.keys(info).length == 0){
return tlResponseSvrError("关注失败")
}
let friendTypeStr = ''
if(newFriendType == TlUserFriendType.NORMAL){
friendTypeStr = '普通好友'
}else if(newFriendType == TlUserFriendType.SPECIAL){
friendTypeStr = '特别关注'
}
return tlResponseSuccess(special ? '关注成功' : '取消关注成功', {
friendType: friendTypeStr
})
}
module.exports = {
getFriendList,
@ -555,5 +542,4 @@ module.exports = {
updateRename,
initChannelForPassFriend,
initUserFriendForPassFriend,
updateFriendSpecical
}

View File

@ -1,7 +1,9 @@
const crypto = require('crypto')
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess,
tlConsole, verifyEncryptStr
tlResponseSuccess,
tlConsole, verifyEncryptStr, getFormattedDate, encryptStr,
setBit
} = require('../../utils/utils')
const {
getAvatarOssUrl
@ -15,12 +17,12 @@ const userFingerPrintService = require('../../service/user/tl_user_finger_print_
const { fields: companyFields } = require('../../tables/tl_company')
const { Def: TlCompanyDef } = companyFields
const { fields: userFields } = require('../../tables/tl_user')
const { Def: TlUserDef } = userFields
const { Def: TlUserDef, Flag: TlUserFlag } = userFields
const { fields: userFingerPrintFields } = require('../../tables/tl_user_finger_print')
const { Def: TlUserFingerPrintDef } = userFingerPrintFields
const { fields: channelUserFields } = require('../../tables/tl_channel_user')
const { Def: TlChannelUserDef, Type: TlChannelUserType } = channelUserFields
const { inner: TlInnerRole } = require('../../tables/tl_role')
const { inner: TlRoleInner } = require('../../tables/tl_role')
/**
@ -28,8 +30,9 @@ const { inner: TlInnerRole } = require('../../tables/tl_role')
* @param {*} account
* @param {*} password
* @param {*} fps
* @param {*} inviteCode
*/
const userLoginByAccount = async function({account, password, fps}){
const userLoginByAccount = async function({account, password, fps, inviteCode}){
if(!account){
return tlResponseArgsError("用户名或密码错误")
}
@ -38,11 +41,42 @@ const userLoginByAccount = async function({account, password, fps}){
return tlResponseArgsError("用户名或密码错误")
}
if(!inviteCode){
return tlResponseArgsError("邀请码错误")
}
// base64解码
account = Buffer.from(account, 'base64').toString()
password = Buffer.from(password, 'base64').toString()
const user = await userService.getInfoByNameForLogin({
if(account.length > 20){
return tlResponseArgsError("用户名或密码错误")
}
if(password.length > 64){
return tlResponseArgsError("用户名或密码错误")
}
const company = await companyService.getInfoByCode({
code: inviteCode
}, [
TlCompanyDef.id,
TlCompanyDef.name
])
if(Object.keys(company).length === 0){
return tlResponseArgsError("邀请码无效")
}
const companyId = company[TlCompanyDef.id]
const companyName = company[TlCompanyDef.name]
if(!companyId){
return tlResponseForbidden("非法用户")
}
const user = await userService.getInfoByName({
companyId: companyId,
name: account
}, [
TlUserDef.id,
@ -68,20 +102,6 @@ const userLoginByAccount = async function({account, password, fps}){
return tlResponseArgsError("用户名或密码错误")
}
const company = await companyService.getInfoById({
id: user[TlUserDef.companyId]
}, [
TlCompanyDef.id,
TlCompanyDef.name,
])
const companyId = company[TlCompanyDef.id]
const companyName = company[TlCompanyDef.name]
if(!companyId){
return tlResponseForbidden("非法用户")
}
const token = userSessionService.generateLoginToken();
const info = {
loginUserId: user[TlUserDef.id],
@ -107,98 +127,58 @@ const userLoginByAccount = async function({account, password, fps}){
return tlResponseSuccess("登录成功", token)
}
/**
* 通过手机号登录接口
* @param {*} mobile
* @param {*} code
* @param {*} fps
*/
const userLoginByMobile = async function({mobile, code, fps}){
if(!mobile){
return tlResponseArgsError("手机号或验证码错误")
}
if(!code){
return tlResponseArgsError("手机号或验证码错误")
}
// base64解码
mobile = Buffer.from(mobile, 'base64').toString()
password = Buffer.from(password, 'base64').toString()
const user = await userService.getInfoByMobileForLogin({
mobile
}, [
TlUserDef.id,
TlUserDef.companyId,
TlUserDef.mobile,
TlUserDef.avatarUrl,
TlUserDef.roleId,
TlUserDef.email,
TlUserDef.name
])
if(!user[TlUserDef.id]){
return tlResponseArgsError("手机号或验证码错误")
}
const company = await companyService.getInfoById({
id: user[TlUserDef.companyId]
}, [
TlCompanyDef.id,
TlCompanyDef.name
])
const companyId = company[TlCompanyDef.id]
const companyName = company[TlCompanyDef.name]
if(!companyId){
return tlResponseForbidden("非法用户")
}
const token = userSessionService.generateLoginToken();
const info = {
loginUserId: user[TlUserDef.id],
loginUserMobile: user[TlUserDef.mobile],
loginUsername: user[TlUserDef.name],
loginUserEmail: user[TlUserDef.email],
loginUserRoleId: user[TlUserDef.roleId],
loginUserCompanyName : companyName,
loginUserCompanyId: companyId,
loginUserAvatar: await getAvatarOssUrl(user[TlUserDef.avatarUrl]),
loginTime: new Date().getTime(),
token
}
// 设置登录信息
await userSessionService.setUserInfoByToken({token, info})
// 设置指纹
await setFps({ userId: user[TlUserDef.id], fps })
// 设置用户频道角色
await setUserChannelRole({ userId: user[TlUserDef.id], companyId })
return tlResponseSuccess("登录成功", token)
}
/**
* 通过邮箱登录接口
* @param {*} email
* @param {*} password
* @param {*} fps
* @param {*} inviteCode
*/
const userLoginByEmail = async function({email, password, fps}){
const userLoginByEmail = async function({email, password, fps, inviteCode}){
if(!email){
return tlResponseArgsError("邮箱或密码错误")
}
if(!password){
return tlResponseArgsError("邮箱或密码错误")
}
if(!inviteCode){
return tlResponseArgsError("邀请码错误")
}
// base64解码
email = Buffer.from(email, 'base64').toString()
password = Buffer.from(password, 'base64').toString()
const user = await userService.getInfoByEmailForLogin({
if(email.length > 50){
return tlResponseArgsError("邮箱或密码错误")
}
if(password.length > 64){
return tlResponseArgsError("邮箱或密码错误")
}
const company = await companyService.getInfoByCode({
code: inviteCode
}, [
TlCompanyDef.id,
TlCompanyDef.name
])
if(Object.keys(company).length === 0){
return tlResponseArgsError("邀请码无效")
}
const companyId = company[TlCompanyDef.id]
const companyName = company[TlCompanyDef.name]
if(!companyId){
return tlResponseForbidden("非法用户")
}
const user = await userService.getInfoByEmail({
companyId: companyId,
email
}, [
TlUserDef.id,
@ -216,20 +196,6 @@ const userLoginByEmail = async function({email, password, fps}){
return tlResponseArgsError("邮箱或密码错误")
}
const company = await companyService.getInfoById({
id: user[TlUserDef.companyId]
}, [
TlCompanyDef.id,
TlCompanyDef.name
])
const companyId = company[TlCompanyDef.id]
const companyName = company[TlCompanyDef.name]
if(!companyId){
return tlResponseForbidden("非法用户")
}
if(!verifyEncryptStr({
inputStr: password,
hashedStr: user[TlUserDef.password],
@ -263,61 +229,26 @@ const userLoginByEmail = async function({email, password, fps}){
return tlResponseSuccess("登录成功", token)
}
/**
* 通过微信登录接口
* @param {*} code
* @param {*} openId
*/
const userLoginByWechat = async function({openId, code}){
return tlResponseSuccess("登录成功")
}
/**
* 通过qq登录接口
* @param {*} code
* @param {*} openId
*/
const userLoginByQQ = async function({openId, code}){
return tlResponseSuccess("登录成功")
}
/**
* 通过企业微信登录接口
* @param {*} code
* @param {*} openId
*/
const userLoginByQyWechat = async function({openId, code}){
return tlResponseSuccess("登录成功")
}
/**
* 游客登录接口
* @param {*} code
*/
const userLoginByGuest = async function({code}){
return tlResponseSuccess("登录成功")
}
/**
* 通过指纹登录接口 - 一键登录
* @param {*} fps
* @param {*} username
* @param {*} inviteCode
*/
const userLoginByFingerPrint = async function({fps, username}){
if(!fps){
return tlResponseArgsError("一键登录失败, 请使用其他登录方式登录")
}
if(!username){
return tlResponseArgsError("一键登录失败, 请使用其他登录方式登录")
}
if(username.length > 20){
return tlResponseArgsError("一键登录失败, 请使用其他登录方式登录")
}
const user = await userService.getInfoByNameForLogin({
name: username
}, [
@ -466,14 +397,15 @@ const setUserChannelRole = async function({userId, companyId}){
/**
* 官网登录 - 支持邮箱登录
* 管理后台登录 - 支持邮箱登录
* @param {*} email
* @param {*} password
*/
const userLoginByWebsite = async function({ email, password }){
const userLoginBySystem = async function({ email, password }){
if(!email){
return tlResponseArgsError("邮箱或密码错误")
}
if(!password){
return tlResponseArgsError("邮箱或密码错误")
}
@ -482,6 +414,14 @@ const userLoginByWebsite = async function({ email, password }){
email = Buffer.from(email, 'base64').toString()
password = Buffer.from(password, 'base64').toString()
if(email.length > 50){
return tlResponseArgsError("邮箱或密码错误")
}
if(password.length > 64){
return tlResponseArgsError("邮箱或密码错误")
}
const user = await userService.getInfoByEmailForLogin({
email
}, [
@ -493,7 +433,7 @@ const userLoginByWebsite = async function({ email, password }){
TlUserDef.roleId,
TlUserDef.mobile,
TlUserDef.salt,
TlUserDef.name
TlUserDef.name,
])
if(!user[TlUserDef.id]){
@ -523,11 +463,11 @@ const userLoginByWebsite = async function({ email, password }){
}
const roleId = user[TlUserDef.roleId]
if([
TlInnerRole.website.user.id,
TlInnerRole.user.admin.id
TlRoleInner.user.admin.id
].indexOf(roleId) === -1){
return tlResponseArgsError("非官网用户")
return tlResponseArgsError("非法用户")
}
const token = userSessionService.generateLoginToken();
@ -544,19 +484,15 @@ const userLoginByWebsite = async function({ email, password }){
token
}
// 设置登录信息
await userSessionService.setUserInfoByToken({token, info, isWebsite: true})
await userSessionService.setUserInfoByToken({token, info, isSystem: true})
return tlResponseSuccess("登录成功", token)
}
module.exports = {
userLoginByAccount,
userLoginByMobile,
userLoginByEmail,
userLoginByWechat,
userLoginByQQ,
userLoginByQyWechat,
userLoginByGuest,
userLoginByFingerPrint,
userLoginByWebsite
userLoginBySystem
}

View File

@ -2,7 +2,6 @@ const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess
} = require('../../utils/utils')
const userService = require('../../service/user/tl_user_service')
const userSessionService = require('../../service/user/tl_user_session_service')

View File

@ -1,11 +1,12 @@
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess
tlResponseArgsError, tlResponseSvrError,
tlResponseNotFound, tlResponseSuccess, checkIsId
} = require('../../utils/utils')
const userReadService = require('../../service/user/tl_user_read_service')
const userSessionService = require('../../service/user/tl_user_session_service')
const channelUserService = require('../../service/channel/tl_channel_user_service')
const { fields: userReadDef } = require('../../tables/tl_user_read')
const { fields: channelDef } = require('../../tables/tl_channel')
const { Def: TlUserReadDef, Type: TlUserReadType } = userReadDef
@ -21,21 +22,42 @@ const updateChannelUserRead = async function({
loginInfo, channelId, latestReadId, type
}){
if (!latestReadId) {
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
latestReadId = parseInt(latestReadId)
if(!checkIsId(latestReadId)){
return tlResponseArgsError("请求参数错误")
}
if (!channelId) {
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
channelId = parseInt(channelId)
if(!checkIsId(channelId)){
return tlResponseArgsError("请求参数错误")
}
if(!type){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
const {
loginUserCompanyId, loginUserId, loginUsername
} = loginInfo
// 当前用户是否存在频道
const channelUserInfo = await channelUserService.getInfoByChannelIdAndUserId({
companyId: loginUserCompanyId,
channelId: channelId,
userId: loginUserId
})
if(Object.keys(channelUserInfo).length == 0){
return tlResponseNotFound("非法操作")
}
const userReadList = await userReadService.getListByChannelUserId({
companyId: loginUserCompanyId,
userId: loginUserId,
@ -60,7 +82,7 @@ const updateChannelUserRead = async function({
// 聊天消息已读记录不存在,新增, 否则更新已读消息最新ID
if(type === TlUserReadType.CHAT){
if(!chatReadRecord){
if(!chatReadRecord || Object.keys(chatReadRecord).length === 0){
chatReadRecord = await userReadService.addInfo({
companyId: loginUserCompanyId,
userId: loginUserId,
@ -72,29 +94,29 @@ const updateChannelUserRead = async function({
if(Object.keys(chatReadRecord).length === 0){
return tlResponseSvrError("更新失败")
}
}
const readId = chatReadRecord[TlUserReadDef.id]
if(!readId){
return tlResponseSvrError("更新失败")
}
// 更新聊天消息已读记录
const updateInfo = await userReadService.updateInfoById({
companyId: loginUserCompanyId,
id: readId
}, {
[TlUserReadDef.latestReadId]: latestReadId
})
if(Object.keys(updateInfo).length === 0){
return tlResponseSvrError("更新失败")
}else{
const readId = chatReadRecord[TlUserReadDef.id]
if(!readId){
return tlResponseSvrError("更新失败")
}
// 更新聊天消息已读记录
const updateInfo = await userReadService.updateInfoById({
companyId: loginUserCompanyId,
id: readId
}, {
[TlUserReadDef.latestReadId]: latestReadId
})
if(Object.keys(updateInfo).length === 0){
return tlResponseSvrError("更新失败")
}
}
}
// 媒体消息已读记录不存在,新增, 否则更新已读消息最新ID
if(type === TlUserReadType.MEDIA){
if(!mediaReadRecord){
if(!mediaReadRecord || Object.keys(mediaReadRecord).length === 0){
mediaReadRecord = await userReadService.addInfo({
companyId: loginUserCompanyId,
userId: loginUserId,
@ -106,29 +128,29 @@ const updateChannelUserRead = async function({
if(Object.keys(mediaReadRecord).length === 0){
return tlResponseSvrError("更新失败")
}
}
}else{
const readId = mediaReadRecord[TlUserReadDef.id]
if(!readId){
return tlResponseSvrError("更新失败")
}
const readId = mediaReadRecord[TlUserReadDef.id]
if(!readId){
return tlResponseSvrError("更新失败")
}
// 更新媒体消息已读记录
const updateInfo = await userReadService.updateInfoById({
companyId: loginUserCompanyId,
id: readId
}, {
[TlUserReadDef.latestReadId]: latestReadId
})
// 更新媒体消息已读记录
const updateInfo = await userReadService.updateInfoById({
companyId: loginUserCompanyId,
id: readId
}, {
[TlUserReadDef.latestReadId]: latestReadId
})
if(Object.keys(updateInfo).length === 0){
return tlResponseSvrError("更新失败")
if(Object.keys(updateInfo).length === 0){
return tlResponseSvrError("更新失败")
}
}
}
// 文件消息已读记录不存在,新增, 否则更新已读消息最新ID
if(type === TlUserReadType.FILE){
if(!fileReadRecord){
if(!fileReadRecord || Object.keys(fileReadRecord).length === 0){
fileReadRecord = await userReadService.addInfo({
companyId: loginUserCompanyId,
userId: loginUserId,
@ -140,23 +162,23 @@ const updateChannelUserRead = async function({
if(Object.keys(fileReadRecord).length === 0){
return tlResponseSvrError("更新失败")
}
}
}else{
const readId = fileReadRecord[TlUserReadDef.id]
if(!readId){
return tlResponseSvrError("更新失败")
}
const readId = fileReadRecord[TlUserReadDef.id]
if(!readId){
return tlResponseSvrError("更新失败")
}
// 更新文件消息已读记录
const updateInfo = await userReadService.updateInfoById({
companyId: loginUserCompanyId,
id: readId
}, {
[TlUserReadDef.latestReadId]: latestReadId
})
// 更新文件消息已读记录
const updateInfo = await userReadService.updateInfoById({
companyId: loginUserCompanyId,
id: readId
}, {
[TlUserReadDef.latestReadId]: latestReadId
})
if(Object.keys(updateInfo).length === 0){
return tlResponseSvrError("更新失败")
if(Object.keys(updateInfo).length === 0){
return tlResponseSvrError("更新失败")
}
}
}
@ -174,8 +196,13 @@ const updateChannelUserRead = async function({
*/
const updateChannelMuiltRead = async function({
loginInfo, channelId, latestChatReadId, latestMediaReadId, latestFileReadId
}){
}){
if(latestChatReadId){
latestChatReadId = parseInt(latestChatReadId)
if(!checkIsId(latestChatReadId)){
return tlResponseArgsError("请求参数错误")
}
const chatResult = await updateChannelChatRead({
loginInfo, channelId, latestReadId: latestChatReadId
});
@ -186,6 +213,11 @@ const updateChannelMuiltRead = async function({
}
if(latestMediaReadId){
latestMediaReadId = parseInt(latestMediaReadId)
if(!checkIsId(latestMediaReadId)){
return tlResponseArgsError("请求参数错误")
}
const mediaResult = await updateChannelMediaRead({
loginInfo, channelId, latestReadId: latestMediaReadId
});
@ -196,6 +228,11 @@ const updateChannelMuiltRead = async function({
}
if(latestFileReadId){
latestFileReadId = parseInt(latestFileReadId)
if(!checkIsId(latestFileReadId)){
return tlResponseArgsError("请求参数错误")
}
const fileResult = await updateChannelFileRead({
loginInfo, channelId, latestReadId: latestFileReadId
});
@ -264,7 +301,12 @@ const addUserFriendApplyRead = async function({
loginInfo, recordId
}){
if (!recordId) {
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
recordId = parseInt(recordId)
if(!checkIsId(recordId)){
return tlResponseArgsError("请求参数错误")
}
const {
@ -296,7 +338,12 @@ const addUserFriendApplyPassRead = async function({
loginInfo, recordId
}){
if (!recordId) {
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
recordId = parseInt(recordId)
if(!checkIsId(recordId)){
return tlResponseArgsError("请求参数错误")
}
const {
@ -328,7 +375,12 @@ const addUserFriendApplyRejectRead = async function({
loginInfo, recordId
}){
if (!recordId) {
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
recordId = parseInt(recordId)
if(!checkIsId(recordId)){
return tlResponseArgsError("请求参数错误")
}
const {
@ -349,6 +401,118 @@ const addUserFriendApplyRejectRead = async function({
return tlResponseSuccess("更新成功")
}
/**
* 新增群申请消息已读记录
* @param {*} loginInfo
* @param {*} recordId
* @param {*} type
* @returns
*/
const addUserGroupApplyRead = async function({
loginInfo, recordId
}){
if (!recordId) {
return tlResponseArgsError("请求参数错误")
}
recordId = parseInt(recordId)
if(!checkIsId(recordId)){
return tlResponseArgsError("请求参数错误")
}
const {
loginUserCompanyId, loginUserId, loginUsername
} = loginInfo
const addInfo = await userReadService.addInfo({
companyId: loginUserCompanyId,
userId: loginUserId,
recordId,
type: TlUserReadType.GROUP_APPLY
})
if(Object.keys(addInfo).length === 0){
return tlResponseSvrError("更新失败")
}
return tlResponseSuccess("更新成功")
}
/**
* 新增群同意消息已读记录
* @param {*} loginInfo
* @param {*} recordId
* @param {*} type
* @returns
*/
const addUserGroupApplyPassRead = async function({
loginInfo, recordId
}){
if (!recordId) {
return tlResponseArgsError("请求参数错误")
}
recordId = parseInt(recordId)
if(!checkIsId(recordId)){
return tlResponseArgsError("请求参数错误")
}
const {
loginUserCompanyId, loginUserId, loginUsername
} = loginInfo
const addInfo = await userReadService.addInfo({
companyId: loginUserCompanyId,
userId: loginUserId,
recordId,
type: TlUserReadType.GROUP_APPLY_PASS
})
if(Object.keys(addInfo).length === 0){
return tlResponseSvrError("更新失败")
}
return tlResponseSuccess("更新成功")
}
/**
* 新增群拒绝消息已读记录
* @param {*} loginInfo
* @param {*} recordId
* @param {*} type
* @returns
*/
const addUserGroupApplyRejectRead = async function({
loginInfo, recordId
}){
if (!recordId) {
return tlResponseArgsError("请求参数错误")
}
recordId = parseInt(recordId)
if(!checkIsId(recordId)){
return tlResponseArgsError("请求参数错误")
}
const {
loginUserCompanyId, loginUserId, loginUsername
} = loginInfo
const addInfo = await userReadService.addInfo({
companyId: loginUserCompanyId,
userId: loginUserId,
recordId,
type: TlUserReadType.GROUP_APPLY_REJECT
})
if(Object.keys(addInfo).length === 0){
return tlResponseSvrError("更新失败")
}
return tlResponseSuccess("更新成功")
}
module.exports = {
updateChannelChatRead,
updateChannelMediaRead,
@ -357,5 +521,9 @@ module.exports = {
addUserFriendApplyRead,
addUserFriendApplyPassRead,
addUserFriendApplyRejectRead
addUserFriendApplyRejectRead,
addUserGroupApplyRead,
addUserGroupApplyPassRead,
addUserGroupApplyRejectRead,
}

View File

@ -1,14 +1,14 @@
const crypto = require('crypto')
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess,
tlResponseSuccess,
tlConsole,
checkIsEmail, checkIsMobile,
tlConsoleError,
encryptStr
} = require('../../utils/utils');
const {
sendVerificationCodeEmail
sendVerificationCodeEmail, sendResetPasswordEmail
} = require('../../utils/mail/mail');
const companyService = require('../../service/company/tl_company_service')
@ -21,7 +21,7 @@ const { inner: TlRoleInner } = require('../../tables/tl_role')
const { fields: userFields } = require('../../tables/tl_user')
const { fields: userAuthFields } = require('../../tables/tl_user_auth');
const { Def: TlUserDef } = userFields
const { Def: TlUserAuthDef, Type: TlUserAuthType } = userAuthFields
const { Type: TlUserAuthType } = userAuthFields
const { Def: TlCompanyFields } = companyFields
@ -31,7 +31,9 @@ const { Def: TlCompanyFields } = companyFields
* @param {*} password
* @param {*} invite_code
*/
const userRegisterByAccount = async function({account, password, invite_code}){
const userRegisterByAccount = async function({
account, password, invite_code
}){
if(!account){
return tlResponseArgsError("帐号不能为空")
}
@ -48,6 +50,14 @@ const userRegisterByAccount = async function({account, password, invite_code}){
return tlResponseArgsError("邀请码不能为空")
}
if(account.length > 20){
return tlResponseArgsError("帐号长度不能超过20")
}
if(password.length > 64){
return tlResponseArgsError("密码长度不能超过64")
}
const company = await companyService.getInfoByCode({
code: invite_code
}, [
@ -95,72 +105,6 @@ const userRegisterByAccount = async function({account, password, invite_code}){
return tlResponseSuccess("注册成功")
}
/**
* 通过手机号注册接口
* @param {*} mobile
* @param {*} code
* @param {*} invite_code
*/
const userRegisterByMobile = async function({mobile, code, invite_code}){
if(!mobile){
return tlResponseArgsError("手机号不能为空")
}
if(!code){
return tlResponseArgsError("验证码不能为空")
}
if(!invite_code){
return tlResponseArgsError("邀请码不能为空")
}
if(!checkIsMobile(mobile)){
return tlResponseArgsError("手机号格式不正确")
}
const company = await companyService.getInfoByCode({
code: invite_code
}, [
TlCompanyFields.id
])
if(Object.keys(company).length === 0){
return tlResponseArgsError("邀请码无效")
}
// 检查code
const checkCode = await userSessionService.getMobileCode({
mobile
})
if (checkCode !== code) {
return tlResponseArgsError("手机验证码错误")
}
const companyId = company.id
const user = await userService.getInfoByMobile({
companyId: companyId,
mobile
}, [
TlUserDef.id
])
if(user[TlUserDef.id]){
return tlResponseArgsError("手机号已存在")
}
const salt = crypto.randomBytes(16).toString('hex')
const result = await userService.addInfo({
companyId : companyId,
name : '手机用户-' + Math.floor(Math.random() * 1000000),
mobile,
roleId : TlRoleInner.user.normal.id,
salt,
})
if (Object.keys(result).length === 0) {
return tlResponseSvrError("注册失败")
}
return tlResponseSuccess("注册成功")
}
/**
* 通过邮箱注册接口
@ -169,19 +113,25 @@ const userRegisterByMobile = async function({mobile, code, invite_code}){
* @param {*} invite_code
* @param {*} password
*/
const userRegisterByEmail = async function({email, code, invite_code, password}){
const userRegisterByEmail = async function({
email, code, invite_code, password
}){
if(!email){
return tlResponseArgsError("邮箱不能为空")
}
if(!code){
return tlResponseArgsError("验证码不能为空")
}
if(!invite_code){
return tlResponseArgsError("邀请码不能为空")
}
if (!password) {
return tlResponseArgsError("密码不能为空")
}
// base64解码
email = Buffer.from(email, 'base64').toString()
password = Buffer.from(password, 'base64').toString()
@ -244,45 +194,6 @@ const userRegisterByEmail = async function({email, code, invite_code, password})
return tlResponseSuccess("注册成功")
}
/**
* 通过微信注册接口
* @param {*} code
* @param {*} openId
*/
const userRegisterByWechat = async function({openId, code}){
const params = {
code, openId
}
return tlResponseSuccess("注册成功", params)
}
/**
* 通过qq注册接口
* @param {*} code
* @param {*} openId
*/
const userRegisterByQQ = async function({openId, code}){
const params = {
code, openId
}
return tlResponseSuccess("注册成功", params)
}
/**
* 通过企业微信注册接口
* @param {*} code
* @param {*} openId
*/
const userRegisterByWechatWork = async function({openId, code}){
const params = {
code, openId
}
return tlResponseSuccess("注册成功", params)
}
/**
* 获取邮箱验证码
* @param {*} email
@ -339,42 +250,51 @@ const getEmailCode = async function({email}){
})
if (Object.keys(result).length === 0) {
tlConsoleError("验证码发送添加记录失败")
tlConsoleError("发送异常")
}
return tlResponseSuccess("验证码发送成功", {
code
return tlResponseSuccess("发送成功", {
// code
})
}
/**
* 注册官网用户
* @param {*} email
* @param {*} code
* @param {*} password
* @returns
* 通过邮箱重置密码接口
* @param {*} email
* @param {*} code
* @param {*} invite_code
*/
const registerWebsiteUser = async function({ email, code, password }){
// 默认挂在首个企业下
const companyId = 1
const resetPasswordByEmail = async function({
email, code, invite_code
}){
if(!email){
return tlResponseArgsError("邮箱不能为空")
}
if(!code){
return tlResponseArgsError("验证码不能为空")
}
if(!password) {
return tlResponseArgsError("密码不能为空")
if(!invite_code){
return tlResponseArgsError("邀请码不能为空")
}
// base64解码
email = Buffer.from(email, 'base64').toString()
password = Buffer.from(password, 'base64').toString()
// base64解码
email = Buffer.from(email, 'base64').toString()
if(!checkIsEmail(email)){
return tlResponseArgsError("邮箱格式不正确")
}
const company = await companyService.getInfoByCode({
code: invite_code
}, [
TlCompanyFields.id
])
if(Object.keys(company).length === 0){
return tlResponseArgsError("邀请码无效")
}
// 检查code
const checkCode = await userSessionService.getEmailCode({
email
@ -383,6 +303,18 @@ const registerWebsiteUser = async function({ email, code, password }){
return tlResponseArgsError("邮箱验证码错误")
}
// 检查次数, 一天之内重置一次
const count = await userAuthService.getDayCountByTypeAndKey({
type: TlUserAuthType.EMAIL_RESET_PASSWORD,
key: email
})
if(count >= 1){
return tlResponseForbidden("当天获重置次数已达上限")
}
const companyId = company[TlCompanyFields.id]
const user = await userService.getInfoByEmail({
companyId: companyId,
email
@ -390,41 +322,61 @@ const registerWebsiteUser = async function({ email, code, password }){
TlUserDef.id
])
if(user.id){
return tlResponseArgsError("邮箱已注册")
if(Object.keys(user).length === 0){
return tlResponseArgsError("邮箱不存在")
}
const userId = user[TlUserDef.id]
const newPassword = Math.floor(Math.random() * 100000000) + ""
const salt = crypto.randomBytes(16).toString('hex')
const saltPassword = encryptStr({
str: password,
str: newPassword,
salt: salt
})
const result = await userService.addInfo({
const updateRes = await userService.updateInfoById({
companyId : companyId,
name : "官网用户-" + String(Math.floor(Math.random() * 1000000)),
email,
password: saltPassword,
roleId : TlRoleInner.website.user.id,
salt,
avatarUrl: "/image/default-avatar.png"
id: userId
}, {
[TlUserDef.password]: saltPassword,
[TlUserDef.salt]: salt
})
if (Object.keys(updateRes).length === 0) {
return tlResponseSvrError("重置密码失败")
}
// 发送重置密码邮件
await sendResetPasswordEmail({
to: email,
password: newPassword,
companyName: "tl-open-source开源团队",
companyUrl: "https://tl-open-source.github.com/"
}).then((res) => {
tlConsole("重置密码邮件发送成功", res)
})
// 添加重置记录
const result = await userAuthService.addInfo({
key: email,
type: TlUserAuthType.EMAIL_RESET_PASSWORD,
code: String(newPassword)
})
if (Object.keys(result).length === 0) {
return tlResponseSvrError("注册失败")
tlConsoleError("重置密码添加记录失败")
}
return tlResponseSuccess("注册成功")
return tlResponseSuccess("重置成功")
}
module.exports = {
userRegisterByAccount,
userRegisterByMobile,
userRegisterByEmail,
userRegisterByWechat,
userRegisterByQQ,
userRegisterByWechatWork,
getEmailCode,
registerWebsiteUser
resetPasswordByEmail
}

View File

@ -1,6 +1,6 @@
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess
tlResponseArgsError, tlResponseSvrError,
tlResponseSuccess, checkIsId
} = require('../../utils/utils')
const userTagService = require('../../service/user/tl_user_tag_service')
const { fields: userTagDef } = require('../../tables/tl_user_tag')
@ -19,11 +19,15 @@ const addUserTag = async function({
loginInfo, name, type
}){
if(!name) {
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
if(name.length > 255){
return tlResponseArgsError("请求参数过长")
}
if(!type){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
const {
@ -53,7 +57,7 @@ const getUserTagList = async function({
loginInfo, type
}){
if(!type){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
const {
@ -87,7 +91,12 @@ const delUserTag = async function({
loginInfo, id
}){
if(!id){
return tlResponseArgsError("请求参数为空")
return tlResponseArgsError("请求参数错误")
}
id = parseInt(id)
if(!checkIsId(id)){
return tlResponseArgsError("请求参数错误")
}
const {
@ -135,20 +144,6 @@ const addFriendTag = async function({
})
}
/**
* 添加资源库标签
* @param {*} loginInfo
* @param {*} name
* @returns
*/
const addCloudTag = async function({
loginInfo, name
}){
return await addUserTag({
loginInfo, name, type: TlUserTagType.CLOUD
})
}
/**
* 获取频道标签列表
* @param {*} loginInfo
@ -175,18 +170,6 @@ const getFriendTagList = async function({
})
}
/**
* 获取资源库标签列表
* @param {*} loginInfo
* @returns
*/
const getCloudTagList = async function({
loginInfo
}){
return await getUserTagList({
loginInfo, type: TlUserTagType.CLOUD
})
}
module.exports = {
@ -195,8 +178,6 @@ module.exports = {
delUserTag,
addChannelTag,
addFriendTag,
addCloudTag,
getChannelTagList,
getFriendTagList,
getCloudTagList
}

View File

@ -1 +0,0 @@
module.exports = {}

View File

@ -1 +0,0 @@
module.exports = {}

View File

@ -1,10 +1,13 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, tlResponseArgsError,
checkRequestParams
tlResponseSvrError, tlConsoleError, tlResponseArgsError,
checkRequestParams,
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const channelChatBiz = require('../../../biz/channel/channel_chat_biz');
const {
contentFilter, objectContentFilter
} = require('../../../utils/sensitive/content')
/**
@ -27,8 +30,10 @@ router.post('/add-friend-channel-chat', async function(request, response) {
const loginInfo = request.ctx || {}
const result = await channelChatBiz.addFriendChannelChat({
loginInfo, message, toUserId, toUserName, channelId, atUserId, atUserName
loginInfo, message: contentFilter(message),
toUserId, toUserName, channelId, atUserId, atUserName
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -56,8 +61,9 @@ router.post('/add-group-channel-chat', async function(request, response) {
const loginInfo = request.ctx || {}
const result = await channelChatBiz.addGroupChannelChat({
loginInfo, message, channelId, atUserId, atUserName, isAtAll
loginInfo, message: contentFilter(message), channelId, atUserId, atUserName, isAtAll
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -85,8 +91,9 @@ router.post('/add-reply-friend-channel-chat', async function(request, response)
const loginInfo = request.ctx || {}
const result = await channelChatBiz.addReplyFriendChannelChat({
loginInfo, message, channelId, messageId, messageType, atUserId, atUserName
loginInfo, message: contentFilter(message), channelId, messageId, messageType, atUserId, atUserName
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -114,8 +121,9 @@ router.post('/add-reply-group-channel-chat', async function(request, response) {
const loginInfo = request.ctx || {}
const result = await channelChatBiz.addReplyGroupChannelChat({
loginInfo, message, channelId, messageId, messageType, atUserId, atUserName, atAll
loginInfo, message: contentFilter(message), channelId, messageId, messageType, atUserId, atUserName, atAll
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -123,34 +131,5 @@ router.post('/add-reply-group-channel-chat', async function(request, response) {
}
});
/**
* #controller post /api/web/channel-chat/rollback-channel-chat
* #desc 撤回消息
* @param {*} request
* @param {*} response
*/
router.post('/rollback-channel-chat', async function(request, response) {
try {
const { channelId, messageId, messageType } = request.body;
if (!checkRequestParams({
channelId, messageId, messageType
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelChatBiz.rollbackChannelChat({
loginInfo, channelId, messageId, messageType
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
});
module.exports = router;

View File

@ -1,9 +1,12 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, checkRequestParams, tlResponseArgsError
tlResponseSvrError, tlConsoleError, checkRequestParams, tlResponseArgsError,
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const channelBiz = require('../../../biz/channel/channel_biz');
const {
contentFilter, objectContentFilter
} = require('../../../utils/sensitive/content')
/**
@ -14,10 +17,10 @@ const channelBiz = require('../../../biz/channel/channel_biz');
*/
router.post('/search-channel-by-id', async function(request, response) {
try{
const { channelId } = request.body;
const { channelId, shareUserId } = request.body;
if (!checkRequestParams({
channelId,
channelId, shareUserId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
@ -25,7 +28,7 @@ router.post('/search-channel-by-id', async function(request, response) {
const loginInfo = request.ctx || {}
const result = await channelBiz.searchChannelById({
channelId, loginInfo
channelId, loginInfo, shareUserId
});
response.json(result);
@ -54,7 +57,7 @@ router.post('/add-channel', async function(request, response) {
const loginInfo = request.ctx || {}
const result = await channelBiz.addChannel({
channelName, loginInfo
channelName: contentFilter(channelName), loginInfo
});
response.json(result);
@ -75,7 +78,7 @@ router.get('/get-channel-list', async function(request, response) {
try {
const loginInfo = request.ctx || {}
const result = await channelBiz.getChannelList({ loginInfo });
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -103,7 +106,7 @@ router.get('/get-channel-info', async function(request, response) {
const loginInfo = request.ctx || {}
const result = await channelBiz.getChannelInfo({ loginInfo, channelId });
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -113,14 +116,14 @@ router.get('/get-channel-info', async function(request, response) {
/**
* #controller get /api/web/channel/get-channel-name
* #controller post /api/web/channel/get-channel-name
* #desc 获取频道名称
* @param {*} request
* @param {*} response
*/
router.get('/get-channel-name', async function(request, response) {
router.post('/get-channel-name', async function(request, response) {
try {
const { channelId } = request.query;
const { channelId } = request.body;
if (!checkRequestParams({
channelId,
@ -159,7 +162,36 @@ router.post('/update-channel-name', async function(request, response) {
const loginInfo = request.ctx || {}
const result = await channelBiz.updateChannelName({
channelId, channelName, loginInfo
channelId, channelName: contentFilter(channelName), loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/channel/update-channel-can-search
* #desc 修改频道是否可以被搜索
* @param {*} request
* @param {*} response
*/
router.post('/update-channel-can-search', async function(request, response) {
try {
const { channelId, canSearch } = request.body;
if (!checkRequestParams({
channelId, canSearch
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelBiz.updateChannelCanSearch({
channelId, canSearch, loginInfo
});
response.json(result);
@ -169,26 +201,6 @@ router.post('/update-channel-name', async function(request, response) {
}
});
/**
* #controller get /api/web/channel/get-group-channel-list
* #desc 获取群组频道列表
* @param {*} request
* @param {*} response
*/
router.get('/get-group-channel-list', async function(request, response) {
try {
const loginInfo = request.ctx || {}
const result = await channelBiz.getChannelGroupList({ loginInfo });
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/channel/get-channel-message
* #desc 获取频道聊天记录
@ -249,6 +261,57 @@ router.post('/get-channel-message-list', async function(request, response) {
}
});
/**
* #controller post /api/web/channel/search-channel-message
* #desc 搜索频道聊天记录
* @param {*} request
* @param {*} response
*/
router.post('/search-channel-message', async function(request, response) {
try {
const {
channelId, keyword, startTime, endTime,
types, chatMinId, fileMinId, mediaMinId
} = request.body;
if (!checkRequestParams({
channelId, keyword, startTime, endTime,
types, chatMinId, fileMinId, mediaMinId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelBiz.searchChannelChatList({
loginInfo, channelId, startTimeStamp: startTime, endTimeStamp: endTime, types, keyword,
chatMinId, fileMinId, mediaMinId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
})
/**
* #controller get /api/web/channel/get-group-channel-list
* #desc 获取群组频道列表
* @param {*} request
* @param {*} response
*/
router.get('/get-group-channel-list', async function(request, response) {
try {
const loginInfo = request.ctx || {}
const result = await channelBiz.getChannelGroupList({ loginInfo });
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
module.exports = router;

View File

@ -0,0 +1,70 @@
const {
tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams,
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const channelFileBiz = require('../../../biz/channel/channel_file_biz');
/**
* #controller post /api/web/channel-file/add-friend-channel-offline-file
* #desc 发送好友频道离线文件消息
* @param {*} request
* @param {*} response
*/
router.post('/add-friend-channel-offline-file', async function(request, response) {
try {
const { channelId, cloudFileId } = request.body;
if (!checkRequestParams({
channelId, cloudFileId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelFileBiz.addFriendChannelOfflineFile({
loginInfo, cloudFileId, channelId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
});
/**
* #controller post /api/web/channel-file/add-group-channel-offline-file
* #desc 发送群聊频道离线文件消息
* @param {*} request
* @param {*} response
*/
router.post('/add-group-channel-offline-file', async function(request, response) {
try {
const { channelId, cloudFileId } = request.body;
if (!checkRequestParams({
channelId, cloudFileId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelFileBiz.addGroupChannelOfflineFile({
loginInfo, cloudFileId, channelId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
});
module.exports = router;

View File

@ -0,0 +1,126 @@
const {
tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams,
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const channelMediaBiz = require('../../../biz/channel/channel_media_biz');
/**
* #controller post /api/web/channel-media/add-friend-channel-audio
* #desc 发送好友频道语音聊天消息
* @param {*} request
* @param {*} response
*/
router.post('/add-friend-channel-audio', async function(request, response) {
try {
const { channelId } = request.body;
if (!checkRequestParams({
channelId,
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelMediaBiz.addFriendChannelAudio({
loginInfo, media : {}, channelId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
});
/**
* #controller post /api/web/channel-media/add-friend-channel-video
* #desc 发送好友频道视频消息
* @param {*} request
* @param {*} response
*/
router.post('/add-friend-channel-video', async function(request, response) {
try {
const { channelId } = request.body;
if (!checkRequestParams({
channelId,
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelMediaBiz.addFriendChannelVideo({
loginInfo, media: {}, channelId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
});
/**
* #controller post /api/web/channel-media/add-group-channel-audio
* #desc 发送多人频道语音聊天消息
* @param {*} request
* @param {*} response
*/
router.post('/add-group-channel-audio', async function(request, response) {
try {
const { channelId } = request.body;
if (!checkRequestParams({
channelId,
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelMediaBiz.addGroupChannelAudio({
loginInfo, media: {}, channelId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
});
/**
* #controller post /api/web/channel-media/add-group-channel-video
* #desc 发送多人频道视频消息
* @param {*} request
* @param {*} response
*/
router.post('/add-group-channel-video', async function(request, response) {
try {
const { channelId } = request.body;
if (!checkRequestParams({
channelId,
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelMediaBiz.addGroupChannelVideo({
loginInfo, media: {}, channelId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
});
module.exports = router;

View File

@ -0,0 +1,68 @@
const {
tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams,
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const channelNoticeBiz = require('../../../biz/channel/channel_notice_biz');
/**
* #controller post /api/web/channel-notice/add-channel-notice
* #desc 发布频道公告
* @param {*} request
* @param {*} response
*/
router.post('/add-channel-notice', async function(request, response) {
try {
const { channelId, content } = request.body;
if (!checkRequestParams({
channelId, content
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelNoticeBiz.addNotice({
loginInfo, channelId, content
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
});
/**
* #controller get /api/web/channel-notice/get-channel-notice-list
* #desc 获取频道公告
* @param {*} request
* @param {*} response
*/
router.get('/get-channel-notice-list', async function(request, response) {
try {
const { channelId } = request.query;
if (!checkRequestParams({
channelId,
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelNoticeBiz.getNoticeList({
loginInfo, channelId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
})
module.exports = router;

View File

@ -1,5 +1,5 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams
tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams,
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
@ -34,32 +34,6 @@ router.post('/add-channel-user', async function(request, response){
});
/**
* #controller post /api/web/channel-user/share-join-channel
* #desc 分享加入群聊
* @param {*} request
* @param {*} response
*/
router.post('/share-join-channel', async function(request, response){
try {
const { channelId } = request.body;
if (!checkRequestParams({
channelId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelUserBiz.shareJoinGroupChannel({ loginInfo, channelId });
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/channel-user/add-channel-user-normal
* #desc 添加频道普通身份用户
@ -78,6 +52,7 @@ router.post('/add-channel-user-normal', async function(request, response){
const loginInfo = request.ctx || {}
const result = await channelUserBiz.addChannelUserNormal({ loginInfo, channelId, userId });
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -104,32 +79,7 @@ router.post('/add-channel-user-list-normal', async function(request, response){
const loginInfo = request.ctx || {}
const result = await channelUserBiz.addChannelUserListNormal({ loginInfo, channelId, userIdList });
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/channel-user/add-channel-user-admin
* #desc 添加频道管理员身份用户
* @param {*} request
* @param {*} response
*/
router.post('/add-channel-user-admin', async function(request, response){
try {
const { channelId, userId } = request.body;
if (!checkRequestParams({
channelId, userId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelUserBiz.addChannelUserAdmin({ loginInfo, channelId, userId });
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -156,6 +106,7 @@ router.post('/delete-channel-user', async function(request, response){
const loginInfo = request.ctx || {}
const result = await channelUserBiz.removeChannelUser({ loginInfo, channelId, userId });
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -182,6 +133,7 @@ router.post('/update-channel-user-role-admin', async function(request, response)
const loginInfo = request.ctx || {}
const result = await channelUserBiz.updateChannelUserRoleAdmin({ loginInfo, channelId, userId });
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -208,6 +160,7 @@ router.post('/update-channel-user-role-normal', async function(request, response
const loginInfo = request.ctx || {}
const result = await channelUserBiz.updateChannelUserRoleNormal({ loginInfo, channelId, userId });
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -227,6 +180,7 @@ router.get('/get-channel-list-user-list', async function(request, response) {
const loginInfo = request.ctx || {}
const result = await channelUserBiz.getChannelListUserList({ loginInfo });
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -254,6 +208,7 @@ router.get('/get-channel-user-list', async function(request, response) {
const loginInfo = request.ctx || {}
const result = await channelUserBiz.getChannelUserList({ loginInfo, channelId });
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -283,7 +238,7 @@ router.post('/update-channel-top', async function(request, response) {
const result = await channelUserBiz.updateChannelToTop({
channelId, top, loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -291,6 +246,7 @@ router.post('/update-channel-top', async function(request, response) {
}
});
/**
* #controller get /api/web/channel-user/update-channel-black
* #desc 修改频道是否拉黑
@ -320,6 +276,7 @@ router.post('/update-channel-black', async function(request, response) {
}
});
/**
* #controller get /api/web/channel-user/exit-channel
* #desc 退出频道

View File

@ -0,0 +1,76 @@
const {
tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams,
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const cloudFileBiz = require('../../../biz/cloud/cloud_file_biz');
/**
* #controller post /api/web/cloud-file/upload-file
* #desc 上传文件
* @param {*} request
* @param {*} response
*/
router.post('/upload-file', async function(request, response) {
try {
const file = request.files[0];
const { channelId, dirId } = request.body;
if (!checkRequestParams({
channelId, dirId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const fileId = request.fileId
const result = await cloudFileBiz.uploadFile({
loginInfo, file, channelId, dirId, fileId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/cloud-file/download-server-file
* #desc 下载服务器云文件
* @param {*} request
* @param {*} response
*/
router.get('/download-server-file', async function(request, response) {
try {
const { fileId, key } = request.query;
if (!checkRequestParams({
fileId, key
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await cloudFileBiz.downloadCloudFile({
loginInfo, fileId, key
});
if (!result.success) {
response.json(result);
return;
}
response.download(result.data);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
module.exports = router;

View File

@ -1,42 +1,14 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams
tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams,
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const companyBiz = require('../../../biz/company/company_biz');
/**
* #controller post /api/web/company/add-company
* #desc 添加企业
* @param {*} request
* @param {*} response
*/
router.post('/add-company', async function(request, response) {
try {
const { name, address, phone, email, website, logo, description } = request.body;
if (!checkRequestParams({
name, address, phone, email, website, logo, description
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await companyBiz.addCompany({
name, address, phone, email, website, logo, description, loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/company/get-company
* #desc 获取企业
* #desc 获取企业信息
* @param {*} request
* @param {*} response
*/
@ -46,6 +18,7 @@ router.post('/get-company', async function(request, response) {
const result = await companyBiz.getCompanyInfo({
loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)

View File

@ -1,5 +1,5 @@
const {
getClientIP, getLocalIP, tlConsole, tlResponseSvrError, tlConsoleError
getClientIP, getLocalIP, tlConsole, tlResponseSvrError, tlConsoleError,
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();

View File

@ -0,0 +1,53 @@
const {
tlResponseSvrError, tlConsoleError,
checkRequestParams, tlResponseArgsError,
tlResponseSuccess
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const {
LOGIN : {
LOGIN_TOKEN_KEY
}
} = require('../../../utils/constant');
const darkConf = require('../../../../conf/skin/dark');
const lightConf = require('../../../../conf/skin/light');
/**
* #controller get /api/web/config-skin/detail
* #desc 获取皮肤配置
* @param {*} request
* @param {*} response
*/
router.get("/get-detail", async function(request, response){
try {
const { [LOGIN_TOKEN_KEY]: token } = request.cookies;
const { skin } = request.query;
if (!checkRequestParams({
skin
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
if(skin === 'dark'){
response.json(tlResponseSuccess("获取成功", darkConf))
return
}
if(skin === 'light'){
response.json(tlResponseSuccess("获取成功", lightConf))
return
}
response.json(tlResponseArgsError("请求参数非法"));
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
})
module.exports = router

View File

@ -0,0 +1,308 @@
const {
tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams,
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const cutPasteBiz = require('../../../biz/cut_paste/cut_paste_biz');
const {
contentFilter, objectContentFilter
} = require('../../../utils/sensitive/content')
/**
* #controller get /api/web/cut-paste/get-cut-paste-list
* #desc 获取剪切板列表
* @param {*} request
* @param {*} response
*/
router.get('/get-cut-paste-list', async function(request, response) {
try {
const loginInfo = request.ctx || {}
const result = await cutPasteBiz.getCutPasteList({
loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/cut-paste/add-cut-paste
* #desc 新增剪切板
* @param {*} request
* @param {*} response
*/
router.post('/add-cut-paste', async function(request, response) {
try {
const { code, title, password } = request.body;
const loginInfo = request.ctx || {}
if (!checkRequestParams({
code, title, password
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await cutPasteBiz.createCutPaste({
loginInfo, code, title: contentFilter(title), password
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/cut-paste/update-cut-paste-title
* #desc 更新剪切板标题
* @param {*} request
* @param {*} response
*/
router.post('/update-cut-paste-title', async function(request, response) {
try {
const { cutPasteId, title } = request.body;
const loginInfo = request.ctx || {}
if (!checkRequestParams({
cutPasteId, title
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await cutPasteBiz.updateCutPasteTitle({
loginInfo, cutPasteId, title: contentFilter(title),
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/cut-paste/update-cut-paste-password
* #desc 更新剪切板密码
* @param {*} request
* @param {*} response
*/
router.post('/update-cut-paste-password', async function(request, response) {
try {
const { cutPasteId, password } = request.body;
const loginInfo = request.ctx || {}
if (!checkRequestParams({
cutPasteId, password
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await cutPasteBiz.updateCutPastePassword({
loginInfo, cutPasteId, password
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/cut-paste/close-cut-paste
* #desc 关闭剪切板
* @param {*} request
* @param {*} response
*/
router.post('/close-cut-paste', async function(request, response) {
try {
const { cutPasteId } = request.body;
const loginInfo = request.ctx || {}
if (!checkRequestParams({
cutPasteId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await cutPasteBiz.closeCutPaste({
loginInfo, cutPasteId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/cut-paste/open-cut-paste
* #desc 开启剪切板
* @param {*} request
* @param {*} response
*/
router.post('/open-cut-paste', async function(request, response) {
try {
const { cutPasteId } = request.body;
const loginInfo = request.ctx || {}
if (!checkRequestParams({
cutPasteId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await cutPasteBiz.openCutPaste({
loginInfo, cutPasteId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/cut-paste/delete-cut-paste
* #desc 删除剪切板
* @param {*} request
* @param {*} response
*/
router.post('/delete-cut-paste', async function(request, response) {
try {
const { cutPasteId } = request.body;
const loginInfo = request.ctx || {}
if (!checkRequestParams({
cutPasteId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await cutPasteBiz.deleteCutPaste({
loginInfo, cutPasteId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/cut-paste/delete-cut-paste-detail
* #desc 删除剪切板详情
* @param {*} request
* @param {*} response
*/
router.post('/delete-cut-paste-detail', async function(request, response) {
try {
const { cutPasteDetailId } = request.body;
const loginInfo = request.ctx || {}
if (!checkRequestParams({
cutPasteDetailId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await cutPasteBiz.deleteCutPasteDetail({
loginInfo, cutPasteDetailId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/cut-paste/add-cut-paste-detail
* #desc 新增剪切板详情
* @param {*} request
* @param {*} response
*/
router.post('/add-cut-paste-detail', async function(request, response) {
try {
const { cutPasteId, content } = request.body;
const loginInfo = request.ctx || {}
if (!checkRequestParams({
cutPasteId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await cutPasteBiz.addCutPasteDetail({
loginInfo, cutPasteId, content: contentFilter(content),
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/cut-paste/get-cut-paste-detail-list
* #desc 获取剪切板详情列表
* @param {*} request
* @param {*} response
*/
router.post('/get-cut-paste-detail-list', async function(request, response) {
try {
const { cutPasteId, typeList } = request.body;
const loginInfo = request.ctx || {}
if (!checkRequestParams({
cutPasteId, typeList
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await cutPasteBiz.getCutPasteDetailList({
loginInfo, cutPasteId, typeList
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
module.exports = router;

View File

@ -0,0 +1,67 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const cutPasteBiz = require('../../../biz/cut_paste/cut_paste_biz');
/**
* #controller post /api/web/cut-paste-share/share-get-cut-paste-list
* #desc 通过分享渠道获取剪切板列表
* @param {*} request
* @param {*} response
*/
router.post('/share-get-cut-paste-list', async function(request, response) {
try {
const { code, typeList, password } = request.body;
if (!checkRequestParams({
code, typeList, password
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await cutPasteBiz.getCutPasteDetailListByCode({
code, typeList, inputPassword: password
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/cut-paste-share/share-add-cut-paste-detail
* #desc 通过分享渠道新增剪切板详情
* @param {*} request
* @param {*} response
*/
router.post('/share-add-cut-paste-detail', async function(request, response) {
try {
const { code, content, password } = request.body;
if (!checkRequestParams({
code, password
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await cutPasteBiz.addCutPasteDetailByCode({
code, content, inputPassword: password
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
module.exports = router;

View File

@ -0,0 +1,165 @@
const {
tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams,
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const channelBiz = require('../../../biz/channel/channel_biz');
/**
* #controller post /api/web/system-web-channel/add-channel
* #desc 添加频道
* @param {*} request
* @param {*} response
*/
router.post('/add-channel', async function(request, response) {
try {
const {
channelName, companyId, userId, canSearch
} = request.body;
if (!checkRequestParams({
channelName, companyId, userId, canSearch
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelBiz.adminAddChannel({
channelName, loginInfo, companyId, userId, canSearch
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/system-web-channel/update-channel
* #desc 更新频道
* @param {*} request
* @param {*} response
*/
router.post('/update-channel', async function(request, response) {
try {
const {
companyId, channelName, id, canSearch
} = request.body;
if (!checkRequestParams({
companyId, channelName, id, canSearch
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelBiz.adminUpdateChannel({
companyId, channelName, channelId: id, loginInfo, canSearch
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
})
/**
* #controller post /api/web/system-web-channel/delete-channel
* #desc 删除频道
* @param {*} request
* @param {*} response
*/
router.post('/delete-channel', async function(request, response) {
try {
const { id, companyId } = request.body;
if (!checkRequestParams({ id, companyId })) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelBiz.adminDeleteChannel({ channelId: id, companyId, loginInfo });
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
})
/**
* #controller post /api/web/system-web-channel/get-channel-list
* #desc 获取频道列表
* @param {*} request
* @param {*} response
*/
router.get('/get-channel-list', async function(request, response) {
try {
const {
keyword, page, limit
} = request.query;
if (!checkRequestParams({
keyword, page, limit
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelBiz.adminGetChannelList({
keyword, page, limit, loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
})
/**
* #controller post /api/web/system-web-channel/get-channel-user-list
* #desc 获取频道用户列表
* @param {*} request
* @param {*} response
*/
router.get('/get-channel-user-list', async function(request, response) {
try {
const {
keyword, page, limit, channelId
} = request.query;
if (!checkRequestParams({
keyword, page, limit, channelId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelBiz.adminGetChannelUserList({
keyword, page, limit, loginInfo, channelId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
})
module.exports = router;

View File

@ -0,0 +1,164 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams,
encryptData
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const companyBiz = require('../../../biz/company/company_biz');
/**
* #controller post /api/web/system-web-company/add-company
* #desc 添加企业
* @param {*} request
* @param {*} response
*/
router.post('/add-company', async function(request, response) {
try {
const { name, address, phone, email, website, logo, description, openRegister } = request.body;
if (!checkRequestParams({
name, address, phone, email, website, logo, description, openRegister
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await companyBiz.adminAddCompany({
name, address, phone, email, website, logo, description, loginInfo, openRegister
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/system-web-company/update-company
* #desc 更新企业信息
* @param {*} request
* @param {*} response
*/
router.post('/update-company', async function(request, response) {
try {
const {
id, name, address, phone, email, website, logo,
description, code, authStatus, expiredStatus, openRegister
} = request.body;
if (!checkRequestParams({
id, name, address, phone, email, website, logo, description,
code, authStatus, expiredStatus
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await companyBiz.adminUpdateCompany({
id, name, address, phone, email, website,
logo, description, loginInfo, code, authStatus, expiredStatus, openRegister
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/system-web-company/get-company-list
* #desc 获取企业列表
* @param {*} request
* @param {*} response
*/
router.get('/get-company-list', async function(request, response) {
try {
const { page, limit, keyword } = request.query;
if (!checkRequestParams({
page, limit, keyword
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await companyBiz.adminGetCompanyList({
loginInfo, page, limit, keyword
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/system-web-company/get-company-info
* #desc 获取企业详情
* @param {*} request
* @param {*} response
*/
router.get('/get-company-info', async function(request, response) {
try {
const { id } = request.query;
if (!checkRequestParams({
id
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await companyBiz.adminGetCompanyInfo({
loginInfo, id
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/system-web-company/delete-company
* #desc 删除企业
* @param {*} request
* @param {*} response
*/
router.post('/delete-company', async function(request, response) {
try {
const { id } = request.body;
if (!checkRequestParams({
id
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await companyBiz.adminDeleteCompany({
loginInfo, id
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
module.exports = router;

View File

@ -0,0 +1,74 @@
const {
tlResponseSvrError, tlConsoleError, checkRequestParams, tlResponseArgsError,
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const configBiz = require('../../../biz/config/config_biz');
const {
contentFilter, objectContentFilter
} = require('../../../utils/sensitive/content')
/**
* #controller post /api/web/system-web-config/get-system-config
* #desc 获取系统配置
* @param {*} request
* @param {*} response
*/
router.get('/get-system-config', async function(request, response) {
try{
const loginInfo = request.ctx || {}
const result = await configBiz.adminGetSystemEnvConfig({
loginInfo
});
response.json(result);
}catch(error){
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/system-web-config/update-system-config
* #desc 修改系统配置
* @param {*} request
* @param {*} response
*/
router.post('/update-system-config', async function(request, response) {
try{
const {
redisConfig,
webrtcConfig,
mysqlConfig,
emailConfig,
} = request.body;
if (!checkRequestParams({
redisConfig,
webrtcConfig,
mysqlConfig,
emailConfig,
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await configBiz.adminSetSystemEnvConfig({
loginInfo,
redisConfig,
webrtcConfig,
mysqlConfig,
emailConfig,
});
response.json(result);
}catch(error){
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
module.exports = router;

View File

@ -0,0 +1,112 @@
const {
tlResponseSvrError, tlConsoleError, checkRequestParams, tlResponseArgsError,
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const systemServiceBiz = require("../../../biz/system/system_service_biz");
/**
* #controller post /api/web/system-web-service/restart-service
* #desc 重启服务
* @param {*} request
* @param {*} response
*/
router.post('/restart-service', async function(request, response) {
try{
const { serviceName } = request.body;
if (!checkRequestParams({
serviceName
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await systemServiceBiz.adminReadminStartPm2Service({
loginInfo, services: serviceName
});
response.json(result);
}catch(error){
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/system-web-service/stop-service
* #desc 停止服务服务
* @param {*} request
* @param {*} response
*/
router.post('/stop-service', async function(request, response) {
try{
const { serviceName } = request.body;
if (!checkRequestParams({
serviceName
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await systemServiceBiz.adminStopPm2Service({
loginInfo, services: serviceName
});
response.json(result);
}catch(error){
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/system-web-service/start-service
* #desc 启动服务
* @param {*} request
* @param {*} response
*/
router.post('/start-service', async function(request, response) {
try{
const { serviceName } = request.body;
if (!checkRequestParams({
serviceName
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await systemServiceBiz.adminStartPm2Service({
loginInfo, services: serviceName
});
response.json(result);
}catch(error){
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller get /api/web/system-web-service/get-service-status
* #desc 获取服务状态
* @param {*} request
* @param {*} response
*/
router.get('/get-service-status', async function(request, response) {
try{
const loginInfo = request.ctx || {}
const result = await systemServiceBiz.adminGetServiceStatus({
loginInfo,
});
response.json(result);
}catch(error){
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
module.exports = router;

View File

@ -0,0 +1,168 @@
const {
tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams,
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const userBiz = require('../../../biz/user/user_biz');
/**
* #controller post /api/web/system-web-user/add-user
* #desc 添加用户
* @param {*} request
* @param {*} response
*/
router.post('/add-user', async function(request, response) {
try {
const {
companyId, name, password, email, mobile, avatarUrl, roleId,
} = request.body;
if (!checkRequestParams({
companyId, name, password, email, mobile, avatarUrl, roleId,
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userBiz.adminAddUser({
companyId, name, password, email, mobile, avatarUrl, roleId, loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/system-web-user/update-user
* #desc 更新用户
* @param {*} request
* @param {*} response
*/
router.post('/update-user', async function(request, response) {
try {
const {
id, companyId, name, password, email, mobile, avatarUrl, roleId,
wchatName, wchatOpenId, wchatUnionId, wchatAvatarUrl,
} = request.body;
if (!checkRequestParams({
id, companyId, name, password, email, mobile, avatarUrl, roleId,
wchatName, wchatOpenId, wchatUnionId, wchatAvatarUrl,
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userBiz.adminUpdateUser({
id, companyId, name, password, email, mobile, avatarUrl, roleId,
wchatName, wchatOpenId, wchatUnionId, wchatAvatarUrl, loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
})
/**
* #controller post /api/web/system-web-user/delete-user
* #desc 删除用户
* @param {*} request
* @param {*} response
*/
router.post('/delete-user', async function(request, response) {
try {
const { id, companyId } = request.body;
if (!checkRequestParams({ id, companyId })) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userBiz.adminDeleteUser({ id, companyId, loginInfo });
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
})
/**
* #controller post /api/web/system-web-user/get-user-list
* #desc 获取用户列表
* @param {*} request
* @param {*} response
*/
router.get('/get-user-list', async function(request, response) {
try {
const {
keyword, page, limit, companyId
} = request.query;
if (!checkRequestParams({
keyword, page, limit, companyId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userBiz.adminGetUserList({
keyword, page, limit, loginInfo, companyId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
})
/**
* #controller post /api/web/system-web-user/get-user-info
* #desc 获取用户信息
* @param {*} request
* @param {*} response
*/
router.get('/get-user-info', async function(request, response) {
try {
const {
companyId, id
} = request.query;
if (!checkRequestParams({
companyId, id
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userBiz.adminGetUserInfo({
loginInfo, companyId, id
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
})
module.exports = router;

View File

@ -1,5 +1,5 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams
tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams,
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
@ -14,10 +14,10 @@ const userApplyBiz = require('../../../biz/user/user_apply_biz');
*/
router.post('/add-user-friend-apply', async function(request, response) {
try {
const { friendId, remark, origin } = request.body;
const { friendId, remark } = request.body;
if (!checkRequestParams({
friendId, remark, origin
friendId, remark
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
@ -25,8 +25,9 @@ router.post('/add-user-friend-apply', async function(request, response) {
const loginInfo = request.ctx || {}
const result = await userApplyBiz.applyAddFriend({
loginInfo, friendId, remark, origin
loginInfo, friendId, remark
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -56,6 +57,7 @@ router.post('/pass-user-friend', async function(request, response) {
const result = await userApplyBiz.passUserFriendApply({
loginInfo, id, remark
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -84,6 +86,7 @@ router.post('/reject-user-friend', async function(request, response) {
const result = await userApplyBiz.rejectUserFriendApply({
loginInfo, id, remark
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -104,6 +107,7 @@ router.get('/get-user-friend-other-apply-list', async function(request, response
const result = await userApplyBiz.getUserFriendListFromOther({
loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -124,6 +128,7 @@ router.get('/get-user-friend-self-apply-list', async function(request, response)
const result = await userApplyBiz.getUserFriendApplyListFromSelf({
loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -132,6 +137,135 @@ router.get('/get-user-friend-self-apply-list', async function(request, response)
});
/**
* #controller get /api/web/user-apply/get-user-group-other-apply-list
* #desc 获取自己收到的群聊申请列表
* @param {*} request
* @param {*} response
*/
router.get('/get-user-group-other-apply-list', async function(request, response) {
try {
const loginInfo = request.ctx || {}
const result = await userApplyBiz.getUserGroupListFromOther({
loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller get /api/web/user-apply/get-user-group-self-apply-list
* #desc 获取自己发出的群聊申请列表
* @param {*} request
* @param {*} response
*/
router.get('/get-user-group-self-apply-list', async function(request, response) {
try {
const loginInfo = request.ctx || {}
const result = await userApplyBiz.getUserGroupApplyListFromSelf({
loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user-apply/add-user-group-apply
* #desc 添加群聊申请
* @param {*} request
* @param {*} response
*/
router.post('/add-user-group-apply', async function(request, response) {
try {
const { channelId, remark, shareUserId } = request.body;
if (!checkRequestParams({
channelId, remark, shareUserId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userApplyBiz.applyAddGroup({
loginInfo, channelId, remark, shareUserId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user-apply/pass-user-group
* #desc 通过群聊申请
* @param {*} request
* @param {*} response
*/
router.post('/pass-user-group', async function(request, response) {
try {
const { id, remark } = request.body;
if (!checkRequestParams({
id, remark
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userApplyBiz.passUserGroupApply({
loginInfo, id, remark
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user-apply/reject-user-group
* #desc 拒绝群聊申请
* @param {*} request
* @param {*} response
*/
router.post('/reject-user-group', async function(request, response) {
try {
const { id, remark } = request.body;
if (!checkRequestParams({
id, remark
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userApplyBiz.rejectUserGroupApply({
loginInfo, id, remark
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
module.exports = router;

View File

@ -0,0 +1,129 @@
const {
tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams,
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const userClearBiz = require('../../../biz/user/user_clear_biz');
/**
* #controller post /api/web/user-clear/update-channel-mutil-clear
* #desc 更新频道文件/媒体/聊天消息清理记录
* @param {*} request
* @param {*} response
*/
router.post('/update-channel-mutil-clear', async function(request, response) {
try {
const {
channelId
} = request.body;
if (!checkRequestParams({
channelId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userClearBiz.updateChannelMuiltClear({
loginInfo, channelId
})
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
})
/**
* #controller post /api/web/user-clear/update-channel-chat-clear
* #desc 更新频道聊天消息清理记录
* @param {*} request
* @param {*} response
*/
router.post('/update-channel-chat-read', async function(request, response) {
try {
const { channelId } = request.body;
if (!checkRequestParams({
channelId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userClearBiz.updateChannelChatClear({
loginInfo, channelId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
});
/**
* #controller post /api/web/user-clear/update-channel-media-clear
* #desc 更新频道媒体消息清理记录
* @param {*} request
* @param {*} response
*/
router.post('/update-channel-media-clear', async function(request, response) {
try {
const { channelId } = request.body;
if (!checkRequestParams({
channelId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userClearBiz.updateChannelMediaClear({
loginInfo, channelId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
})
/**
* #controller post /api/web/user-clear/update-channel-file-clear
* #desc 更新频道文件消息清理记录
* @param {*} request
* @param {*} response
*/
router.post('/update-channel-file-clear', async function(request, response) {
try {
const { channelId } = request.body;
if (!checkRequestParams({
channelId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userClearBiz.updateChannelFileClear({
loginInfo, channelId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
})
module.exports = router;

View File

@ -1,5 +1,5 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams
tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams,
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
@ -18,6 +18,7 @@ router.get('/get-user-config', async function(request, response) {
const result = await userConfigBiz.getUserConfigSetting({
loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -47,6 +48,7 @@ router.post('/update-user-config-normal', async function(request, response) {
const result = await userConfigBiz.updateUserConfigNormal({
loginInfo, normal
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -54,6 +56,37 @@ router.post('/update-user-config-normal', async function(request, response) {
}
});
/**
* #controller post /api/web/user-config/update-user-config-skin
* #desc 更新用户皮肤设置
* @param {*} request
* @param {*} response
*/
router.post('/update-user-config-skin', async function(request, response) {
try {
const { skin } = request.body;
if (!checkRequestParams({
skin
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userConfigBiz.updateUserConfigSkin({
loginInfo, skin
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user-config/update-user-config-account
* #desc 更新用户账号设置
@ -75,6 +108,7 @@ router.post('/update-user-config-account', async function(request, response) {
const result = await userConfigBiz.updateUserConfigAccount({
loginInfo, account
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -104,6 +138,7 @@ router.post('/update-user-config-message', async function(request, response) {
const result = await userConfigBiz.updateUserConfigMessage({
loginInfo, message
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -133,6 +168,7 @@ router.post('/update-user-config-other', async function(request, response) {
const result = await userConfigBiz.updateUserConfigOther({
loginInfo, other
});
response.json(result);
} catch (error) {
tlConsoleError(error)

View File

@ -1,5 +1,5 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams
tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams,
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
@ -33,6 +33,7 @@ router.get('/search-user-by-name', async function(request, response) {
const result = await userBiz.searchUserByName({
loginInfo, name,
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -62,6 +63,7 @@ router.post('/search-user-by-id', async function(request, response) {
const result = await userBiz.searchUserById({
loginInfo, id,
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -69,6 +71,36 @@ router.post('/search-user-by-id', async function(request, response) {
}
});
/**
* #controller post /api/web/user/update-user-avatar
* #desc 更新用户头像
* @param {*} request
* @param {*} response
* @return {*}
*/
router.post('/update-user-avatar', async function(request, response) {
try {
const { cloudFileId } = request.body;
const { [LOGIN_TOKEN_KEY]: token } = request.cookies;
if (!checkRequestParams({
cloudFileId,
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userBiz.updateUserAvatar({
loginInfo, cloudFileId, token
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user/bind-email
@ -92,6 +124,7 @@ router.post('/bind-email', async function(request, response) {
const result = await userBiz.bindEmail({
loginInfo, email, code, token
});
response.json(result);
} catch (error) {
tlConsoleError(error)

View File

@ -1,5 +1,5 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams
tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams,
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
@ -27,6 +27,7 @@ router.post('/delete-user-friend', async function(request, response) {
const result = await userFriendBiz.deleteFriend({
loginInfo, channelId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -55,6 +56,7 @@ router.post('/update-user-friend-remark', async function(request, response) {
const result = await userFriendBiz.updateRemark({
loginInfo, channelId, remark
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -83,34 +85,7 @@ router.post('/update-user-friend-rename', async function(request, response) {
const result = await userFriendBiz.updateRename({
loginInfo, channelId, rename
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError(error));
}
});
/**
* #controller post /api/web/user-friend/update-user-special
* #desc 关注好友
* @param {*} request
* @param {*} response
*/
router.post('/update-user-friend-special', async function(request, response) {
try {
const { channelId, special } = request.body;
if (!checkRequestParams({
channelId, special
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userFriendBiz.updateFriendSpecical({
loginInfo, channelId, special
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -130,6 +105,7 @@ router.get('/get-user-friend-list', async function(request, response) {
const result = await userFriendBiz.getFriendList({
loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)

View File

@ -1,5 +1,4 @@
const {
tlConsole,
tlResponseSvrError, tlConsoleError,
tlResponseArgsError, checkRequestParams,
tlResponseSuccess
@ -12,9 +11,8 @@ const {
LOGIN : {
LOGIN_TOKEN_KEY,
LOGIN_TOKEN_EXPIRE,
WEBSITE_LOGIN_TOKEN_KEY,
WEBSITE_LOGIN_TOKEN_EXPIRE
SYSTEM_LOGIN_TOKEN_EXPIRE,
SYSTEM_LOGIN_TOKEN_KEY
}
} = require('../../../utils/constant');
@ -31,6 +29,7 @@ router.get('/login-state', async function(request, response) {
const result = await userLoginStateBiz.userIsLogin({
token
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -46,7 +45,7 @@ router.get('/login-state', async function(request, response) {
*/
router.post('/login-by-account', async function(request, response) {
try {
const { account, password, fps } = request.body;
const { account, password, fps, inviteCode } = request.body;
const { [LOGIN_TOKEN_KEY]: token } = request.cookies;
if(token){
@ -59,14 +58,14 @@ router.post('/login-by-account', async function(request, response) {
}
if (!checkRequestParams({
account, password, fps
account, password, fps, inviteCode
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await userLoginBiz.userLoginByAccount({
account, password, fps
account, password, fps, inviteCode
});
response.cookie(LOGIN_TOKEN_KEY, result.data, {
@ -80,48 +79,6 @@ router.post('/login-by-account', async function(request, response) {
}
});
/**
* #controller post /api/web/user-login/login-by-mobile
* #desc 通过手机号登录
* @param {*} request
* @param {*} response
*/
router.post('/login-by-mobile', async function(request, response) {
try {
const { mobile, code, fps } = request.body;
const { [LOGIN_TOKEN_KEY]: token } = request.cookies;
if(token){
const loginResult = await userLoginStateBiz.userIsLogin({
token
});
if(loginResult.success){
return response.json(loginResult)
}
}
if (!checkRequestParams({
mobile, code, fps
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await userLoginBiz.userLoginByMobile({
mobile, code, fps
});
response.cookie(LOGIN_TOKEN_KEY, result.data, {
maxAge: LOGIN_TOKEN_EXPIRE, httpOnly: true
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
})
/**
* #controller post /api/web/user-login/login-by-email
* #desc 通过邮箱登录
@ -130,7 +87,7 @@ router.post('/login-by-mobile', async function(request, response) {
*/
router.post('/login-by-email', async function(request, response) {
try {
const { email, password, fps } = request.body;
const { email, password, fps, inviteCode } = request.body;
const { [LOGIN_TOKEN_KEY]: token } = request.cookies;
if(token){
@ -143,14 +100,14 @@ router.post('/login-by-email', async function(request, response) {
}
if (!checkRequestParams({
email, password, fps
email, password, fps, inviteCode
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await userLoginBiz.userLoginByEmail({
email, password, fps
email, password, fps, inviteCode
});
response.cookie(LOGIN_TOKEN_KEY, result.data, {
@ -164,154 +121,6 @@ router.post('/login-by-email', async function(request, response) {
}
});
/**
* #controller post /api/web/user-login/login-by-code
* #desc 游客登录
* @param {*} request
* @param {*} response
*/
router.post('/login-by-guest', async function(request, response) {
try {
const { code } = request.body;
const { [LOGIN_TOKEN_KEY]: token } = request.cookies;
if(token){
const loginResult = await userLoginStateBiz.userIsLogin({
token
});
if(loginResult.success){
return response.json(loginResult)
}
}
if (!checkRequestParams({
code
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await userLoginBiz.userLoginByGuest({
code
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
});
/**
* #controller post /api/web/user-login/login-by-wechat
* #desc 微信登录
* @param {*} request
* @param {*} response
*/
router.post('/login-by-wechat', async function(request, response) {
try {
const { openId, code } = request.body;
const { [LOGIN_TOKEN_KEY]: token } = request.cookies;
if(token){
const loginResult = await userLoginStateBiz.userIsLogin({
token
});
if(loginResult.success){
return response.json(loginResult)
}
}
if (!checkRequestParams({
openId, code
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await userLoginBiz.userLoginByWechat({
openId, code
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
});
/**
* #controller post /api/web/user-login/login-by-qq
* #desc QQ登录
* @param {*} request
* @param {*} response
*/
router.post('/login-by-qq', async function(request, response) {
try {
const { openId, code } = request.body;
const { [LOGIN_TOKEN_KEY]: token } = request.cookies;
if(token){
const loginResult = await userLoginStateBiz.userIsLogin({
token
});
if(loginResult.success){
return response.json(loginResult)
}
}
if (!checkRequestParams({
openId, code
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await userLoginBiz.userLoginByQQ({
openId, code
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
});
/**
* #controller post /api/web/user-login/login-by-qy-wechat
* #desc 企业微信登录
* @param {*} request
* @param {*} response
*/
router.post('/login-by-qy-wechat', async function(request, response) {
try {
const { openId, code } = request.body;
const { [LOGIN_TOKEN_KEY]: token } = request.cookies;
if(token){
const loginResult = await userLoginStateBiz.userIsLogin({
token
});
if(loginResult.success){
return response.json(loginResult)
}
}
if (!checkRequestParams({
openId, code
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await userLoginBiz.userLoginByQyWechat({
openId, code
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
});
/**
* #controller post /api/web/user-login/login-by-fp
@ -321,7 +130,7 @@ router.post('/login-by-qy-wechat', async function(request, response) {
*/
router.post('/login-by-fp', async function(request, response) {
try {
const { username, fps} = request.body;
const { username, fps, inviteCode } = request.body;
const { [LOGIN_TOKEN_KEY]: token } = request.cookies;
if(token){
@ -334,14 +143,14 @@ router.post('/login-by-fp', async function(request, response) {
}
if (!checkRequestParams({
username, fps
username, fps, inviteCode
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await userLoginBiz.userLoginByFingerPrint({
username, fps
username, fps, inviteCode
});
response.cookie(LOGIN_TOKEN_KEY, result.data, {
@ -358,14 +167,14 @@ router.post('/login-by-fp', async function(request, response) {
/**
* #controller get /api/web/user-login/website-login-state
* #desc 获取官网登录状态
* #controller get /api/web/user-login/system-login-state
* #desc 获取管理员登录状态
* @param {*} request
* @param {*} response
*/
router.get('/website-login-state', async function(request, response) {
router.get('/system-login-state', async function(request, response) {
try {
const { [WEBSITE_LOGIN_TOKEN_KEY]: token } = request.cookies;
const { [SYSTEM_LOGIN_TOKEN_KEY]: token } = request.cookies;
const result = await userLoginStateBiz.userIsLogin({
token
});
@ -391,15 +200,15 @@ router.get('/website-login-state', async function(request, response) {
/**
* #controller post /api/web/user-login/login-by-website
* #desc 官网登录
* #controller post /api/web/user-login/login-by-system
* #desc 管理员登录
* @param {*} request
* @param {*} response
*/
router.post('/login-by-website', async function(request, response) {
router.post('/login-by-system', async function(request, response) {
try {
const { name, email, password } = request.body;
const { [WEBSITE_LOGIN_TOKEN_KEY]: token } = request.cookies;
const { email, password } = request.body;
const { [SYSTEM_LOGIN_TOKEN_KEY]: token } = request.cookies;
if(token){
const loginResult = await userLoginStateBiz.userIsLogin({
@ -411,18 +220,18 @@ router.post('/login-by-website', async function(request, response) {
}
if (!checkRequestParams({
name, email, password
email, password
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await userLoginBiz.userLoginByWebsite({
name, email, password
const result = await userLoginBiz.userLoginBySystem({
email, password
});
response.cookie(WEBSITE_LOGIN_TOKEN_KEY, result.data, {
maxAge: WEBSITE_LOGIN_TOKEN_EXPIRE, httpOnly: true
response.cookie(SYSTEM_LOGIN_TOKEN_KEY, result.data, {
maxAge: SYSTEM_LOGIN_TOKEN_EXPIRE, httpOnly: true
});
response.json(result);
@ -432,4 +241,8 @@ router.post('/login-by-website', async function(request, response) {
}
});
module.exports = router

View File

@ -1,5 +1,5 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError
tlResponseSvrError, tlConsoleError
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
@ -8,7 +8,7 @@ const {
LOGIN : {
LOGIN_TOKEN_KEY,
WEBSITE_LOGIN_TOKEN_KEY
SYSTEM_LOGIN_TOKEN_KEY
}
} = require('../../../utils/constant');
@ -39,19 +39,19 @@ router.get('/logout', async function(request, response) {
/**
* #controller get /api/web/user-logout/website-logout
* #controller get /api/web/user-logout/system-logout
* #desc 退出登录
* @param {*} request
* @param {*} response
*/
router.get('/website-logout', async function(request, response) {
router.get('/system-logout', async function(request, response) {
try {
const { [WEBSITE_LOGIN_TOKEN_KEY]: token } = request.cookies;
const { [SYSTEM_LOGIN_TOKEN_KEY]: token } = request.cookies;
const result = await userLogoutBiz.userLogout({
token
});
response.clearCookie(WEBSITE_LOGIN_TOKEN_KEY);
response.clearCookie(SYSTEM_LOGIN_TOKEN_KEY);
response.json(result);
} catch (error) {

View File

@ -1,5 +1,6 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams
tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams,
encryptData
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
@ -29,6 +30,7 @@ router.post('/update-channel-mutil-read', async function(request, response) {
const result = await userReadBiz.updateChannelMuiltRead({
loginInfo, channelId, latestChatReadId, latestMediaReadId, latestFileReadId
})
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -57,6 +59,7 @@ router.post('/update-channel-chat-read', async function(request, response) {
const result = await userReadBiz.updateChannelChatRead({
loginInfo, channelId, latestReadId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -85,6 +88,7 @@ router.post('/update-channel-media-read', async function(request, response) {
const result = await userReadBiz.updateChannelMediaRead({
loginInfo, channelId, latestReadId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -113,6 +117,7 @@ router.post('/update-channel-file-read', async function(request, response) {
const result = await userReadBiz.updateChannelFileRead({
loginInfo, channelId, latestReadId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -122,7 +127,7 @@ router.post('/update-channel-file-read', async function(request, response) {
/**
* #controller post /api/web/user-read/update-user-friend-apply-read
* #desc 新增申请消息已读记录
* #desc 新增好友申请消息已读记录
* @param {*} request
* @param {*} response
*/
@ -141,6 +146,7 @@ router.post('/update-user-friend-apply-read', async function(request, response)
const result = await userReadBiz.addUserFriendApplyRead({
loginInfo, recordId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -151,7 +157,7 @@ router.post('/update-user-friend-apply-read', async function(request, response)
/**
* #controller post /api/web/user-read/update-user-friend-apply-pass-read
* #desc 新增通过申请消息已读记录
* #desc 新增通过好友申请消息已读记录
* @param {*} request
* @param {*} response
*/
@ -170,6 +176,7 @@ router.post('/update-user-friend-apply-pass-read', async function(request, respo
const result = await userReadBiz.addUserFriendApplyPassRead({
loginInfo, recordId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -179,7 +186,7 @@ router.post('/update-user-friend-apply-pass-read', async function(request, respo
/**
* #controller post /api/web/user-read/update-user-friend-apply-reject-read
* #desc 新增拒绝申请消息已读记录
* #desc 新增拒绝好友申请消息已读记录
* @param {*} request
* @param {*} response
*/
@ -198,6 +205,7 @@ router.post('/update-user-friend-apply-reject-read', async function(request, res
const result = await userReadBiz.addUserFriendApplyRejectRead({
loginInfo, applyId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -206,4 +214,91 @@ router.post('/update-user-friend-apply-reject-read', async function(request, res
})
/**
* #controller post /api/web/user-read/update-user-group-apply-read
* 新增群聊申请消息已读记录
* @param {*} request
* @param {*} response
*/
router.post('/update-user-group-apply-read', async function(request, response) {
try {
const { recordId } = request.body;
if (!checkRequestParams({
recordId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userReadBiz.addUserGroupApplyRead({
loginInfo, recordId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
})
/**
* #controller post /api/web/user-read/update-user-group-apply-pass-read
* 新增通过群聊申请消息已读记录
* @param {*} request
* @param {*} response
*/
router.post('/update-user-group-apply-pass-read', async function(request, response) {
try {
const { recordId } = request.body;
if (!checkRequestParams({
recordId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userReadBiz.addUserGroupApplyPassRead({
loginInfo, recordId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
})
/**
* #controller post /api/web/user-read/update-user-group-apply-reject-read
* 新增拒绝群聊申请消息已读记录
* @param {*} request
* @param {*} response
*/
router.post('/update-user-group-apply-reject-read', async function(request, response) {
try {
const { recordId } = request.body;
if (!checkRequestParams({
recordId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userReadBiz.addUserGroupApplyRejectRead({
loginInfo, recordId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
})
module.exports = router;

View File

@ -1,5 +1,5 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams
tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
@ -10,6 +10,9 @@ const {
LOGIN_TOKEN_KEY
}
} = require('../../../utils/constant');
const {
contentFilter, objectContentFilter
} = require('../../../utils/sensitive/content')
/**
@ -40,44 +43,7 @@ router.post('/register-by-account', async function(request, response) {
}
const result = await bizUserRegister.userRegisterByAccount({
account, password, invite_code
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user-register/register-by-mobile
* #desc 通过手机号注册
* @param {*} request
* @param {*} response
*/
router.post('/register-by-mobile', async function(request, response) {
try {
const { mobile, code, invite_code } = request.body;
const { [LOGIN_TOKEN_KEY]: token } = request.cookies;
if(token){
const loginResult = await bizUserLoginState.userIsLogin({
token
});
if(loginResult.success){
return response.json(loginResult)
}
}
if (!checkRequestParams({
mobile, code, invite_code
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await bizUserRegister.userRegisterByMobile({
mobile, code, invite_code
account: contentFilter(account), password, invite_code
});
response.json(result);
} catch (error) {
@ -152,35 +118,24 @@ router.post('/get-email-code', async function(request, response) {
/**
* #controller post /api/web/user-register/register-website-user
* #desc 注册官网用户
* #controller post /api/web/user-register/reset-by-email
* #desc 重置邮箱用户密码
* @param {*} request
* @param {*} response
*/
router.post('/register-website-user', async function(request, response) {
router.post('/reset-by-email', async function(request, response) {
try {
const { code, email, password } = request.body;
const { [LOGIN_TOKEN_KEY]: token } = request.cookies;
if(token){
const loginResult = await bizUserLoginState.userIsLogin({
token
});
if(loginResult.success){
return response.json(loginResult)
}
}
const { code, email, invite_code } = request.body;
if (!checkRequestParams({
code, email, password
code, email, invite_code
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await bizUserRegister.registerWebsiteUser({
code, email, password
const result = await bizUserRegister.resetPasswordByEmail({
code, email, invite_code
});
response.json(result);
} catch (error) {
@ -189,4 +144,5 @@ router.post('/register-website-user', async function(request, response) {
}
});
module.exports = router

View File

@ -1,5 +1,5 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams
tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams,
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
@ -27,6 +27,7 @@ router.post('/add-channel-tag', async function(request, response) {
const result = await userTagBiz.addChannelTag({
loginInfo, name
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -55,6 +56,7 @@ router.post('/add-friend-tag', async function(request, response) {
const result = await userTagBiz.addFriendTag({
loginInfo, name
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -83,6 +85,7 @@ router.post('/add-cloud-tag', async function(request, response) {
const result = await userTagBiz.addCloudTag({
loginInfo, name
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -102,6 +105,7 @@ router.get('/get-channel-tag-list', async function(request, response) {
const result = await userTagBiz.getChannelTagList({
loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -121,6 +125,7 @@ router.get('/get-friend-tag-list', async function(request, response) {
const result = await userTagBiz.getFriendTagList({
loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -140,6 +145,7 @@ router.get('/get-cloud-tag-list', async function(request, response) {
const result = await userTagBiz.getCloudTagList({
loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
@ -168,6 +174,7 @@ router.post('/delete-tag', async function(request, response) {
const result = await userTagBiz.delUserTag({
loginInfo, id
});
response.json(result);
} catch (error) {
tlConsoleError(error)

View File

@ -2,8 +2,16 @@
// web包含的controller定义
// Date: 2024-01-13
// 系统
const systemWebConfig = require('./system/system_web_config_controller')
const systemWebCompany = require('./system/system_web_company_controller')
const systemWebUser = require('./system/system_web_user_controller')
const systemWebChannel = require('./system/system_web_channel_controller')
const systemWebService = require('./system/system_web_service_controller')
// 配置
const configInit = require('./config/init_controller')
const configSkin = require('./config/skin_controller')
// 企业
const company = require('./company/company_controller')
@ -18,15 +26,34 @@ const userApply = require('./user/user_apply_controller')
const userRead = require('./user/user_read_controller')
const userConfig = require('./user/user_config_controller')
const userTag = require('./user/user_tag_controller')
const userClear = require('./user/user_clear_controller')
// 频道
const channel = require('./channel/channel_controller')
const channelChat = require('./channel/channel_chat_controller')
const channelNotice = require('./channel/channel_notice_controller')
const channelUser = require('./channel/channel_user_controller')
const channelFile = require('./channel/channel_file_controller')
const channelMedia = require('./channel/channel_media_controller')
// 文件
const cloudFile = require('./cloud/cloud_file_controller')
// 剪贴板
const cutPaste = require('./cut_paste/cut_paste_controller')
const cutPasteShare = require('./cut_paste/cut_paste_share_controller')
module.exports = {
"system-web-config" : systemWebConfig,
"system-web-company" : systemWebCompany,
"system-web-user" : systemWebUser,
"system-web-channel" : systemWebChannel,
"system-web-service" : systemWebService,
"config" : configInit,
"config-skin" : configSkin,
"company" : company,
"user" : user,
@ -38,7 +65,16 @@ module.exports = {
"user-read" : userRead,
"user-config" : userConfig,
"user-tag" : userTag,
"user-clear" : userClear,
"channel" : channel,
"channel-chat" : channelChat,
"channel-user" : channelUser,
"channel-notice" : channelNotice,
"channel-file" : channelFile,
"channel-media" : channelMedia,
"cut-paste" : cutPaste,
"cut-paste-share" : cutPasteShare,
"cloud-file" : cloudFile,
}

View File

@ -1,4 +1,4 @@
const { DataTypes, where } = require('sequelize');
const { DataTypes } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_channel_chat')
const Table = model(dbClient, DataTypes).TlChannelChat
@ -155,7 +155,13 @@ const updateInfo = async function(params, data){
tlConsole(TableName, params, data, info)
return info
if(info[0] === 0){
return null
}
return {
count: info[0]
}
}

View File

@ -1,4 +1,4 @@
const { DataTypes, where, or } = require('sequelize');
const { DataTypes } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_channel')
const Table = model(dbClient, DataTypes).TlChannel
@ -155,7 +155,13 @@ const updateInfo = async function(params, data){
tlConsole(TableName, params, data, info)
return info
if(info[0] === 0){
return null
}
return {
count: info[0]
}
}

View File

@ -0,0 +1,239 @@
const { DataTypes } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_channel_file')
const Table = model(dbClient, DataTypes).TlChannelFile
const TableName = fields.Name
const TableFields = Object.keys(fields.Def).map(key => fields.Def[key])
const { tlConsoleError, tlConsole, checkRawFieldType} = require("../../src/utils/utils");
/**
* addInfo 接口
* @param {*} data
*/
const addInfo = async function(data){
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
// 参数校验
const checkStatus = checkRawFieldType(Table.rawAttributes, data)
if (!checkStatus) {
tlConsoleError(TableName, "请求dao参数类型错误")
return null
}
const info = await Table.create(data)
tlConsole(TableName, data, info)
return info
}
/**
* addList 接口
* @param {*} dataList
*/
const addList = async function(dataList){
if(dataList.length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
for(let data of dataList){
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
// 参数校验
const checkStatus = checkRawFieldType(Table.rawAttributes, data)
if (!checkStatus) {
tlConsoleError(TableName, "请求dao参数类型错误")
return null
}
}
const list = await Table.bulkCreate(dataList)
tlConsole(TableName, dataList, list)
return list
}
/**
* getInfo 接口
* @param {*} params
* @param {*} fields
*/
const getInfo = async function(params, fields = TableFields){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
const info = await Table.findOne({
where: params,
attributes: fields
})
return info
}
/**
* getList 接口
* @param {*} params
* @param {*} fields
* @param {*} order
*/
const getList = async function(params, fields = TableFields, order = [['id', 'ASC']]){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const list = await Table.findAll({
where : params,
attributes: fields,
order: order,
})
return list
}
/**
* getListForPage 接口
* @param {*} params
* @param {*} fields
* @param {*} order
* @param {*} page
* @param {*} pageSize
*/
const getListForPage = async function(params, fields = TableFields, order = [['id', 'ASC']], page = 1, pageSize = 10){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const list = await Table.findAll({
where : params,
attributes: fields,
order: order,
limit: pageSize,
offset: (page - 1) * pageSize
})
return list
}
/**
* updateInfo 接口
* @param {*} params
* @param {*} data
*/
const updateInfo = async function(params, data){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
// 参数校验
const checkStatus = checkRawFieldType(Table.rawAttributes, data)
if (!checkStatus) {
tlConsoleError(TableName, "请求dao参数类型错误")
return null
}
const info = await Table.update(data, {
where: params
})
tlConsole(TableName, params, data, info)
if(info[0] === 0){
return null
}
return {
count: info[0]
}
}
/**
* deleteInfo 接口
* @param {*} params
*/
const deleteInfo = async function(params){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
const info = await Table.destroy({
where: params
})
tlConsole(TableName, params, info)
return info
}
/**
* getCount 接口
* @param {*} params
*/
const getCount = async function(params){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const count = await Table.count({
where : params
})
return count
}
/**
* getGroupCount 接口
* @param {*} params
* @param {*} group
*/
const getGroupCount = async function(params, group){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
if(Object.keys(group).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const count = await Table.count({
where : params,
attributes: [group],
group: group,
})
return count
}
module.exports = {
addInfo, addList,
getInfo, getList, getListForPage,
updateInfo,
deleteInfo,
getCount,
getGroupCount
}

View File

@ -0,0 +1,211 @@
const { DataTypes } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_channel_media')
const Table = model(dbClient, DataTypes).TlChannelMedia
const TableName = fields.Name
const TableFields = Object.keys(fields.Def).map(key => fields.Def[key])
const { tlConsoleError, tlConsole, checkRawFieldType } = require("../../src/utils/utils");
/**
* addInfo 接口
* @param {*} data
*/
const addInfo = async function(data){
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
// 参数校验
const checkStatus = checkRawFieldType(Table.rawAttributes, data)
if (!checkStatus) {
tlConsoleError(TableName, "请求dao参数类型错误")
return null
}
const info = await Table.create(data)
tlConsole(TableName, data, info)
return info
}
/**
* addList 接口
* @param {*} dataList
*/
const addList = async function(dataList){
if(dataList.length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
for(let data of dataList){
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
// 参数校验
const checkStatus = checkRawFieldType(Table.rawAttributes, data)
if (!checkStatus) {
tlConsoleError(TableName, "请求dao参数类型错误")
return null
}
}
const list = await Table.bulkCreate(dataList)
tlConsole(TableName, dataList, list)
return list
}
/**
* getInfo 接口
* @param {*} params
* @param {*} fields
*/
const getInfo = async function(params, fields = TableFields){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
const info = await Table.findOne({
where: params,
attributes: fields
})
return info
}
/**
* getList 接口
* @param {*} params
* @param {*} fields
* @param {*} order
*/
const getList = async function(params, fields = TableFields, order = [['id', 'ASC']]){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const list = await Table.findAll({
where : params,
attributes: fields,
order: order
})
return list
}
/**
* getListForPage 接口
* @param {*} params
* @param {*} fields
* @param {*} order
* @param {*} page
* @param {*} pageSize
*/
const getListForPage = async function(params, fields = TableFields, order = [['id', 'ASC']], page = 1, pageSize = 10){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const list = await Table.findAll({
where : params,
attributes: fields,
order: order,
offset: (page - 1) * pageSize,
limit: pageSize
})
return list
}
/**
* updateInfo 接口
* @param {*} params
* @param {*} data
*/
const updateInfo = async function(params, data){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
// 参数校验
const checkStatus = checkRawFieldType(Table.rawAttributes, data)
if (!checkStatus) {
tlConsoleError(TableName, "请求dao参数类型错误")
return null
}
const info = await Table.update(data, {
where: params
})
tlConsole(TableName, params, data, info)
if(info[0] === 0){
return null
}
return {
count: info[0]
}
}
/**
* deleteInfo 接口
* @param {*} params
*/
const deleteInfo = async function(params){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
const info = await Table.destroy({
where: params
})
tlConsole(TableName, params, info)
return info
}
/**
* getCount 接口
* @param {*} params
*/
const getCount = async function(params){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const count = await Table.count({
where : params
})
return count
}
module.exports = {
addInfo, addList,
getInfo, getList, getListForPage,
updateInfo,
deleteInfo,
getCount,
}

View File

@ -0,0 +1,62 @@
const { QueryTypes } = require('sequelize');
const { dbClient } = require('../tables/db')
const { tlConsoleError } = require("../../src/utils/utils");
const TableName = "TlChannelMessageDao"
/**
* getListBySql 接口
* @param {*} querySql
* @param {*} params
*/
const getListBySql = async function(
querySql, params,
){
if(!querySql){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const list = await dbClient.query(querySql, {
replacements: params,
type: QueryTypes.SELECT,
});
return list
}
/**
* getCountBySql 接口
* @param {*} querySql
* @param {*} params
*/
const getCountBySql = async function(
querySql, params,
){
if(!querySql){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const count = await dbClient.query(querySql, {
replacements: params,
type: QueryTypes.SELECT,
});
return count
}
module.exports = {
getListBySql,
getCountBySql,
}

View File

@ -0,0 +1,211 @@
const { DataTypes } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_channel_notice')
const Table = model(dbClient, DataTypes).TlChannelNotice
const TableName = fields.Name
const TableFields = Object.keys(fields.Def).map(key => fields.Def[key])
const { tlConsoleError, tlConsole, checkRawFieldType } = require("../../src/utils/utils");
/**
* addInfo 接口
* @param {*} data
*/
const addInfo = async function(data){
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
// 参数校验
const checkStatus = checkRawFieldType(Table.rawAttributes, data)
if (!checkStatus) {
tlConsoleError(TableName, "请求dao参数类型错误")
return null
}
const info = await Table.create(data)
tlConsole(TableName, data, info)
return info
}
/**
* addList 接口
* @param {*} dataList
*/
const addList = async function(dataList){
if(dataList.length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
for(let data of dataList){
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
// 参数校验
const checkStatus = checkRawFieldType(Table.rawAttributes, data)
if (!checkStatus) {
tlConsoleError(TableName, "请求dao参数类型错误")
return null
}
}
const list = await Table.bulkCreate(dataList)
tlConsole(TableName, dataList, list)
return list
}
/**
* getInfo 接口
* @param {*} params
* @param {*} fields
*/
const getInfo = async function(params, fields = TableFields){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
const info = await Table.findOne({
where: params,
attributes: fields
})
return info
}
/**
* getList 接口
* @param {*} params
* @param {*} fields
* @param {*} order
*/
const getList = async function(params, fields = TableFields, order = [['id', 'ASC']]){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const list = await Table.findAll({
where : params,
attributes: fields,
order: order
})
return list
}
/**
* getListForPage 接口
* @param {*} params
* @param {*} fields
* @param {*} order
* @param {*} page
* @param {*} pageSize
*/
const getListForPage = async function(params, fields = TableFields, order = [['id', 'ASC']], page = 1, pageSize = 10){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const list = await Table.findAll({
where : params,
attributes: fields,
order: order,
limit: pageSize,
offset: (page - 1) * pageSize
})
return list
}
/**
* updateInfo 接口
* @param {*} params
* @param {*} data
*/
const updateInfo = async function(params, data){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
// 参数校验
const checkStatus = checkRawFieldType(Table.rawAttributes, data)
if (!checkStatus) {
tlConsoleError(TableName, "请求dao参数类型错误")
return null
}
const info = await Table.update(data, {
where: params
})
tlConsole(TableName, params, data, info)
if(info[0] === 0){
return null
}
return {
count: info[0]
}
}
/**
* deleteInfo 接口
* @param {*} params
*/
const deleteInfo = async function(params){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
const info = await Table.destroy({
where: params
})
tlConsole(TableName, params, info)
return info
}
/**
* getCount 接口
* @param {*} params
*/
const getCount = async function(params){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const count = await Table.count({
where : params
})
return count
}
module.exports = {
addInfo, addList,
getInfo, getList, getListForPage,
updateInfo,
deleteInfo,
getCount,
}

View File

@ -1,4 +1,4 @@
const { DataTypes, Sequelize } = require('sequelize');
const { DataTypes } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_channel_user')
const Table = model(dbClient, DataTypes).TlChannelUser
@ -201,7 +201,13 @@ const updateInfo = async function(params, data){
tlConsole(TableName, params, data, info)
return info
if(info[0] === 0){
return null
}
return {
count: info[0]
}
}

View File

@ -0,0 +1,339 @@
const { DataTypes } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_cloud_file')
const Table = model(dbClient, DataTypes).TlCloudFile
const TableName = fields.Name
const TableDef = fields.Def
const TableFields = Object.keys(fields.Def).map(key => fields.Def[key])
const { tlConsoleError, tlConsole, checkRawFieldType } = require("../../src/utils/utils");
/**
* addInfo 接口
* @param {*} data
*/
const addInfo = async function(data){
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
// 参数校验
const checkStatus = checkRawFieldType(Table.rawAttributes, data)
if (!checkStatus) {
tlConsoleError(TableName, "请求dao参数类型错误")
return null
}
const info = await Table.create(data)
tlConsole(TableName, data, info)
return info
}
/**
* addList 接口
* @param {*} dataList
*/
const addList = async function(dataList){
if(dataList.length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
for(let data of dataList){
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
// 参数校验
const checkStatus = checkRawFieldType(Table.rawAttributes, data)
if (!checkStatus) {
tlConsoleError(TableName, "请求dao参数类型错误")
return null
}
}
const list = await Table.bulkCreate(dataList)
tlConsole(TableName, dataList, list)
return list
}
/**
* getInfo 接口
* @param {*} params
* @param {*} fields
*/
const getInfo = async function(params, fields = TableFields){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
const info = await Table.findOne({
where: params,
attributes: fields
})
return info
}
/**
* getInfoDeleted 接口
* @param {*} params
* @param {*} fields
* @returns
*/
const getInfoDeleted = async function(params, fields = TableFields){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
const info = await Table.findOne({
where: params,
paranoid: false,
attributes: fields
})
return info
}
/**
* getList 接口
* @param {*} params
* @param {*} fields
* @param {*} order
*/
const getList = async function(params, fields = TableFields, order = [['id', 'ASC']]){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const list = await Table.findAll({
where : params,
attributes: fields,
order: order
})
return list
}
/**
* getListForPage 接口
* @param {*} params
* @param {*} fields
* @param {*} order
* @param {*} page
* @param {*} pageSize
*/
const getListForPage = async function(params, fields = TableFields, order = [['id', 'ASC']], page = 1, pageSize = 10){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const list = await Table.findAll({
where : params,
attributes: fields,
order: order,
limit: pageSize,
offset: (page - 1) * pageSize
})
return list
}
/**
* getListDeleted 接口
* @param {*} params
* @param {*} fields
* @param {*} order
*/
const getListDeleted = async function(params, fields = TableFields, order = [['id', 'ASC']]){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const list = await Table.findAll({
where : params,
paranoid: false,
attributes: fields,
order: order
})
return list
}
/**
* getListDeletedForPage 接口
* @param {*} params
* @param {*} fields
* @param {*} order
* @param {*} page
* @param {*} pageSize
*/
const getListDeletedForPage = async function(params, fields = TableFields, order = [['id', 'ASC']], page = 1, pageSize = 10){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const list = await Table.findAll({
where : params,
paranoid: false,
attributes: fields,
order: order,
limit: pageSize,
offset: (page - 1) * pageSize
})
return list
}
/**
* updateInfo 接口
* @param {*} params
* @param {*} data
*/
const updateInfo = async function(params, data){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
// 参数校验
const checkStatus = checkRawFieldType(Table.rawAttributes, data)
if (!checkStatus) {
tlConsoleError(TableName, "请求dao参数类型错误")
return null
}
const info = await Table.update(data, {
where: params
})
tlConsole(TableName, params, data, info)
if(info[0] === 0){
return null
}
return {
count: info[0]
}
}
/**
* deleteInfo 接口
* @param {*} params
*/
const deleteInfo = async function(params){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
const info = await Table.destroy({
where: params
})
tlConsole(TableName, params, info)
return info
}
/**
* restoreInfo 接口
* @param {*} params
*/
const restoreInfo = async function(params){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
const info = await Table.restore({
where: params
})
tlConsole(TableName, params, info)
return info
}
/**
* getCount 接口
* @param {*} params
*/
const getCount = async function(params){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const count = await Table.count({
where : params
})
return count
}
/**
* getCountDeleted 接口
* @param {*} params
*/
const getCountDeleted = async function(params){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const count = await Table.count({
where : params,
paranoid: false
})
return count
}
/**
* deleteInfoForce 接口
* @param {*} params
* @returns
*/
const deleteInfoForce = async function(params){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
const info = await Table.destroy({
where: params,
force: true,
})
tlConsole(TableName, params, info)
return info
}
module.exports = {
addInfo, addList,
getInfo, getList, getListDeleted, getListForPage, getListDeletedForPage, getInfoDeleted,
updateInfo,
deleteInfo, restoreInfo, deleteInfoForce,
getCount, getCountDeleted
}

View File

@ -1,4 +1,4 @@
const { DataTypes, where } = require('sequelize');
const { DataTypes } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_company')
const Table = model(dbClient, DataTypes).TlCompany
@ -156,7 +156,13 @@ const updateInfo = async function(params, data){
tlConsole(TableName, params, data, info)
return info
if(info[0] === 0){
return null
}
return {
count: info[0]
}
}

211
src/dao/tl_cut_paste_dao.js Normal file
View File

@ -0,0 +1,211 @@
const { DataTypes, where } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_cut_paste')
const Table = model(dbClient, DataTypes).TlCutPaste
const TableName = fields.Name
const TableFields = Object.keys(fields.Def).map(key => fields.Def[key])
const { tlConsoleError, tlConsole, checkRawFieldType } = require("../utils/utils");
/**
* addInfo 接口
* @param {*} data
*/
const addInfo = async function(data){
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
// 参数校验
const checkStatus = checkRawFieldType(Table.rawAttributes, data)
if (!checkStatus) {
tlConsoleError(TableName, "请求dao参数类型错误")
return null
}
const info = await Table.create(data)
tlConsole(TableName, data, info)
return info
}
/**
* addList 接口
* @param {*} dataList
*/
const addList = async function(dataList){
if(dataList.length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
for(let data of dataList){
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
// 参数校验
const checkStatus = checkRawFieldType(Table.rawAttributes, data)
if (!checkStatus) {
tlConsoleError(TableName, "请求dao参数类型错误")
return null
}
}
const list = await Table.bulkCreate(dataList)
tlConsole(TableName, dataList, list)
return list
}
/**
* getInfo 接口
* @param {*} params
* @param {*} fields
*/
const getInfo = async function(params, fields = TableFields){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
const info = await Table.findOne({
where: params,
attributes: fields
})
return info
}
/**
* getList 接口
* @param {*} params
* @param {*} fields
* @param {*} order
*/
const getList = async function(params, fields = TableFields, order = [['id', 'ASC']]){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const list = await Table.findAll({
where : params,
attributes: fields,
order: order
})
return list
}
/**
* getListForPage 接口
* @param {*} params
* @param {*} fields
* @param {*} order
* @param {*} page
* @param {*} pageSize
*/
const getListForPage = async function(params, fields = TableFields, order = [['id', 'ASC']], page = 1, pageSize = 10){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const list = await Table.findAll({
where : params,
attributes: fields,
order: order,
offset: (page - 1) * pageSize,
limit: pageSize
})
return list
}
/**
* updateInfo 接口
* @param {*} params
*/
const updateInfo = async function(params, data){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
// 参数校验
const checkStatus = checkRawFieldType(Table.rawAttributes, data)
if (!checkStatus) {
tlConsoleError(TableName, "请求dao参数类型错误")
return null
}
const info = await Table.update(data, {
where: params
})
tlConsole(TableName, params, data, info)
if(info[0] === 0){
return null
}
return {
count: info[0]
}
}
/**
* deleteInfo 接口
* @param {*} params
*/
const deleteInfo = async function(params){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
const info = await Table.destroy({
where: params
})
tlConsole(TableName, params, info)
return info
}
/**
* getCount 接口
* @param {*} params
*/
const getCount = async function(params){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const count = await Table.count({
where : params
})
return count
}
module.exports = {
addInfo, addList,
getInfo, getList, getListForPage,
updateInfo,
deleteInfo,
getCount,
}

View File

@ -0,0 +1,238 @@
const { DataTypes, where } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_cut_paste_detail')
const Table = model(dbClient, DataTypes).TlCutPasteDetail
const TableName = fields.Name
const TableFields = Object.keys(fields.Def).map(key => fields.Def[key])
const { tlConsoleError, tlConsole, checkRawFieldType } = require("../utils/utils");
/**
* addInfo 接口
* @param {*} data
*/
const addInfo = async function(data){
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
// 参数校验
const checkStatus = checkRawFieldType(Table.rawAttributes, data)
if (!checkStatus) {
tlConsoleError(TableName, "请求dao参数类型错误")
return null
}
const info = await Table.create(data)
tlConsole(TableName, data, info)
return info
}
/**
* addList 接口
* @param {*} dataList
*/
const addList = async function(dataList){
if(dataList.length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
for(let data of dataList){
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
// 参数校验
const checkStatus = checkRawFieldType(Table.rawAttributes, data)
if (!checkStatus) {
tlConsoleError(TableName, "请求dao参数类型错误")
return null
}
}
const list = await Table.bulkCreate(dataList)
tlConsole(TableName, dataList, list)
return list
}
/**
* getInfo 接口
* @param {*} params
* @param {*} fields
*/
const getInfo = async function(params, fields = TableFields){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
const info = await Table.findOne({
where: params,
attributes: fields
})
return info
}
/**
* getList 接口
* @param {*} params
* @param {*} fields
* @param {*} order
*/
const getList = async function(params, fields = TableFields, order = [['id', 'ASC']]){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const list = await Table.findAll({
where : params,
attributes: fields,
order: order
})
return list
}
/**
* getListForPage 接口
* @param {*} params
* @param {*} fields
* @param {*} order
* @param {*} page
* @param {*} pageSize
*/
const getListForPage = async function(params, fields = TableFields, order = [['id', 'ASC']], page = 1, pageSize = 10){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const list = await Table.findAll({
where : params,
attributes: fields,
order: order,
offset: (page - 1) * pageSize,
limit: pageSize
})
return list
}
/**
* updateInfo 接口
* @param {*} params
*/
const updateInfo = async function(params, data){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
// 参数校验
const checkStatus = checkRawFieldType(Table.rawAttributes, data)
if (!checkStatus) {
tlConsoleError(TableName, "请求dao参数类型错误")
return null
}
const info = await Table.update(data, {
where: params
})
tlConsole(TableName, params, data, info)
if(info[0] === 0){
return null
}
return {
count: info[0]
}
}
/**
* deleteInfo 接口
* @param {*} params
*/
const deleteInfo = async function(params){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
const info = await Table.destroy({
where: params
})
tlConsole(TableName, params, info)
return info
}
/**
* getCount 接口
* @param {*} params
*/
const getCount = async function(params){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const count = await Table.count({
where : params
})
return count
}
/**
* getGroupCount 接口
* @param {*} params
* @param {*} group
*/
const getGroupCount = async function(params, group){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
if(Object.keys(group).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const count = await Table.count({
where : params,
attributes: [group],
group: group,
})
return count
}
module.exports = {
addInfo, addList,
getInfo, getList, getListForPage,
updateInfo,
deleteInfo,
getCount,
getGroupCount
}

View File

@ -1,4 +1,4 @@
const { DataTypes, where } = require('sequelize');
const { DataTypes } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_role')
const Table = model(dbClient, DataTypes).TlRole
@ -156,7 +156,13 @@ const updateInfo = async function(params, data){
tlConsole(TableName, params, data, info)
return info
if(info[0] === 0){
return null
}
return {
count: info[0]
}
}

View File

@ -1,4 +1,4 @@
const { DataTypes, where } = require('sequelize');
const { DataTypes } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_user_apply')
const Table = model(dbClient, DataTypes).TlUserApply
@ -156,7 +156,13 @@ const updateInfo = async function(params, data){
tlConsole(TableName, params, data, info)
return info
if(info[0] === 0){
return null
}
return {
count: info[0]
}
}

View File

@ -1,4 +1,4 @@
const { DataTypes, where } = require('sequelize');
const { DataTypes } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_user_auth')
const Table = model(dbClient, DataTypes).TlUserAuth
@ -156,7 +156,13 @@ const updateInfo = async function(params, data){
tlConsole(TableName, params, data, info)
return info
if(info[0] === 0){
return null
}
return {
count: info[0]
}
}

View File

@ -0,0 +1,211 @@
const { DataTypes } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_user_clear')
const Table = model(dbClient, DataTypes).TlUserClear
const TableName = fields.Name
const TableFields = Object.keys(fields.Def).map(key => fields.Def[key])
const { tlConsoleError, tlConsole, checkRawFieldType } = require("../utils/utils");
/**
* addInfo 接口
* @param {*} data
*/
const addInfo = async function(data){
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
// 参数校验
const checkStatus = checkRawFieldType(Table.rawAttributes, data)
if (!checkStatus) {
tlConsoleError(TableName, "请求dao参数类型错误")
return null
}
const info = await Table.create(data)
tlConsole(TableName, data, info)
return info
}
/**
* addList 接口
* @param {*} dataList
*/
const addList = async function(dataList){
if(dataList.length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
for(let data of dataList){
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
// 参数校验
const checkStatus = checkRawFieldType(Table.rawAttributes, data)
if (!checkStatus) {
tlConsoleError(TableName, "请求dao参数类型错误")
return null
}
}
const list = await Table.bulkCreate(dataList)
tlConsole(TableName, dataList, list)
return list
}
/**
* getInfo 接口
* @param {*} params
* @param {*} fields
*/
const getInfo = async function(params, fields = TableFields){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
const info = await Table.findOne({
where: params,
attributes: fields
})
return info
}
/**
* getList 接口
* @param {*} params
* @param {*} fields
* @param {*} order
*/
const getList = async function(params, fields = TableFields, order = [['id', 'ASC']]){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const list = await Table.findAll({
where : params,
attributes: fields,
order: order,
})
return list
}
/**
* getListForPage 接口
* @param {*} params
* @param {*} fields
* @param {*} order
* @param {*} page
* @param {*} pageSize
*/
const getListForPage = async function(params, fields = TableFields, order = [['id', 'ASC']], page = 1, pageSize = 10){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const list = await Table.findAll({
where : params,
attributes: fields,
order: order,
offset: (page - 1) * pageSize,
limit: pageSize
})
return list
}
/**
* updateInfo 接口
* @param {*} params
* @param {*} data
*/
const updateInfo = async function(params, data){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
// 参数校验
const checkStatus = checkRawFieldType(Table.rawAttributes, data)
if (!checkStatus) {
tlConsoleError(TableName, "请求dao参数类型错误")
return null
}
const info = await Table.update(data, {
where: params
})
tlConsole(TableName, params, data, info)
if(info[0] === 0){
return null
}
return {
count: info[0]
}
}
/**
* deleteInfo 接口
* @param {*} params
*/
const deleteInfo = async function(params){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数为空")
return null
}
const info = await Table.destroy({
where: params
})
tlConsole(TableName, params, info)
return info
}
/**
* getCount 接口
* @param {*} params
*/
const getCount = async function(params){
if(Object.keys(params).length === 0){
tlConsoleError(TableName, "请求dao参数有为空项")
return null
}
const count = await Table.count({
where : params
})
return count
}
module.exports = {
addInfo, addList,
getInfo, getList, getListForPage,
updateInfo,
deleteInfo,
getCount,
}

View File

@ -1,4 +1,4 @@
const { DataTypes, where } = require('sequelize');
const { DataTypes } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_user_config')
const Table = model(dbClient, DataTypes).TlUserConfig
@ -156,7 +156,13 @@ const updateInfo = async function(params, data){
tlConsole(TableName, params, data, info)
return info
if(info[0] === 0){
return null
}
return {
count: info[0]
}
}

View File

@ -1,4 +1,4 @@
const { DataTypes, where } = require('sequelize');
const { DataTypes } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_user')
const Table = model(dbClient, DataTypes).TlUser
@ -157,7 +157,13 @@ const updateInfo = async function(params, data){
tlConsole(TableName, params, data, info)
return info
if(info[0] === 0){
return null
}
return {
count: info[0]
}
}

View File

@ -1,4 +1,4 @@
const { DataTypes, where } = require('sequelize');
const { DataTypes } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_user_finger_print')
const Table = model(dbClient, DataTypes).TlUserFingerPrint
@ -156,7 +156,13 @@ const updateInfo = async function(params, data){
tlConsole(TableName, params, data, info)
return info
if(info[0] === 0){
return null
}
return {
count: info[0]
}
}

View File

@ -156,7 +156,13 @@ const updateInfo = async function(params, data){
tlConsole(TableName, params, data, info)
return info
if(info[0] === 0){
return null
}
return {
count: info[0]
}
}

View File

@ -1,4 +1,4 @@
const { DataTypes, where } = require('sequelize');
const { DataTypes } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_user_read')
const Table = model(dbClient, DataTypes).TlUserRead
@ -156,7 +156,13 @@ const updateInfo = async function(params, data){
tlConsole(TableName, params, data, info)
return info
if(info[0] === 0){
return null
}
return {
count: info[0]
}
}

View File

@ -1,4 +1,4 @@
const { DataTypes, where } = require('sequelize');
const { DataTypes } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_user_tag')
const Table = model(dbClient, DataTypes).TlUserTag
@ -156,7 +156,13 @@ const updateInfo = async function(params, data){
tlConsole(TableName, params, data, info)
return info
if(info[0] === 0){
return null
}
return {
count: info[0]
}
}

View File

@ -0,0 +1,133 @@
const crypto = require('crypto');
const { get_env_config } = require("./../../conf/env_config");
const {
tlConsoleWarn, encryptStr, verifyEncryptStr, setBit
} = require("./../../src/utils/utils");
//获取环境变量
const conf = get_env_config();
const userService = require('../service/user/tl_user_service')
const companyService = require('../service/company/tl_company_service')
const { fields: userFields } = require('../tables/tl_user')
const { inner: TlRoleInner } = require('../tables/tl_role')
const { fields: companyFields } = require('../tables/tl_company')
const TlUserDef = userFields.Def
const TlCompanyDef = companyFields.Def
const TlCompanyFlag = companyFields.Flag
/**
* 检查默认数据是否已经初始化,默认企业、默认管理员
*/
const checkDefaultBeforStartServer = async function(){
const adminUserEmail = conf.admin_user_email;
const adminPassword = conf.admin_password;
if(!adminUserEmail || !adminPassword){
tlConsoleWarn('please set admin_user_email and admin_password in tlrtcapp.env file');
process.exit(1);
}
// 检查公司是否已经初始化
const companyInfo = await companyService.getInfoByCode({
code: 'tl-rtc-app'
})
let companyId = 0;
// 默认创建一个公司
if(Object.keys(companyInfo).length === 0){
const result = await companyService.addInfo({
name: 'TL-RTC-APP默认企业',
address: '广州市海珠区',
phone: '1234567890',
email: adminUserEmail,
website: 'https://github.com/tl-open-source/tl-rtc-app',
description: 'TL-RTC-APP默认企业',
logo: '/image/tlrtcapp-logo.svg',
code: 'tl-rtc-app',
flag: setBit(0, TlCompanyFlag.IS_OPEN_REGISTER, true)
})
if(Object.keys(result).length === 0){
tlConsoleWarn('auto init default company failed');
process.exit(1);
}
companyId = result[TlCompanyDef.id];
tlConsoleWarn('auto init default company success...', companyId);
}else{
companyId = companyInfo[TlCompanyDef.id];
}
tlConsoleWarn("auto check company done...", companyId);
// 检查管理员是否已经初始化
const adminUserInfo = await userService.getAdminUser({
email: adminUserEmail
})
if(Object.keys(adminUserInfo).length === 0){
const salt = crypto.randomBytes(16).toString('hex')
const saltPassword = encryptStr({
str: adminPassword,
salt: salt
})
const result = await userService.addInfo({
companyId,
email: adminUserEmail,
password: saltPassword,
salt,
name: '管理员',
roleId: TlRoleInner.user.admin.id,
})
if(Object.keys(result).length === 0){
tlConsoleWarn('auto init admin failed');
process.exit(1);
}
tlConsoleWarn('auto init admin success...', result[TlUserDef.id]);
}else{
// 检查是否需要更新管理员密码
if(!verifyEncryptStr({
inputStr: adminPassword,
hashedStr: adminUserInfo[TlUserDef.password],
salt: adminUserInfo[TlUserDef.salt]
})){
const salt = crypto.randomBytes(16).toString('hex')
const saltPassword = encryptStr({
str: adminPassword,
salt: salt
})
const result = await userService.updateInfoById({
companyId: adminUserInfo[TlUserDef.companyId],
id: adminUserInfo[TlUserDef.id],
}, {
[TlUserDef.password]: saltPassword,
[TlUserDef.salt]: salt
})
if(Object.keys(result).length === 0){
tlConsoleWarn('auto update admin password failed');
process.exit(1);
}
tlConsoleWarn('auto update admin password success...');
}
}
tlConsoleWarn("auto check admin done...", adminUserEmail);
return true;
}
module.exports = {
checkDefaultBeforStartServer
}

View File

@ -1,12 +1,10 @@
const {
tlConsoleApiIcon, tlConsole, tlConsoleError,
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess
tlConsole, tlResponseForbidden,
} = require("../utils/utils");
const {
LOGIN : {
LOGIN_TOKEN_KEY,
WEBSITE_LOGIN_TOKEN_KEY
SYSTEM_LOGIN_TOKEN_KEY
}
} = require('../utils/constant');
const userSessionService = require('../service/user/tl_user_session_service')
@ -18,27 +16,18 @@ const loginAuthIngoreApi = [
// 登录
'/api/web/user-login/login-state',
'/api/web/user-login/website-login-state',
'/api/web/user-login/system-login-state',
'/api/web/user-login/login-by-account',
'/api/web/user-login/login-by-mobile',
'/api/web/user-login/login-by-email',
'/api/web/user-login/login-by-code',
'/api/web/user-login/login-by-wechat',
'/api/web/user-login/login-by-qq',
'/api/web/user-login/login-by-qy-wechat',
'/api/web/user-login/login-by-fp',
'/api/web/user-login/login-by-website',
'/api/web/user-login/login-by-system',
// 注册
'/api/web/user-register/register-by-account',
'/api/web/user-register/register-by-mobile',
'/api/web/user-register/register-by-email',
'/api/web/user-register/get-email-code',
'/api/web/user-register/register-website-user',
// 退出
'/api/web/user-logout/logout',
'/api/web/user-logout/website-logout',
'/api/web/user-logout/system-logout',
]
@ -62,16 +51,21 @@ const loginAuthHandler = async function(request, response, next) {
}
}
const isWebsite = request.url.includes("/website-")
let tokenKey = LOGIN_TOKEN_KEY
if(isWebsite){
tokenKey = WEBSITE_LOGIN_TOKEN_KEY
const isSystem = request.url.includes("/system-")
if(isSystem){
tokenKey = SYSTEM_LOGIN_TOKEN_KEY
}
const { [tokenKey]: token } = request.cookies;
let { [tokenKey]: token } = request.cookies;
if (!token) {
return response.json(tlResponseForbidden("不在线, 请先登录"))
// 如果没有token,尝试从请求头中获取
token = request.headers[tokenKey];
if (!token) {
// 如果请求头中也没有token,返回401
return response.json(tlResponseForbidden("不在线, 请先登录"))
}
}
const {
@ -86,11 +80,7 @@ const loginAuthHandler = async function(request, response, next) {
loginUserMobile
} = await userSessionService.getUserInfoByToken({token})
if(isWebsite){
tlConsole("website login check:", request.url, token, loginUserCompanyId, loginUserId)
}else{
tlConsole("login check:", request.url, token, loginUserCompanyId, loginUserId)
}
tlConsole("login check:", request.url, token, loginUserCompanyId, loginUserId)
if (!loginUserCompanyId) {
return response.json(tlResponseForbidden("不在线, 请先登录"))

View File

@ -1,7 +1,5 @@
const {
tlConsoleApiIcon, tlConsole, tlConsoleError,
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess
tlConsole, tlConsoleError, tlResponseForbidden,
} = require("../utils/utils");
const {
LOGIN : {
@ -21,27 +19,25 @@ const loginRoleIngoreApi = [
// 登录
'/api/web/user-login/login-state',
'/api/web/user-login/website-login-state',
'/api/web/user-login/system-login-state',
'/api/web/user-login/login-by-account',
'/api/web/user-login/login-by-mobile',
'/api/web/user-login/login-by-email',
'/api/web/user-login/login-by-code',
'/api/web/user-login/login-by-wechat',
'/api/web/user-login/login-by-qq',
'/api/web/user-login/login-by-qy-wechat',
'/api/web/user-login/login-by-fp',
'/api/web/user-login/login-by-website',
'/api/web/user-login/login-by-system',
// 注册
'/api/web/user-register/register-by-account',
'/api/web/user-register/register-by-mobile',
'/api/web/user-register/register-by-email',
'/api/web/user-register/get-email-code',
'/api/web/user-register/register-website-user',
// 退出
'/api/web/user-logout/logout',
'/api/web/user-logout/website-logout',
'/api/web/user-logout/system-logout',
// 获取频道名称
'/api/web/channel/get-channel-name',
// 获取频道信息
'/api/web/channel/search-channel-by-id',
// 分享加入频道
'/api/web/channel-user/share-join-channel',
]
@ -55,7 +51,7 @@ const getRoleInfoById = function({roleId}){
const roleList = [
TlRoleInner.user.normal,
TlRoleInner.user.admin,
TlRoleInner.channel.creator,
TlRoleInner.channel.admin,
TlRoleInner.channel.member,
@ -172,14 +168,12 @@ const loginRoleHandler = async function(request, response, next) {
return next()
}
const isWebsite = request.url.includes("/website-")
const {
loginUserCompanyId,
loginUserCompanyName,
loginUserId,
loginUsername,
loginUserRoleId,
loginUserRoleId,
loginUserAvatar,
loginTime,
loginUserEmail,
@ -192,11 +186,7 @@ const loginRoleHandler = async function(request, response, next) {
let permissionId = getRequestApiPermissionId(request.url)
if(isWebsite){
tlConsole("website role check:", request.url, loginUserCompanyId, loginUserId, loginUserRoleId, permissionId)
}else{
tlConsole("role check:", request.url, loginUserCompanyId, loginUserId, loginUserRoleId, permissionId)
}
tlConsole("role check:", request.url, loginUserCompanyId, loginUserId, loginUserRoleId, permissionId)
if(!permissionId){
return response.json(tlResponseForbidden("请求无权限"))
@ -206,6 +196,7 @@ const loginRoleHandler = async function(request, response, next) {
roleId: loginUserRoleId,
permissionId: permissionId
})
if(!hasPermission){
return response.json(tlResponseForbidden("操作无权限"))
}
@ -274,6 +265,7 @@ const loginChannelRoleHandler = async function(request, response, next) {
permissionId: permissionId,
channelId: channelId
})
if(!hasPermission){
return response.json(tlResponseForbidden("操作无权限"))
}

View File

@ -0,0 +1,58 @@
const multer = require('multer')
const fs = require('fs')
const uuid = require('uuid')
const { get_env_config } = require("../../conf/env_config");
//获取环境变量
const conf = get_env_config();
const { genServiceSaveFileFolder } = require('../utils/oss/oss')
/**
* 配置 multer 存储
* @returns {Object} - multer 存储配置
*/
const storageConfig = function () {
// 配置 multer 存储
return multer.diskStorage({
// 设置文件存储路径
destination: function (request, file, callback) {
const loginInfo = request.ctx || {}
const {
loginUserCompanyId, loginUserId,
} = loginInfo
let path = genServiceSaveFileFolder({
companyId: loginUserCompanyId, userId: loginUserId
})
// 如果文件夹不存在则创建
if (!fs.existsSync(path)) {
fs.mkdirSync(path, {
recursive: true
})
}
callback(null, path)
},
// 设置文件名
filename: function (request, file, callback) {
// 获取文件后缀
const ext = file.originalname.split('.').pop()
// 生成文件名: 时间戳-随机数.后缀
const filename = `${uuid.v4()}.${ext}`
request.fileId = filename
callback(null, filename)
},
limits: {
fileSize: 1024 * 1024 * 5 // 5MB
},
})
}
module.exports = {
storageConfig,
}

View File

@ -1,10 +1,14 @@
const {
systemPermission,
channelPermission,
cloudPermission,
userPermission,
companyPermission,
configPermission,
cutPastePermission,
channelPerfix,
channelNoticePerfix,
channelUserPerfix,
} = require('./permission');
@ -19,13 +23,23 @@ const userNormalPermissions = function(){
// 频道权限
const channelKeys = Object.keys(channelPermission.channel).filter((key) => {
return ![
channelPerfix + "UPDATE_CHANNEL_NAME"
channelPerfix + "UPDATE_CHANNEL_NAME",
channelPerfix + "UPDATE_CHANNEL_CAN_SEARCH",
].includes(key)
})
channelKeys.forEach((key) => {
returnPermission.push(channelPermission.channel[key]);
})
const channelNoticeKeys = Object.keys(channelPermission.channelNotice).filter((key) => {
return ![
channelNoticePerfix + "ADD_CHANNEL_NOTICE"
].includes(key)
})
channelNoticeKeys.forEach((key) => {
returnPermission.push(channelPermission.channelNotice[key]);
})
const channelUserKeys = Object.keys(channelPermission.channelUser).filter((key) => {
return ![
channelUserPerfix + "ADD_CHANNEL_USER_ADMIN",
@ -39,7 +53,13 @@ const userNormalPermissions = function(){
returnPermission.push(channelPermission.channelUser[key]);
})
returnPermission.push(...Object.values(channelPermission.channelChat))
returnPermission.push(...Object.values(channelPermission.channelMedia))
returnPermission.push(...Object.values(channelPermission.channelFile))
// 资源库权限
Object.keys(cloudPermission).forEach((key) => {
returnPermission.push(...Object.values(cloudPermission[key]));
})
// 用户权限
Object.keys(userPermission).forEach((key) => {
returnPermission.push(...Object.values(userPermission[key]));
@ -48,22 +68,34 @@ const userNormalPermissions = function(){
Object.keys(configPermission).forEach((key) => {
returnPermission.push(...Object.values(configPermission[key]));
})
// 剪切板权限
Object.keys(cutPastePermission).forEach((key) => {
returnPermission.push(...Object.values(cutPastePermission[key]));
})
return returnPermission;
}
/**
* 系统管理员权限 - 所有权限
* 系统超级管理员权限 - 所有权限
* @returns
*/
const userAdminPermissions = function(){
let returnPermission = [];
// 系统管理员权限
Object.keys(systemPermission).forEach((key) => {
returnPermission.push(...Object.values(systemPermission[key]));
})
// 频道权限
Object.keys(channelPermission).forEach((key) => {
returnPermission.push(...Object.values(channelPermission[key]));
})
// 用户权限
// 资源库权限
Object.keys(cloudPermission).forEach((key) => {
returnPermission.push(...Object.values(cloudPermission[key]));
})
// 企业权限
Object.keys(companyPermission).forEach((key) => {
returnPermission.push(...Object.values(companyPermission[key]));
})
@ -75,6 +107,10 @@ const userAdminPermissions = function(){
Object.keys(configPermission).forEach((key) => {
returnPermission.push(...Object.values(configPermission[key]));
})
// 剪切板权限
Object.keys(cutPastePermission).forEach((key) => {
returnPermission.push(...Object.values(cutPastePermission[key]));
})
return returnPermission;
}

View File

@ -17,6 +17,9 @@ const userChannelCreatorPermissions = function(){
// 频道权限
returnPermission.push(...Object.values(channelPermission.channel))
returnPermission.push(...Object.values(channelPermission.channelChat))
returnPermission.push(...Object.values(channelPermission.channelMedia))
returnPermission.push(...Object.values(channelPermission.channelFile))
returnPermission.push(...Object.values(channelPermission.channelNotice))
returnPermission.push(...Object.values(channelPermission.channelUser))
return returnPermission;
@ -32,7 +35,8 @@ const userChannelAdminPermissions = function(){
// 频道权限
const channelKeys = Object.keys(channelPermission.channel).filter((key) => {
return ![
channelPerfix + "UPDATE_CHANNEL_NAME"
channelPerfix + "UPDATE_CHANNEL_NAME",
channelPerfix + "UPDATE_CHANNEL_CAN_SEARCH",
].includes(key)
})
channelKeys.forEach((key) => {
@ -52,6 +56,9 @@ const userChannelAdminPermissions = function(){
})
returnPermission.push(...Object.values(channelPermission.channelChat))
returnPermission.push(...Object.values(channelPermission.channelMedia))
returnPermission.push(...Object.values(channelPermission.channelFile))
returnPermission.push(...Object.values(channelPermission.channelNotice))
return returnPermission;
}
@ -66,13 +73,23 @@ const userChannelNormalPermissions = function(){
// 频道权限
const channelKeys = Object.keys(channelPermission.channel).filter((key) => {
return ![
channelPerfix + "UPDATE_CHANNEL_NAME"
channelPerfix + "UPDATE_CHANNEL_NAME",
channelPerfix + "UPDATE_CHANNEL_CAN_SEARCH",
].includes(key)
})
channelKeys.forEach((key) => {
returnPermission.push(channelPermission.channel[key]);
})
const channelNoticeKeys = Object.keys(channelPermission.channelNotice).filter((key) => {
return ![
channelNoticePerfix + "ADD_CHANNEL_NOTICE"
].includes(key)
})
channelNoticeKeys.forEach((key) => {
returnPermission.push(channelPermission.channelNotice[key]);
})
const channelUserKeys = Object.keys(channelPermission.channelUser).filter((key) => {
return ![
channelUserPerfix + "ADD_CHANNEL_USER_ADMIN",
@ -87,11 +104,14 @@ const userChannelNormalPermissions = function(){
})
returnPermission.push(...Object.values(channelPermission.channelChat))
returnPermission.push(...Object.values(channelPermission.channelMedia))
returnPermission.push(...Object.values(channelPermission.channelFile))
return returnPermission;
}
module.exports = {
userChannelCreatorPermissions,
userChannelAdminPermissions,

View File

@ -7,15 +7,25 @@
// 权限id基数
const systemPermissionIdBase = 1
const channelPermissionIdBase = 100000
const cloudPermissionIdBase = 200000
const companyPermissionIdBase = 300000
const userPermissionIdBase = 600000
const configPermissionIdBase = 700000
const userPermissionIdBase = 400000
const configPermissionIdBase = 500000
const cutPastePermissionIdBase = 600000
// key前缀
const systemPerfix = 'SYSTEM:'
const systemWebConfigPerfix = 'SYSTEM_WEB_CONFIG:'
const systemWebCompanyPerfix = 'SYSTEM_WEB_COMPANY:'
const systemWebUserPerfix = 'SYSTEM_WEB_USER:'
const systemWebChannelPerfix = 'SYSTEM_WEB_CHANNEL:'
const systemWebServicePerfix = 'SYSTEM_WEB_SERVICE:'
const channelPerfix = 'CHANNEL:'
const channelChatPerfix = 'CHANNEL_CHAT:'
const channelMediaPerfix = 'CHANNEL_MEDIA:'
const channelFilePerfix = 'CHANNEL_FILE:'
const channelNoticePerfix = 'CHANNEL_NOTICE:'
const channelUserPerfix = 'CHANNEL_USER:'
const cloudFilePerfix = 'CLOUD_FILE:'
const companyPerfix = 'COMPANY:'
const userPerfix = 'USER:'
const userApplyPerfix = 'USER_APPLY:'
@ -26,6 +36,9 @@ const userTagPerfix = 'USER_TAG:'
const userRegisterPerfix = 'USER_REGISTER:'
const userLoginPerfix = 'USER_LOGIN:'
const userLogoutPerfix = 'USER_LOGOUT:'
const userClearPerfix = 'USER_CLEAR:'
const configSkinPerfix = 'CONFIG_SKIN:'
const cutPastePerfix = 'CUT_PASTE:'
// 补充前缀
@ -38,7 +51,60 @@ const addPerfix = function(permission, perfix){
// 系统默认预设权限 1-999999
let systemPermission = {
systemWebConfig: { // 1 ~ 9999
// 获取网站配置
GET_SYSTEM_CONFIG: systemPermissionIdBase + 1,
// 更新网站配置
UPDATE_SYSTEM_CONFIG: systemPermissionIdBase + 2,
},
systemWebService: { // 10000 ~ 19999
// 重启服务
RESTART_SERVICE: systemPermissionIdBase + 10000,
// 获取服务状态
GET_SERVICE_STATUS: systemPermissionIdBase + 10001,
// 停止服务
STOP_SERVICE: systemPermissionIdBase + 10002,
// 启动服务
START_SERVICE: systemPermissionIdBase + 10003,
// 启动socket
START_SOCKET: systemPermissionIdBase + 10004,
},
systemWebCompany: { // 20000 ~ 29999
// 获取公司信息
GET_COMPANY_LIST: systemPermissionIdBase + 20000,
// 更新公司信息
UPDATE_COMPANY: systemPermissionIdBase + 20001,
// 添加公司
ADD_COMPANY: systemPermissionIdBase + 20002,
// 删除公司
DELETE_COMPANY: systemPermissionIdBase + 20003,
// 获取公司信息
GET_COMPANY_INFO: systemPermissionIdBase + 20004,
},
systemWebUser: { // 30000 ~ 39999
// 删除用户
DELETE_USER: systemPermissionIdBase + 30000,
// 获取用户列表
GET_USER_LIST: systemPermissionIdBase + 30001,
// 更新用户信息
UPDATE_USER: systemPermissionIdBase + 30002,
// 添加用户
ADD_USER: systemPermissionIdBase + 30003,
// 获取用户信息
GET_USER_INFO: systemPermissionIdBase + 30004,
},
systemWebChannel: { // 40000 ~ 49999
// 添加频道
ADD_CHANNEL: systemPermissionIdBase + 40000,
// 更新频道
UPDATE_CHANNEL: systemPermissionIdBase + 40001,
// 删除频道
DELETE_CHANNEL: systemPermissionIdBase + 40002,
// 获取频道列表
GET_CHANNEL_LIST: systemPermissionIdBase + 40003,
// 获取频道用户列表
GET_CHANNEL_USER_LIST: systemPermissionIdBase + 40004,
},
}
// 频道权限 100000 - 199999
@ -49,19 +115,23 @@ let channelPermission = {
// 获取频道列表
GET_CHANNEL_LIST: channelPermissionIdBase + 2,
// 获取频道信息
GET_CHANNEL_INFO: channelPermissionIdBase + 4,
GET_CHANNEL_INFO: channelPermissionIdBase + 3,
// 获取频道名称
GET_CHANNEL_NAME: channelPermissionIdBase + 5,
GET_CHANNEL_NAME: channelPermissionIdBase + 4,
// 修改频道名称
UPDATE_CHANNEL_NAME: channelPermissionIdBase + 6,
UPDATE_CHANNEL_NAME: channelPermissionIdBase + 5,
// 获取频道聊天记录
GET_CHANNEL_MESSAGE: channelPermissionIdBase + 7,
GET_CHANNEL_MESSAGE: channelPermissionIdBase + 6,
// 获取频道列表聊天记录
GET_CHANNEL_MESSAGE_LIST: channelPermissionIdBase + 8,
GET_CHANNEL_MESSAGE_LIST: channelPermissionIdBase + 7,
// 搜索频道聊天记录
SEARCH_CHANNEL_MESSAGE: channelPermissionIdBase + 8,
// 通过频道id获取频道信息
SEARCH_CHANNEL_BY_ID: channelPermissionIdBase + 10,
SEARCH_CHANNEL_BY_ID: channelPermissionIdBase + 9,
// 获取群组频道列表
GET_GROUP_CHANNEL_LIST: channelPermissionIdBase + 11,
GET_GROUP_CHANNEL_LIST: channelPermissionIdBase + 10,
// 修改频道是否可以被搜索
UPDATE_CHANNEL_CAN_SEARCH: channelPermissionIdBase + 11,
},
channelChat: { // 101000 ~ 101999
// 发送好友频道聊天
@ -72,14 +142,33 @@ let channelPermission = {
ADD_REPLY_FRIEND_CHANNEL_CHAT: channelPermissionIdBase + 1002,
// 回复多人频道聊天
ADD_REPLY_GROUP_CHANNEL_CHAT: channelPermissionIdBase + 1003,
// 撤回聊天消息
ROLLBACK_CHANNEL_CHAT: channelPermissionIdBase + 1004,
},
channelFile: { // 102000 ~ 102999
// 发送好友频道离线文件消息
ADD_FRIEND_CHANNEL_OFFLINE_FILE: channelPermissionIdBase + 2001,
// 发送群聊频道离线文件消息
ADD_GROUP_CHANNEL_OFFLINE_FILE: channelPermissionIdBase + 2002,
},
channelMedia: { // 103000 ~ 103999
// 发送好友频道语音聊天消息
ADD_FRIEND_CHANNEL_AUDIO: channelPermissionIdBase + 3001,
// 发送好友频道视频消息
ADD_FRIEND_CHANNEL_VIDEO: channelPermissionIdBase + 3002,
// 发送多人频道语音聊天消息
ADD_GROUP_CHANNEL_AUDIO: channelPermissionIdBase + 3003,
// 发送多人频道视频消息
ADD_GROUP_CHANNEL_VIDEO: channelPermissionIdBase + 3004,
},
channelNotice: { // 104000 ~ 104999
// 发布频道公告
ADD_CHANNEL_NOTICE: channelPermissionIdBase + 4001,
// 获取频道公告
GET_CHANNEL_NOTICE_LIST: channelPermissionIdBase + 4002,
},
channelUser: { // 105000 ~ 105999
// 系统管理员添加频道用户
ADD_CHANNEL_USER: channelPermissionIdBase + 5001,
// 分享加入群聊
SHARE_JOIN_CHANNEL: channelPermissionIdBase + 5002,
// 添加频道普通身份用户
ADD_CHANNEL_USER_NORMAL: channelPermissionIdBase + 5003,
// 批量添加频道普通身份用户
@ -105,19 +194,27 @@ let channelPermission = {
}
}
// 资源库权限 200000 - 299999
let cloudPermission = {
cloudFile: { // 200000 ~ 200999
// 上传文件
UPLOAD_FILE: cloudPermissionIdBase + 1,
// 从服务器获取云文件
DOWNLOAD_SERVER_FILE: cloudPermissionIdBase + 2,
},
}
// 企业权限 300000 - 399999
let companyPermission = {
company: { // 300000 ~ 300999
// 添加企业
ADD_COMPANY: companyPermissionIdBase + 1,
// 获取企业
GET_COMPANY: companyPermissionIdBase + 2,
// 获取企业信息
GET_COMPANY: companyPermissionIdBase + 1,
}
}
// 用户权限 600000 - 699999
// 用户权限 400000 - 499999
let userPermission = {
user: { // 600000 ~ 600999
user: { // 400000 ~ 400999
// 搜索用户
SEARCH_USER_BY_NAME: userPermissionIdBase + 1,
// 搜索用户通过id
@ -127,7 +224,7 @@ let userPermission = {
// 绑定邮箱
BIND_EMAIL: userPermissionIdBase + 4
},
userApply: { // 601000 ~ 601999
userApply: { // 401000 ~ 401999
// 添加好友申请
ADD_USER_FRIEND_APPLY: userPermissionIdBase + 1000,
// 通过好友申请
@ -138,8 +235,18 @@ let userPermission = {
GET_USER_FRIEND_OTHER_APPLY_LIST: userPermissionIdBase + 1003,
// 获取自己发出的用户好友申请列表
GET_USER_FRIEND_SELF_APPLY_LIST: userPermissionIdBase + 1004,
// 获取自己收到的群聊申请列表
GET_USER_GROUP_OTHER_APPLY_LIST: userPermissionIdBase + 1005,
// 获取自己发出的群聊申请列表
GET_USER_GROUP_SELF_APPLY_LIST: userPermissionIdBase + 1006,
// 通过群聊申请
PASS_USER_GROUP: userPermissionIdBase + 1007,
// 拒绝群聊申请
REJECT_USER_GROUP: userPermissionIdBase + 1008,
// 添加群聊申请
ADD_USER_GROUP_APPLY: userPermissionIdBase + 1009,
},
userFriend: { // 602000 ~ 602999
userFriend: { // 402000 ~ 402999
// 删除好友
DELETE_USER_FRIEND: userPermissionIdBase + 2000,
// 更新好友信息备注
@ -151,7 +258,7 @@ let userPermission = {
// 关注好友
UPDATE_USER_FRIEND_SPECIAL: userPermissionIdBase + 2004,
},
userConfig: { // 603000 ~ 603999
userConfig: { // 403000 ~ 403999
// 获取用户配置
GET_USER_CONFIG: userPermissionIdBase + 3000,
// 更新用户通用设置
@ -167,7 +274,7 @@ let userPermission = {
// 更新用户其他设置
UPDATE_USER_CONFIG_OTHER: userPermissionIdBase + 3006,
},
userRead: { // 604000 ~ 604999
userRead: { // 404000 ~ 404999
// 更新频道文件/媒体/聊天消息已读记录
UPDATE_CHANNEL_MUTIL_READ: userPermissionIdBase + 4000,
// 更新频道聊天消息已读记录
@ -182,45 +289,97 @@ let userPermission = {
UPDATE_USER_FRIEND_APPLY_PASS_READ: userPermissionIdBase + 4005,
// 新增拒绝申请消息已读记录
UPDATE_USER_FRIEND_APPLY_REJECT_READ: userPermissionIdBase + 4006,
// 新增群聊申请消息已读记录
UPDATE_USER_GROUP_APPLY_READ: userPermissionIdBase + 4007,
// 新增通过群聊申请消息已读记录
UPDATE_USER_GROUP_APPLY_PASS_READ: userPermissionIdBase + 4008,
// 新增拒绝群聊申请消息已读记录
UPDATE_USER_GROUP_APPLY_REJECT_READ: userPermissionIdBase + 4009,
},
userTag: { // 605000 ~ 605999
userTag: { // 405000 ~ 405999
// 添加频道分组标签
ADD_CHANNEL_TAG: userPermissionIdBase + 5000,
// 添加好友分组标签
ADD_FRIEND_TAG: userPermissionIdBase + 5001,
// 添加资源库分组标签
ADD_CLOUD_TAG: userPermissionIdBase + 5002,
// 获取频道分组标签列表
GET_CHANNEL_TAG_LIST: userPermissionIdBase + 5003,
GET_CHANNEL_TAG_LIST: userPermissionIdBase + 5002,
// 获取好友分组标签列表
GET_FRIEND_TAG_LIST: userPermissionIdBase + 5004,
// 获取资源库分组标签列表
GET_CLOUD_TAG_LIST: userPermissionIdBase + 5005,
GET_FRIEND_TAG_LIST: userPermissionIdBase + 5003,
// 删除标签
DELETE_TAG: userPermissionIdBase + 5006,
DELETE_TAG: userPermissionIdBase + 5004,
},
userRegister: { // 606000 ~ 606999
userRegister: { // 406000 ~ 406999
},
userLogin: { // 607000 ~ 607999
userLogin: { // 407000 ~ 407999
},
userLogout: { // 608000 ~ 608999
userLogout: { // 408000 ~ 408999
},
userClear: { // 409000 ~ 409999
// 更新频道聊天清理记录
UPDATE_CHANNEL_CHAT_CLEAR: userPermissionIdBase + 9000,
// 更新频道媒体清理记录
UPDATE_CHANNEL_MEDIA_CLEAR: userPermissionIdBase + 9001,
// 更新频道文件清理记录
UPDATE_CHANNEL_FILE_CLEAR: userPermissionIdBase + 9002,
// 更新频道多消息清理记录
UPDATE_CHANNEL_MUTIL_CLEAR: userPermissionIdBase + 9003,
}
}
// 配置权限 700000 - 799999
// 配置权限 500000 - 599999
const configPermission = {
skin: { // 700000 ~ 700999
GET_DETAIL: configPermissionIdBase + 1,
}
}
// 剪切板权限 600000 - 699999
const cutPastePermission = {
cutPaste: { // 600000 ~ 699999
// 添加剪切板
ADD_CUT_PASTE: cutPastePermissionIdBase + 1,
// 获取剪切板列表
GET_CUT_PASTE_LIST: cutPastePermissionIdBase + 2,
// 删除剪切板
DELETE_CUT_PASTE: cutPastePermissionIdBase + 3,
// 更新剪切板标题
UPDATE_CUT_PASTE_TITLE: cutPastePermissionIdBase + 4,
// 更新剪切板密码
UPDATE_CUT_PASTE_PASSWORD: cutPastePermissionIdBase + 5,
// 关闭剪切板
CLOSE_CUT_PASTE: cutPastePermissionIdBase + 6,
// 开启剪切板
OPEN_CUT_PASTE: cutPastePermissionIdBase + 7,
// 添加剪切板内容详情
ADD_CUT_PASTE_DETAIL: cutPastePermissionIdBase + 8,
// 获取剪切板内容详情列表
GET_CUT_PASTE_DETAIL_LIST: cutPastePermissionIdBase + 9,
// 删除剪切板内容详情
DELETE_CUT_PASTE_DETAIL: cutPastePermissionIdBase + 10,
}
}
addPerfix(systemPermission.systemWebConfig, systemWebConfigPerfix)
addPerfix(systemPermission.systemWebCompany, systemWebCompanyPerfix)
addPerfix(systemPermission.systemWebUser, systemWebUserPerfix)
addPerfix(systemPermission.systemWebChannel, systemWebChannelPerfix)
addPerfix(systemPermission.systemWebService, systemWebServicePerfix)
addPerfix(channelPermission.channel, channelPerfix)
addPerfix(channelPermission.channelChat, channelChatPerfix)
addPerfix(channelPermission.channelMedia, channelMediaPerfix)
addPerfix(channelPermission.channelFile, channelFilePerfix)
addPerfix(channelPermission.channelNotice, channelNoticePerfix)
addPerfix(channelPermission.channelUser, channelUserPerfix)
addPerfix(companyPermission.company, companyPerfix)
addPerfix(cloudPermission.cloudFile, cloudFilePerfix)
addPerfix(companyPermission.company, companyPerfix)
addPerfix(userPermission.user, userPerfix)
addPerfix(userPermission.userApply, userApplyPerfix)
@ -231,18 +390,32 @@ addPerfix(userPermission.userRegister, userRegisterPerfix)
addPerfix(userPermission.userLogin, userLoginPerfix)
addPerfix(userPermission.userLogout, userLogoutPerfix)
addPerfix(userPermission.userTag, userTagPerfix)
addPerfix(userPermission.userClear, userClearPerfix)
addPerfix(configPermission.skin, configSkinPerfix)
addPerfix(cutPastePermission.cutPaste, cutPastePerfix)
module.exports = {
systemPermission,
channelPermission,
cloudPermission,
companyPermission,
userPermission,
configPermission,
cutPastePermission,
systemPerfix,
systemWebConfigPerfix,
systemWebCompanyPerfix,
systemWebUserPerfix,
systemWebChannelPerfix,
systemWebServicePerfix,
channelPerfix,
channelChatPerfix,
channelFilePerfix,
channelNoticePerfix,
channelUserPerfix,
cloudFilePerfix,
companyPerfix,
userPerfix,
userApplyPerfix,
@ -253,4 +426,6 @@ module.exports = {
userLoginPerfix,
userLogoutPerfix,
userTagPerfix,
configSkinPerfix,
cutPastePerfix,
}

View File

@ -1,8 +1,11 @@
const {
systemPermission,
channelPermission,
cloudPermission,
userPermission,
companyPermission,
configPermission,
cutPastePermission
} = require('./permission');
const {
@ -25,10 +28,21 @@ const {
const getAllPermissionsMap = function(){
let returnPermissionMap = {};
// 系统权限
returnPermissionMap = Object.assign(returnPermissionMap, systemPermission.systemWebConfig)
returnPermissionMap = Object.assign(returnPermissionMap, systemPermission.systemWebService)
returnPermissionMap = Object.assign(returnPermissionMap, systemPermission.systemWebCompany)
returnPermissionMap = Object.assign(returnPermissionMap, systemPermission.systemWebUser)
returnPermissionMap = Object.assign(returnPermissionMap, systemPermission.systemWebChannel)
// 频道权限
returnPermissionMap = Object.assign(returnPermissionMap, channelPermission.channel)
returnPermissionMap = Object.assign(returnPermissionMap, channelPermission.channelChat)
returnPermissionMap = Object.assign(returnPermissionMap, channelPermission.channelMedia)
returnPermissionMap = Object.assign(returnPermissionMap, channelPermission.channelFile)
returnPermissionMap = Object.assign(returnPermissionMap, channelPermission.channelNotice)
returnPermissionMap = Object.assign(returnPermissionMap, channelPermission.channelUser)
// 资源库权限
returnPermissionMap = Object.assign(returnPermissionMap, cloudPermission.cloudFile)
// 企业权限
returnPermissionMap = Object.assign(returnPermissionMap, companyPermission.company)
// 用户权限
@ -41,7 +55,11 @@ const getAllPermissionsMap = function(){
returnPermissionMap = Object.assign(returnPermissionMap, userPermission.userLogout)
returnPermissionMap = Object.assign(returnPermissionMap, userPermission.userRegister)
returnPermissionMap = Object.assign(returnPermissionMap, userPermission.userTag)
returnPermissionMap = Object.assign(returnPermissionMap, userPermission.userClear)
// 配置权限
returnPermissionMap = Object.assign(returnPermissionMap, configPermission.skin)
// 剪切板权限
returnPermissionMap = Object.assign(returnPermissionMap, cutPastePermission.cutPaste)
return returnPermissionMap;
}

View File

@ -1,10 +1,8 @@
const { Op } = require('sequelize')
const { fields } = require('../../tables/tl_channel_chat')
const TlChannelChatDao = require('../../dao/tl_channel_chat_dao')
const TlChannelChatDef = fields.Def
const TlChannelChatType = fields.Type
const TableName = fields.Name
const TableFields = Object.keys(fields.Def).map(key => fields.Def[key])
const { tlConsoleError, tlConsole } = require("../../../src/utils/utils");
@ -47,11 +45,7 @@ const addInfo = async function({
return {}
}
if(![
TlChannelChatType.SYSTEM,
TlChannelChatType.FRIEND,
TlChannelChatType.GROUP
].includes(type)){
if(Object.values(TlChannelChatType).indexOf(type) === -1){
tlConsoleError(TableName, "请求service参数type不合法")
return {}
}
@ -252,680 +246,6 @@ const getInfoById = async function({companyId, id}, fields){
return info
}
/**
* getListByChannelId 接口
* @param {*} companyId
* @param {*} channelId
* @param {*} fields
*/
const getListByChannelId = async function({companyId, channelId}, fields){
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
const list = await TlChannelChatDao.getList({
[TlChannelChatDef.companyId]: companyId,
[TlChannelChatDef.channelId]: channelId,
}, fields, [
[TlChannelChatDef.messageTimeStamp, 'DESC']
])
if(list == null){
return []
}
return list
}
/**
* getListByChannelIdForPage 接口
* @param {*} companyId
* @param {*} channelId
* @param {*} fields
* @param {*} page
* @param {*} pageSize
*/
const getListByChannelIdForPage = async function({companyId, channelId}, fields, page, pageSize){
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!page){
tlConsoleError(TableName, "请求service参数page为空")
return []
}
if(!pageSize){
tlConsoleError(TableName, "请求service参数pageSize为空")
return []
}
if(page <= 0){
tlConsoleError(TableName, "请求service参数page不合法")
return []
}
if(pageSize <= 0){
tlConsoleError(TableName, "请求service参数pageSize不合法")
return []
}
if(pageSize > 1000){
tlConsoleError(TableName, "请求service参数pageSize过大")
return []
}
const list = await TlChannelChatDao.getListForPage({
[TlChannelChatDef.companyId]: companyId,
[TlChannelChatDef.channelId]: channelId,
}, fields, [
[TlChannelChatDef.messageTimeStamp, 'DESC']
], page, pageSize)
if(list == null){
return []
}
return list
}
/**
* getListByChannelIdAndMinIdForPage 接口
* @desc 查看频道历史聊天记录
* @param {*} companyId
* @param {*} channelId
* @param {*} fields
* @param {*} minId
* @param {*} page
* @param {*} pageSize
*/
const getListByChannelIdAndMinIdForPage = async function({
companyId, channelId, minId
}, fields, page, pageSize){
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!minId){
tlConsoleError(TableName, "请求service参数minId为空")
return []
}
if(!pageSize){
tlConsoleError(TableName, "请求service参数pageSize为空")
return []
}
if(page <= 0){
tlConsoleError(TableName, "请求service参数page不合法")
return []
}
if(pageSize <= 0){
tlConsoleError(TableName, "请求service参数pageSize不合法")
return []
}
if(pageSize > 1000){
tlConsoleError(TableName, "请求service参数pageSize过大")
return []
}
const list = await TlChannelChatDao.getListForPage({
[TlChannelChatDef.companyId]: companyId,
[TlChannelChatDef.channelId]: channelId,
[TlChannelChatDef.id]: {
[Op.lt]: minId
}
}, fields, [
[TlChannelChatDef.messageTimeStamp, 'DESC']
], page, pageSize)
if(list == null){
return []
}
return list
}
/**
* getListByChannelIdAndMinIdTimeRangeForPage 接口
* @desc 搜索频道聊天记录
* @param {*} companyId
* @param {*} channelId
* @param {*} fields
* @param {*} minId
* @param {*} startTimeStamp
* @param {*} endTimeStamp
* @param {*} keyword
* @param {*} page
* @param {*} pageSize
*/
const getListByChannelIdAndMinIdTimeRangeForPage = async function({
companyId, channelId, minId, startTimeStamp, endTimeStamp, keyword
}, fields, page, pageSize){
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!minId){
tlConsoleError(TableName, "请求service参数minId为空")
return []
}
if(!pageSize){
tlConsoleError(TableName, "请求service参数pageSize为空")
return []
}
if(page <= 0){
tlConsoleError(TableName, "请求service参数page不合法")
return []
}
if(pageSize <= 0){
tlConsoleError(TableName, "请求service参数pageSize不合法")
return []
}
if(pageSize > 1000){
tlConsoleError(TableName, "请求service参数pageSize过大")
return []
}
let query = {
[TlChannelChatDef.companyId]: companyId,
[TlChannelChatDef.channelId]: channelId,
[TlChannelChatDef.id]: {
[Op.lte]: minId,
}
}
if(startTimeStamp && endTimeStamp){
query[TlChannelChatDef.messageTimeStamp] = {
[Op.between]: [startTimeStamp, endTimeStamp]
}
}
if(keyword !== '' && keyword !== undefined && keyword !== null){
query[TlChannelChatDef.message] = {
[Op.like]: `%${keyword}%`
}
}
const list = await TlChannelChatDao.getListForPage(query, fields, [
[TlChannelChatDef.messageTimeStamp, 'DESC']
], page, pageSize)
if(list == null){
return []
}
return list
}
/**
* getListByChannelIdAndMaxIdForPage 接口
* @desc 查看频道最新聊天记录
* @param {*} companyId
* @param {*} channelId
* @param {*} fields
* @param {*} maxId
* @param {*} page
* @param {*} pageSize
*/
const getListByChannelIdAndMaxIdForPage = async function({
companyId, channelId, maxId
}, fields, page, pageSize){
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!maxId){
tlConsoleError(TableName, "请求service参数maxId为空")
return []
}
if(!pageSize){
tlConsoleError(TableName, "请求service参数pageSize为空")
return []
}
if(page <= 0){
tlConsoleError(TableName, "请求service参数page不合法")
return []
}
if(pageSize <= 0){
tlConsoleError(TableName, "请求service参数pageSize不合法")
return []
}
if(pageSize > 1000){
tlConsoleError(TableName, "请求service参数pageSize过大")
return []
}
const list = await TlChannelChatDao.getListForPage({
[TlChannelChatDef.companyId]: companyId,
[TlChannelChatDef.channelId]: channelId,
[TlChannelChatDef.id]: {
[Op.gte]: maxId
}
}, fields, [
[TlChannelChatDef.messageTimeStamp, 'DESC']
], page, pageSize)
if(list == null){
return []
}
return list
}
/**
* getListByChannelIdList 接口
* @param {*} companyId
* @param {*} channelIdList
* @param {*} fields
*/
const getListByChannelIdList = async function({companyId, channelIdList}, fields){
if(!channelIdList){
tlConsoleError(TableName, "请求service参数channelIdList为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
const list = await TlChannelChatDao.getList({
[TlChannelChatDef.companyId]: companyId,
[TlChannelChatDef.channelId]: channelIdList,
}, fields, [
[TlChannelChatDef.messageTimeStamp, 'DESC']
])
if(list == null){
return []
}
return list
}
/**
* getListByChannelIdListForPage 接口
* @param {*} companyId
* @param {*} channelIdList
* @param {*} page
* @param {*} pageSize
* @param {*} fields
*/
const getListByChannelIdListForPage = async function({companyId, channelIdList}, fields, page, pageSize){
if(!channelIdList){
tlConsoleError(TableName, "请求service参数channelIdList为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!page){
tlConsoleError(TableName, "请求service参数page为空")
return []
}
if(!pageSize){
tlConsoleError(TableName, "请求service参数pageSize为空")
return []
}
if(page <= 0){
tlConsoleError(TableName, "请求service参数page不合法")
return []
}
if(pageSize <= 0){
tlConsoleError(TableName, "请求service参数pageSize不合法")
return []
}
if(pageSize > 1000){
tlConsoleError(TableName, "请求service参数pageSize过大")
return []
}
const list = await TlChannelChatDao.getListForPage({
[TlChannelChatDef.companyId]: companyId,
[TlChannelChatDef.channelId]: channelIdList,
}, fields, [
[TlChannelChatDef.messageTimeStamp, 'DESC']
], page, pageSize)
if(list == null){
return []
}
return list
}
/**
* getListByChannelFromUserId 接口
* @param {*} companyId
* @param {*} channelId
* @param {*} fromUserId
* @param {*} fields
*/
const getListByChannelFromUserId = async function({companyId, channelId, fromUserId}, fields){
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!fromUserId){
tlConsoleError(TableName, "请求service参数fromUserId为空")
return []
}
const list = await TlChannelChatDao.getList({
[TlChannelChatDef.companyId]: companyId,
[TlChannelChatDef.channelId]: channelId,
[TlChannelChatDef.fromUserId]: fromUserId,
}, fields, [
[TlChannelChatDef.messageTimeStamp, 'DESC']
])
if(list == null){
return []
}
return list
}
/**
* getListByChannelFromUserIdForPage 接口
* @param {*} companyId
* @param {*} channelId
* @param {*} fromUserId
* @param {*} page
* @param {*} pageSize
* @param {*} fields
*/
const getListByChannelFromUserIdForPage = async function({companyId, channelId, fromUserId}, fields, page, pageSize){
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!fromUserId){
tlConsoleError(TableName, "请求service参数fromUserId为空")
return []
}
if(!page){
tlConsoleError(TableName, "请求service参数page为空")
return []
}
if(!pageSize){
tlConsoleError(TableName, "请求service参数pageSize为空")
return []
}
if(page <= 0){
tlConsoleError(TableName, "请求service参数page不合法")
return []
}
if(pageSize <= 0){
tlConsoleError(TableName, "请求service参数pageSize不合法")
return []
}
if(pageSize > 1000){
tlConsoleError(TableName, "请求service参数pageSize过大")
return []
}
const list = await TlChannelChatDao.getListForPage({
[TlChannelChatDef.companyId]: companyId,
[TlChannelChatDef.channelId]: channelId,
[TlChannelChatDef.fromUserId]: fromUserId,
}, fields, [
[TlChannelChatDef.messageTimeStamp, 'DESC']
], page, pageSize)
if(list == null){
return []
}
return list
}
/**
* getListByChannelToUserId 接口
* @param {*} companyId
* @param {*} channelId
* @param {*} toUserId
* @param {*} fields
*/
const getListByChannelToUserId = async function({companyId, channelId, toUserId}, fields){
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!toUserId){
tlConsoleError(TableName, "请求service参数toUserId为空")
return []
}
const list = await TlChannelChatDao.getList({
[TlChannelChatDef.companyId]: companyId,
[TlChannelChatDef.channelId]: channelId,
[TlChannelChatDef.toUserId]: toUserId,
}, fields, [
[TlChannelChatDef.messageTimeStamp, 'DESC']
])
if(list == null){
return []
}
return list
}
/**
* getListByChannelToUserIdForPage 接口
* @param {*} companyId
* @param {*} channelId
* @param {*} toUserId
* @param {*} page
* @param {*} pageSize
* @param {*} fields
*/
const getListByChannelToUserIdForPage = async function({companyId, channelId, toUserId}, fields, page, pageSize){
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!toUserId){
tlConsoleError(TableName, "请求service参数toUserId为空")
return []
}
if(!page){
tlConsoleError(TableName, "请求service参数page为空")
return []
}
if(!pageSize){
tlConsoleError(TableName, "请求service参数pageSize为空")
return []
}
if(page <= 0){
tlConsoleError(TableName, "请求service参数page不合法")
return []
}
if(pageSize <= 0){
tlConsoleError(TableName, "请求service参数pageSize不合法")
return []
}
if(pageSize > 1000){
tlConsoleError(TableName, "请求service参数pageSize过大")
return []
}
const list = await TlChannelChatDao.getListForPage({
[TlChannelChatDef.companyId]: companyId,
[TlChannelChatDef.channelId]: channelId,
[TlChannelChatDef.toUserId]: toUserId,
}, fields, [
[TlChannelChatDef.messageTimeStamp, 'DESC']
], page, pageSize)
if(list == null){
return []
}
return list
}
/**
* getListByCompanyId 接口
* @param {*} companyId
* @param {*} fields
*/
const getListByCompanyId = async function({companyId}, fields){
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
const list = await TlChannelChatDao.getList({
[TlChannelChatDef.companyId]: companyId,
}, fields, [
[TlChannelChatDef.messageTimeStamp, 'DESC']
])
if(list == null){
return []
}
return list
}
/**
* getListByCompanyIdForPage 接口
* @param {*} companyId
* @param {*} fields
* @param {*} page
* @param {*} pageSize
*/
const getListByCompanyIdForPage = async function({companyId}, fields, page, pageSize){
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!page){
tlConsoleError(TableName, "请求service参数page为空")
return []
}
if(!pageSize){
tlConsoleError(TableName, "请求service参数pageSize为空")
return []
}
if(page <= 0){
tlConsoleError(TableName, "请求service参数page不合法")
return []
}
if(pageSize <= 0){
tlConsoleError(TableName, "请求service参数pageSize不合法")
return []
}
if(pageSize > 1000){
tlConsoleError(TableName, "请求service参数pageSize过大")
return []
}
const list = await TlChannelChatDao.getListForPage({
[TlChannelChatDef.companyId]: companyId,
}, fields, [
[TlChannelChatDef.messageTimeStamp, 'DESC']
], page, pageSize)
if(list == null){
return []
}
return list
}
/**
* getListByChannelIdAndIdList 接口
* @param {*} companyId
@ -962,66 +282,6 @@ const getListByChannelIdAndIdList = async function({companyId, channelId, idList
return list
}
/**
* getListByChannelIdAndIdListForPage 接口
* @param {*} companyId
* @param {*} channelId
* @param {*} idList
* @param {*} fields
* @param {*} page
* @param {*} pageSize
*/
const getListByChannelIdAndIdListForPage = async function({companyId, channelId, idList}, fields, page, pageSize){
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return []
}
if(!idList){
tlConsoleError(TableName, "请求service参数idList为空")
return []
}
if(!page){
tlConsoleError(TableName, "请求service参数page为空")
return []
}
if(!pageSize){
tlConsoleError(TableName, "请求service参数pageSize为空")
return []
}
if(page <= 0){
tlConsoleError(TableName, "请求service参数page不合法")
return []
}
if(pageSize <= 0){
tlConsoleError(TableName, "请求service参数pageSize不合法")
return []
}
const list = await TlChannelChatDao.getListForPage({
[TlChannelChatDef.companyId]: companyId,
[TlChannelChatDef.channelId]: channelId,
[TlChannelChatDef.id]: idList
}, fields, [
[TlChannelChatDef.messageTimeStamp, 'DESC']
], page, pageSize)
if(list == null){
return []
}
return list
}
/**
* getListByIdList 接口
* @param {*} companyId
@ -1051,151 +311,6 @@ const getListByIdList = async function({companyId, idList}, fields){
return list
}
/**
* getListByIdListForPage 接口
* @param {*} companyId
* @param {*} idList
* @param {*} fields
* @param {*} page
* @param {*} pageSize
*/
const getListByIdListForPage = async function({companyId, idList}, fields, page, pageSize){
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!idList){
tlConsoleError(TableName, "请求service参数idList为空")
return []
}
if(!page){
tlConsoleError(TableName, "请求service参数page为空")
return []
}
if(!pageSize){
tlConsoleError(TableName, "请求service参数pageSize为空")
return []
}
if(page <= 0){
tlConsoleError(TableName, "请求service参数page不合法")
return []
}
if(pageSize <= 0){
tlConsoleError(TableName, "请求service参数pageSize不合法")
return []
}
const list = await TlChannelChatDao.getListForPage({
[TlChannelChatDef.companyId]: companyId,
[TlChannelChatDef.id]: idList,
}, fields, [
[TlChannelChatDef.messageTimeStamp, 'DESC']
], page, pageSize)
if(list == null){
return []
}
return list
}
/**
* updateInfoById 接口
* @param {*} id
* @param {*} companyId
* @param {*} data
*/
const updateInfoById = async function({id, companyId}, data){
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求service参数为空")
return {}
}
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
const info = await TlChannelChatDao.updateInfo({
[TlChannelChatDef.companyId]: companyId,
[TlChannelChatDef.id]: id,
}, data)
if(info == null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* deleteInfoById 接口
* @param {*} id
* @param {*} companyId
*/
const deleteInfoById = async function({id, companyId}){
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
const info = await TlChannelChatDao.deleteInfo({
[TlChannelChatDef.companyId]: companyId,
[TlChannelChatDef.id]: id,
})
if(info == null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* getCountByChannelId 接口
* @param {*} companyId
* @param {*} channelId
*/
const getCountByChannelId = async function({companyId, channelId}){
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return 0
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return 0
}
const count = await TlChannelChatDao.getCount({
[TlChannelChatDef.companyId]: companyId,
[TlChannelChatDef.channelId]: channelId,
})
if(count == null){
return 0
}
return count
}
/**
* getCountByChannelIdList 接口
* @param {*} companyId
@ -1257,37 +372,44 @@ const getChannelChatLatestId = async function({companyId, channelId}, fields){
return latestId
}
/**
* 删除聊天记录
* @param {*} companyId
* @param {*} id
*/
const deleteInfoById = async function({companyId, id}){
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return 0
}
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return 0
}
const info = await TlChannelChatDao.deleteInfo({
[TlChannelChatDef.companyId]: companyId,
[TlChannelChatDef.id]: id
})
if(info == null){
return 0
}
return info
}
module.exports = {
addInfo,
getInfoById,
getChannelChatLatestId,
updateInfoById,
deleteInfoById,
addSystemChatnfo,
addFriendChatInfo,
addGroupChatInfo,
getCountByChannelId,
getCountByChannelIdList,
getListByChannelId,
getListByChannelIdForPage,
getListByChannelFromUserId,
getListByChannelFromUserIdForPage,
getListByChannelToUserId,
getListByChannelToUserIdForPage,
getListByCompanyId,
getListByCompanyIdForPage,
getListByChannelIdList,
getListByChannelIdListForPage,
getListByChannelIdAndMinIdForPage,
getListByChannelIdAndMinIdTimeRangeForPage,
getListByChannelIdAndMaxIdForPage,
deleteInfoById,
getListByChannelIdAndIdList,
getListByChannelIdAndIdListForPage,
getListByIdList,
getListByIdListForPage,
}

View File

@ -0,0 +1,272 @@
const { fields } = require('../../tables/tl_channel_file')
const TlChannelFileDao = require('../../dao/tl_channel_file_dao')
const TlChannelFileDef = fields.Def
const TlChannelFileType = fields.Type
const TlChannelFileStatus = fields.Status
const TableName = fields.Name
const { tlConsoleError, tlConsole } = require("../../../src/utils/utils");
/**
* addInfo 接口
* @param {*} data
*/
const addInfo = async function({
companyId, channelId, flag, cloudFileId, other, fromUserId, fromUserName,
type, status, messageTimeStamp, messageVersion
}){
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return {}
}
if(!messageTimeStamp){
tlConsoleError(TableName, "请求service参数messageTimeStamp为空")
return {}
}
if(!messageVersion){
tlConsoleError(TableName, "请求service参数messageVersion为空")
return {}
}
if(flag === undefined || flag === null){
tlConsoleError(TableName, "请求service参数flag为空")
return {}
}
if(!cloudFileId){
tlConsoleError(TableName, "请求service参数file为空")
return {}
}
if(!other){
tlConsoleError(TableName, "请求service参数other为空")
return {}
}
if(!fromUserId){
tlConsoleError(TableName, "请求service参数fromUserId为空")
return {}
}
if(!fromUserName){
tlConsoleError(TableName, "请求service参数fromUserName为空")
return {}
}
if(!type){
tlConsoleError(TableName, "请求service参数type为空")
return {}
}
if(![
TlChannelFileType.OFFLINE,
TlChannelFileType.P2P,
].includes(type)){
tlConsoleError(TableName, "请求service参数type不合法")
return {}
}
if(!status){
tlConsoleError(TableName, "请求service参数status为空")
return {}
}
if(![
TlChannelFileStatus.INIT,
TlChannelFileStatus.RECEIVED,
TlChannelFileStatus.RECEIVING,
].includes(status)){
tlConsoleError(TableName, "请求service参数status不合法")
return {}
}
const info = await TlChannelFileDao.addInfo({
[TlChannelFileDef.companyId]: companyId,
[TlChannelFileDef.channelId]: channelId,
[TlChannelFileDef.flag]: flag,
[TlChannelFileDef.cloudFileId]: cloudFileId,
[TlChannelFileDef.other]: other,
[TlChannelFileDef.fromUserId]: fromUserId,
[TlChannelFileDef.fromUserName]: fromUserName,
[TlChannelFileDef.type]: type,
[TlChannelFileDef.status]: status,
[TlChannelFileDef.messageTimeStamp]: messageTimeStamp,
[TlChannelFileDef.messageVersion]: messageVersion,
})
if(info == null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* getInfoById 接口
* @param {*} companyId
* @param {*} id
* @param {*} fields
*/
const getInfoById = async function({companyId, id}, fields){
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
const info = await TlChannelFileDao.getInfo({
[TlChannelFileDef.companyId] : companyId,
[TlChannelFileDef.id] : id,
}, fields)
if(info == null){
return {}
}
return info
}
/**
* getListByChannelId 接口
* @param {*} companyId
* @param {*} channelId
* @param {*} fields
*/
const getListByChannelId = async function({companyId, channelId}, fields){
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
const list = await TlChannelFileDao.getList({
[TlChannelFileDef.companyId]: companyId,
[TlChannelFileDef.channelId]: channelId,
}, fields, [
[TlChannelFileDef.messageTimeStamp, 'DESC']
])
if(list == null){
return []
}
return list
}
/**
* getListByChannelIdList 接口
* @param {*} companyId
* @param {*} channelIdList
* @param {*} fields
*/
const getListByChannelIdList = async function({companyId, channelIdList}, fields){
if(!channelIdList){
tlConsoleError(TableName, "请求service参数channelIdList为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
const list = await TlChannelFileDao.getList({
[TlChannelFileDef.companyId]: companyId,
[TlChannelFileDef.channelId]: channelIdList,
}, fields, [
[TlChannelFileDef.messageTimeStamp, 'DESC']
])
if(list == null){
return []
}
return list
}
/**
* deleteInfoById 接口
* @param {*} companyId
* @param {*} id
*/
const deleteInfoById = async function({companyId, id}){
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return 0
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return 0
}
const info = await TlChannelFileDao.deleteInfo({
[TlChannelFileDef.companyId]: companyId,
[TlChannelFileDef.id]: id,
})
if(info == null){
return 0
}
return info
}
/**
* 获取频道文件最新id
* @param {*} companyId
* @param {*} channelId
* @param {*} fields
*/
const getChannelFileLatestId = async function({companyId, channelId}, fields){
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return 0
}
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return 0
}
const list = await TlChannelFileDao.getListForPage({
[TlChannelFileDef.companyId]: companyId,
[TlChannelFileDef.channelId]: channelId,
}, fields, [
[TlChannelFileDef.id, 'DESC']
], 1, 1)
if(list == null || list.length === 0){
return 0
}
const latestId = list[0][TlChannelFileDef.id]
return latestId
}
module.exports = {
addInfo,
getInfoById,
deleteInfoById,
getChannelFileLatestId,
getListByChannelId,
getListByChannelIdList,
}

View File

@ -0,0 +1,206 @@
const { fields } = require('../../tables/tl_channel_media')
const TlChannelMediaDao = require('../../dao/tl_channel_media_dao')
const TlChannelMediaDef = fields.Def
const TlChannelMediaType = fields.Type
const TlChannelMediaStatus = fields.Status
const TableName = fields.Name
const { tlConsoleError, tlConsole } = require("../../../src/utils/utils");
/**
* addInfo 接口
* @param {*} data
*/
const addInfo = async function({
companyId, channelId, flag, media, other, fromUserId, fromUserName,
type, status, messageTimeStamp, messageVersion
}){
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return {}
}
if(!messageTimeStamp){
tlConsoleError(TableName, "请求service参数messageTimeStamp为空")
return {}
}
if(!messageVersion){
tlConsoleError(TableName, "请求service参数messageVersion为空")
return {}
}
if(flag === undefined || flag === null){
tlConsoleError(TableName, "请求service参数flag为空")
return {}
}
if(!media){
tlConsoleError(TableName, "请求service参数media为空")
return {}
}
if(!other){
tlConsoleError(TableName, "请求service参数other为空")
return {}
}
if(!fromUserId){
tlConsoleError(TableName, "请求service参数fromUserId为空")
return {}
}
if(!fromUserName){
tlConsoleError(TableName, "请求service参数fromUserName为空")
return {}
}
if(!type){
tlConsoleError(TableName, "请求service参数type为空")
return {}
}
if(![
TlChannelMediaType.AUDIO,
TlChannelMediaType.VIDEO,
].includes(type)){
tlConsoleError(TableName, "请求service参数type不合法")
return {}
}
if(!status){
tlConsoleError(TableName, "请求service参数status为空")
return {}
}
if(![
TlChannelMediaStatus.INIT,
TlChannelMediaStatus.RECEIVED,
TlChannelMediaStatus.RECEIVING,
].includes(status)){
tlConsoleError(TableName, "请求service参数status不合法")
return {}
}
const info = await TlChannelMediaDao.addInfo({
[TlChannelMediaDef.companyId]: companyId,
[TlChannelMediaDef.channelId]: channelId,
[TlChannelMediaDef.flag]: flag,
[TlChannelMediaDef.media]: media,
[TlChannelMediaDef.other]: other,
[TlChannelMediaDef.fromUserId]: fromUserId,
[TlChannelMediaDef.fromUserName]: fromUserName,
[TlChannelMediaDef.type]: type,
[TlChannelMediaDef.status]: status,
[TlChannelMediaDef.messageTimeStamp]: messageTimeStamp,
[TlChannelMediaDef.messageVersion]: messageVersion,
})
if(info == null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* getInfoById 接口
* @param {*} companyId
* @param {*} id
* @param {*} fields
*/
const getInfoById = async function({companyId, id}, fields){
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
const info = await TlChannelMediaDao.getInfo({
[TlChannelMediaDef.companyId] : companyId,
[TlChannelMediaDef.id] : id,
}, fields)
if(info == null){
return {}
}
return info
}
/**
* deleteInfoById 接口
* @param {*} companyId
* @param {*} id
*/
const deleteInfoById = async function({companyId, id}){
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return 0
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return 0
}
const info = await TlChannelMediaDao.deleteInfo({
[TlChannelMediaDef.companyId]: companyId,
[TlChannelMediaDef.id]: id,
})
if(info == null){
return 0
}
return info
}
/**
* 获取频道媒体最新id
* @param {*} companyId
* @param {*} channelId
* @param {*} fields
*/
const getChannelMediaLatestId = async function({companyId, channelId}, fields){
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return 0
}
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return 0
}
const list = await TlChannelMediaDao.getListForPage({
[TlChannelMediaDef.companyId]: companyId,
[TlChannelMediaDef.channelId]: channelId,
}, fields, [
[TlChannelMediaDef.id, 'DESC']
], 1, 1)
if(list == null || list.length === 0){
return 0
}
const latestId = list[0][TlChannelMediaDef.id]
return latestId
}
module.exports = {
addInfo,
getInfoById,
deleteInfoById,
getChannelMediaLatestId,
}

View File

@ -0,0 +1,829 @@
const { tlConsoleError } = require("../../../src/utils/utils");
const TlChannelMessageDao = require('../../dao/tl_channel_message_dao')
const { fields: TlChannelChatFields } = require('../../tables/tl_channel_chat')
const { fields: TlChannelFileFields } = require('../../tables/tl_channel_file')
const { fields: TlChannelMediaFields } = require('../../tables/tl_channel_media')
const TlChannelChatDef = TlChannelChatFields.Def
const TlChannelChatType = TlChannelChatFields.Type
const TlChannelChatTableName = TlChannelChatFields.Name
const TlChannelFileDef = TlChannelFileFields.Def
const TlChannelFileType = TlChannelFileFields.Type
const TlChannelFileTableName = TlChannelFileFields.Name
const TlChannelMediaDef = TlChannelMediaFields.Def
const TlChannelMediaType = TlChannelMediaFields.Type
const TlChannelMediaTableName = TlChannelMediaFields.Name
const TableName = "TlChannelMessageService"
/**
* 查询频道最新消息接口
* @param {*} companyId
* @param {*} channelId
* @param {*} chatClearId
* @param {*} fileClearId
* @param {*} mediaClearId
* @param {*} chatFields
* @param {*} fileFields
* @param {*} mediaFields
* @param {*} page
* @param {*} pageSize
*/
const getCombinedChannelMessageListForPage = async function({
companyId, channelId, chatClearId, fileClearId, mediaClearId
}, commonFields, chatFields, fileFields, mediaFields, page, pageSize){
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return []
}
if(!chatClearId){
tlConsoleError(TableName, "请求service参数chatClearId为空")
return []
}
if(!fileClearId){
tlConsoleError(TableName, "请求service参数fileClearId为空")
return []
}
if(!mediaClearId){
tlConsoleError(TableName, "请求service参数mediaClearId为空")
return []
}
if(!pageSize){
tlConsoleError(TableName, "请求service参数pageSize为空")
return []
}
if(page <= 0){
tlConsoleError(TableName, "请求service参数page不合法")
return []
}
if(pageSize <= 0){
tlConsoleError(TableName, "请求service参数pageSize不合法")
return []
}
if(pageSize > 1000){
tlConsoleError(TableName, "请求service参数pageSize过大")
return []
}
let searchChatFields = []
let searchFileFields = []
let searchMediaFields = []
const chatFieldsPerfix = "field_chat_"
const fileFieldsPerfix = "field_file_"
const mediaFieldsPerfix = "field_media_"
if(chatFields){
if(commonFields){
commonFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchChatFields.push(`${field} AS \`${field}\``)
})
}
chatFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchChatFields.push(`${field} AS \`${chatFieldsPerfix + field}\``)
})
// 如果三个表字段不一致,需要补齐处理
if(fileFields){
fileFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchChatFields.push(`NULL AS \`${fileFieldsPerfix + field}\``)
})
}
// 如果三个表字段不一致,需要补齐处理
if(mediaFields){
mediaFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchChatFields.push(`NULL AS \`${mediaFieldsPerfix + field}\``)
})
}
}
if(fileFields){
if(commonFields){
commonFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchFileFields.push(`${field} AS \`${field}\``)
})
}
// 如果三个表字段不一致,需要补齐处理
if(chatFields){
chatFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchFileFields.push(`NULL AS \`${chatFieldsPerfix + field}\``)
})
}
fileFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchFileFields.push(`${field} AS \`${fileFieldsPerfix + field}\``)
})
// 如果三个表字段不一致,需要补齐处理
if(mediaFields){
mediaFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchFileFields.push(`NULL AS \`${mediaFieldsPerfix + field}\``)
})
}
}
if(mediaFields){
if(commonFields){
commonFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchMediaFields.push(`${field} AS \`${field}\``)
})
}
// 如果三个表字段不一致,需要补齐处理
if(chatFields){
chatFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchMediaFields.push(`NULL AS \`${chatFieldsPerfix + field}\``)
})
}
// 如果三个表字段不一致,需要补齐处理
if(fileFields){
fileFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchMediaFields.push(`NULL AS \`${fileFieldsPerfix + field}\``)
})
}
mediaFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchMediaFields.push(`${field} AS \`${mediaFieldsPerfix + field}\``)
})
}
// 补充 null 字段
const querySql = `
SELECT * FROM (
(
SELECT
${searchChatFields.map(field => `${field}`).join(", ")}
FROM \`${TlChannelChatTableName}\`
WHERE
\`${TlChannelChatDef.companyId}\` = :companyId
AND \`${TlChannelChatDef.channelId}\` = :channelId
AND \`${TlChannelChatDef.id}\` > :chatClearId
AND \`deleted_at\` IS NULL
)
UNION ALL
(
SELECT
${searchFileFields.map(field => `${field}`).join(", ")}
FROM \`${TlChannelFileTableName}\`
WHERE
\`${TlChannelFileDef.companyId}\` = :companyId
AND \`${TlChannelFileDef.channelId}\` = :channelId
AND \`${TlChannelFileDef.id}\` > :fileClearId
AND \`deleted_at\` IS NULL
)
UNION ALL
(
SELECT
${searchMediaFields.map(field => `${field}`).join(", ")}
FROM \`${TlChannelMediaTableName}\`
WHERE
\`${TlChannelMediaDef.companyId}\` = :companyId
AND \`${TlChannelMediaDef.channelId}\` = :channelId
AND \`${TlChannelMediaDef.id}\` > :mediaClearId
AND \`deleted_at\` IS NULL
)
) AS \`combined\`
ORDER BY \`${TlChannelMediaDef.messageTimeStamp}\` DESC
LIMIT :limit
OFFSET :offset;
`;
const list = await TlChannelMessageDao.getListBySql(querySql, {
companyId, channelId, chatClearId, fileClearId, mediaClearId, limit: pageSize, offset: (page - 1) * pageSize
})
if(list == null){
return []
}
// 处理字段
list.forEach(item => {
const type = item[TlChannelChatDef.type]
if(Object.values(TlChannelChatType).includes(type)){
for(let key in item){
if(key.startsWith(chatFieldsPerfix)){
item[key.replace(chatFieldsPerfix, "")] = item[key]
delete item[key]
}
}
}else if(Object.values(TlChannelFileType).includes(type)){
for(let key in item){
if(key.startsWith(fileFieldsPerfix)){
item[key.replace(fileFieldsPerfix, "")] = item[key]
delete item[key]
}
}
}else if(Object.values(TlChannelMediaType).includes(type)){
for(let key in item){
if(key.startsWith(mediaFieldsPerfix)){
item[key.replace(mediaFieldsPerfix, "")] = item[key]
delete item[key]
}
}
}
})
return list
}
/**
* 查询频道历史消息接口
* @param {*} companyId
* @param {*} channelId
* @param {*} chatClearId
* @param {*} fileClearId
* @param {*} mediaClearId
* @param {*} chatMinId
* @param {*} fileMinId
* @param {*} mediaMinId
* @param {*} chatFields
* @param {*} fileFields
* @param {*} mediaFields
* @param {*} page
* @param {*} pageSize
*/
const getCombinedChannelHistoryMessageListForPage = async function({
companyId, channelId, chatClearId, fileClearId, mediaClearId,
chatMinId, fileMinId, mediaMinId
}, commonFields, chatFields, fileFields, mediaFields, page, pageSize){
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return []
}
if(!chatClearId){
tlConsoleError(TableName, "请求service参数chatClearId为空")
return []
}
if(!fileClearId){
tlConsoleError(TableName, "请求service参数fileClearId为空")
return []
}
if(!mediaClearId){
tlConsoleError(TableName, "请求service参数mediaClearId为空")
return []
}
if(!pageSize){
tlConsoleError(TableName, "请求service参数pageSize为空")
return []
}
if(page <= 0){
tlConsoleError(TableName, "请求service参数page不合法")
return []
}
if(pageSize <= 0){
tlConsoleError(TableName, "请求service参数pageSize不合法")
return []
}
if(pageSize > 1000){
tlConsoleError(TableName, "请求service参数pageSize过大")
return []
}
if(!chatMinId){
tlConsoleError(TableName, "请求service参数chatMinId为空")
return []
}
if(!fileMinId){
tlConsoleError(TableName, "请求service参数fileMinId为空")
return []
}
if(!mediaMinId){
tlConsoleError(TableName, "请求service参数mediaMinId为空")
return []
}
let searchChatFields = []
let searchFileFields = []
let searchMediaFields = []
const chatFieldsPerfix = "field_chat_"
const fileFieldsPerfix = "field_file_"
const mediaFieldsPerfix = "field_media_"
if(chatFields){
if(commonFields){
commonFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchChatFields.push(`${field} AS \`${field}\``)
})
}
chatFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchChatFields.push(`${field} AS \`${chatFieldsPerfix + field}\``)
})
// 如果三个表字段不一致,需要补齐处理
if(fileFields){
fileFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchChatFields.push(`NULL AS \`${fileFieldsPerfix + field}\``)
})
}
// 如果三个表字段不一致,需要补齐处理
if(mediaFields){
mediaFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchChatFields.push(`NULL AS \`${mediaFieldsPerfix + field}\``)
})
}
}
if(fileFields){
if(commonFields){
commonFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchFileFields.push(`${field} AS \`${field}\``)
})
}
// 如果三个表字段不一致,需要补齐处理
if(chatFields){
chatFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchFileFields.push(`NULL AS \`${chatFieldsPerfix + field}\``)
})
}
fileFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchFileFields.push(`${field} AS \`${fileFieldsPerfix + field}\``)
})
// 如果三个表字段不一致,需要补齐处理
if(mediaFields){
mediaFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchFileFields.push(`NULL AS \`${mediaFieldsPerfix + field}\``)
})
}
}
if(mediaFields){
if(commonFields){
commonFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchMediaFields.push(`${field} AS \`${field}\``)
})
}
// 如果三个表字段不一致,需要补齐处理
if(chatFields){
chatFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchMediaFields.push(`NULL AS \`${chatFieldsPerfix + field}\``)
})
}
// 如果三个表字段不一致,需要补齐处理
if(fileFields){
fileFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchMediaFields.push(`NULL AS \`${fileFieldsPerfix + field}\``)
})
}
mediaFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchMediaFields.push(`${field} AS \`${mediaFieldsPerfix + field}\``)
})
}
// 补充 null 字段
const querySql = `
SELECT * FROM (
(
SELECT
${searchChatFields.map(field => `${field}`).join(", ")}
FROM \`${TlChannelChatTableName}\`
WHERE
\`${TlChannelChatDef.companyId}\` = :companyId
AND \`${TlChannelChatDef.channelId}\` = :channelId
AND \`${TlChannelChatDef.id}\` > :chatClearId
AND \`${TlChannelChatDef.id}\` < :chatMinId
AND \`deleted_at\` IS NULL
)
UNION ALL
(
SELECT
${searchFileFields.map(field => `${field}`).join(", ")}
FROM \`${TlChannelFileTableName}\`
WHERE
\`${TlChannelFileDef.companyId}\` = :companyId
AND \`${TlChannelFileDef.channelId}\` = :channelId
AND \`${TlChannelFileDef.id}\` > :fileClearId
AND \`${TlChannelFileDef.id}\` < :fileMinId
AND \`deleted_at\` IS NULL
)
UNION ALL
(
SELECT
${searchMediaFields.map(field => `${field}`).join(", ")}
FROM \`${TlChannelMediaTableName}\`
WHERE
\`${TlChannelMediaDef.companyId}\` = :companyId
AND \`${TlChannelMediaDef.channelId}\` = :channelId
AND \`${TlChannelMediaDef.id}\` > :mediaClearId
AND \`${TlChannelMediaDef.id}\` < :mediaMinId
AND \`deleted_at\` IS NULL
)
) AS \`combined\`
ORDER BY \`${TlChannelMediaDef.messageTimeStamp}\` DESC
LIMIT :limit
OFFSET :offset;
`;
const list = await TlChannelMessageDao.getListBySql(querySql, {
companyId, channelId, chatClearId, fileClearId, mediaClearId,
chatMinId, fileMinId, mediaMinId,
limit: pageSize, offset: (page - 1) * pageSize,
})
if(list == null){
return []
}
// 处理字段
list.forEach(item => {
const type = item[TlChannelChatDef.type]
if(Object.values(TlChannelChatType).includes(type)){
for(let key in item){
if(key.startsWith(chatFieldsPerfix)){
item[key.replace(chatFieldsPerfix, "")] = item[key]
delete item[key]
}
}
}else if(Object.values(TlChannelFileType).includes(type)){
for(let key in item){
if(key.startsWith(fileFieldsPerfix)){
item[key.replace(fileFieldsPerfix, "")] = item[key]
delete item[key]
}
}
}else if(Object.values(TlChannelMediaType).includes(type)){
for(let key in item){
if(key.startsWith(mediaFieldsPerfix)){
item[key.replace(mediaFieldsPerfix, "")] = item[key]
delete item[key]
}
}
}
})
return list
}
/**
* 搜索频道消息接口
* @param {*} companyId
* @param {*} channelId
* @param {*} chatClearId
* @param {*} fileClearId
* @param {*} mediaClearId
* @param {*} startTimeStamp
* @param {*} endTimeStamp
* @param {*} chatMinId
* @param {*} fileMinId
* @param {*} mediaMinId
* @param {*} chatFields
* @param {*} fileFields
* @param {*} mediaFields
* @param {*} page
* @param {*} pageSize
*/
const searchCombinedChannelMessageListForPage = async function({
companyId, channelId, chatClearId, fileClearId, mediaClearId,
startTimeStamp, endTimeStamp, chatMinId, fileMinId, mediaMinId
}, commonFields, chatFields, fileFields, mediaFields, page, pageSize){
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return []
}
if(!chatClearId){
tlConsoleError(TableName, "请求service参数chatClearId为空")
return []
}
if(!fileClearId){
tlConsoleError(TableName, "请求service参数fileClearId为空")
return []
}
if(!mediaClearId){
tlConsoleError(TableName, "请求service参数mediaClearId为空")
return []
}
if(!pageSize){
tlConsoleError(TableName, "请求service参数pageSize为空")
return []
}
if(page <= 0){
tlConsoleError(TableName, "请求service参数page不合法")
return []
}
if(pageSize <= 0){
tlConsoleError(TableName, "请求service参数pageSize不合法")
return []
}
if(pageSize > 1000){
tlConsoleError(TableName, "请求service参数pageSize过大")
return []
}
if(!startTimeStamp){
tlConsoleError(TableName, "请求service参数startTimeStamp为空")
return []
}
if(!endTimeStamp){
tlConsoleError(TableName, "请求service参数endTimeStamp为空")
return []
}
let searchChatFields = []
let searchFileFields = []
let searchMediaFields = []
const chatFieldsPerfix = "field_chat_"
const fileFieldsPerfix = "field_file_"
const mediaFieldsPerfix = "field_media_"
if(chatFields){
if(commonFields){
commonFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchChatFields.push(`${field} AS \`${field}\``)
})
}
chatFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchChatFields.push(`${field} AS \`${chatFieldsPerfix + field}\``)
})
// 如果三个表字段不一致,需要补齐处理
if(fileFields){
fileFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchChatFields.push(`NULL AS \`${fileFieldsPerfix + field}\``)
})
}
// 如果三个表字段不一致,需要补齐处理
if(mediaFields){
mediaFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchChatFields.push(`NULL AS \`${mediaFieldsPerfix + field}\``)
})
}
}
if(fileFields){
if(commonFields){
commonFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchFileFields.push(`${field} AS \`${field}\``)
})
}
// 如果三个表字段不一致,需要补齐处理
if(chatFields){
chatFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchFileFields.push(`NULL AS \`${chatFieldsPerfix + field}\``)
})
}
fileFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchFileFields.push(`${field} AS \`${fileFieldsPerfix + field}\``)
})
// 如果三个表字段不一致,需要补齐处理
if(mediaFields){
mediaFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchFileFields.push(`NULL AS \`${mediaFieldsPerfix + field}\``)
})
}
}
if(mediaFields){
if(commonFields){
commonFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchMediaFields.push(`${field} AS \`${field}\``)
})
}
// 如果三个表字段不一致,需要补齐处理
if(chatFields){
chatFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchMediaFields.push(`NULL AS \`${chatFieldsPerfix + field}\``)
})
}
// 如果三个表字段不一致,需要补齐处理
if(fileFields){
fileFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchMediaFields.push(`NULL AS \`${fileFieldsPerfix + field}\``)
})
}
mediaFields.forEach(field => {
// 如果字段是驼峰命名,需要转换为下划线命名
field = field.replace(/([A-Z])/g, "_$1").toLowerCase()
searchMediaFields.push(`${field} AS \`${mediaFieldsPerfix + field}\``)
})
}
// 补充 null 字段
const querySql = `
SELECT * FROM (
(
SELECT
${searchChatFields.map(field => `${field}`).join(", ")}
FROM \`${TlChannelChatTableName}\`
WHERE
\`${TlChannelChatDef.companyId}\` = :companyId
AND \`${TlChannelChatDef.channelId}\` = :channelId
AND \`${TlChannelChatDef.id}\` > :chatClearId
${chatMinId !== -1 ? `AND \`${TlChannelChatDef.id}\` < :chatMinId` : ""}
AND \`${TlChannelChatDef.messageTimeStamp}\` >= :startTimeStamp
AND \`deleted_at\` IS NULL
)
UNION ALL
(
SELECT
${searchFileFields.map(field => `${field}`).join(", ")}
FROM \`${TlChannelFileTableName}\`
WHERE
\`${TlChannelFileDef.companyId}\` = :companyId
AND \`${TlChannelFileDef.channelId}\` = :channelId
AND \`${TlChannelFileDef.id}\` > :fileClearId
${fileMinId !== -1 ? `AND \`${TlChannelFileDef.id}\` < :fileMinId` : ""}
AND \`${TlChannelFileDef.messageTimeStamp}\` >= :startTimeStamp
AND \`deleted_at\` IS NULL
)
UNION ALL
(
SELECT
${searchMediaFields.map(field => `${field}`).join(", ")}
FROM \`${TlChannelMediaTableName}\`
WHERE
\`${TlChannelMediaDef.companyId}\` = :companyId
AND \`${TlChannelMediaDef.channelId}\` = :channelId
AND \`${TlChannelMediaDef.id}\` > :mediaClearId
${mediaMinId !== -1 ? `AND \`${TlChannelMediaDef.id}\` < :mediaMinId` : ""}
AND \`${TlChannelMediaDef.messageTimeStamp}\` >= :startTimeStamp
AND \`deleted_at\` IS NULL
)
) AS \`combined\`
ORDER BY \`${TlChannelMediaDef.messageTimeStamp}\` DESC
LIMIT :limit
OFFSET :offset;
`;
const list = await TlChannelMessageDao.getListBySql(querySql, {
companyId, channelId, chatClearId, fileClearId, mediaClearId, limit: pageSize, offset: (page - 1) * pageSize,
startTimeStamp, endTimeStamp
})
if(list == null){
return []
}
// 处理字段
list.forEach(item => {
const type = item[TlChannelChatDef.type]
if(Object.values(TlChannelChatType).includes(type)){
for(let key in item){
if(key.startsWith(chatFieldsPerfix)){
item[key.replace(chatFieldsPerfix, "")] = item[key]
delete item[key]
}
}
}else if(Object.values(TlChannelFileType).includes(type)){
for(let key in item){
if(key.startsWith(fileFieldsPerfix)){
item[key.replace(fileFieldsPerfix, "")] = item[key]
delete item[key]
}
}
}else if(Object.values(TlChannelMediaType).includes(type)){
for(let key in item){
if(key.startsWith(mediaFieldsPerfix)){
item[key.replace(mediaFieldsPerfix, "")] = item[key]
delete item[key]
}
}
}
})
return list
}
module.exports = {
getCombinedChannelMessageListForPage,
getCombinedChannelHistoryMessageListForPage,
searchCombinedChannelMessageListForPage,
}

View File

@ -0,0 +1,114 @@
const { fields } = require('../../tables/tl_channel_notice')
const TlChannelNoticeDao = require('../../dao/tl_channel_notice_dao')
const TlChannelNoticeDef = fields.Def
const TableName = fields.Name
const { tlConsoleError } = require("../../../src/utils/utils");
/**
* addInfo 接口
* @param {*} data
*/
const addInfo = async function({
companyId, channelId, userId, content
}){
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return {}
}
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return {}
}
if(!content){
tlConsoleError(TableName, "请求service参数type为空")
return {}
}
const info = await TlChannelNoticeDao.addInfo({
[TlChannelNoticeDef.companyId] : companyId,
[TlChannelNoticeDef.channelId] : channelId,
[TlChannelNoticeDef.userId] : userId,
[TlChannelNoticeDef.content] : content,
[TlChannelNoticeDef.flag] : 0
})
if(info == null){
tlConsoleError(TableName, "请求service参数为空")
return {}
}
return info
}
/**
* getListByChannelId 接口
* @param {*} companyId
* @param {*} channelId
* @param {*} fields
*/
const getListByChannelId = async function({companyId, channelId}, fields){
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
const list = await TlChannelNoticeDao.getList({
[TlChannelNoticeDef.companyId]: companyId,
[TlChannelNoticeDef.channelId]: channelId,
}, fields, [
[TlChannelNoticeDef.createdAt, 'DESC']
])
if(list == null){
return []
}
return list
}
/**
* deleteInfoById 接口
* @param {*} companyId
* @param {*} id
*/
const deleteInfoById = async function({companyId, id}){
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return 0
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return 0
}
const info = await TlChannelNoticeDao.deleteInfo({
[TlChannelNoticeDef.companyId]: companyId,
[TlChannelNoticeDef.id]: id,
})
if(info == null){
return 0
}
return info
}
module.exports = {
addInfo,
deleteInfoById,
getListByChannelId,
}

View File

@ -4,8 +4,8 @@ const TlChannelDef = fields.Def
const TlChannelType = fields.Type
const TlChannelStatus = fields.Status
const TableName = fields.Name
const TableFields = Object.keys(fields.Def).map(key => fields.Def[key])
const { tlConsoleError, tlConsole } = require("../../../src/utils/utils");
const { Op } = require('sequelize')
/**
@ -87,6 +87,27 @@ const getInfoById = async function({companyId, id}){
return info
}
/**
* getInfoByIdNoCompanyId 接口
* @param {*} id
*/
const getInfoByIdNoCompanyId = async function({id}){
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
const info = await TlChannelDao.getInfo({
[TlChannelDef.id]: id,
})
if(info == null){
return {}
}
return info
}
/**
* getListByIdList 接口
* @param {*} companyId
@ -118,6 +139,30 @@ const getListByIdList = async function({companyId, idList}, fields){
return list
}
/**
* getListByIdListNoCompanyId 接口
* @param {*} idList
* @param {*} fields
*/
const getListByIdListNoCompanyId = async function({ idList }, fields){
if(!idList){
tlConsoleError(TableName, "请求service参数idList为空")
return []
}
const list = await TlChannelDao.getList({
[TlChannelDef.id]: idList
}, fields, [
[TlChannelDef.createdAt, "DESC"]
])
if(list == null){
return []
}
return list
}
/**
* getListByIdListForPage 接口
* @param {*} companyId
@ -221,12 +266,12 @@ const deleteInfoById = async function({companyId, id}){
// 参数校验
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
return 0
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
return 0
}
const info = await TlChannelDao.deleteInfo({
@ -236,19 +281,172 @@ const deleteInfoById = async function({companyId, id}){
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
return 0
}
return info
}
/**
* getListForPage 接口
* @param {*} fields
* @param {*} page
* @param {*} pageSize
*/
const getListForPage = async function({ }, fields, page, pageSize){
if(!page){
tlConsoleError(TableName, "请求service参数page为空")
return []
}
if(!pageSize){
tlConsoleError(TableName, "请求service参数pageSize为空")
return []
}
if(page <= 0){
tlConsoleError(TableName, "请求service参数page不合法")
return []
}
if(pageSize <= 0){
tlConsoleError(TableName, "请求service参数pageSize不合法")
return []
}
if(pageSize > 1000){
tlConsoleError(TableName, "请求service参数pageSize过大")
return []
}
const list = await TlChannelDao.getListForPage({
[TlChannelDef.id]: {
[Op.gte]: 0
}
}, fields, [
[TlChannelDef.createdAt, "DESC"]
], page, pageSize)
if(list == null){
return []
}
return list
}
/**
* getListByKeywordForPage 接口
* @param {*} keyword
* @param {*} fields
* @param {*} page
* @param {*} pageSize
* @returns
*/
const getListByKeywordForPage = async function({ keyword }, fields, page, pageSize){
if(!keyword){
tlConsoleError(TableName, "请求service参数keyword为空")
return []
}
if(!page){
tlConsoleError(TableName, "请求service参数page为空")
return []
}
if(!pageSize){
tlConsoleError(TableName, "请求service参数pageSize为空")
return []
}
if(page <= 0){
tlConsoleError(TableName, "请求service参数page不合法")
return []
}
if(pageSize <= 0){
tlConsoleError(TableName, "请求service参数pageSize不合法")
return []
}
if(pageSize > 1000){
tlConsoleError(TableName, "请求service参数pageSize过大")
return []
}
const list = await TlChannelDao.getListForPage({
[TlChannelDef.name]: {
[Op.like]: `%${keyword}%`
}
}, fields, [
[TlChannelDef.createdAt, "DESC"]
], page, pageSize)
if(list == null){
return []
}
return list
}
/**
* getCount 接口
* @returns
*/
const getCount = async function({ }){
const count = await TlChannelDao.getCount({
[TlChannelDef.id]: {
[Op.gte]: 0
}
})
if(count === null){
return 0
}
return count
}
/**
* getCountByKeyword 接口
* @param {*} keyword
* @returns
*/
const getCountByKeyword = async function({ keyword }){
if(!keyword){
tlConsoleError(TableName, "请求service参数keyword为空")
return 0
}
const count = await TlChannelDao.getCount({
[TlChannelDef.name]: {
[Op.like]: `%${keyword}%`
}
})
if(count === null){
return 0
}
return count
}
module.exports = {
addInfo,
updateInfoById,
deleteInfoById,
getInfoById,
getInfoByIdNoCompanyId,
getListByIdList,
getListByIdListForPage
getListByIdListNoCompanyId,
getListByIdListForPage,
getListForPage,
getListByKeywordForPage,
getCount,
getCountByKeyword
}

Some files were not shown because too many files have changed in this diff Show More