Merge pull request #1 from tl-open-source/feat-init-project

feat: first init project
This commit is contained in:
https://blog.iamtsm.cn 2025-02-07 12:40:15 +08:00 committed by GitHub
commit 30ed2d54be
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
240 changed files with 72762 additions and 104 deletions

113
.gitignore vendored
View File

@ -1,130 +1,39 @@
# ---> Node
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Dependency directory
# https://docs.npmjs.com/misc/faq#should-i-check-my-node-modules-folder-into-git
node_modules
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
.DS_Store
# TypeScript cache
*.tsbuildinfo
dist/
# Optional npm cache directory
.npm
tmp/
# Optional eslint cache
.eslintcache
.VSCodeCounter/
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
electron-dist/

View File

@ -1,2 +1,27 @@
# tl-rtc-app
tl rtc apps
![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) 文件。

66
conf/env_config.js Normal file
View File

@ -0,0 +1,66 @@
const path = require("path");
const dotEnv = require("dotenv");
/**
* 从.env文件中加载环境变量
* docker环境下,使用docker-compose.yml中指定的env逻辑,不使用主动加载的.env文件中的环境变量
* docker环境下,使用docker run 中指定的 -e 逻辑,不使用主动加载的.env文件中的环境变量
* 非docker环境下,使用.env文件中的环境变量
*/
const load_env_config = function(){
if(process.env.tl_rtc_app_node_load_env === 'false'){
return
}
const pathsEnv = path.resolve(__dirname, "../")
dotEnv.config({ path: `${pathsEnv}/tlrtcapp.env` })
console.log(`load env config from .env file ${pathsEnv}/tlrtcapp.env`)
}
/**
* 从环境变量中注入配置
* 1. 适配容器环境
* 2. 数据格式转换
* 3. 统一管理
*/
const get_env_config = function () {
let defaultConfJson = {}
Object.keys(process.env).filter( key => key.startsWith("tl_rtc_app_") ).map(key => {
let value = process.env[key]
key = key.replace("tl_rtc_app_","")
//端口相关的配置转换为数字
if (key.endsWith('_port')) {
value = parseInt(value)
}
//过期时间相关的配置转换为数字
if(key.endsWith("_expire")){
value = parseInt(value)
}
//开关相关的配置转换为boolean
if (key.endsWith('_open')) {
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
}
module.exports = {
get_env_config,
load_env_config
}

15
conf/keys/server.crt Normal file
View File

@ -0,0 +1,15 @@
-----BEGIN CERTIFICATE-----
MIICVTCCAb4CCQCCDZ6FebPIqjANBgkqhkiG9w0BAQsFADBvMQswCQYDVQQGEwJV
UzENMAsGA1UECAwETWFyczETMBEGA1UEBwwKaVRyYW5zd2FycDETMBEGA1UECgwK
aVRyYW5zd2FycDETMBEGA1UECwwKaVRyYW5zd2FycDESMBAGA1UEAwwJMTI3LjAu
MC4xMB4XDTE4MDcxMDAzMTYzN1oXDTI4MDcwNzAzMTYzN1owbzELMAkGA1UEBhMC
VVMxDTALBgNVBAgMBE1hcnMxEzARBgNVBAcMCmlUcmFuc3dhcnAxEzARBgNVBAoM
CmlUcmFuc3dhcnAxEzARBgNVBAsMCmlUcmFuc3dhcnAxEjAQBgNVBAMMCTEyNy4w
LjAuMTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1I6AQ6eNez85kcKjwy3g
/vcnXtw+EbP4Ab37fLhIIWG+XzmEBAqnCYjM3nmlDIGEfNylGReo9mD2OHg46a1D
wjd3pxTMit41pCTCiu8S9A2UJfbhSzQrfs+IZcNye4KR9/FzNEW6KoKQ0uc6X33E
0xe41hbRMQoKB3WmxvyN8PcCAwEAATANBgkqhkiG9w0BAQsFAAOBgQAd7GNDtKWA
0OpSCzMu0pbmss9Erh4/RC8D+wK4+TXgPDKyZ6hX4FYPvk+ryMvwxJf0o4jjx5cx
Yew7UjaKHlGXq+CNVRFYlltsbvO3oQTNkajuyYGWzMSuNxNsT3apOxH7SIu3qao8
COSwj5FxZ2JU7O+SBVFZoJrFXEa+KJMQzQ==
-----END CERTIFICATE-----

15
conf/keys/server.key Normal file
View File

@ -0,0 +1,15 @@
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQDUjoBDp417PzmRwqPDLeD+9yde3D4Rs/gBvft8uEghYb5fOYQE
CqcJiMzeeaUMgYR83KUZF6j2YPY4eDjprUPCN3enFMyK3jWkJMKK7xL0DZQl9uFL
NCt+z4hlw3J7gpH38XM0RboqgpDS5zpffcTTF7jWFtExCgoHdabG/I3w9wIDAQAB
AoGAWsy1BjGhQrDzisy24D3NC53Q97jl2vIiU7wwnkqqpXf3tv3+4ysZx/zkZ3VX
iEwbqKso69srlnQ9OkpBJbGaa6lZe+z7BGzv2eJr+hKjjVjR122eDjAtXw+Tmt6c
iBUG9+ITC1GdhXLEgTXtYuPq8hbDhoAVI007E+5JuQoO8kECQQD3aR6zGfR7EOmn
byGkNMMPY/FoH894BpB4l7gIlNXH3pxBqukrEwnmVXSfak2PAkeLFO+bgCc6baIZ
+R4iOLn/AkEA2++dIndbY7nmGs7Q//sM7MkFMiFQ4h1nN38V9AEHaUonxlwo+Nks
PTAaVd78YIh6yBlfexm0Fxi1mEVQApqZCQJAFUPqyJglhGJqwuJxcMy8K1l6yWla
isV9q2/W+J3aViiTI63OBs7HHg4gTQd1DSK0BYdSJPp55LLBqRvZdDWN/wJBAMQa
M46exAL4p55xl9MWwyCB4LshD6B9vSGzlBx7qmMMNsjcNcAkzBhGwsScTYW5S1kN
nqABfB037/s0mjGoLRkCQF18j4MovyFaj8VAqY8YUmf86Ez9JmL9kHNA8yEoSjuI
xsRa6y5Nza5y83Mojt4W+PfS386riJ7txqrPdezyag4=
-----END RSA PRIVATE KEY-----

347
gulpfile.js Normal file
View File

@ -0,0 +1,347 @@
'use strict';
const pkg = require('./package.json');
const gulp = require('gulp');
const uglifyEs = require('gulp-uglify-es').default;
const cleanCSS = require('gulp-clean-css');
const concat = require('gulp-concat');
const rename = require('gulp-rename');
const replace = require('gulp-replace');
const header = require('gulp-header');
const babel = require('gulp-babel');
const del = require('del');
const minimist = require('minimist');
const gulpHtmlmin = require('gulp-htmlmin');
const gzip = require('gulp-gzip');
// 文件版本
const fileVersion = new Date().getTime();
// 基础配置
const config = {
//注释
comment: [
`/**
File: TL-RTC-APP-SDK-V<%= pkg.version %>
Licensed: <%= pkg.license %>
Repository: <%= pkg.repository.url %>
Author: <%= pkg.author %>
Build: <%= new Date().toLocaleString() %>
*/
`
, { pkg: pkg, js: '' }
]
};
// 获取参数
const argv = minimist(process.argv.slice(2), {
default: {
version: pkg.version
}
});
// 输出目录
const dest = ({
dist: './dist'
}[argv.dest || 'dist'] || argv.dest) + (argv.vs ? '/' + pkg.version : '');
// lib-entry-sdk.min.js
const entry_js = () => {
return gulp.src([
'./web-v2-res/js/tl_rtc_entry.js',
])
.pipe(babel())
.pipe(uglifyEs({
mangle: true,
compress: true,
output: {
ascii_only: true
},
}))
.pipe(replace(' ', ''))
.pipe(replace('\n', ''))
.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(replace(
'lib-module-sdk.min.js', 'lib-module-sdk.min.' + fileVersion + '.js'
))
.pipe(concat('lib-entry-sdk.min.' + fileVersion + '.js', { newLine: ' ' }))
.pipe(header.apply(null, config.comment))
.pipe(gulp.dest(dest))
.pipe(gzip({
append: true,
gzipOptions: {
level: 9,
memLevel: 9
}
}))
.pipe(gulp.dest(dest));
};
// lib-basic-sdk.min.js
const basic_js = () => {
return gulp.src([
'./web-v2-res/js/basic/*.js',
])
.pipe(babel())
.pipe(uglifyEs({
mangle: true,
compress: true,
output: {
ascii_only: true
},
}))
.pipe(replace(' ', ''))
.pipe(replace('\n', ''))
.pipe(concat('lib-basic-sdk.min.' + fileVersion + '.js', { newLine: ';' }))
.pipe(header.apply(null, config.comment))
.pipe(gulp.dest(dest))
.pipe(gzip({
append: true,
gzipOptions: {
level: 9,
memLevel: 9
}
}))
.pipe(gulp.dest(dest));
};
// lib-component-sdk.min.js
const component_js = () => {
return gulp.src([
'./web-v2-res/js/component/*.js',
])
.pipe(babel())
.pipe(uglifyEs({
mangle: true,
compress: true,
output: {
ascii_only: true
},
}))
.pipe(replace(' ', ''))
.pipe(replace('\n', ''))
.pipe(concat('lib-component-sdk.min.' + fileVersion + '.js', { newLine: ' ' }))
.pipe(header.apply(null, config.comment))
.pipe(gulp.dest(dest))
.pipe(gzip({
append: true,
gzipOptions: {
level: 9,
memLevel: 9
}
}))
.pipe(gulp.dest(dest));
};
// lib-module-sdk.min.js
const 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',
// 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',
// 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',
// 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',
// 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',
// 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',
// 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',
//setting模块
'./web-v2-res/js/module/setting/list.js',
'./web-v2-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',
//blank模块
'./web-v2-res/js/module/blank/content.js',
//主模块
'./web-v2-res/js/tl_rtc_app.js',
])
.pipe(babel())
.pipe(uglifyEs({
mangle: true,
compress: true,
output: {
ascii_only: true
},
}))
.pipe(replace(' ', ''))
.pipe(replace('\n', ''))
.pipe(concat('lib-module-sdk.min.' + fileVersion + '.js', { newLine: ' ' }))
.pipe(header.apply(null, config.comment))
.pipe(gulp.dest(dest))
.pipe(gzip({
append: true,
gzipOptions: {
level: 9,
memLevel: 9
}
}))
.pipe(gulp.dest(dest));
};
// js
const js = gulp.parallel(
basic_js, entry_js, component_js, module_js
);
// css
const 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',
])
.pipe(cleanCSS())
.pipe(concat('lib-css-sdk.min.' + fileVersion + '.css', { newLine: '\n' }))
.pipe(header.apply(null, config.comment))
.pipe(gulp.dest(dest))
.pipe(gzip({
append: true,
gzipOptions: {
level: 9,
memLevel: 9
}
}))
.pipe(gulp.dest(dest));
};
// html
const html = () => {
return gulp.src([
'./web-v2-res/*.{html,json}',
])
.pipe(replace(
'lib-entry-sdk.min.js', 'lib-entry-sdk.min.' + fileVersion + '.js'
))
.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(replace(
'lib-module-sdk.min.js', 'lib-module-sdk.min.' + fileVersion + '.js'
))
.pipe(replace(
'lib-css-sdk.min.css', 'lib-css-sdk.min.' + fileVersion + '.css'
))
.pipe(gulpHtmlmin({
collapseWhitespace: true,
removeComments: true,
}))
.pipe(gulp.dest(dest))
.pipe(gzip({
append: true,
gzipOptions: {
level: 9,
memLevel: 9
}
}))
.pipe(gulp.dest(dest));
};
// image
const 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}',
])
.pipe(gulp.dest(dest + '/image'))
.pipe(gzip({
append: true,
gzipOptions: {
level: 9,
memLevel: 9
}
}))
.pipe(gulp.dest(dest + '/image'));
};
// statics
const statics = () => {
return gulp.src([
'./web-v2-res/static/**/*.*',
])
.pipe(gulp.dest(dest + '/static'))
.pipe(gzip({
append: true,
gzipOptions: {
level: 9,
memLevel: 9
}
}))
.pipe(gulp.dest(dest + '/static'));
};
// clean
const clean = cb => {
return del([dest], {
force: true
});
};
const defaultTask = gulp.series(clean, gulp.parallel(
basic_js, entry_js, component_js, module_js, css, html, image, statics
));
// task
exports.default = gulp.series(clean, gulp.parallel(
js, css, html, image, statics
));
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);
};

12313
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

69
package.json Normal file
View File

@ -0,0 +1,69 @@
{
"name": "tl-rtc-app",
"version": "0.0.1",
"description": "im chat",
"main": "main.js",
"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"
},
"repository": {
"type": "git",
"url": "https://github.com/tl-open-source/tl-rtc-app"
},
"keywords": [
"none"
],
"author": "iamtsm",
"license": "MIT",
"dependencies": {
"@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",
"gulp": "^4.0.2",
"gulp-babel": "^8.0.0",
"gulp-clean-css": "^4.3.0",
"gulp-concat": "^2.6.1",
"gulp-footer": "^2.1.0",
"gulp-gzip": "^1.4.2",
"gulp-header": "^2.0.9",
"gulp-htmlmin": "^5.0.1",
"gulp-javascript-obfuscator": "^1.1.6",
"gulp-jshint": "^2.1.0",
"gulp-minify-css": "^1.2.4",
"gulp-rename": "^2.0.0",
"gulp-replace": "^1.1.3",
"gulp-rev": "^11.0.0",
"gulp-rev-all": "^4.0.0",
"gulp-uglify": "^3.0.2",
"gulp-uglify-es": "^3.0.0",
"lru-cache": "^10.0.1",
"minimist": "^1.2.5",
"multer": "^1.4.5-lts.1",
"mysql2": "^2.1.0",
"nodemailer": "^6.9.14",
"nodemailer-smtp-transport": "^2.7.4",
"redis": "^4.6.13",
"request": "^2.88.2",
"rollup-plugin-copy": "^3.4.0",
"sequelize": "^6.1.0",
"sequelize-pool": "^6.0.0",
"socket.io": "^2.3.0",
"socket.io-msgpack-parser": "^3.0.2",
"terser": "^5.18.2",
"uuid": "^9.0.1"
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,691 @@
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess,
setBit
} = 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 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 {
Def: TlChannelChatDef,
Type: TlChannelChatType,
Other: TlChannelChatOther,
Flag: TlChannelChatFlag
} = channelChatFields
const {
Def: TlChannelUserDef
} = channelUserFields
const {
Def: TlUserDef
} = userFields
const {
Def: TlChannelDef, Type: TlChannelType
} = channelFields
/**
* 发送好友频道聊天消息
* @param {*} loginInfo
* @param {*} message
* @param {*} toUserId
* @param {*} toUserName
* @param {*} channelId
* @param {*} atUserId
* @param {*} atUserName
*/
const addFriendChannelChat = async function ({
loginInfo, message, toUserId, toUserName, channelId, atUserId, atUserName
}) {
if (!message) {
return tlResponseArgsError("请求参数为空")
}
if (!channelId) {
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId, loginUsername, loginUserAvatar
} = loginInfo
// 频道是否存在
const channelInfo = await channelService.getInfoById({
companyId: loginUserCompanyId,
id: channelId
})
if(Object.keys(channelInfo).length == 0){
return tlResponseNotFound("发送失败,频道不存在")
}
// 设置@标志
let flag = 0
if (atUserId && atUserName) {
flag = setBit(flag, TlChannelChatFlag.IS_AT_USER, true)
}
let other = {
[TlChannelChatOther.ip]: '',
}
if (atUserId && atUserName) {
other = {
...other,
[TlChannelChatOther.atUserId]: atUserId,
[TlChannelChatOther.atUserName]: atUserName,
}
}
// 发送好友消息,如果没有toUserName或toUserId,说明可能已被对方删除
// 如果没有找到好友,返回错误,如果找到好友,返回参数错误
if(!toUserName || !toUserId){
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("发送失败,好友不存在")
}
return tlResponseArgsError("请求参数为空")
}
const info = await channelChatService.addFriendChatInfo({
companyId: loginUserCompanyId,
channelId,
message,
fromUserId: loginUserId,
fromUserName: loginUsername,
toUserId,
toUserName,
other: JSON.stringify(other),
messageTimeStamp: Date.now(),
messageVersion: 'v1',
flag
})
if (Object.keys(info).length == 0) {
return tlResponseSvrError("添加好友频道聊天失败")
}
// 更新用户已读消息
const updateUserReadRes = await userReadBiz.updateChannelChatRead({
loginInfo, channelId,
latestReadId: info[TlChannelChatDef.id],
})
if(!updateUserReadRes.success){
return tlResponseSvrError("发送失败")
}
return tlResponseSuccess("发送成功", {
id: info[TlChannelChatDef.id],
message: info[TlChannelChatDef.message],
type: info[TlChannelChatDef.type],
createTime: info[TlChannelChatDef.createdAt],
fromUserId: info[TlChannelChatDef.fromUserId],
fromUserName: info[TlChannelChatDef.fromUserName],
fromUserAvatar: loginUserAvatar,
hasRead: true,
atUserId,
atUserName,
messageTimeStamp: info[TlChannelChatDef.messageTimeStamp],
messageVersion: info[TlChannelChatDef.messageVersion],
})
}
/**
* 发送多人频道聊天消息
* @param {*} loginInfo
* @param {*} message
* @param {*} channelId
* @param {*} atUserId
* @param {*} atUserName
* @param {*} atAll
*/
const addGroupChannelChat = async function ({
loginInfo, message, channelId, atUserId, atUserName, atAll
}) {
if (!message) {
return tlResponseArgsError("请求参数为空")
}
if (!channelId) {
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId, loginUsername,
loginUserAvatar
} = loginInfo
// 频道是否存在
const channelInfo = await channelService.getInfoById({
companyId: loginUserCompanyId,
id: channelId
})
if(Object.keys(channelInfo).length == 0){
return tlResponseNotFound("发送失败,频道不存在")
}
// 设置@标志
let flag = 0
if (atUserId && atUserName) {
flag = setBit(flag, TlChannelChatFlag.IS_AT_USER, true)
}else if (atAll) {
flag = setBit(flag, TlChannelChatFlag.IS_AT_ALL, true)
}
let other = {
[TlChannelChatOther.ip]: '',
}
if (atUserId && atUserName) {
other = {
...other,
[TlChannelChatOther.atUserId]: atUserId,
[TlChannelChatOther.atUserName]: atUserName,
}
}
const info = await channelChatService.addGroupChatInfo({
companyId: loginUserCompanyId,
channelId,
message,
fromUserId: loginUserId,
fromUserName: loginUsername,
other: JSON.stringify(other),
messageTimeStamp: Date.now(),
messageVersion: 'v1',
flag
})
if (Object.keys(info).length == 0) {
return tlResponseSvrError("添加群组聊天失败")
}
// 更新用户已读消息
const updateUserReadRes = await userReadBiz.updateChannelChatRead({
loginInfo, channelId,
latestReadId: info[TlChannelChatDef.id],
})
if(!updateUserReadRes.success){
return tlResponseSvrError("发送失败")
}
return tlResponseSuccess("发送成功", {
id: info[TlChannelChatDef.id],
message: info[TlChannelChatDef.message],
type: info[TlChannelChatDef.type],
createTime: info[TlChannelChatDef.createdAt],
fromUserId: info[TlChannelChatDef.fromUserId],
fromUserName: info[TlChannelChatDef.fromUserName],
fromUserAvatar: loginUserAvatar,
hasRead: true,
atUserId,
atUserName,
isAtAll: atAll,
messageTimeStamp: info[TlChannelChatDef.messageTimeStamp],
messageVersion: info[TlChannelChatDef.messageVersion],
})
}
/**
* 撤回群组/好友消息
* @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
* @param {*} message
* @param {*} channelId
* @param {*} messageId
* @param {*} atUserId
* @param {*} atUserName
* @param {*} messageType
*/
const addReplyFriendChannelChat = async function ({
loginInfo, message, channelId, messageId, messageType, atUserId, atUserName
}) {
const {
loginUserCompanyId, loginUserId, loginUsername, loginUserAvatar
} = loginInfo
if (!message) {
return tlResponseArgsError("请求参数为空")
}
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("发送失败,频道不存在")
}
const channelType = channelInfo[TlChannelDef.type]
if(channelType !== TlChannelType.FRIEND){
return tlResponseArgsError("发送失败,频道类型错误")
}
// 消息是否存在
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("发送失败,回复消息不存在")
}
// 设置回复标志
let flag = setBit(0, TlChannelChatFlag.IS_REPLAY, true)
if (atUserId && atUserName) {
flag = setBit(flag, TlChannelChatFlag.IS_AT_USER, true)
}
let other = {
[TlChannelChatOther.ip]: '',
[TlChannelChatOther.replyToMessageId]: messageId,
[TlChannelChatOther.replyToMessageType]: messageType,
}
if (atUserId && atUserName) {
other = {
...other,
[TlChannelChatOther.atUserId]: atUserId,
[TlChannelChatOther.atUserName]: atUserName,
}
}
const info = await channelChatService.addFriendChatInfo({
companyId: loginUserCompanyId,
channelId,
message,
fromUserId: loginUserId,
fromUserName: loginUsername,
toUserId: messageInfo[TlChannelChatDef.fromUserId],
toUserName: messageInfo[TlChannelChatDef.fromUserName],
other: JSON.stringify(other),
messageTimeStamp: Date.now(),
messageVersion: 'v1',
flag
})
if(Object.keys(info).length == 0){
return tlResponseSvrError("回复失败")
}
// 更新用户已读消息
const updateUserReadRes = await userReadBiz.updateChannelChatRead({
loginInfo, channelId,
latestReadId: info[TlChannelChatDef.id],
})
if(!updateUserReadRes.success){
return tlResponseSvrError("回复失败")
}
let replyToMessageContent = ''
if([
TlChannelChatType.FRIEND,
TlChannelChatType.GROUP,
].includes(messageType)){
replyToMessageContent = messageInfo[TlChannelChatDef.message]
}else{
replyToMessageContent = '未知消息'
}
return tlResponseSuccess("回复成功", {
id: info[TlChannelChatDef.id],
message: info[TlChannelChatDef.message],
type: info[TlChannelChatDef.type],
createTime: info[TlChannelChatDef.createdAt],
fromUserId: info[TlChannelChatDef.fromUserId],
fromUserName: info[TlChannelChatDef.fromUserName],
fromUserAvatar: loginUserAvatar,
toUserId: messageInfo[TlChannelChatDef.fromUserId],
toUserName: messageInfo[TlChannelChatDef.fromUserName],
hasRead: true,
replyToMessageId: messageId,
replyToMessageType: messageType,
replyToMessageContent,
atUserId,
atUserName,
messageTimeStamp: info[TlChannelChatDef.messageTimeStamp],
messageVersion: info[TlChannelChatDef.messageVersion],
})
}
/**
* 回复群组聊天
* @param {*} loginInfo
* @param {*} message
* @param {*} channelId
* @param {*} messageId
* @param {*} atUserId
* @param {*} atUserName
* @param {*} atAll
* @param {*} messageType
*/
const addReplyGroupChannelChat = async function ({
loginInfo, message, channelId, messageId, messageType, atUserId, atUserName, atAll
}) {
const {
loginUserCompanyId, loginUserId, loginUsername, loginUserAvatar
} = loginInfo
if (!message) {
return tlResponseArgsError("请求参数为空")
}
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("发送失败,频道不存在")
}
const channelType = channelInfo[TlChannelDef.type]
if(channelType !== TlChannelType.GROUP){
return tlResponseArgsError("发送失败,频道类型错误")
}
// 消息是否存在
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("发送失败,回复消息不存在")
}
// 设置回复标志
let flag = setBit(0, TlChannelChatFlag.IS_REPLAY, true)
if (atUserId && atUserName) {
flag = setBit(flag, TlChannelChatFlag.IS_AT_USER, true)
}else if (atAll) {
flag = setBit(flag, TlChannelChatFlag.IS_AT_ALL, true)
}
let other = {
[TlChannelChatOther.ip]: '',
[TlChannelChatOther.replyToMessageId]: messageId,
[TlChannelChatOther.replyToMessageType]: messageType,
}
if (atUserId && atUserName) {
other = {
...other,
[TlChannelChatOther.atUserId]: atUserId,
[TlChannelChatOther.atUserName]: atUserName,
}
}
const info = await channelChatService.addGroupChatInfo({
companyId: loginUserCompanyId,
channelId,
message,
fromUserId: loginUserId,
fromUserName: loginUsername,
toUserId: messageInfo[TlChannelChatDef.fromUserId],
toUserName: messageInfo[TlChannelChatDef.fromUserName],
other: JSON.stringify(other),
messageTimeStamp: Date.now(),
messageVersion: 'v1',
flag
})
if(Object.keys(info).length == 0){
return tlResponseSvrError("回复失败")
}
// 更新用户已读消息
const updateUserReadRes = await userReadBiz.updateChannelChatRead({
loginInfo, channelId,
latestReadId: info[TlChannelChatDef.id],
})
if(!updateUserReadRes.success){
return tlResponseSvrError("回复失败")
}
let replyToMessageContent = ''
if([
TlChannelChatType.FRIEND,
TlChannelChatType.GROUP,
].includes(messageType)){
replyToMessageContent = messageInfo[TlChannelChatDef.message]
}else{
replyToMessageContent = '未知消息'
}
return tlResponseSuccess("回复成功", {
id: info[TlChannelChatDef.id],
message: info[TlChannelChatDef.message],
type: info[TlChannelChatDef.type],
createTime: info[TlChannelChatDef.createdAt],
fromUserId: info[TlChannelChatDef.fromUserId],
fromUserName: info[TlChannelChatDef.fromUserName],
fromUserAvatar: loginUserAvatar,
toUserId: messageInfo[TlChannelChatDef.fromUserId],
toUserName: messageInfo[TlChannelChatDef.fromUserName],
hasRead: true,
replyToMessageId: messageId,
replyToMessageType: messageType,
replyToMessageContent,
atUserId,
atUserName,
isAtAll: atAll,
messageTimeStamp: info[TlChannelChatDef.messageTimeStamp],
messageVersion: info[TlChannelChatDef.messageVersion],
})
}
module.exports = {
addFriendChannelChat,
addGroupChannelChat,
addReplyFriendChannelChat,
addReplyGroupChannelChat,
rollbackChannelChat,
}

View File

@ -0,0 +1,738 @@
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess, setBit, checkBit
} = require('../../utils/utils')
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 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 { inner: TlRoleInner } = require('../../tables/tl_role')
const { fields: channelUserFields } = require('../../tables/tl_channel_user')
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 { Def: TlChannelUserDef, Type: TlChannelUserType, Flag: TlChannelUserFlag } = channelUserFields
const { Def : TlUserDef } = userFields
const { Def: TlUserFriendDef } = userFriendFields
const { Def: TlChannelDef, Type: TlChannelType } = channelFields
const { Def: TlChannelChatDef, Other: TlChannelChatOther } = channelChatFields
/**
* 添加频道用户
* @param {*} loginInfo
* @param {*} channelId
* @param {*} userId
* @param {*} roleId
*/
const addChannelUser = async function({ loginInfo, channelId, userId, roleId }){
if(!channelId){
return tlResponseArgsError("请求参数为空")
}
if(!userId){
return tlResponseArgsError("请求参数为空")
}
if(!roleId){
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("频道不存在")
}
const channelType = channelInfo[TlChannelDef.type]
if (channelType != TlChannelType.GROUP){
return tlResponseArgsError("频道非法操作")
}
const channelUser = await channelUserService.getInfoByChannelIdAndUserId({
companyId: loginUserCompanyId,
channelId,
userId,
}, [
TlChannelUserDef.userId
])
if(Object.keys(channelUser).length > 0){
return tlResponseArgsError("频道用户已存在")
}
const userInfo = await userService.getInfoById({
companyId: loginUserCompanyId,
id: userId,
},[
TlUserDef.name
])
// 生成邀请消息
const channelMessage = await channelChatService.addSystemChatnfo({
companyId: loginUserCompanyId,
channelId,
message: '<p>' + loginUsername + "邀请 " + userInfo[TlUserDef.name] + "加入频道" + '</p>',
other: JSON.stringify({
[TlChannelChatOther.ip]: '',
}),
messageTimeStamp: Date.now(),
messageVersion: 'v1',
flag: 0
})
if(Object.keys(channelMessage).length == 0){
return tlResponseSvrError("添加频道用户失败")
}
// 添加频道用户
const info = await channelUserService.addInfo({
companyId: loginUserCompanyId,
channelId,
userId,
type: TlChannelUserType.GROUP,
roleId,
})
if(Object.keys(info).length == 0){
return tlResponseSvrError("添加频道用户失败")
}
// 更新用户频道角色
await userSessionService.updateUserChannelRoleMap({
userId: loginUserId,
channelRoleMap: {
[channelId]: roleId
}
})
return tlResponseSuccess("添加频道用户成功")
}
/**
* 批量添加频道用户
* @param {*} loginInfo
* @param {*} channelId
* @param {*} userIdList
* @param {*} roleId
*/
const addChannelUserList = async function({ loginInfo, channelId, userIdList, roleId }){
if(!channelId){
return tlResponseArgsError("请求参数为空")
}
if(!userIdList){
return tlResponseArgsError("请求参数为空")
}
if(userIdList.length == 0){
return tlResponseArgsError("请求参数为空")
}
if(userIdList.length > 100){
return tlResponseArgsError("邀请用户数量超过限制")
}
if(!roleId){
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("频道不存在")
}
const channelType = channelInfo[TlChannelDef.type]
if (channelType != TlChannelType.GROUP){
return tlResponseArgsError("频道非法操作")
}
// userIdList去重
userIdList = Array.from(new Set(userIdList))
const existChannelUserList = await channelUserService.getListByChannelUserIdList({
companyId: loginUserCompanyId,
channelId,
userIdList: userIdList,
}, [
TlChannelUserDef.userId
])
if(existChannelUserList.length > 0){
return tlResponseArgsError("部分频道用户已存在", {
existUserIdList: existChannelUserList.map(item => item[TlChannelUserDef.userId])
})
}
// 获取用户信息
const userInfoList = await userService.getListByIdList({
companyId: loginUserCompanyId,
idList: userIdList,
}, [
TlUserDef.name
])
// 生成邀请消息
const channelMessage = await channelChatService.addSystemChatnfo({
companyId: loginUserCompanyId,
channelId,
message: '<p>' + loginUsername + "邀请 " + userInfoList.map(
item => item[TlUserDef.name]
).join(",") + " 共" + userInfoList.length + "人加入频道" + '</p>',
other: JSON.stringify({
[TlChannelChatOther.ip]: '',
}),
messageTimeStamp: Date.now(),
messageVersion: 'v1',
flag: 0
})
if(Object.keys(channelMessage).length == 0){
return tlResponseSvrError("添加频道用户失败")
}
let infoList = []
userIdList.forEach(userId => {
infoList.push({
companyId: loginUserCompanyId,
channelId,
userId,
type: TlChannelUserType.GROUP,
roleId,
})
})
const list = await channelUserService.addInfoList({
companyId: loginUserCompanyId,
channelId,
userInfoList: infoList,
})
if(list == null){
return tlResponseSvrError("添加频道用户失败")
}
// 更新用户频道角色
await userSessionService.batchUpdateUserChannelRoleMap({
userIdList: userIdList,
channelRoleMap: {
[channelId]: roleId
}
})
return tlResponseSuccess("添加频道用户成功", {
id: channelMessage[TlChannelChatDef.id],
message: channelMessage[TlChannelChatDef.message],
type: channelMessage[TlChannelChatDef.type],
createTime: channelMessage[TlChannelChatDef.createdAt],
fromUserId: channelMessage[TlChannelChatDef.fromUserId],
fromUserName: channelMessage[TlChannelChatDef.fromUserName],
fromUserAvatar: await getAvatarOssUrl(),
hasRead: false,
})
}
/**
* 分享加入群聊
* @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
})
}
/**
* 添加频道普通身份用户
* @param {*} loginInfo
* @param {*} channelId
* @param {*} userId
*/
const addChannelUserNormal = async function({ loginInfo, channelId, userId }){
return addChannelUser({
loginInfo, channelId, userId, roleId: TlRoleInner.channel.member.id
})
}
/**
* 批量添加频道普通身份用户
* @param {*} loginInfo
* @param {*} channelId
* @param {*} userIdList
*/
const addChannelUserListNormal = async function({ loginInfo, channelId, userIdList }){
return addChannelUserList({
loginInfo, channelId, userIdList, roleId: TlRoleInner.channel.member.id
})
}
/**
* 添加频道管理员身份用户
* @param {*} loginInfo
* @param {*} channelId
* @param {*} userId
*/
const addChannelUserAdmin = async function({ loginInfo, channelId, userId }){
return addChannelUser({
loginInfo, channelId, userId, roleId: TlRoleInner.channel.admin.id
})
}
/**
* 删除频道用户
* @param {*} loginInfo
* @param {*} channelUserId
*/
const deleteChannelUser = async function({ loginInfo, channelUserId }){
if(!channelUserId){
return tlResponseArgsError("请求参数为空")
}
const {
loginUserId, loginUserCompanyId
} = loginInfo
const info = await channelUserService.deleteInfoById({
companyId: loginUserCompanyId,
id: channelUserId,
})
if(info == 0){
return tlResponseSvrError("删除频道用户失败")
}
return tlResponseSuccess("删除频道用户成功")
}
/**
* 修改频道用户身份权限为普通用户
* @param {*} loginInfo
* @param {*} channelUserId
*/
const updateChannelUserRoleNormal = async function({ loginInfo, channelUserId }){
if(!channelUserId){
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId
} = loginInfo
const info = await channelUserService.updateInfoById({
companyId: loginUserCompanyId,
id: channelUserId,
},{
roleId: TlRoleInner.channel.member.id,
})
return tlResponseSuccess("修改频道用户成功")
}
/**
* 修改频道用户身份权限为管理员
* @param {*} loginInfo
* @param {*} channelUserId
*/
const updateChannelUserRoleAdmin = async function({ loginInfo, channelUserId }){
if(!channelUserId){
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId
} = loginInfo
const info = await channelUserService.updateInfoById({
companyId: loginUserCompanyId,
id: channelUserId,
}, {
roleId: TlRoleInner.channel.admin.id,
})
if(Object.keys(info).length == 0){
return tlResponseSvrError("修改频道用户失败")
}
return tlResponseSuccess("修改频道用户成功")
}
/**
* 获取频道用户列表
* @param {*} loginInfo
* @param {*} channelId
*/
const getChannelUserList = async function({ loginInfo, channelId }){
if(!channelId){
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId
} = loginInfo
const channelUserList = await channelUserService.getListByChannelId({
companyId: loginUserCompanyId,
channelId,
}, [
TlChannelUserDef.userId,
TlChannelUserDef.roleId,
TlChannelUserDef.channelId
])
const userIdList = channelUserList.map(channelUser => channelUser[TlChannelUserDef.userId])
// 获取用户信息
const userList = await userService.getListByIdList({
companyId: loginUserCompanyId,
idList: userIdList
}, [
TlUserDef.id,
TlUserDef.name,
TlUserDef.avatarUrl,
])
const userMap = {}
userList.forEach(user => userMap[user[TlUserDef.id]] = user)
// 获取好友关系
const friendList = await userFriendService.getListByUserIdAndFriendIdList({
companyId: loginUserCompanyId,
userId: loginUserId,
friendIdList: userIdList
}, [
TlUserFriendDef.id,
TlUserFriendDef.friendId,
TlUserFriendDef.rename
])
const firendMap = {}
friendList.forEach(friend => firendMap[friend[TlUserFriendDef.friendId]] = friend)
// 组装结果
let resultList = []
for(let i = 0; i < channelUserList.length; i++){
const channelUser = channelUserList[i]
const userId = channelUser[TlChannelUserDef.userId]
const user = userMap[userId]
if(!user){
return
}
// 获取好友关系名称
const friend = firendMap[userId] || {}
let friendName = friend[TlUserFriendDef.rename] || ""
let userFriendId = friend[TlUserFriendDef.id]
resultList.push({
userId: user[TlUserDef.id],
username: user[TlUserDef.name],
userAvatar: await getOssUrl(user[TlUserDef.avatarUrl]),
friendName: friendName,
userFriendId: userFriendId
})
}
return tlResponseSuccess("获取单个频道用户列表成功", resultList)
}
/**
* 获取频道列表的用户列表
* @param {*} loginInfo
*/
const getChannelListUserList = async function({loginInfo}){
const {
loginUserCompanyId, loginUserId
} = loginInfo
// 获取自己所在的频道列表
const selfShannelUserList = await channelUserService.getListByUserId({
companyId: loginUserCompanyId,
userId: loginUserId
}, [
TlChannelUserDef.channelId
])
const channelIdList = selfShannelUserList.map(channelUser => channelUser[TlChannelUserDef.channelId])
// 获取自己所在频道的所有用户列表
const allChannelUserList = await channelUserService.getListByChannelIdList({
companyId: loginUserCompanyId,
channelIdList
}, [
TlChannelUserDef.userId,
TlChannelUserDef.channelId,
])
const userIdList = allChannelUserList.map(channelUser => channelUser[TlChannelUserDef.userId])
// 获取用户信息
const userList = await userService.getListByIdList({
companyId: loginUserCompanyId,
idList: userIdList
}, [
TlUserDef.id,
TlUserDef.name,
TlUserDef.avatarUrl,
])
const userMap = {}
userList.forEach(user => userMap[user[TlUserDef.id]] = user)
// 获取好友关系
const friendList = await userFriendService.getListByUserIdAndFriendIdList({
companyId: loginUserCompanyId,
userId: loginUserId,
friendIdList: userIdList
}, [
TlUserFriendDef.id,
TlUserFriendDef.friendId,
TlUserFriendDef.rename
])
const firendMap = {}
friendList.forEach(friend => firendMap[friend[TlUserFriendDef.friendId]] = friend)
// 组装结果
let result = {}
for(let i = 0; i < allChannelUserList.length; i++){
const channelUser = allChannelUserList[i]
const channelId = channelUser[TlChannelUserDef.channelId]
const userId = channelUser[TlChannelUserDef.userId]
const user = userMap[userId]
if(!user){
return
}
// 获取好友关系名称
const friend = firendMap[userId] || {}
let friendName = friend[TlUserFriendDef.rename]
let userFriendId = friend[TlUserFriendDef.id]
const channelUserList = result[channelId] || []
channelUserList.push({
userId: user[TlUserDef.id],
username: user[TlUserDef.name],
userAvatar: await getOssUrl(user[TlUserDef.avatarUrl]),
friendName: friendName,
userFriendId: userFriendId
})
result[channelId] = channelUserList
}
return tlResponseSuccess("获取全部频道用户列表成功", result)
}
/**
* 设置频道置顶
* @param {*} channelId
* @param {*} loginInfo
* @param {*} top
* @returns
*/
const updateChannelToTop = async function({channelId, top = false, loginInfo}){
if(!channelId){
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId
} = loginInfo
const channelUserInfo = await channelUserService.getInfoByChannelIdAndUserId({
companyId: loginUserCompanyId,
channelId,
userId: loginUserId
}, [
TlChannelUserDef.id,
TlChannelUserDef.flag
])
if(Object.keys(channelUserInfo).length == 0){
return tlResponseNotFound("频道不存在")
}
const channelUserInfoId = channelUserInfo[TlChannelUserDef.id]
let flag = channelUserInfo[TlChannelUserDef.flag]
if(top){
flag = setBit(flag, TlChannelUserFlag.IS_SET_TOP, true)
}else{
flag = setBit(flag, TlChannelUserFlag.IS_SET_TOP, false)
}
const updateChannelUserInfo = await channelUserService.updateInfoById({
companyId: loginUserCompanyId,
id: channelUserInfoId
}, {
flag: flag
})
if(Object.keys(updateChannelUserInfo).length == 0){
return tlResponseSvrError(top ? "置顶失败" : "取消置顶失败")
}
return tlResponseSuccess(top ? "置顶成功" : "取消置顶成功")
}
/**
* 设置拉黑频道
* @param {*} channelId
* @param {*} loginInfo
* @param {*} black
* @returns
*/
const updateChannelToBlack = async function({channelId, black = false, loginInfo}){
if(!channelId){
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId
} = loginInfo
const channelUserInfo = await channelUserService.getInfoByChannelIdAndUserId({
companyId: loginUserCompanyId,
channelId,
userId: loginUserId
}, [
TlChannelUserDef.id,
TlChannelUserDef.flag
])
if(Object.keys(channelUserInfo).length == 0){
return tlResponseNotFound("频道不存在")
}
const channelUserInfoId = channelUserInfo[TlChannelUserDef.id]
let flag = channelUserInfo[TlChannelUserDef.flag]
if(black){
flag = setBit(flag, TlChannelUserFlag.IS_SET_BLACK, true)
}else{
flag = setBit(flag, TlChannelUserFlag.IS_SET_BLACK, false)
}
const updateChannelUserInfo = await channelUserService.updateInfoById({
companyId: loginUserCompanyId,
id: channelUserInfoId
}, {
flag: flag
})
if(Object.keys(updateChannelUserInfo).length == 0){
return tlResponseSvrError(black ? "拉黑失败" : "取消拉黑失败")
}
return tlResponseSuccess(black ? "拉黑成功" : "取消拉黑成功")
}
/**
* 退出群聊
* @param {*} channelId
*/
const exitChannel = async function({channelId, loginInfo}){
if(!channelId){
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId
} = loginInfo
// 获取频道用户
const channelUserInfo = await channelUserService.getInfoByChannelIdAndUserId({
companyId: loginUserCompanyId,
channelId,
userId: loginUserId
}, [
TlChannelUserDef.id,
])
if(Object.keys(channelUserInfo).length == 0){
return tlResponseNotFound("退出频道成功")
}
// 删除自己在频道的数据
await channelUserService.deleteInfoById({
companyId: loginUserCompanyId,
id: channelUserInfo[TlChannelUserDef.id]
})
return tlResponseSuccess("退出频道成功")
}
module.exports = {
addChannelUser,
addChannelUserNormal,
addChannelUserAdmin,
deleteChannelUser,
updateChannelUserRoleNormal,
updateChannelUserRoleAdmin,
getChannelUserList,
addChannelUserListNormal,
getChannelListUserList,
shareJoinGroupChannel,
updateChannelToTop,
updateChannelToBlack,
exitChannel
}

View File

@ -0,0 +1,97 @@
const uuid = require('uuid')
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess
} = require('../../utils/utils')
const companyService = require('../../service/company/tl_company_service')
const userSessionService = require('../../service/user/tl_user_session_service')
/**
* 添加企业
* @param {*} loginInfo
* @param {*} name
* @param {*} address
* @param {*} phone
* @param {*} email
* @param {*} website
* @param {*} logo
* @param {*} description
*/
const addCompany = async function ({
loginInfo, name, address, phone, email, website, logo, description
}) {
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("请求参数为空")
}
const {
loginUserCompanyId, loginUserId
} = loginInfo
const code = uuid.v4().replace(/-/g, '')
const info = await companyService.addInfo({
name,
address,
phone,
email,
website,
logo,
description,
code
})
if(Object.keys(info).length == 0){
return tlResponseSvrError("添加企业失败")
}
return tlResponseSuccess("添加企业成功", info)
}
/**
* 获取企业信息
* @param {*} loginInfo
*/
const getCompanyInfo = async function ({loginInfo}) {
const {
loginUserCompanyId, loginUserId
} = loginInfo
const info = await companyService.getInfoById({
id: loginUserCompanyId
})
return tlResponseSuccess("获取企业信息成功", info)
}
module.exports = {
addCompany,
getCompanyInfo
}

View File

@ -0,0 +1,138 @@
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')
/**
* 获取ip地址,初始化等相关配置
* @param {*} openTurn 是否开启turn
* @param {*} useSecret 使用的账号模式
* @param {*} ip ip地址
* @param {*} loginInfo 登录信息
*/
const initData = async function({openTurn, useSecret, ip, token}){
if(!token){
return tlResponseSuccess("获取成功",{
version : conf.version,
wsHost: "ws://127.0.0.1",
rtcConfig: { iceServers: [] },
options: {},
logo : genClientLogo(),
})
}
const {
loginUserCompanyId, loginUserId, loginUsername
} = await userSessionService.getUserInfoByToken({token})
if (!loginUserCompanyId || !loginUserId) {
return tlResponseSuccess("获取成功",{
version : conf.version,
wsHost: "ws://127.0.0.1",
rtcConfig: { iceServers: [] },
options: {},
logo : genClientLogo(),
})
}
//ice服务器配置
let iceServers = genTurnServerIceServersConfig(openTurn, useSecret, "tlrtcfile");
if(process.env.tl_rtc_app_env_mode === 'http'){
let wsHost = conf.socket_host || ip + conf.socket_port;
return tlResponseSuccess("获取成功",{
version : conf.version,
wsHost: "ws://" + wsHost,
rtcConfig: { iceServers },
options: {
"offerToReceiveAudio": 1,
"offerToReceiveVideo": 1
},
logo : genClientLogo(),
})
}
let wsHost = conf.socket_host || ip;
return tlResponseSuccess("获取成功",{
version : conf.version,
wsHost: "wss://" + wsHost,
rtcConfig: { iceServers },
options: {
"offerToReceiveAudio": 1,
"offerToReceiveVideo": 1
},
logo : genClientLogo(),
})
}
/**
* 生成客户端控制台打印logo
*/
const genClientLogo = function(){
let style = "font-size:20px;color: black; font-style: italic;";
style += "font-weight: bold; font-family: system-ui;";
style += "padding: 8px;cursor: pointer;"
return style;
}
/**
* 生成turn服务的iceServers配置
* @param {*} withTurn
* @param {*} useSecret
* @param {*} username
* @returns
*/
const genTurnServerIceServersConfig = function(withTurn, useSecret, username){
let iceServers = [{
urls : conf.webrtc_stun_host
}];
//无需turn中继
if(!withTurn){
return iceServers;
}
//turn固定账号模式
if(!useSecret){
iceServers.push({
urls : conf.webrtc_turn_host,
username: conf.webrtc_turn_username,
credential: conf.webrtc_turn_credential
})
return iceServers;
}
// 有效账号模式
const secret = conf.webrtc_turn_secret;
//生成账号的有效期
const expirseTime = conf.webrtc_turn_expire;
//当前时间
const time = new Date().getTime();
//turn服务的用户名规则
const turnUsername = `${time + expirseTime}:${username}`;
//turn服务的密码规则
const dig = crypto.createHmac('sha1', secret).update(turnUsername).digest();
const turnPassword = Buffer.from(dig, 'utf-8').toString('base64');
iceServers.push({
urls : conf.webrtc_turn_host,
username: turnUsername,
credential: turnPassword,
})
return iceServers;
}
module.exports = {
initData
}

View File

@ -0,0 +1,495 @@
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess,
setBit, checkBit,
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 userApplyService = require('../../service/user/tl_user_apply_service')
const userReadService = require('../../service/user/tl_user_read_service')
const userFriendBiz = require('./user_friend_biz')
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 { getOssUrl } = require('../../utils/oss/oss')
const TlUserDef = userFields.Def
const TlUserFriendDef = userFriendFields.Def
const TlUserFriendType = userFriendFields.FriendType
const TlUserFriendStatus = userFriendFields.Status
const TlUserApplyDef = userApplyFields.Def
const TlUserApplyStatus = userApplyFields.Status
const TlUserApplyType = userApplyFields.Type
const TlUserApplyOrigin = userApplyFields.Origin
const TlUserReadDef = userReadFields.Def
const TlUserReadType = userReadFields.Type
/**
* 申请添加好友
* @param {*} friendId
* @param {*} origin
* @param {*} remark
* @param {*} loginInfo
*/
const applyAddFriend = async function({ friendId, origin, remark, loginInfo }){
if(!friendId){
return tlResponseArgsError("请求参数为空")
}
if(!origin){
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId
} = loginInfo
if (loginUserId == friendId) {
return tlResponseForbidden("不能添加自己为好友")
}
const friendInfo = await userService.getInfoById({
companyId: loginUserCompanyId,
id: friendId
})
if(Object.keys(friendInfo).length == 0){
return tlResponseNotFound("用户不存在")
}
const userFriendInfo = await userFriendService.getInfoByUserIdAndFriendId({
companyId: loginUserCompanyId,
userId: loginUserId,
friendId
})
const status = userFriendInfo[TlUserFriendDef.status]
if(status == TlUserFriendStatus.NORMAL){
return tlResponseForbidden("已经是好友")
}
// 查看自己是否存在待验证的申请记录
let applyHistroryList = await userApplyService.getListByUserIdAndTargetIdAndStatuAndType({
companyId: loginUserCompanyId,
userId: loginUserId,
targetId: friendId,
status: TlUserApplyStatus.WAIT,
type: TlUserApplyType.FRIEND
}, [
TlUserApplyDef.id
])
if(applyHistroryList.length > 0){
return tlResponseForbidden("你已经向该用户发送过申请,请查看申请记录")
}
// 查看对方是否存在待验证的申请记录
applyHistroryList = await userApplyService.getListByUserIdAndTargetIdAndStatuAndType({
companyId: loginUserCompanyId,
userId: friendId,
targetId: loginUserId,
status: TlUserApplyStatus.WAIT,
type: TlUserApplyType.FRIEND
}, [
TlUserApplyDef.id
])
if(applyHistroryList.length > 0){
return tlResponseForbidden("对方已经向你发送过申请,请查看申请记录")
}
// 生成申请记录
const applyInfo = await userApplyService.addInfo({
companyId: loginUserCompanyId,
userId: loginUserId,
targetId: friendId,
origin,
remark,
type: TlUserApplyType.FRIEND,
status: TlUserApplyStatus.WAIT
})
if(Object.keys(applyInfo).length == 0){
return tlResponseSvrError("发送申请失败")
}
return tlResponseSuccess("发送申请成功", {
applyId: applyInfo[TlUserApplyDef.id]
})
}
/**
* 通过用户好友申请
* @param {*} id
* @param {*} loginInfo
* @returns
*/
const passUserFriendApply = async function({ id, loginInfo }){
if(!id){
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId, loginUsername
} = loginInfo
// 查询申请记录
const applyInfo = await userApplyService.getInfoById({
companyId: loginUserCompanyId,
id
})
if(Object.keys(applyInfo).length == 0){
return tlResponseNotFound("申请记录不存在")
}
const status = applyInfo[TlUserApplyDef.status]
if(status != TlUserApplyStatus.WAIT){
return tlResponseForbidden("申请记录状态不正确")
}
const type = applyInfo[TlUserApplyDef.type]
if(type != TlUserApplyType.FRIEND){
return tlResponseForbidden("申请记录类型不正确")
}
// 查询申请人信息
const applyUserId = applyInfo[TlUserApplyDef.userId]
const applyUserInfo = await userService.getInfoById({
companyId: loginUserCompanyId,
id: applyUserId
}, [
TlUserDef.id,
TlUserDef.name
])
if(Object.keys(applyUserInfo).length == 0){
return tlResponseNotFound("用户不存在")
}
// 生成频道,生成一条系统消息,生成对应的频道用户
let initChannelRes = await userFriendBiz.initChannelForPassFriend({
applyUserId, loginUserCompanyId, loginUserId
})
if (!initChannelRes.success) {
return initChannelRes
}
// 生成双向好友记录
let initUserFriendRes = await userFriendBiz.initUserFriendForPassFriend({
loginUserCompanyId,
loginUserId,
loginUsername,
applyUserId,
applyUserName: applyUserInfo[TlUserDef.name],
origin: applyInfo[TlUserApplyDef.origin],
remark: applyInfo[TlUserApplyDef.remark],
channelId: initChannelRes.data.channelId
})
if (!initUserFriendRes.success) {
return initUserFriendRes
}
// 更新申请记录状态
const updateInfo = await userApplyService.updateInfoById({
companyId: loginUserCompanyId,
id
}, {
[TlUserApplyDef.status]: TlUserApplyStatus.PASS
})
if(Object.keys(updateInfo).length == 0){
return tlResponseSvrError("更新申请记录状态失败")
}
return tlResponseSuccess("通过申请成功", {
applyId : id,
applyUserId: applyUserId
})
}
/**
* 拒绝用户好友申请
* @param {*} id
* @param {*} loginInfo
* @returns
*/
const rejectUserFriendApply = async function({ id, loginInfo }){
if(!id){
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId
} = loginInfo
const applyInfo = await userApplyService.getInfoById({
companyId: loginUserCompanyId,
id
}, [
TlUserApplyDef.id,
TlUserApplyDef.status,
TlUserApplyDef.type,
TlUserApplyDef.userId
])
if(Object.keys(applyInfo).length == 0){
return tlResponseNotFound("申请记录不存在")
}
const status = applyInfo[TlUserApplyDef.status]
if(status != TlUserApplyStatus.WAIT){
return tlResponseForbidden("申请记录状态不正确")
}
const type = applyInfo[TlUserApplyDef.type]
if(type != TlUserApplyType.FRIEND){
return tlResponseForbidden("申请记录类型不正确")
}
const applyUserId = applyInfo[TlUserApplyDef.userId]
const applyUserInfo = await userService.getInfoById({
companyId: loginUserCompanyId,
id: applyUserId
}, [
TlUserDef.id
])
if(Object.keys(applyUserInfo).length == 0){
return tlResponseNotFound("用户不存在")
}
// 更新申请记录状态
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: applyUserId
})
}
/**
* 获取我发出的好友申请记录
* @param {*} loginInfo
* @returns
*/
const getUserFriendApplyListFromSelf = async function({ loginInfo }){
const {
loginUserCompanyId, loginUserId, loginUserCompanyName
} = loginInfo
const applyList = await userApplyService.getListByUserIdAndType({
companyId: loginUserCompanyId,
userId: loginUserId,
type: TlUserApplyType.FRIEND
}, [
TlUserApplyDef.id,
TlUserApplyDef.targetId,
TlUserApplyDef.origin,
TlUserApplyDef.status,
TlUserApplyDef.remark,
TlUserApplyDef.createdAt
])
// 用户信息
let userIdList = new Set(
applyList.map(item => item[TlUserApplyDef.targetId])
)
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.FRIEND_APPLY,
TlUserReadType.FRIEND_APPLY_PASS,
TlUserReadType.FRIEND_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]
let originStr = ''
const origin = item[TlUserApplyDef.origin]
if(origin == TlUserApplyOrigin.SEARCH_NAME){
originStr = "搜索用户名添加"
}
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.targetId])
if(!userInfo){
userInfo = {}
}
resultList.push({
id : item[TlUserApplyDef.id],
username: userInfo[TlUserDef.name],
userAvatar: await getOssUrl(userInfo[TlUserDef.avatarUrl]),
userApplyRemark: item[TlUserApplyDef.remark],
origin : originStr,
createTime: item[TlUserApplyDef.createdAt],
status : statusStr,
userCompanyName: loginUserCompanyName,
hasRead: userReadMap.has(item[TlUserApplyDef.id])
})
}
return tlResponseSuccess("获取我发出的申请记录成功", resultList)
}
/**
* 获取我收到的好友申请记录
* @param {*} loginInfo
* @returns
*/
const getUserFriendListFromOther = async function({ loginInfo }){
const {
loginUserCompanyId, loginUserId, loginUserCompanyName
} = loginInfo
const applyList = await userApplyService.getListByTargetIdAndType({
companyId: loginUserCompanyId,
targetId: loginUserId,
type: TlUserApplyType.FRIEND
}, [
TlUserApplyDef.id,
TlUserApplyDef.userId,
TlUserApplyDef.origin,
TlUserApplyDef.status,
TlUserApplyDef.remark,
TlUserApplyDef.createdAt
])
// 用户信息
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.FRIEND_APPLY,
TlUserReadType.FRIEND_APPLY_PASS,
TlUserReadType.FRIEND_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]
let originStr = ''
const origin = item[TlUserApplyDef.origin]
if(origin == TlUserApplyOrigin.SEARCH_NAME){
originStr = "搜索用户名添加"
}
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 = {}
}
resultList.push({
id : item[TlUserApplyDef.id],
username: userInfo[TlUserDef.name],
userAvatar: await getOssUrl(userInfo[TlUserDef.avatarUrl]),
userApplyRemark: item[TlUserApplyDef.remark],
origin : originStr,
createTime: item[TlUserApplyDef.createdAt],
status : statusStr,
userCompanyName: loginUserCompanyName,
hasRead: userReadMap.has(item[TlUserApplyDef.id])
})
}
return tlResponseSuccess("获取我收到的申请记录成功", resultList)
}
module.exports = {
applyAddFriend,
passUserFriendApply,
rejectUserFriendApply,
getUserFriendApplyListFromSelf,
getUserFriendListFromOther
}

235
src/biz/user/user_biz.js Normal file
View File

@ -0,0 +1,235 @@
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess,
setBit, checkBit, checkIsEmail
} = 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 { fields: userFields } = require('../../tables/tl_user')
const { fields: userFriendFields } = require('../../tables/tl_user_friend')
const TlUserDef = userFields.Def
const TlUserFriendDef = userFriendFields.Def
const TlUserFriendStatus = userFriendFields.Status
const TlUserFriendType = userFriendFields.FriendType
/**
* 搜索用户
* @param {*} name
* @param {*} loginInfo
*/
const searchUserByName = async function({ name, loginInfo }){
if(!name){
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId, loginUserCompanyName
} = loginInfo
const info = await userService.getInfoByName({
companyId: loginUserCompanyId,
name
}, [
TlUserDef.id,
TlUserDef.name,
TlUserDef.avatarUrl,
TlUserDef.wchatName,
])
if(Object.keys(info).length == 0){
return tlResponseNotFound("用户不存在")
}
const userFriendInfo = await userFriendService.getInfoByUserIdAndFriendId({
companyId: loginUserCompanyId,
userId: loginUserId,
friendId: info[TlUserDef.id]
}, [
TlUserFriendDef.channelId,
TlUserFriendDef.remark,
TlUserFriendDef.friendType
])
let isFriend = true
if(Object.keys(userFriendInfo).length == 0){
isFriend = false
}
if(info[TlUserDef.id] == loginUserId){
isFriend = true
}
let friendTypeStr = ''
if(isFriend){
let friendType = userFriendInfo[TlUserFriendDef.friendType]
if(friendType === TlUserFriendType.NORMAL){
friendTypeStr = '普通好友'
}else if(friendType === TlUserFriendType.SPECIAL){
friendTypeStr = '特别关注'
}
}
const result = {
userId: info[TlUserDef.id],
username: info[TlUserDef.name],
userAvatar: await getAvatarOssUrl(info[TlUserDef.avatarUrl]),
userCompanyName: loginUserCompanyName,
wechatName: info[TlUserDef.wchatName],
channelId: userFriendInfo[TlUserFriendDef.channelId],
isFriend: isFriend,
remark: userFriendInfo[TlUserFriendDef.remark],
friendType: friendTypeStr
}
return tlResponseSuccess("搜索用户成功", result)
}
/**
* 搜索用户通过id
* @param {*} id
* @param {*} loginInfo
*/
const searchUserById = async function({ id, loginInfo }){
if(!id){
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId, loginUserCompanyName
} = loginInfo
const info = await userService.getInfoById({
companyId: loginUserCompanyId,
id
}, [
TlUserDef.id,
TlUserDef.name,
TlUserDef.avatarUrl,
TlUserDef.wchatName
])
if(Object.keys(info).length == 0){
return tlResponseNotFound("用户不存在")
}
const userFriendInfo = await userFriendService.getInfoByUserIdAndFriendId({
companyId: loginUserCompanyId,
userId: loginUserId,
friendId: info[TlUserDef.id]
}, [
TlUserFriendDef.channelId,
])
let isFriend = true
if(Object.keys(userFriendInfo).length == 0){
isFriend = false
}
if(id == loginUserId){
isFriend = true
}
const result = {
userId: info[TlUserDef.id],
username: info[TlUserDef.name],
userAvatar: await getAvatarOssUrl(info[TlUserDef.avatarUrl]),
userCompanyName: loginUserCompanyName,
wechatName: info[TlUserDef.wchatName],
channelId: userFriendInfo[TlUserFriendDef.channelId],
isFriend: isFriend
}
return tlResponseSuccess("搜索用户成功", result)
}
/**
* 用户绑定邮箱
* @param {*} token
* @param {*} loginInfo
* @param {*} email
* @param {*} code
*/
const bindEmail = async function({ token, loginInfo, email, code }) {
const {
loginUserCompanyId, loginUserId, loginUserEmail
} = loginInfo
if(!email){
return tlResponseArgsError("邮箱不能为空")
}
if(!code){
return tlResponseArgsError("验证码不能为空")
}
// base64解码
email = Buffer.from(email, 'base64').toString()
if(!checkIsEmail(email)){
return tlResponseArgsError("邮箱格式不正确")
}
if(email == loginUserEmail){
return tlResponseForbidden("邮箱未更换")
}
// 检查code
const checkCode = await userSessionService.getEmailCode({
email
})
if (checkCode !== code) {
return tlResponseArgsError("邮箱验证码错误")
}
const emailExist = await userService.getInfoByEmail({
companyId: loginUserCompanyId,
email
}, [
TlUserDef.id
])
if(emailExist[id] == loginUserId){
return tlResponseForbidden("邮箱未更换")
}
if(Object.keys(emailExist).length > 0){
return tlResponseForbidden("该邮箱已被其他帐号绑定")
}
const result = await userService.updateInfoById({
companyId: loginUserCompanyId,
id: loginUserId,
}, {
[TlUserDef.email]: email
})
if(Object.keys(result).length == 0){
return tlResponseSvrError("绑定邮箱失败")
}
// 更新登录态信息
await userSessionService.setUserInfoByToken({
token, info: Object.assign(loginInfo, {
loginUserEmail: email
})
})
return tlResponseSuccess("绑定邮箱成功")
}
module.exports = {
searchUserByName,
searchUserById,
bindEmail
}

View File

@ -0,0 +1,389 @@
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess,
setBit, checkBit
} = 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')
const TlUserConfigDef = userConfigFields.Def
const TlUserConfigAccountDef = userConfigFields.Account
const TlUserConfigSkinDef = userConfigFields.Skin
const TlUserConfigAuthorityDef = userConfigFields.Authority
const TlUserConfigMessageDef = userConfigFields.Message
const TlUserConfigOtherDef = userConfigFields.Other
/**
* 获取用户自定义配置
* @param {*} loginInfo
* @returns
*/
const getUserConfigSetting = async function({ loginInfo }){
const {
loginUserCompanyId, loginUserId
} = loginInfo
let userConfig = await userConfigService.getInfoByUserId({
companyId: loginUserCompanyId,
userId: loginUserId
},[
TlUserConfigDef.account,
TlUserConfigDef.message,
TlUserConfigDef.authority,
TlUserConfigDef.skin,
TlUserConfigDef.other,
TlUserConfigDef.normal
])
// 不存在则创建
if(Object.keys(userConfig).length == 0){
const result = await userConfigService.addDefaultInfo({
companyId: loginUserCompanyId,
userId: loginUserId
})
if(Object.keys(result).length == 0){
return tlResponseSvrError("获取设置失败")
}
userConfig = result
}
let userConfigAccount = userConfig[TlUserConfigDef.account]
let userConfigMessage = userConfig[TlUserConfigDef.message]
let userConfigAuthority = userConfig[TlUserConfigDef.authority]
let userConfigSkin = userConfig[TlUserConfigDef.skin]
let userConfigOther = userConfig[TlUserConfigDef.other]
let userConfigNormal = userConfig[TlUserConfigDef.normal]
let result = {
account: JSON.parse(userConfigAccount),
message: JSON.parse(userConfigMessage),
authority: JSON.parse(userConfigAuthority),
skin: JSON.parse(userConfigSkin),
other: JSON.parse(userConfigOther),
normal: JSON.parse(userConfigNormal)
}
return tlResponseSuccess("获取设置成功", result)
}
/**
* 更新用户配置
* @param {*} loginInfo
* @param {*} normal
* @returns
*/
const updateUserConfigNormal = async function({ loginInfo, normal }){
const {
loginUserCompanyId, loginUserId
} = loginInfo
const userConfig = await userConfigService.getInfoByUserId({
companyId: loginUserCompanyId,
userId: loginUserId
},[
TlUserConfigDef.id,
TlUserConfigDef.normal
])
if(Object.keys(userConfig).length == 0){
return tlResponseNotFound("用户配置不存在")
}
let preNormal = userConfig[TlUserConfigDef.normal]
preNormal = JSON.parse(preNormal)
let newNormal = Object.assign(preNormal, normal)
// 更新用户配置
let updateNormal = {}
for (let key in TlUserConfigNormalDef) {
updateNormal[key] = newNormal[key]
}
// 更新用户配置
let userConfigId = userConfig[TlUserConfigDef.id]
const result = await userConfigService.updateInfoById({
companyId: loginUserCompanyId,
id: userConfigId
}, {
[TlUserConfigDef.normal]: JSON.stringify(updateNormal)
})
if(Object.keys(result).length == 0){
return tlResponseSvrError("更新设置失败")
}
return tlResponseSuccess("更新设置成功")
}
/**
* 更新用户帐号配置
* @param {*} loginInfo
* @param {*} account
* @returns
*/
const updateUserConfigAccount = async function({ loginInfo, account }){
const {
loginUserCompanyId, loginUserId
} = loginInfo
const userConfig = await userConfigService.getInfoByUserId({
companyId: loginUserCompanyId,
userId: loginUserId
},[
TlUserConfigDef.id,
TlUserConfigDef.account
])
if(Object.keys(userConfig).length == 0){
return tlResponseNotFound("用户配置不存在")
}
let preAccount = userConfig[TlUserConfigDef.account]
preAccount = JSON.parse(preAccount)
let newAccount = Object.assign(preAccount, account)
// 更新用户配置
let updateAccount = {}
for (let key in TlUserConfigAccountDef) {
updateAccount[key] = newAccount[key]
}
// 更新用户配置
let userConfigId = userConfig[TlUserConfigDef.id]
const result = await userConfigService.updateInfoById({
companyId: loginUserCompanyId,
id: userConfigId
}, {
[TlUserConfigDef.account]: JSON.stringify(updateAccount)
})
if(Object.keys(result).length == 0){
return tlResponseSvrError("更新设置失败")
}
return tlResponseSuccess("更新设置成功")
}
/**
* 更新用户消息配置
* @param {*} loginInfo
* @param {*} message
* @returns
*/
const updateUserConfigMessage = async function({ loginInfo, message }){
const {
loginUserCompanyId, loginUserId
} = loginInfo
const userConfig = await userConfigService.getInfoByUserId({
companyId: loginUserCompanyId,
userId: loginUserId
},[
TlUserConfigDef.id,
TlUserConfigDef.message
])
if(Object.keys(userConfig).length == 0){
return tlResponseNotFound("用户配置不存在")
}
let preMessage = userConfig[TlUserConfigDef.message]
preMessage = JSON.parse(preMessage)
let newMessage = Object.assign(preMessage, message)
// 更新用户配置
let updateMessage = {}
for (let key in TlUserConfigMessageDef) {
updateMessage[key] = newMessage[key]
}
// 更新用户配置
let userConfigId = userConfig[TlUserConfigDef.id]
const result = await userConfigService.updateInfoById({
companyId: loginUserCompanyId,
id: userConfigId
}, {
[TlUserConfigDef.message]: JSON.stringify(updateMessage)
})
if(Object.keys(result).length == 0){
return tlResponseSvrError("更新设置失败")
}
return tlResponseSuccess("更新设置成功")
}
/**
* 更新用户权限配置
* @param {*} loginInfo
* @param {*} authority
* @returns
*/
const updateUserConfigAuthority = async function({ loginInfo, authority }){
const {
loginUserCompanyId, loginUserId
} = loginInfo
const userConfig = await userConfigService.getInfoByUserId({
companyId: loginUserCompanyId,
userId: loginUserId
},[
TlUserConfigDef.id,
TlUserConfigDef.authority
])
if(Object.keys(userConfig).length == 0){
return tlResponseNotFound("用户配置不存在")
}
let preAuthority = userConfig[TlUserConfigDef.authority]
preAuthority = JSON.parse(preAuthority)
let newAuthority = Object.assign(preAuthority, authority)
// 更新用户配置
let updateAuthority = {}
for (let key in TlUserConfigAuthorityDef) {
updateAuthority[key] = newAuthority[key]
}
// 更新用户配置
let userConfigId = userConfig[TlUserConfigDef.id]
const result = await userConfigService.updateInfoById({
companyId: loginUserCompanyId,
id: userConfigId
}, {
[TlUserConfigDef.authority]: JSON.stringify(updateAuthority)
})
if(Object.keys(result).length == 0){
return tlResponseSvrError("更新设置失败")
}
return tlResponseSuccess("更新设置成功")
}
/**
* 更新用户皮肤配置
* @param {*} loginInfo
* @param {*} skin
* @returns
*/
const updateUserConfigSkin = async function({ loginInfo, skin }){
const {
loginUserCompanyId, loginUserId
} = loginInfo
const userConfig = await userConfigService.getInfoByUserId({
companyId: loginUserCompanyId,
userId: loginUserId
},[
TlUserConfigDef.id,
TlUserConfigDef.skin
])
if(Object.keys(userConfig).length == 0){
return tlResponseNotFound("用户配置不存在")
}
let preSkin = userConfig[TlUserConfigDef.skin]
preSkin = JSON.parse(preSkin)
let newSkin = Object.assign(preSkin, skin)
// 更新用户配置
let updateSkin = {}
for (let key in TlUserConfigSkinDef) {
updateSkin[key] = newSkin[key]
}
// 更新用户配置
let userConfigId = userConfig[TlUserConfigDef.id]
const result = await userConfigService.updateInfoById({
companyId: loginUserCompanyId,
id: userConfigId
}, {
[TlUserConfigDef.skin]: JSON.stringify(updateSkin)
})
if(Object.keys(result).length == 0){
return tlResponseSvrError("更新设置失败")
}
return tlResponseSuccess("更新设置成功")
}
/**
* 更新用户其他配置
* @param {*} loginInfo
* @param {*} other
* @returns
*/
const updateUserConfigOther = async function({ loginInfo, other }){
const {
loginUserCompanyId, loginUserId
} = loginInfo
const userConfig = await userConfigService.getInfoByUserId({
companyId: loginUserCompanyId,
userId: loginUserId
},[
TlUserConfigDef.id,
TlUserConfigDef.other
])
if(Object.keys(userConfig).length == 0){
return tlResponseNotFound("用户配置不存在")
}
let preOther = userConfig[TlUserConfigDef.other]
preOther = JSON.parse(preOther)
let newOther = Object.assign(preOther, other)
// 更新用户配置
let updateOther = {}
for (let key in TlUserConfigOtherDef) {
updateOther[key] = newOther[key]
}
// 更新用户配置
let userConfigId = userConfig[TlUserConfigDef.id]
const result = await userConfigService.updateInfoById({
companyId: loginUserCompanyId,
id: userConfigId
}, {
[TlUserConfigDef.other]: JSON.stringify(updateOther)
})
if(Object.keys(result).length == 0){
return tlResponseSvrError("更新设置失败")
}
return tlResponseSuccess("更新设置成功")
}
module.exports = {
getUserConfigSetting,
updateUserConfigNormal,
updateUserConfigAccount,
updateUserConfigMessage,
updateUserConfigAuthority,
updateUserConfigSkin,
updateUserConfigOther
}

View File

@ -0,0 +1,559 @@
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess,
setBit, checkBit,
tlConsole
} = require('../../utils/utils')
const userFriendService = require('../../service/user/tl_user_friend_service')
const userService = require('../../service/user/tl_user_service')
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 { fields: userFriendFields } = require('../../tables/tl_user_friend')
const { fields: userFields } = require('../../tables/tl_user')
const { fields: channelFields } = require('../../tables/tl_channel')
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: TlUserDef } = userFields
const { Def: TlChannelDef, Type: TlChannelType } = channelFields
const { Def: TlChannelChatDef, Other: TlChannelChatOther } = channelChatFields
const { Def: TlchannelUserDef, Type: TlChannelUserType } = channelUserFields
/**
* 获取好友列表
* @param {*} loginInfo
*/
const getFriendList = async function({ loginInfo }){
const {
loginUserCompanyId, loginUserId, loginUserCompanyName
} = loginInfo
// 查询所有好友记录
let userFriendList = await userFriendService.getListByUserId({
companyId: loginUserCompanyId,
userId: loginUserId,
}, [
TlUserFriendDef.id,
TlUserFriendDef.friendId,
TlUserFriendDef.origin,
TlUserFriendDef.createdAt,
TlUserFriendDef.friendType,
TlUserFriendDef.remark,
TlUserFriendDef.channelId,
])
const friendIdList = new Set(
[...userFriendList.map(item => item[TlUserFriendDef.friendId])]
)
let userInfoList = await userService.getListByIdList({
companyId: loginUserCompanyId,
idList: [...friendIdList]
}, [
TlUserDef.id,
TlUserDef.name,
TlUserDef.email,
TlUserDef.mobile,
TlUserDef.avatarUrl,
])
let userInfoMap = new Map()
userInfoList.forEach(item => {
userInfoMap.set(item[TlUserFriendDef.id], item)
})
// 查询好友在线状态
const statusMap = await userSessionService.getUserLoginStatusByIdList({
userIdList: [...friendIdList]
})
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)
if(!friendInfo){
friendInfo = {}
}
const loginStatus = statusMap[friendId+''] || 0
let friendTypeStr = ''
let friendType = item[TlUserFriendDef.friendType]
if(friendType == TlUserFriendType.NORMAL){
friendTypeStr = '普通好友'
}else if(friendType == TlUserFriendType.SPECIAL){
friendTypeStr = '特别关注'
}
resultList.push({
id : item[TlUserFriendDef.id],
origin : originStr,
friendType: friendTypeStr,
remark: item[TlUserFriendDef.remark],
createTime: item[TlUserFriendDef.createdAt],
channelId: item[TlUserFriendDef.channelId],
loginStatus: loginStatus,
userId: friendInfo[TlUserDef.id],
userCompanyName: loginUserCompanyName,
username: friendInfo[TlUserDef.name],
userEmail: friendInfo[TlUserDef.email],
userMobile: friendInfo[TlUserDef.mobile],
userAvatar: await getOssUrl(friendInfo[TlUserDef.avatarUrl]),
})
}
return tlResponseSuccess("获取好友列表成功", resultList)
}
/**
* 删除好友
* @param {*} loginInfo
* @param {*} channelId
*/
const deleteFriend = async function({ loginInfo, channelId }){
if(!channelId){
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId
} = loginInfo
// 获取频道用户
const channelUserInfo = await channelUserService.getInfoByChannelIdAndUserId({
companyId: loginUserCompanyId,
channelId,
userId: loginUserId
}, [
TlchannelUserDef.id,
TlchannelUserDef.type
])
if(Object.keys(channelUserInfo).length == 0){
return tlResponseNotFound("删除好友成功")
}
const channelType = channelUserInfo[TlchannelUserDef.type]
if(channelType !== TlChannelUserType.FRIEND){
return tlResponseNotFound("删除失败,操作非法")
}
// 删除自己在频道的数据
await channelUserService.deleteInfoById({
companyId: loginUserCompanyId,
id: channelUserInfo[TlchannelUserDef.id]
})
// 获取好友关系
const userFriendInfo = await userFriendService.getInfoByChannelIdAndUserId({
companyId: loginUserCompanyId,
userId: loginUserId,
channelId: channelId
}, [
TlUserFriendDef.id,
])
if(Object.keys(userFriendInfo).length == 0){
return tlResponseNotFound("删除好友成功")
}
const userFriendId = userFriendInfo[TlUserFriendDef.id]
if(!userFriendId){
return tlResponseNotFound("删除好友成功")
}
// 删除好友关系
await userFriendService.deleteInfoById({
companyId: loginUserCompanyId,
id: userFriendId
})
return tlResponseSuccess("删除好友成功")
}
/**
* 更新好友信息备注
* @param loginInfo
* @param channelId
* @param remark
*/
const updateRemark = async function({ loginInfo, channelId, remark }){
if(!channelId){
return tlResponseArgsError("请求参数为空")
}
if(!remark){
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 userFriendId = friendInfo[TlUserFriendDef.id]
const info = await userFriendService.updateInfoById({
companyId: loginUserCompanyId,
id: userFriendId,
}, {
[TlUserFriendDef.remark]: remark
})
if(Object.keys(info).length == 0){
return tlResponseSvrError("修改好友备注失败")
}
return tlResponseSuccess("修改好友备注成功")
}
/**
* 更新好友名称备注
* @param loginInfo
* @param channelId
* @param rename
*/
const updateRename = async function({ loginInfo, channelId, rename }){
if(!channelId){
return tlResponseArgsError("请求参数为空")
}
if(!rename){
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 userFriendId = friendInfo[TlUserFriendDef.id]
const info = await userFriendService.updateInfoById({
companyId: loginUserCompanyId,
id: userFriendId,
}, {
[TlUserFriendDef.rename]: rename
})
if(Object.keys(info).length == 0){
return tlResponseSvrError("修改好友备注失败")
}
return tlResponseSuccess("修改好友备注成功")
}
/**
* 通过好友后-初始化好友频道
* @param {*} loginUserCompanyId
* @param {*} loginUserId
* @param {*} applyUserId
* @returns
*/
const initChannelForPassFriend = async function({
loginUserCompanyId, loginUserId, applyUserId
}){
if(!applyUserId){
return tlResponseArgsError("初始化好友频道失败,请求参数为空")
}
// 获取这两个人的用户频道信息
const channelUserList = await channelUserService.getListByTypeUserIdList({
companyId: loginUserCompanyId,
type: TlChannelUserType.FRIEND,
userIdList: [loginUserId, applyUserId]
}, [
TlchannelUserDef.id,
TlchannelUserDef.userId,
TlchannelUserDef.channelId,
])
const channelMap = {}
channelUserList.forEach(item => {
const userId = item[TlchannelUserDef.userId]
const channelId = item[TlchannelUserDef.channelId]
if(!channelMap[userId]){
channelMap[userId] = []
}
channelMap[userId].push(channelId)
})
// 如果两个用户存在相同的channelId,说明已经存在相应的好友频道
const loginUserIdChannelIdList = channelMap[loginUserId] || []
const applyUserIdChannelIdList = channelMap[applyUserId] || []
const existChannelId = loginUserIdChannelIdList.find(item => applyUserIdChannelIdList.includes(item))
// 如果已经存在频道用户数据,直接返回
if(existChannelId){
return tlResponseSuccess("初始化好友频道成功1", { channelId: existChannelId })
}
// 创建新频道
const channelInfo = await channelService.addInfo({
companyId: loginUserCompanyId,
name: '好友频道',
type: TlChannelType.FRIEND,
})
if(Object.keys(channelInfo).length == 0){
return tlResponseSvrError("初始化好友频道失败")
}
const channelId = channelInfo[TlChannelDef.id]
// 生成一条系统消息
const channelChatSystemInfo = await channelChatService.addSystemChatnfo({
companyId: loginUserCompanyId,
channelId: channelId,
message: '<p>' + `已经是好友啦,快来聊天吧` + '</p>',
other: JSON.stringify({
[TlChannelChatOther.ip]: '',
}),
messageTimeStamp: Date.now(),
messageVersion: 'v1',
flag: 0
})
if(Object.keys(channelChatSystemInfo).length == 0){
return tlResponseSvrError("初始化好友频道失败")
}
// 将自己加入单聊频道
const addSelfRes = await channelUserService.addInfo({
companyId: loginUserCompanyId,
channelId: channelId,
userId: loginUserId,
type: TlChannelUserType.FRIEND,
roleId: TlRoleInner.channel.creator.id
})
if(Object.keys(addSelfRes).length == 0) {
return tlResponseSvrError("初始化好友频道失败")
}
// 更新用户频道角色
await userSessionService.updateUserChannelRoleMap({
userId: loginUserId,
channelRoleMap: {
[channelId]: TlRoleInner.channel.creator.id
}
})
// 将好友加入单聊频道
const addFriendRes = await channelUserService.addInfo({
companyId: loginUserCompanyId,
channelId: channelId,
userId: applyUserId,
type: TlChannelUserType.FRIEND,
roleId: TlRoleInner.channel.creator.id
})
if(Object.keys(addFriendRes).length == 0) {
return tlResponseSvrError("初始化好友频道失败")
}
// 更新用户频道角色
await userSessionService.updateUserChannelRoleMap({
userId: applyUserId,
channelRoleMap: {
[channelId]: TlRoleInner.channel.creator.id
}
})
return tlResponseSuccess("初始化好友频道成功2", { channelId })
}
/**
* 通过好友后 - 生成双向好友记录
* @param {*} loginUserCompanyId
* @param {*} loginUserId
* @param {*} applyUserId
* @param {*} applyUserName
* @param {*} origin
* @param {*} remark
* @param {*} channelId
*/
const initUserFriendForPassFriend = async function({
loginUserCompanyId, loginUserId, loginUsername, applyUserId, applyUserName, origin, remark, channelId
}){
if(!applyUserId){
return tlResponseForbidden("生成好友记录失败,参数错误")
}
// 好友记录是否存在
const userFriendInfo = await userFriendService.getInfoByUserIdAndFriendId({
companyId: loginUserCompanyId,
userId: loginUserId,
friendId: applyUserId
}, [
TlUserFriendDef.id,
])
// 存在,更新好友记录状态
if(Object.keys(userFriendInfo).length > 0){
const updateUserFriendInfo = await userFriendService.updateInfoById({
companyId: loginUserCompanyId,
id: userFriendInfo[TlUserFriendDef.id],
}, {
[TlUserFriendDef.status]: TlUserFriendStatus.NORMAL
})
if(Object.keys(updateUserFriendInfo).length == 0){
return tlResponseSvrError("生成好友记录失败")
}
return tlResponseSuccess("生成好友记录成功")
}
// 不存在,生成双向好友记录
const addUserFriendInfo = await userFriendService.addInfo({
companyId: loginUserCompanyId,
userId: loginUserId,
friendId: applyUserId,
origin: origin,
remark: remark,
friendType: TlUserFriendType.NORMAL,
status: TlUserFriendStatus.NORMAL,
channelId: channelId,
rename: applyUserName
})
if(Object.keys(addUserFriendInfo).length == 0){
return tlResponseSvrError("生成好友记录失败")
}
const addFriendUserInfo = await userFriendService.addInfo({
companyId: loginUserCompanyId,
userId: applyUserId,
friendId: loginUserId,
origin: origin,
remark: remark,
friendType: TlUserFriendType.NORMAL,
status: TlUserFriendStatus.NORMAL,
channelId: channelId,
rename: loginUsername
})
if(Object.keys(addFriendUserInfo).length == 0){
return tlResponseSvrError("生成好友记录失败")
}
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,
deleteFriend,
updateRemark,
updateRename,
initChannelForPassFriend,
initUserFriendForPassFriend,
updateFriendSpecical
}

View File

@ -0,0 +1,562 @@
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess,
tlConsole, verifyEncryptStr
} = require('../../utils/utils')
const {
getAvatarOssUrl
} = require('../../utils/oss/oss')
const userService = require('../../service/user/tl_user_service')
const userSessionService = require('../../service/user/tl_user_session_service')
const companyService = require('../../service/company/tl_company_service')
const channelUserService = require('../../service/channel/tl_channel_user_service')
const userFingerPrintService = require('../../service/user/tl_user_finger_print_service')
const { fields: companyFields } = require('../../tables/tl_company')
const { Def: TlCompanyDef } = companyFields
const { fields: userFields } = require('../../tables/tl_user')
const { Def: TlUserDef } = 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')
/**
* 通过帐号登录接口
* @param {*} account
* @param {*} password
* @param {*} fps
*/
const userLoginByAccount = async function({account, password, fps}){
if(!account){
return tlResponseArgsError("用户名或密码错误")
}
if(!password){
return tlResponseArgsError("用户名或密码错误")
}
// base64解码
account = Buffer.from(account, 'base64').toString()
password = Buffer.from(password, 'base64').toString()
const user = await userService.getInfoByNameForLogin({
name: account
}, [
TlUserDef.id,
TlUserDef.companyId,
TlUserDef.name,
TlUserDef.password,
TlUserDef.avatarUrl,
TlUserDef.salt,
TlUserDef.roleId,
TlUserDef.email,
TlUserDef.mobile
])
if(!user[TlUserDef.id]){
return tlResponseArgsError("用户名或密码错误")
}
if(!verifyEncryptStr({
inputStr: password,
hashedStr: user[TlUserDef.password],
salt: user[TlUserDef.salt]
})){
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],
loginUsername: user[TlUserDef.name],
loginUserEmail: user[TlUserDef.email],
loginUserMobile: user[TlUserDef.mobile],
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 {*} 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
*/
const userLoginByEmail = async function({email, password, fps}){
if(!email){
return tlResponseArgsError("邮箱或密码错误")
}
if(!password){
return tlResponseArgsError("邮箱或密码错误")
}
// base64解码
email = Buffer.from(email, 'base64').toString()
password = Buffer.from(password, 'base64').toString()
const user = await userService.getInfoByEmailForLogin({
email
}, [
TlUserDef.id,
TlUserDef.companyId,
TlUserDef.email,
TlUserDef.avatarUrl,
TlUserDef.password,
TlUserDef.roleId,
TlUserDef.mobile,
TlUserDef.salt,
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("非法用户")
}
if(!verifyEncryptStr({
inputStr: password,
hashedStr: user[TlUserDef.password],
salt: user[TlUserDef.salt]
})){
return tlResponseArgsError("邮箱或密码错误")
}
const token = userSessionService.generateLoginToken();
const info = {
loginUserId: user[TlUserDef.id],
loginUserEmail: user[TlUserDef.email],
loginUsername: user[TlUserDef.name],
loginUserRoleId: user[TlUserDef.roleId],
loginUserMobile: user[TlUserDef.mobile],
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 {*} 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
*/
const userLoginByFingerPrint = async function({fps, username}){
if(!fps){
return tlResponseArgsError("一键登录失败, 请使用其他登录方式登录")
}
const user = await userService.getInfoByNameForLogin({
name: username
}, [
TlUserDef.id,
TlUserDef.companyId,
TlUserDef.name,
TlUserDef.avatarUrl,
TlUserDef.roleId,
TlUserDef.email,
TlUserDef.salt,
TlUserDef.mobile
])
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 fingerPrintList = await userFingerPrintService.getListByUserId({
userId: user[TlUserDef.id]
}, [
TlUserFingerPrintDef.finger_print,
])
let isExist = false
fps.forEach(fp => {
fingerPrintList.forEach(element => {
if(element[TlUserFingerPrintDef.finger_print] === fp){
isExist = true
return
}
})
})
if(!isExist){
return tlResponseForbidden("一键登录失败, 请使用其他登录方式登录")
}
const token = userSessionService.generateLoginToken();
const info = {
loginUserId: user[TlUserDef.id],
loginUsername: user[TlUserDef.name],
loginUserRoleId: user[TlUserDef.roleId],
loginUserCompanyName : companyName,
loginUserEmail: user[TlUserDef.email],
loginUserMobile: user[TlUserDef.mobile],
loginUserCompanyId: companyId,
loginUserAvatar: await getAvatarOssUrl(user[TlUserDef.avatarUrl]),
loginTime: new Date().getTime(),
token
}
// 设置登录信息
await userSessionService.setUserInfoByToken({token, info})
// 设置用户频道角色
await setUserChannelRole({ userId: user[TlUserDef.id], companyId })
return tlResponseSuccess("一键登录成功", token)
}
/**
* 设置指纹
* @param {*} userId
* @param {*}
* @returns
*/
const setFps = async function({userId, fps}){
let addFingerPrintList = []
// 设置指纹
if(fps){
const fingerPrintList = await userFingerPrintService.getListByUserId({
userId: userId
}, [
TlUserFingerPrintDef.finger_print,
])
fps.forEach(fp => {
let isExist = false
fingerPrintList.forEach(element => {
if(element[TlUserFingerPrintDef.finger_print] === fp){
isExist = true
return
}
});
if(!isExist){
addFingerPrintList.push(fp)
}
})
// 每个用户最多只能有10个指纹
if(addFingerPrintList.length > 0 && fingerPrintList.length < 10){
await userFingerPrintService.addInfoList({
userId: userId,
dataList: addFingerPrintList
})
}
}
return addFingerPrintList
}
/**
* 设置频道用户角色
* @param {*} userId
* @param {*} companyId
*/
const setUserChannelRole = async function({userId, companyId}){
const channelUserList = await channelUserService.getListByUserId({
companyId: companyId,
userId: userId
}, [
TlChannelUserDef.channelId,
TlChannelUserDef.roleId
])
if(channelUserList.length === 0){
return
}
const channelRoleMap = {}
channelUserList.forEach(channelUser => {
channelRoleMap[channelUser[TlChannelUserDef.channelId]] = channelUser[TlChannelUserDef.roleId]
})
await userSessionService.setUserChannelRoleMap({
userId, channelRoleMap
})
}
/**
* 官网登录 - 支持邮箱登录
* @param {*} email
* @param {*} password
*/
const userLoginByWebsite = async function({ email, password }){
if(!email){
return tlResponseArgsError("邮箱或密码错误")
}
if(!password){
return tlResponseArgsError("邮箱或密码错误")
}
// base64解码
email = Buffer.from(email, 'base64').toString()
password = Buffer.from(password, 'base64').toString()
const user = await userService.getInfoByEmailForLogin({
email
}, [
TlUserDef.id,
TlUserDef.companyId,
TlUserDef.email,
TlUserDef.avatarUrl,
TlUserDef.password,
TlUserDef.roleId,
TlUserDef.mobile,
TlUserDef.salt,
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("非法用户")
}
if(!verifyEncryptStr({
inputStr: password,
hashedStr: user[TlUserDef.password],
salt: user[TlUserDef.salt]
})){
return tlResponseArgsError("邮箱或密码错误")
}
const roleId = user[TlUserDef.roleId]
if([
TlInnerRole.website.user.id,
TlInnerRole.user.admin.id
].indexOf(roleId) === -1){
return tlResponseArgsError("非官网用户")
}
const token = userSessionService.generateLoginToken();
const info = {
loginUserId: user[TlUserDef.id],
loginUserEmail: user[TlUserDef.email],
loginUsername: user[TlUserDef.name],
loginUserRoleId: user[TlUserDef.roleId],
loginUserMobile: user[TlUserDef.mobile],
loginUserCompanyName : companyName,
loginUserCompanyId: companyId,
loginUserAvatar: await getAvatarOssUrl(user[TlUserDef.avatarUrl]),
loginTime: new Date().getTime(),
token
}
// 设置登录信息
await userSessionService.setUserInfoByToken({token, info, isWebsite: true})
return tlResponseSuccess("登录成功", token)
}
module.exports = {
userLoginByAccount,
userLoginByMobile,
userLoginByEmail,
userLoginByWechat,
userLoginByQQ,
userLoginByQyWechat,
userLoginByGuest,
userLoginByFingerPrint,
userLoginByWebsite
}

View File

@ -0,0 +1,31 @@
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess
} = require('../../utils/utils')
const userSessionService = require('../../service/user/tl_user_session_service')
/**
* 是否登陆中
* @param {*} token
*/
const userIsLogin = async function({token}){
if(!token){
return tlResponseArgsError("不在线")
}
const userInfo = await userSessionService.getUserInfoByToken({token})
// 登录用户ID
const loginUserId = userInfo.loginUserId
if(!loginUserId){
return tlResponseArgsError("不在线")
}
return tlResponseSuccess("在线", userInfo)
}
module.exports = {
userIsLogin
}

View File

@ -0,0 +1,38 @@
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')
/**
* 退出登录接口
* @param {*} token
*/
const userLogout = async function({token}){
if(!token){
return tlResponseArgsError("退出成功")
}
const {
loginUserId
} = await userSessionService.getUserInfoByToken({token})
if(!loginUserId){
return tlResponseSuccess("退出成功")
}
await userSessionService.setUserInfoByToken({
token,
info: {
loginUserId
},
isLogin: false
})
return tlResponseSuccess("退出成功")
}
module.exports = {
userLogout
}

View File

@ -0,0 +1,361 @@
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess
} = require('../../utils/utils')
const userReadService = require('../../service/user/tl_user_read_service')
const userSessionService = require('../../service/user/tl_user_session_service')
const { fields: userReadDef } = require('../../tables/tl_user_read')
const { fields: channelDef } = require('../../tables/tl_channel')
const { Def: TlUserReadDef, Type: TlUserReadType } = userReadDef
/**
* 更新频道已读记录
* @param {*} loginInfo
* @param {*} channelId
* @param {*} latestReadId
* @param {*} type
*/
const updateChannelUserRead = async function({
loginInfo, channelId, latestReadId, type
}){
if (!latestReadId) {
return tlResponseArgsError("请求参数为空")
}
if (!channelId) {
return tlResponseArgsError("请求参数为空")
}
if(!type){
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId, loginUsername
} = loginInfo
const userReadList = await userReadService.getListByChannelUserId({
companyId: loginUserCompanyId,
userId: loginUserId,
channelId
})
let chatReadRecord = null
let mediaReadRecord = null
let fileReadRecord = null
userReadList.forEach((userRead) => {
if (userRead[TlUserReadDef.type] === TlUserReadType.CHAT) {
chatReadRecord = userRead
}
if (userRead[TlUserReadDef.type] === TlUserReadType.MEDIA) {
mediaReadRecord = userRead
}
if (userRead[TlUserReadDef.type] === TlUserReadType.FILE) {
fileReadRecord = userRead
}
})
// 聊天消息已读记录不存在,新增, 否则更新已读消息最新ID
if(type === TlUserReadType.CHAT){
if(!chatReadRecord){
chatReadRecord = await userReadService.addInfo({
companyId: loginUserCompanyId,
userId: loginUserId,
channelId,
latestReadId,
type: TlUserReadType.CHAT
})
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("更新失败")
}
}
// 媒体消息已读记录不存在,新增, 否则更新已读消息最新ID
if(type === TlUserReadType.MEDIA){
if(!mediaReadRecord){
mediaReadRecord = await userReadService.addInfo({
companyId: loginUserCompanyId,
userId: loginUserId,
channelId,
latestReadId,
type: TlUserReadType.MEDIA
})
if(Object.keys(mediaReadRecord).length === 0){
return tlResponseSvrError("更新失败")
}
}
const readId = mediaReadRecord[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.FILE){
if(!fileReadRecord){
fileReadRecord = await userReadService.addInfo({
companyId: loginUserCompanyId,
userId: loginUserId,
channelId,
latestReadId,
type: TlUserReadType.FILE
})
if(Object.keys(fileReadRecord).length === 0){
return tlResponseSvrError("更新失败")
}
}
const readId = fileReadRecord[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("更新失败")
}
}
return tlResponseSuccess("更新成功")
}
/**
* 更新频道聊天已读记录 (文件/媒体/聊天)
* @param {*} loginInfo
* @param {*} channelId
* @param {*} latestReadId
* @param {*} latestMediaReadId
* @param {*} latestFileReadId
* @returns
*/
const updateChannelMuiltRead = async function({
loginInfo, channelId, latestChatReadId, latestMediaReadId, latestFileReadId
}){
if(latestChatReadId){
const chatResult = await updateChannelChatRead({
loginInfo, channelId, latestReadId: latestChatReadId
});
if (!chatResult.success) {
return chatResult
}
}
if(latestMediaReadId){
const mediaResult = await updateChannelMediaRead({
loginInfo, channelId, latestReadId: latestMediaReadId
});
if (!mediaResult.success) {
return mediaResult
}
}
if(latestFileReadId){
const fileResult = await updateChannelFileRead({
loginInfo, channelId, latestReadId: latestFileReadId
});
if (!fileResult.success) {
return fileResult
}
}
return tlResponseSuccess("更新成功")
}
/**
* 更新频道聊天消息已读记录
* @param {*} loginInfo
* @param {*} channelId
* @param {*} latestReadId
* @returns
*/
const updateChannelChatRead = async function({
loginInfo, channelId, latestReadId
}){
return await updateChannelUserRead({
loginInfo, channelId, latestReadId, type: TlUserReadType.CHAT
})
}
/**
* 更新频道媒体消息已读记录
* @param {*} loginInfo
* @param {*} channelId
* @param {*} latestReadId
* @returns
*/
const updateChannelMediaRead = async function({
loginInfo, channelId, latestReadId
}){
return await updateChannelUserRead({
loginInfo, channelId, latestReadId, type: TlUserReadType.MEDIA
})
}
/**
* 更新频道文件消息已读记录
* @param {*} loginInfo
* @param {*} channelId
* @param {*} latestReadId
* @returns
*/
const updateChannelFileRead = async function({
loginInfo, channelId, latestReadId
}){
return await updateChannelUserRead({
loginInfo, channelId, latestReadId, type: TlUserReadType.FILE
})
}
/**
* 新增好友申请消息已读记录
* @param {*} loginInfo
* @param {*} recordId
* @param {*} type
* @returns
*/
const addUserFriendApplyRead = async function({
loginInfo, recordId
}){
if (!recordId) {
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId, loginUsername
} = loginInfo
const addInfo = await userReadService.addInfo({
companyId: loginUserCompanyId,
userId: loginUserId,
recordId,
type: TlUserReadType.FRIEND_APPLY
})
if(Object.keys(addInfo).length === 0){
return tlResponseSvrError("更新失败")
}
return tlResponseSuccess("更新成功")
}
/**
* 新增好友同意消息已读记录
* @param {*} loginInfo
* @param {*} recordId
* @param {*} type
* @returns
*/
const addUserFriendApplyPassRead = async function({
loginInfo, recordId
}){
if (!recordId) {
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId, loginUsername
} = loginInfo
const addInfo = await userReadService.addInfo({
companyId: loginUserCompanyId,
userId: loginUserId,
recordId,
type: TlUserReadType.FRIEND_APPLY_PASS
})
if(Object.keys(addInfo).length === 0){
return tlResponseSvrError("更新失败")
}
return tlResponseSuccess("更新成功")
}
/**
* 新增好友拒绝消息已读记录
* @param {*} loginInfo
* @param {*} recordId
* @param {*} type
* @returns
*/
const addUserFriendApplyRejectRead = async function({
loginInfo, recordId
}){
if (!recordId) {
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId, loginUsername
} = loginInfo
const addInfo = await userReadService.addInfo({
companyId: loginUserCompanyId,
userId: loginUserId,
recordId,
type: TlUserReadType.FRIEND_APPLY_REJECT
})
if(Object.keys(addInfo).length === 0){
return tlResponseSvrError("更新失败")
}
return tlResponseSuccess("更新成功")
}
module.exports = {
updateChannelChatRead,
updateChannelMediaRead,
updateChannelFileRead,
updateChannelMuiltRead,
addUserFriendApplyRead,
addUserFriendApplyPassRead,
addUserFriendApplyRejectRead
}

View File

@ -0,0 +1,430 @@
const crypto = require('crypto')
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess,
tlConsole,
checkIsEmail, checkIsMobile,
tlConsoleError,
encryptStr
} = require('../../utils/utils');
const {
sendVerificationCodeEmail
} = require('../../utils/mail/mail');
const companyService = require('../../service/company/tl_company_service')
const userService = require('../../service/user/tl_user_service')
const userSessionService = require('../../service/user/tl_user_session_service')
const userAuthService = require('../../service/user/tl_user_auth_service')
const { fields: companyFields } = require('../../tables/tl_company')
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 { Def: TlCompanyFields } = companyFields
/**
* 通过帐号注册接口
* @param {*} account
* @param {*} password
* @param {*} invite_code
*/
const userRegisterByAccount = async function({account, password, invite_code}){
if(!account){
return tlResponseArgsError("帐号不能为空")
}
if(!password){
return tlResponseArgsError("密码不能为空")
}
// base64解码
account = Buffer.from(account, 'base64').toString()
password = Buffer.from(password, 'base64').toString()
if(!invite_code){
return tlResponseArgsError("邀请码不能为空")
}
const company = await companyService.getInfoByCode({
code: invite_code
}, [
TlCompanyFields.id
])
if(Object.keys(company).length === 0){
return tlResponseArgsError("邀请码无效")
}
const companyId = company.id
const user = await userService.getInfoByName({
companyId: companyId,
name: account
}, [
TlUserDef.id
])
if(user[TlUserDef.id]){
return tlResponseArgsError("帐号已存在")
}
const salt = crypto.randomBytes(16).toString('hex')
const saltPassword = encryptStr({
str: password,
salt: salt
})
tlConsole(account, password, salt, saltPassword)
const result = await userService.addInfo({
companyId : companyId,
name : account,
password: saltPassword,
roleId : TlRoleInner.user.normal.id,
salt,
avatarUrl: "/image/default-avatar.png"
})
if (Object.keys(result).length === 0) {
return tlResponseSvrError("注册失败")
}
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("注册成功")
}
/**
* 通过邮箱注册接口
* @param {*} email
* @param {*} code
* @param {*} invite_code
* @param {*} 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()
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
})
if (checkCode !== code) {
return tlResponseArgsError("邮箱验证码错误")
}
const companyId = company.id
const user = await userService.getInfoByEmail({
companyId: companyId,
email
}, [
TlUserDef.id
])
if(user.id){
return tlResponseArgsError("邮箱已存在")
}
const salt = crypto.randomBytes(16).toString('hex')
const saltPassword = encryptStr({
str: password,
salt: salt
})
const result = await userService.addInfo({
companyId : companyId,
name : '邮箱用户-' + Math.floor(Math.random() * 1000000),
email,
password: saltPassword,
roleId : TlRoleInner.user.normal.id,
salt,
avatarUrl: "/image/default-avatar.png"
})
if (Object.keys(result).length === 0) {
return tlResponseSvrError("注册失败")
}
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
* @returns
*/
const getEmailCode = async function({email}){
if(!email){
return tlResponseArgsError("邮箱不能为空")
}
if(!checkIsEmail(email)){
return tlResponseArgsError("邮箱格式不正确")
}
// 检查总次数
const totalCount = await userAuthService.getDayCountByType({
type: TlUserAuthType.EMAIL_REGISTER_CODE,
})
if(totalCount >= 1000){
return tlResponseForbidden("当天系统发送验证码次数已达上限")
}
// 检查次数
const count = await userAuthService.getDayCountByTypeAndKey({
type: TlUserAuthType.EMAIL_REGISTER_CODE,
key: email
})
if(count >= 5){
return tlResponseForbidden("当天获取验证码次数已达上限")
}
const code = Math.floor(Math.random() * 1000000)
await userSessionService.setEmailCode({
email, code
})
await sendVerificationCodeEmail({
to: email,
code: code,
expire: 5,
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_REGISTER_CODE,
code: String(code)
})
if (Object.keys(result).length === 0) {
tlConsoleError("验证码发送添加记录失败")
}
return tlResponseSuccess("验证码发送成功", {
code
})
}
/**
* 注册官网用户
* @param {*} email
* @param {*} code
* @param {*} password
* @returns
*/
const registerWebsiteUser = async function({ email, code, password }){
// 默认挂在首个企业下
const companyId = 1
if(!email){
return tlResponseArgsError("邮箱不能为空")
}
if(!code){
return tlResponseArgsError("验证码不能为空")
}
if(!password) {
return tlResponseArgsError("密码不能为空")
}
// base64解码
email = Buffer.from(email, 'base64').toString()
password = Buffer.from(password, 'base64').toString()
if(!checkIsEmail(email)){
return tlResponseArgsError("邮箱格式不正确")
}
// 检查code
const checkCode = await userSessionService.getEmailCode({
email
})
if (checkCode !== code) {
return tlResponseArgsError("邮箱验证码错误")
}
const user = await userService.getInfoByEmail({
companyId: companyId,
email
}, [
TlUserDef.id
])
if(user.id){
return tlResponseArgsError("邮箱已注册")
}
const salt = crypto.randomBytes(16).toString('hex')
const saltPassword = encryptStr({
str: password,
salt: salt
})
const result = await userService.addInfo({
companyId : companyId,
name : "官网用户-" + String(Math.floor(Math.random() * 1000000)),
email,
password: saltPassword,
roleId : TlRoleInner.website.user.id,
salt,
avatarUrl: "/image/default-avatar.png"
})
if (Object.keys(result).length === 0) {
return tlResponseSvrError("注册失败")
}
return tlResponseSuccess("注册成功")
}
module.exports = {
userRegisterByAccount,
userRegisterByMobile,
userRegisterByEmail,
userRegisterByWechat,
userRegisterByQQ,
userRegisterByWechatWork,
getEmailCode,
registerWebsiteUser
}

View File

@ -0,0 +1,202 @@
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess
} = require('../../utils/utils')
const userTagService = require('../../service/user/tl_user_tag_service')
const { fields: userTagDef } = require('../../tables/tl_user_tag')
const { Def: TlUserTagDef, Type: TlUserTagType } = userTagDef
/**
* 添加用户标签
* @param {*} loginInfo
* @param {*} name
* @param {*} type
* @returns
*/
const addUserTag = async function({
loginInfo, name, type
}){
if(!name) {
return tlResponseArgsError("请求参数为空")
}
if(!type){
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId, loginUsername
} = loginInfo
const result = await userTagService.addInfo({
name, type,
userId: loginUserId,
companyId: loginUserCompanyId
})
if(Object.keys(result).length == 0){
return tlResponseSvrError("添加标签失败")
}
return tlResponseSuccess(result)
}
/**
* 获取用户标签列表
* @param {*} loginInfo
* @param {*} type
* @returns
*/
const getUserTagList = async function({
loginInfo, type
}){
if(!type){
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId, loginUsername
} = loginInfo
const result = await userTagService.getListByUserIdAndType({
companyId: loginUserCompanyId,
userId: loginUserId,
type
})
let resultList = []
result.forEach((item) => {
resultList.push({
id: item[TlUserTagDef.id],
name: item[TlUserTagDef.name]
})
})
return tlResponseSuccess("获取成功", resultList)
}
/**
* 删除用户标签
* @param {*} loginInfo
* @param {*} id
* @returns
*/
const delUserTag = async function({
loginInfo, id
}){
if(!id){
return tlResponseArgsError("请求参数为空")
}
const {
loginUserCompanyId, loginUserId, loginUsername
} = loginInfo
const result = await userTagService.deleteInfoById({
companyId: loginUserCompanyId,
id
})
if(result == 0){
return tlResponseSvrError("删除失败")
}
return tlResponseSuccess("删除成功")
}
/**
* 添加频道标签
* @param {*} loginInfo
* @param {*} name
* @returns
*/
const addChannelTag = async function({
loginInfo, name
}){
return await addUserTag({
loginInfo, name, type: TlUserTagType.CHANNEL
})
}
/**
* 添加好友标签
* @param {*} loginInfo
* @param {*} name
* @returns
*/
const addFriendTag = async function({
loginInfo, name
}){
return await addUserTag({
loginInfo, name, type: TlUserTagType.FRIEND
})
}
/**
* 添加资源库标签
* @param {*} loginInfo
* @param {*} name
* @returns
*/
const addCloudTag = async function({
loginInfo, name
}){
return await addUserTag({
loginInfo, name, type: TlUserTagType.CLOUD
})
}
/**
* 获取频道标签列表
* @param {*} loginInfo
* @returns
*/
const getChannelTagList = async function({
loginInfo
}){
return await getUserTagList({
loginInfo, type: TlUserTagType.CHANNEL
})
}
/**
* 获取好友标签列表
* @param {*} loginInfo
* @returns
*/
const getFriendTagList = async function({
loginInfo
}){
return await getUserTagList({
loginInfo, type: TlUserTagType.FRIEND
})
}
/**
* 获取资源库标签列表
* @param {*} loginInfo
* @returns
*/
const getCloudTagList = async function({
loginInfo
}){
return await getUserTagList({
loginInfo, type: TlUserTagType.CLOUD
})
}
module.exports = {
addUserTag,
getUserTagList,
delUserTag,
addChannelTag,
addFriendTag,
addCloudTag,
getChannelTagList,
getFriendTagList,
getCloudTagList
}

View File

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

View File

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

31
src/controller/router.js Normal file
View File

@ -0,0 +1,31 @@
const fs = require('fs');
const path = require('path');
const {
tlConsoleError
} = require("../../src/utils/utils");
module.exports = () => {
let allRouterMap = {};
whiteDir = []
whiteFile = ['router.js']
let allApps = fs.readdirSync(__dirname);
for (let client of allApps) {
//过滤文件夹和文件
if (whiteDir.includes(client) || whiteFile.includes(client)) continue;
try {
//添加router
let stat = fs.statSync(path.join(__dirname, client, client + '.js'));
if (stat && stat.isFile()) {
const subModuleRouterMap = require("./" + client + '/' + client);
for(let subModule in subModuleRouterMap){
const subModuleRouter = subModuleRouterMap[subModule];
allRouterMap["/api/" + client + "/" + subModule] = subModuleRouter
}
}
} catch (e) {
tlConsoleError(e)
}
}
return allRouterMap;
}

View File

@ -0,0 +1,156 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, tlResponseArgsError,
checkRequestParams
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const channelChatBiz = require('../../../biz/channel/channel_chat_biz');
/**
* #controller post /api/web/channel-chat/add-friend-channel-chat
* #desc 发送好友频道聊天
* @param {*} request
* @param {*} response
*/
router.post('/add-friend-channel-chat', async function(request, response) {
try {
const { message, toUserId, toUserName, channelId, atUserId, atUserName } = request.body;
// 消息内容不过滤
if (!checkRequestParams({
toUserId, toUserName, channelId, atUserId, atUserName
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelChatBiz.addFriendChannelChat({
loginInfo, message, toUserId, toUserName, channelId, atUserId, atUserName
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
});
/**
* #controller post /api/web/channel-chat/add-group-channel-chat
* #desc 发送多人频道聊天
* @param {*} request
* @param {*} response
*/
router.post('/add-group-channel-chat', async function(request, response) {
try {
const { message, channelId, atUserId, atUserName, isAtAll } = request.body;
// 消息内容不过滤
if (!checkRequestParams({
channelId, atUserId, atUserName, isAtAll
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelChatBiz.addGroupChannelChat({
loginInfo, message, channelId, atUserId, atUserName, isAtAll
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
});
/**
* #controller post /api/web/channel-chat/add-reply-friend-channel-chat
* #desc 回复好友聊天
* @param {*} request
* @param {*} response
*/
router.post('/add-reply-friend-channel-chat', async function(request, response) {
try {
const { message, channelId, messageId, messageType, atUserId, atUserName } = request.body;
// 消息内容不过滤
if (!checkRequestParams({
channelId, messageId, messageType, atUserId, atUserName
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelChatBiz.addReplyFriendChannelChat({
loginInfo, message, channelId, messageId, messageType, atUserId, atUserName
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
});
/**
* #controller post /api/web/channel-chat/add-reply-group-channel-chat
* #desc 回复群组聊天
* @param {*} request
* @param {*} response
*/
router.post('/add-reply-group-channel-chat', async function(request, response) {
try {
const { message, channelId, messageId, messageType, atUserId, atUserName, atAll } = request.body;
// 消息内容不过滤
if (!checkRequestParams({
channelId, messageId, messageType, atUserId, atUserName, atAll
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelChatBiz.addReplyGroupChannelChat({
loginInfo, message, channelId, messageId, messageType, atUserId, atUserName, atAll
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
});
/**
* #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

@ -0,0 +1,254 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, checkRequestParams, tlResponseArgsError
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const channelBiz = require('../../../biz/channel/channel_biz');
/**
* #controller post /api/web/channel/search-channel-by-id
* #desc 根据频道id搜索频道
* @param {*} request
* @param {*} response
*/
router.post('/search-channel-by-id', async function(request, response) {
try{
const { channelId } = request.body;
if (!checkRequestParams({
channelId,
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelBiz.searchChannelById({
channelId, loginInfo
});
response.json(result);
}catch(error){
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/channel/add-channel
* #desc 添加频道
* @param {*} request
* @param {*} response
*/
router.post('/add-channel', async function(request, response) {
try{
const { channelName } = request.body;
if (!checkRequestParams({
channelName,
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelBiz.addChannel({
channelName, loginInfo
});
response.json(result);
}catch(error){
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller get /api/web/channel/get-channel-list
* #desc 获取频道列表
* @param {*} request
* @param {*} response
*/
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)
response.json(tlResponseSvrError());
}
});
/**
* #controller get /api/web/channel/get-channel-info
* #desc 获取频道信息
* @param {*} request
* @param {*} response
*/
router.get('/get-channel-info', async function(request, response) {
try {
const { channelId } = request.query;
if (!checkRequestParams({
channelId,
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelBiz.getChannelInfo({ loginInfo, channelId });
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller get /api/web/channel/get-channel-name
* #desc 获取频道名称
* @param {*} request
* @param {*} response
*/
router.get('/get-channel-name', async function(request, response) {
try {
const { channelId } = request.query;
if (!checkRequestParams({
channelId,
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelBiz.getChannelNameById({ loginInfo, channelId });
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/channel/update-channel-name
* #desc 修改频道名称
* @param {*} request
* @param {*} response
*/
router.post('/update-channel-name', async function(request, response) {
try {
const { channelId, channelName } = request.body;
if (!checkRequestParams({
channelId, channelName
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelBiz.updateChannelName({
channelId, channelName, loginInfo
});
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());
}
});
/**
* #controller post /api/web/channel/get-channel-message
* #desc 获取频道聊天记录
* @param {*} request
* @param {*} response
*/
router.post('/get-channel-message', async function(request, response) {
try {
const {
channelId, chatMinId, fileMinId, mediaMinId
} = request.body;
if (!checkRequestParams({
channelId, chatMinId, fileMinId, mediaMinId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelBiz.getChannelChatList({
loginInfo, channelId, chatMinId, fileMinId, mediaMinId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
})
/**
* #controller post /api/web/channel/get-channel-message-list
* #desc 获取频道列表聊天记录
* @param {*} request
* @param {*} response
*/
router.post('/get-channel-message-list', async function(request, response) {
try {
const { channelIdList } = request.body;
if (!checkRequestParams({
channelIdList
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelBiz.getChannelChatListByChannelIdList({
loginInfo, channelIdList
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
});
module.exports = router;

View File

@ -0,0 +1,354 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const channelUserBiz = require('../../../biz/channel/channel_user_biz');
/**
* #controller post /api/web/channel-user/add-channel-user
* #desc 添加频道用户
* @param {*} request
* @param {*} response
*/
router.post('/add-channel-user', async function(request, response){
try{
const { channelId, userId, roleId } = request.body;
if (!checkRequestParams({
channelId, userId, roleId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelUserBiz.addChannelUser({ loginInfo, channelId, userId, roleId });
response.json(result);
}catch(error){
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #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 添加频道普通身份用户
* @param {*} request
* @param {*} response
*/
router.post('/add-channel-user-normal', 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.addChannelUserNormal({ loginInfo, channelId, userId });
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/channel-user/add-channel-user-list-normal
* #desc 批量添加频道普通身份用户
* @param {*} request
* @param {*} response
*/
router.post('/add-channel-user-list-normal', async function(request, response){
try {
const { channelId, userIdList } = request.body;
if (!checkRequestParams({
channelId, userIdList
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
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)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/channel-user/delete-channel-user
* #desc 删除频道用户
* @param {*} request
* @param {*} response
*/
router.post('/delete-channel-user', 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.removeChannelUser({ loginInfo, channelId, userId });
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/channel-user/update-channel-user-role-admin
* #desc 更新频道用户角色为管理员
* @param {*} request
* @param {*} response
*/
router.post('/update-channel-user-role-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.updateChannelUserRoleAdmin({ loginInfo, channelId, userId });
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/channel-user/update-channel-user-role-normal
* #desc 更新频道用户角色为普通用户
* @param {*} request
* @param {*} response
*/
router.post('/update-channel-user-role-normal', 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.updateChannelUserRoleNormal({ loginInfo, channelId, userId });
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller get /api/web/channel-user/get-channel-list-user-list
* #desc 获取所有频道列表的用户
* @param {*} request
* @param {*} response
*/
router.get('/get-channel-list-user-list', async function(request, response) {
try {
const loginInfo = request.ctx || {}
const result = await channelUserBiz.getChannelListUserList({ loginInfo });
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller get /api/web/channel-user/get-channel-user-list
* #desc 获取某个频道的用户列表
* @param {*} request
* @param {*} response
*/
router.get('/get-channel-user-list', async function(request, response) {
try {
const { channelId } = request.query;
if (!checkRequestParams({
channelId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelUserBiz.getChannelUserList({ loginInfo, channelId });
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller get /api/web/channel-user/update-channel-top
* #desc 修改频道是否置顶
* @param {*} request
* @param {*} response
*/
router.post('/update-channel-top', async function(request, response) {
try {
const { channelId, top } = request.body;
if (!checkRequestParams({
channelId, top
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelUserBiz.updateChannelToTop({
channelId, top, loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller get /api/web/channel-user/update-channel-black
* #desc 修改频道是否拉黑
* @param {*} request
* @param {*} response
*/
router.post('/update-channel-black', async function(request, response) {
try {
const { channelId, black } = request.body;
if (!checkRequestParams({
channelId, black
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await channelUserBiz.updateChannelToBlack({
channelId, black, loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller get /api/web/channel-user/exit-channel
* #desc 退出频道
* @param {*} request
* @param {*} response
*/
router.post('/exit-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.exitChannel({
channelId, loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
module.exports = router;

View File

@ -0,0 +1,57 @@
const {
tlConsole, 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 获取企业
* @param {*} request
* @param {*} response
*/
router.post('/get-company', async function(request, response) {
try {
const loginInfo = request.ctx || {}
const result = await companyBiz.getCompanyInfo({
loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
module.exports = router;

View File

@ -0,0 +1,49 @@
const {
getClientIP, getLocalIP, tlConsole, tlResponseSvrError, tlConsoleError
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const configBiz = require('../../../biz/config/config_biz')
const {
LOGIN : {
LOGIN_TOKEN_KEY
}
} = require('../../../utils/constant');
/**
* #controller get /api/web/config/init
* #desc 获取ip地址,初始化等相关配置
* @param {*} request
* @param {*} response
*/
router.get("/init", async function(request, response){
try {
const { [LOGIN_TOKEN_KEY]: token } = request.cookies;
//是否开启turn
const openTurn = (request.query.turn || "") === 'true';
//使用的账号模式, true : 有效账号模式, false : 固定账号
const useSecret = (request.query.secret || "") === 'true' || true;
//获取ip相关信息
let regexIP = /^((?:(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d?\d))$/;
let ip = getLocalIP();
if (!regexIP.test(ip)) {
ip = getClientIP(request)
}
if (!regexIP.test(ip)) {
ip = "127.0.0.1"
}
const result = await configBiz.initData({
openTurn, useSecret, ip, token
})
response.json(result)
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
})
module.exports = router

View File

@ -0,0 +1,137 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const userApplyBiz = require('../../../biz/user/user_apply_biz');
/**
* #controller post /api/web/user-apply/add-user-friend-apply
* #desc 添加好友申请
* @param {*} request
* @param {*} response
*/
router.post('/add-user-friend-apply', async function(request, response) {
try {
const { friendId, remark, origin } = request.body;
if (!checkRequestParams({
friendId, remark, origin
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userApplyBiz.applyAddFriend({
loginInfo, friendId, remark, origin
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user-apply/pass-user-friend
* #desc 通过好友申请
* @param {*} request
* @param {*} response
*/
router.post('/pass-user-friend', 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.passUserFriendApply({
loginInfo, id, remark
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user-apply/reject-user-friend
* #desc 拒绝好友申请
* @param {*} request
* @param {*} response
*/
router.post('/reject-user-friend', 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.rejectUserFriendApply({
loginInfo, id, remark
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller get /api/web/user-apply/get-user-friend-other-apply-list
* #desc 获取自己收到的用户好友申请列表
* @param {*} request
* @param {*} response
*/
router.get('/get-user-friend-other-apply-list', async function(request, response) {
try {
const loginInfo = request.ctx || {}
const result = await userApplyBiz.getUserFriendListFromOther({
loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller get /api/web/user-apply/get-user-friend-self-apply-list
* #desc 获取自己发出的用户好友申请列表
* @param {*} request
* @param {*} response
*/
router.get('/get-user-friend-self-apply-list', async function(request, response) {
try {
const loginInfo = request.ctx || {}
const result = await userApplyBiz.getUserFriendApplyListFromSelf({
loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
module.exports = router;

View File

@ -0,0 +1,144 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const userConfigBiz = require('../../../biz/user/user_config_biz');
/**
* #controller post /api/web/user-config/get-user-config
* #desc 获取用户配置
* @param {*} request
* @param {*} response
*/
router.get('/get-user-config', async function(request, response) {
try {
const loginInfo = request.ctx || {}
const result = await userConfigBiz.getUserConfigSetting({
loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user-config/update-user-config-normal
* #desc 更新用户通用设置
* @param {*} request
* @param {*} response
*/
router.post('/update-user-config-normal', async function(request, response) {
try {
const { normal } = request.body;
if (!checkRequestParams({
normal
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userConfigBiz.updateUserConfigNormal({
loginInfo, normal
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user-config/update-user-config-account
* #desc 更新用户账号设置
* @param {*} request
* @param {*} response
*/
router.post('/update-user-config-account', async function(request, response) {
try {
const { account } = request.body;
if (!checkRequestParams({
account
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userConfigBiz.updateUserConfigAccount({
loginInfo, account
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user-config/update-user-config-message
* #desc 更新用户消息设置
* @param {*} request
* @param {*} response
*/
router.post('/update-user-config-message', async function(request, response) {
try {
const { message } = request.body;
if (!checkRequestParams({
message
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userConfigBiz.updateUserConfigMessage({
loginInfo, message
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user-config/update-user-config-other
* #desc 更新用户其他设置
* @param {*} request
* @param {*} response
*/
router.post('/update-user-config-other', async function(request, response) {
try {
const { other } = request.body;
if (!checkRequestParams({
other
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userConfigBiz.updateUserConfigOther({
loginInfo, other
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
module.exports = router;

View File

@ -0,0 +1,103 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const userBiz = require('../../../biz/user/user_biz');
const {
LOGIN : {
LOGIN_TOKEN_KEY
}
} = require('../../../utils/constant');
/**
* #controller get /api/web/user/search-user-by-name
* #desc 搜索用户
* @param {*} request
* @param {*} response
* @return {*}
*/
router.get('/search-user-by-name', async function(request, response) {
try {
const { name } = request.query;
if (!checkRequestParams({
name,
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userBiz.searchUserByName({
loginInfo, name,
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user/search-user-by-id
* #desc 搜索用户通过id
* @param {*} request
* @param {*} response
* @return {*}
*/
router.post('/search-user-by-id', async function(request, response) {
try {
const { id } = request.body;
if (!checkRequestParams({
id,
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userBiz.searchUserById({
loginInfo, id,
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user/bind-email
* #desc 绑定邮箱
* @param {*} request
* @param {*} response
*/
router.post('/bind-email', async function(request, response) {
try {
const { email, code } = request.body;
const { [LOGIN_TOKEN_KEY]: token } = request.cookies;
if (!checkRequestParams({
email, code,
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userBiz.bindEmail({
loginInfo, email, code, token
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
module.exports = router;

View File

@ -0,0 +1,141 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const userFriendBiz = require('../../../biz/user/user_friend_biz');
/**
* #controller post /api/web/user-friend/delete-user-friend
* #desc 删除好友
* @param {*} request
* @param {*} response
*/
router.post('/delete-user-friend', async function(request, response) {
try {
const { channelId } = request.body;
if (!checkRequestParams({
channelId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userFriendBiz.deleteFriend({
loginInfo, channelId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError(error));
}
});
/**
* #controller post /api/web/user-friend/update-user-friend-remark
* #desc 更新好友信息备注
* @param {*} request
* @param {*} response
*/
router.post('/update-user-friend-remark', async function(request, response) {
try {
const { channelId, remark } = request.body;
if (!checkRequestParams({
channelId, remark
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userFriendBiz.updateRemark({
loginInfo, channelId, remark
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError(error));
}
});
/**
* #controller post /api/web/user-friend/update-user-friend-rename
* #desc 更新好友名称备注
* @param {*} request
* @param {*} response
*/
router.post('/update-user-friend-rename', async function(request, response) {
try {
const { channelId, rename } = request.body;
if (!checkRequestParams({
channelId, rename
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
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)
response.json(tlResponseSvrError(error));
}
});
/**
* #controller post /api/web/user-friend/get-user-friend-list
* #desc 获取用户好友列表
* @param {*} request
* @param {*} response
*/
router.get('/get-user-friend-list', async function(request, response) {
try {
const loginInfo = request.ctx || {}
const result = await userFriendBiz.getFriendList({
loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError(error));
}
});
module.exports = router;

View File

@ -0,0 +1,435 @@
const {
tlConsole,
tlResponseSvrError, tlConsoleError,
tlResponseArgsError, checkRequestParams,
tlResponseSuccess
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const userLoginBiz = require('../../../biz/user/user_login_biz');
const userLoginStateBiz = require('../../../biz/user/user_login_state_biz');
const {
LOGIN : {
LOGIN_TOKEN_KEY,
LOGIN_TOKEN_EXPIRE,
WEBSITE_LOGIN_TOKEN_KEY,
WEBSITE_LOGIN_TOKEN_EXPIRE
}
} = require('../../../utils/constant');
/**
* #controller get /api/web/user-login/login-state
* #desc 获取登录状态
* @param {*} request
* @param {*} response
*/
router.get('/login-state', async function(request, response) {
try {
const { [LOGIN_TOKEN_KEY]: token } = request.cookies;
const result = await userLoginStateBiz.userIsLogin({
token
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
});
/**
* #controller post /api/web/user-login/login-by-account
* #desc 通过账号登录
* @param {*} request
* @param {*} response
*/
router.post('/login-by-account', async function(request, response) {
try {
const { account, password, 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({
account, password, fps
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await userLoginBiz.userLoginByAccount({
account, password, 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-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 通过邮箱登录
* @param {*} request
* @param {*} response
*/
router.post('/login-by-email', async function(request, response) {
try {
const { email, password, 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({
email, password, fps
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await userLoginBiz.userLoginByEmail({
email, password, 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-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
* #desc 通过指纹一键登录
* @param {*} request
* @param {*} response
*/
router.post('/login-by-fp', async function(request, response) {
try {
const { username, 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({
username, fps
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await userLoginBiz.userLoginByFingerPrint({
username, 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 get /api/web/user-login/website-login-state
* #desc 获取官网登录状态
* @param {*} request
* @param {*} response
*/
router.get('/website-login-state', async function(request, response) {
try {
const { [WEBSITE_LOGIN_TOKEN_KEY]: token } = request.cookies;
const result = await userLoginStateBiz.userIsLogin({
token
});
if(!result.success){
return response.json(result)
}
const data = {
loginUserId: result.data.loginUserId,
loginUserEmail: result.data.loginUserEmail,
loginUsername: result.data.loginUsername,
loginUserAvatar: result.data.loginUserAvatar,
loginTime: result.data.loginTime,
token: result.data.token,
}
response.json(tlResponseSuccess("在线", data));
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
});
/**
* #controller post /api/web/user-login/login-by-website
* #desc 官网登录
* @param {*} request
* @param {*} response
*/
router.post('/login-by-website', async function(request, response) {
try {
const { name, email, password } = request.body;
const { [WEBSITE_LOGIN_TOKEN_KEY]: token } = request.cookies;
if(token){
const loginResult = await userLoginStateBiz.userIsLogin({
token
});
if(loginResult.success){
return response.json(loginResult)
}
}
if (!checkRequestParams({
name, email, password
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await userLoginBiz.userLoginByWebsite({
name, email, password
});
response.cookie(WEBSITE_LOGIN_TOKEN_KEY, result.data, {
maxAge: WEBSITE_LOGIN_TOKEN_EXPIRE, httpOnly: true
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
});
module.exports = router

View File

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

View File

@ -0,0 +1,209 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const userReadBiz = require('../../../biz/user/user_read_biz');
/**
* #controller post /api/web/user-read/update-channel-mutil-read
* #desc 更新频道文件/媒体/聊天消息已读记录
* @param {*} request
* @param {*} response
*/
router.post('/update-channel-mutil-read', async function(request, response) {
try {
const {
channelId, latestChatReadId, latestMediaReadId, latestFileReadId
} = request.body;
if (!checkRequestParams({
channelId, latestChatReadId, latestMediaReadId, latestFileReadId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userReadBiz.updateChannelMuiltRead({
loginInfo, channelId, latestChatReadId, latestMediaReadId, latestFileReadId
})
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
})
/**
* #controller post /api/web/user-read/update-channel-chat-read
* #desc 更新频道聊天消息已读记录
* @param {*} request
* @param {*} response
*/
router.post('/update-channel-chat-read', async function(request, response) {
try {
const { channelId, latestReadId } = request.body;
if (!checkRequestParams({
channelId, latestReadId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userReadBiz.updateChannelChatRead({
loginInfo, channelId, latestReadId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
});
/**
* #controller post /api/web/user-read/update-channel-media-read
* #desc 更新频道媒体消息已读记录
* @param {*} request
* @param {*} response
*/
router.post('/update-channel-media-read', async function(request, response) {
try {
const { channelId, latestReadId } = request.body;
if (!checkRequestParams({
channelId, latestReadId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userReadBiz.updateChannelMediaRead({
loginInfo, channelId, latestReadId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
})
/**
* #controller post /api/web/user-read/update-channel-file-read
* #desc 更新频道文件消息已读记录
* @param {*} request
* @param {*} response
*/
router.post('/update-channel-file-read', async function(request, response) {
try {
const { channelId, latestReadId } = request.body;
if (!checkRequestParams({
channelId, latestReadId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userReadBiz.updateChannelFileRead({
loginInfo, channelId, latestReadId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
})
/**
* #controller post /api/web/user-read/update-user-friend-apply-read
* #desc 新增申请消息已读记录
* @param {*} request
* @param {*} response
*/
router.post('/update-user-friend-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.addUserFriendApplyRead({
loginInfo, recordId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
})
/**
* #controller post /api/web/user-read/update-user-friend-apply-pass-read
* #desc 新增通过申请消息已读记录
* @param {*} request
* @param {*} response
*/
router.post('/update-user-friend-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.addUserFriendApplyPassRead({
loginInfo, recordId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
})
/**
* #controller post /api/web/user-read/update-user-friend-apply-reject-read
* #desc 新增拒绝申请消息已读记录
* @param {*} request
* @param {*} response
*/
router.post('/update-user-friend-apply-reject-read', async function(request, response) {
try {
const { applyId } = request.body;
if (!checkRequestParams({
applyId
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userReadBiz.addUserFriendApplyRejectRead({
loginInfo, applyId
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError())
}
})
module.exports = router;

View File

@ -0,0 +1,192 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const bizUserRegister = require('../../../biz/user/user_register_biz');
const bizUserLoginState = require('../../../biz/user/user_login_state_biz');
const {
LOGIN : {
LOGIN_TOKEN_KEY
}
} = require('../../../utils/constant');
/**
* #controller post /api/web/user-register/register-by-account
* #desc 通过账号注册
* @param {*} request
* @param {*} response
*/
router.post('/register-by-account', async function(request, response) {
try {
const { account, password, 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({
account, password, invite_code
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
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
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user-register/register-by-email
* #desc 通过邮箱注册
* @param {*} request
* @param {*} response
*/
router.post('/register-by-email', async function(request, response) {
try {
const { email, code, invite_code, 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)
}
}
if (!checkRequestParams({
email, code, invite_code, password
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await bizUserRegister.userRegisterByEmail({
email, code, invite_code, password
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user-register/get-email-code
* #desc 获取邮箱验证码
* @param {*} request
* @param {*} response
*/
router.post('/get-email-code', async function(request, response) {
try {
const { email } = request.body;
if (!checkRequestParams({
email
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await bizUserRegister.getEmailCode({
email
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user-register/register-website-user
* #desc 注册官网用户
* @param {*} request
* @param {*} response
*/
router.post('/register-website-user', 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)
}
}
if (!checkRequestParams({
code, email, password
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const result = await bizUserRegister.registerWebsiteUser({
code, email, password
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
module.exports = router

View File

@ -0,0 +1,180 @@
const {
tlConsole, tlResponseSvrError, tlConsoleError, tlResponseArgsError, checkRequestParams
} = require("../../../utils/utils");
const express = require('express');
const router = express.Router();
const userTagBiz = require('../../../biz/user/user_tag_biz');
/**
* #controller post /api/web/user-tag/add-channel-tag
* #desc 添加频道标签
* @param {*} request
* @param {*} response
*/
router.post('/add-channel-tag', async function(request, response) {
try {
const { name } = request.body;
if (!checkRequestParams({
name
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userTagBiz.addChannelTag({
loginInfo, name
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user-tag/add-friend-tag
* #desc 添加好友标签
* @param {*} request
* @param {*} response
*/
router.post('/add-friend-tag', async function(request, response) {
try {
const { name } = request.body;
if (!checkRequestParams({
name
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userTagBiz.addFriendTag({
loginInfo, name
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user-tag/add-cloud-tag
* #desc 添加云资源库标签
* @param {*} request
* @param {*} response
*/
router.post('/add-cloud-tag', async function(request, response) {
try {
const { name } = request.body;
if (!checkRequestParams({
name
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userTagBiz.addCloudTag({
loginInfo, name
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user-tag/get-channel-tag-list
* #desc 获取频道标签列表
* @param {*} request
* @param {*} response
*/
router.get('/get-channel-tag-list', async function(request, response) {
try {
const loginInfo = request.ctx || {}
const result = await userTagBiz.getChannelTagList({
loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user-tag/get-friend-tag-list
* #desc 获取好友标签列表
* @param {*} request
* @param {*} response
*/
router.get('/get-friend-tag-list', async function(request, response) {
try {
const loginInfo = request.ctx || {}
const result = await userTagBiz.getFriendTagList({
loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user-tag/get-cloud-tag-list
* #desc 获取云资源库标签列表
* @param {*} request
* @param {*} response
*/
router.get('/get-cloud-tag-list', async function(request, response) {
try {
const loginInfo = request.ctx || {}
const result = await userTagBiz.getCloudTagList({
loginInfo
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
/**
* #controller post /api/web/user-tag/delete-tag
* #desc 删除标签
* @param {*} request
* @param {*} response
*/
router.post('/delete-tag', async function(request, response) {
try {
const { id } = request.body;
if (!checkRequestParams({
id
})) {
response.json(tlResponseArgsError("请求参数非法"));
return;
}
const loginInfo = request.ctx || {}
const result = await userTagBiz.delUserTag({
loginInfo, id
});
response.json(result);
} catch (error) {
tlConsoleError(error)
response.json(tlResponseSvrError());
}
});
module.exports = router;

44
src/controller/web/web.js Normal file
View File

@ -0,0 +1,44 @@
// Autor: iamtsm
// web包含的controller定义
// Date: 2024-01-13
// 配置
const configInit = require('./config/init_controller')
// 企业
const company = require('./company/company_controller')
// 用户
const userLogin = require('./user/user_login_controller')
const userRegister = require('./user/user_register_controller')
const userLogout = require('./user/user_logout_controller')
const userFriend = require('./user/user_friend_controller')
const user = require('./user/user_controller')
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 channel = require('./channel/channel_controller')
const channelChat = require('./channel/channel_chat_controller')
const channelUser = require('./channel/channel_user_controller')
module.exports = {
"config" : configInit,
"company" : company,
"user" : user,
"user-login" : userLogin,
"user-logout" : userLogout,
"user-register" : userRegister,
"user-friend" : userFriend,
"user-apply" : userApply,
"user-read" : userRead,
"user-config" : userConfig,
"user-tag" : userTag,
"channel" : channel,
"channel-chat" : channelChat,
"channel-user" : channelUser,
}

View File

@ -0,0 +1,232 @@
const { DataTypes, where } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_channel_chat')
const Table = model(dbClient, DataTypes).TlChannelChat
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)
return info
}
/**
* 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
}

205
src/dao/tl_channel_dao.js Normal file
View File

@ -0,0 +1,205 @@
const { DataTypes, where, or } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_channel')
const Table = model(dbClient, DataTypes).TlChannel
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)
return info
}
/**
* 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,234 @@
const { DataTypes, Sequelize } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_channel_user')
const Table = model(dbClient, DataTypes).TlChannelUser
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, JSON.stringify(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
}
/**
* 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
}
/**
* 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)
return info
}
/**
* 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
}
module.exports = {
addInfo, addList,
getInfo, getList, getListForPage,
updateInfo,
deleteInfo,
getCount, getGroupCount,
}

205
src/dao/tl_company_dao.js Normal file
View File

@ -0,0 +1,205 @@
const { DataTypes, where } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_company')
const Table = model(dbClient, DataTypes).TlCompany
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)
return info
}
/**
* 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,
}

206
src/dao/tl_role_dao.js Normal file
View File

@ -0,0 +1,206 @@
const { DataTypes, where } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_role')
const Table = model(dbClient, DataTypes).TlRole
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){
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)
return info
}
/**
* 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,206 @@
const { DataTypes, where } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_user_apply')
const Table = model(dbClient, DataTypes).TlUserApply
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)
return info
}
/**
* 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,
}

206
src/dao/tl_user_auth_dao.js Normal file
View File

@ -0,0 +1,206 @@
const { DataTypes, where } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_user_auth')
const Table = model(dbClient, DataTypes).TlUserAuth
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)
return info
}
/**
* 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,206 @@
const { DataTypes, where } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_user_config')
const Table = model(dbClient, DataTypes).TlUserConfig
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)
return info
}
/**
* 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,
}

207
src/dao/tl_user_dao.js Normal file
View File

@ -0,0 +1,207 @@
const { DataTypes, where } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_user')
const Table = model(dbClient, DataTypes).TlUser
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)
return info
}
/**
* 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,206 @@
const { DataTypes, where } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_user_finger_print')
const Table = model(dbClient, DataTypes).TlUserFingerPrint
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)
return info
}
/**
* 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,206 @@
const { DataTypes } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_user_friend')
const Table = model(dbClient, DataTypes).TlUserFriend
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)
return info
}
/**
* 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,
}

205
src/dao/tl_user_read_dao.js Normal file
View File

@ -0,0 +1,205 @@
const { DataTypes, where } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_user_read')
const Table = model(dbClient, DataTypes).TlUserRead
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)
return info
}
/**
* 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,
}

206
src/dao/tl_user_tag_dao.js Normal file
View File

@ -0,0 +1,206 @@
const { DataTypes, where } = require('sequelize');
const { dbClient } = require('../tables/db')
const { model, fields } = require('../tables/tl_user_tag')
const Table = model(dbClient, DataTypes).TlUserTag
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)
return info
}
/**
* 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,
}

112
src/middleware/loginAuth.js Normal file
View File

@ -0,0 +1,112 @@
const {
tlConsoleApiIcon, tlConsole, tlConsoleError,
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess
} = require("../utils/utils");
const {
LOGIN : {
LOGIN_TOKEN_KEY,
WEBSITE_LOGIN_TOKEN_KEY
}
} = require('../utils/constant');
const userSessionService = require('../service/user/tl_user_session_service')
const loginAuthIngoreApi = [
// 初始化
'/api/web/config/init',
// 登录
'/api/web/user-login/login-state',
'/api/web/user-login/website-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-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',
]
/**
* 登录验证中间件
* @param {*} request
* @param {*} response
* @param {*} next
* @returns
*/
const loginAuthHandler = async function(request, response, next) {
// 非api请求不需要登录验证
if(!request.url.startsWith("/api/")) {
return next()
}
// 跳过忽略登录态校验的api
for (const ignoreApi of loginAuthIngoreApi) {
if (request.url.startsWith(ignoreApi)) {
return next()
}
}
const isWebsite = request.url.includes("/website-")
let tokenKey = LOGIN_TOKEN_KEY
if(isWebsite){
tokenKey = WEBSITE_LOGIN_TOKEN_KEY
}
const { [tokenKey]: token } = request.cookies;
if (!token) {
return response.json(tlResponseForbidden("不在线, 请先登录"))
}
const {
loginUserCompanyId,
loginUserCompanyName,
loginUserId,
loginUsername,
loginUserRoleId,
loginUserAvatar,
loginTime,
loginUserEmail,
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)
}
if (!loginUserCompanyId) {
return response.json(tlResponseForbidden("不在线, 请先登录"))
}
if (!loginUserId) {
return response.json(tlResponseForbidden("不在线, 请先登录"))
}
request.ctx = {
token, loginUserCompanyId, loginUserId,
loginUsername, loginUserRoleId, loginUserCompanyName,
loginUserAvatar, loginTime, loginUserEmail, loginUserMobile
}
next()
}
module.exports = loginAuthHandler

288
src/middleware/loginRole.js Normal file
View File

@ -0,0 +1,288 @@
const {
tlConsoleApiIcon, tlConsole, tlConsoleError,
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess
} = require("../utils/utils");
const {
LOGIN : {
LOGIN_TOKEN_KEY
}
} = require('../utils/constant');
const userSessionService = require('../service/user/tl_user_session_service')
const { inner: TlRoleInner } = require('../tables/tl_role')
const {
getAllPermissionsMap
} = require('../role/role')
const loginRoleIngoreApi = [
// 初始化
'/api/web/config/init',
// 登录
'/api/web/user-login/login-state',
'/api/web/user-login/website-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-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',
]
/**
* 根据角色id获取角色信息
* 目前角色是固定的,后续可以从数据库中获取
* @param {*} roleId
* @returns
*/
const getRoleInfoById = function({roleId}){
const roleList = [
TlRoleInner.user.normal,
TlRoleInner.user.admin,
TlRoleInner.channel.creator,
TlRoleInner.channel.admin,
TlRoleInner.channel.member,
]
return roleList.find(role => role.id === roleId)
}
/**
* 判断角色是否有权限
* @param {*} roleId
* @param {*} permissionId
* @returns
*/
const roleHasPermission = function({ roleId, permissionId }){
const roleInfo = getRoleInfoById({ roleId })
if(!roleInfo){
return false
}
let permissionIdList = []
try{
let permissionIdListJson = roleInfo.permissionIdList
permissionIdList = JSON.parse(permissionIdListJson)
}catch(e){
tlConsoleError(e)
return false
}
return permissionIdList.includes(permissionId)
}
/**
* 判断用户在频道中是否有权限
* @param {*} userId
* @param {*} permissionId
* @param {*} channelId
* @returns
*/
const channelRoleHasPermission = async function({ userId, permissionId, channelId }){
let channelRole = await userSessionService.getUserChannelRole({
userId, channelId
})
channelRole = parseInt(channelRole)
const roleInfo = getRoleInfoById({ roleId: channelRole })
if(!roleInfo){
return false
}
let permissionIdList = []
try{
let permissionIdListJson = roleInfo.permissionIdList
permissionIdList = JSON.parse(permissionIdListJson)
}catch(e){
tlConsoleError(e)
return false
}
return permissionIdList.includes(permissionId)
}
/**
* 根据请求api获取对应的权限id
* @param {*} url
*/
const getRequestApiPermissionId = function(url){
let apiSplit = url.split("/")
if(apiSplit.length !== 5){
return ""
}
let [_a, _b, apiPlatform, apiModule, apiAction] = apiSplit
apiAction = apiAction.split("?")[0]
apiModule = apiModule.replace(/-/g, "_").toUpperCase()
apiAction = apiAction.replace(/-/g, "_").toUpperCase()
// 获取权限key
let permissionKey = apiModule + ":" + apiAction
// 获取权限map
let permissionMap = getAllPermissionsMap()
// 获取权限id
return permissionMap[permissionKey]
}
/**
* 权限验证中间件
* @param {*} request
* @param {*} response
* @param {*} next
* @returns
*/
const loginRoleHandler = async function(request, response, next) {
// 非api请求不需要权限验证
if(!request.url.startsWith("/api/")) {
return next()
}
// 跳过忽略权限校验的api
for (const ignoreApi of loginRoleIngoreApi) {
if (request.url.startsWith(ignoreApi)) {
return next()
}
}
// 频道相关不处理
if(request.url.startsWith("/api/web/channel")){
return next()
}
const isWebsite = request.url.includes("/website-")
const {
loginUserCompanyId,
loginUserCompanyName,
loginUserId,
loginUsername,
loginUserRoleId,
loginUserAvatar,
loginTime,
loginUserEmail,
loginUserMobile
} = request.ctx
if(!loginUserRoleId){
return response.json(tlResponseForbidden("身份无权限"))
}
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)
}
if(!permissionId){
return response.json(tlResponseForbidden("请求无权限"))
}
const hasPermission = roleHasPermission({
roleId: loginUserRoleId,
permissionId: permissionId
})
if(!hasPermission){
return response.json(tlResponseForbidden("操作无权限"))
}
next()
}
/**
* 频道权限验证中间件
* @param {*} request
* @param {*} response
* @param {*} next
* @returns
*/
const loginChannelRoleHandler = async function(request, response, next) {
// 非api请求不需要权限验证
if(!request.url.startsWith("/api/")) {
return next()
}
// 跳过忽略权限校验的api
for (const ignoreApi of loginRoleIngoreApi) {
if (request.url.startsWith(ignoreApi)) {
return next()
}
}
// 只处理频道相关的api
if(!request.url.startsWith("/api/web/channel")){
return next()
}
let channelId = request.query.channelId || request.body.channelId
if(!channelId){
return next()
}
channelId = String(channelId)
const {
loginUserCompanyId,
loginUserCompanyName,
loginUserId,
loginUsername,
loginUserRoleId,
loginUserAvatar,
loginTime,
loginUserEmail,
loginUserMobile
} = request.ctx
if(!loginUserRoleId){
return response.json(tlResponseForbidden("身份无权限"))
}
let permissionId = getRequestApiPermissionId(request.url)
tlConsole("channel role check:", request.url, loginUserCompanyId, loginUserId, loginUserRoleId, permissionId)
if(!permissionId){
return response.json(tlResponseForbidden("请求无权限"))
}
const hasPermission = await channelRoleHasPermission({
userId: loginUserId,
permissionId: permissionId,
channelId: channelId
})
if(!hasPermission){
return response.json(tlResponseForbidden("操作无权限"))
}
next()
}
module.exports = {
loginRoleHandler,
loginChannelRoleHandler
}

86
src/role/accountRole.js Normal file
View File

@ -0,0 +1,86 @@
const {
channelPermission,
userPermission,
companyPermission,
configPermission,
channelPerfix,
channelUserPerfix,
} = require('./permission');
/**
* 普通用户权限
* @returns
*/
const userNormalPermissions = function(){
let returnPermission = [];
// 频道权限
const channelKeys = Object.keys(channelPermission.channel).filter((key) => {
return ![
channelPerfix + "UPDATE_CHANNEL_NAME"
].includes(key)
})
channelKeys.forEach((key) => {
returnPermission.push(channelPermission.channel[key]);
})
const channelUserKeys = Object.keys(channelPermission.channelUser).filter((key) => {
return ![
channelUserPerfix + "ADD_CHANNEL_USER_ADMIN",
channelUserPerfix + "ADD_CHANNEL_USER",
channelUserPerfix + "DELETE_CHANNEL_USER",
channelUserPerfix + "UPDATE_CHANNEL_USER_ROLE_ADMIN",
channelUserPerfix + "UPDATE_CHANNEL_USER_ROLE_NORMAL",
].includes(key)
})
channelUserKeys.forEach((key) => {
returnPermission.push(channelPermission.channelUser[key]);
})
returnPermission.push(...Object.values(channelPermission.channelChat))
// 用户权限
Object.keys(userPermission).forEach((key) => {
returnPermission.push(...Object.values(userPermission[key]));
})
// 配置权限
Object.keys(configPermission).forEach((key) => {
returnPermission.push(...Object.values(configPermission[key]));
})
return returnPermission;
}
/**
* 系统管理员权限 - 所有权限
* @returns
*/
const userAdminPermissions = function(){
let returnPermission = [];
// 频道权限
Object.keys(channelPermission).forEach((key) => {
returnPermission.push(...Object.values(channelPermission[key]));
})
// 用户权限
Object.keys(companyPermission).forEach((key) => {
returnPermission.push(...Object.values(companyPermission[key]));
})
// 用户权限
Object.keys(userPermission).forEach((key) => {
returnPermission.push(...Object.values(userPermission[key]));
})
// 配置权限
Object.keys(configPermission).forEach((key) => {
returnPermission.push(...Object.values(configPermission[key]));
})
return returnPermission;
}
module.exports = {
userNormalPermissions,
userAdminPermissions,
}

99
src/role/channelRole.js Normal file
View File

@ -0,0 +1,99 @@
const {
channelPermission,
channelPerfix,
channelNoticePerfix,
channelUserPerfix
} = require('./permission');
/**
* 频道创建人权限
* @returns
*/
const userChannelCreatorPermissions = function(){
let returnPermission = [];
// 频道权限
returnPermission.push(...Object.values(channelPermission.channel))
returnPermission.push(...Object.values(channelPermission.channelChat))
returnPermission.push(...Object.values(channelPermission.channelUser))
return returnPermission;
}
/**
* 频道管理员权限
* @returns
*/
const userChannelAdminPermissions = function(){
let returnPermission = [];
// 频道权限
const channelKeys = Object.keys(channelPermission.channel).filter((key) => {
return ![
channelPerfix + "UPDATE_CHANNEL_NAME"
].includes(key)
})
channelKeys.forEach((key) => {
returnPermission.push(channelPermission.channel[key]);
})
const channelUserKeys = Object.keys(channelPermission.channelUser).filter((key) => {
return ![
channelUserPerfix + "ADD_CHANNEL_USER_ADMIN",
channelUserPerfix + "ADD_CHANNEL_USER",
channelUserPerfix + "DELETE_CHANNEL_USER",
channelUserPerfix + "UPDATE_CHANNEL_USER_ROLE_ADMIN",
].includes(key)
})
channelUserKeys.forEach((key) => {
returnPermission.push(channelPermission.channelUser[key]);
})
returnPermission.push(...Object.values(channelPermission.channelChat))
return returnPermission;
}
/**
* 频道普通用户权限
* @returns
*/
const userChannelNormalPermissions = function(){
let returnPermission = [];
// 频道权限
const channelKeys = Object.keys(channelPermission.channel).filter((key) => {
return ![
channelPerfix + "UPDATE_CHANNEL_NAME"
].includes(key)
})
channelKeys.forEach((key) => {
returnPermission.push(channelPermission.channel[key]);
})
const channelUserKeys = Object.keys(channelPermission.channelUser).filter((key) => {
return ![
channelUserPerfix + "ADD_CHANNEL_USER_ADMIN",
channelUserPerfix + "ADD_CHANNEL_USER",
channelUserPerfix + "DELETE_CHANNEL_USER",
channelUserPerfix + "UPDATE_CHANNEL_USER_ROLE_ADMIN",
channelUserPerfix + "UPDATE_CHANNEL_USER_ROLE_NORMAL",
].includes(key)
})
channelUserKeys.forEach((key) => {
returnPermission.push(channelPermission.channelUser[key]);
})
returnPermission.push(...Object.values(channelPermission.channelChat))
return returnPermission;
}
module.exports = {
userChannelCreatorPermissions,
userChannelAdminPermissions,
userChannelNormalPermissions,
}

256
src/role/permission.js Normal file
View File

@ -0,0 +1,256 @@
/**
* @description 权限配置
* @module permission
* @auther iamtsm
*/
// 权限id基数
const systemPermissionIdBase = 1
const channelPermissionIdBase = 100000
const companyPermissionIdBase = 300000
const userPermissionIdBase = 600000
const configPermissionIdBase = 700000
// key前缀
const systemPerfix = 'SYSTEM:'
const channelPerfix = 'CHANNEL:'
const channelChatPerfix = 'CHANNEL_CHAT:'
const channelUserPerfix = 'CHANNEL_USER:'
const companyPerfix = 'COMPANY:'
const userPerfix = 'USER:'
const userApplyPerfix = 'USER_APPLY:'
const userFriendPerfix = 'USER_FRIEND:'
const userConfigPerfix = 'USER_CONFIG:'
const userReadPerfix = 'USER_READ:'
const userTagPerfix = 'USER_TAG:'
const userRegisterPerfix = 'USER_REGISTER:'
const userLoginPerfix = 'USER_LOGIN:'
const userLogoutPerfix = 'USER_LOGOUT:'
// 补充前缀
const addPerfix = function(permission, perfix){
for (let key in permission){
permission[perfix + key] = permission[key]
delete permission[key]
}
}
// 系统默认预设权限 1-999999
let systemPermission = {
}
// 频道权限 100000 - 199999
let channelPermission = {
channel: { // 100000 ~ 100999
// 添加频道
ADD_CHANNEL: channelPermissionIdBase + 1,
// 获取频道列表
GET_CHANNEL_LIST: channelPermissionIdBase + 2,
// 获取频道信息
GET_CHANNEL_INFO: channelPermissionIdBase + 4,
// 获取频道名称
GET_CHANNEL_NAME: channelPermissionIdBase + 5,
// 修改频道名称
UPDATE_CHANNEL_NAME: channelPermissionIdBase + 6,
// 获取频道聊天记录
GET_CHANNEL_MESSAGE: channelPermissionIdBase + 7,
// 获取频道列表聊天记录
GET_CHANNEL_MESSAGE_LIST: channelPermissionIdBase + 8,
// 通过频道id获取频道信息
SEARCH_CHANNEL_BY_ID: channelPermissionIdBase + 10,
// 获取群组频道列表
GET_GROUP_CHANNEL_LIST: channelPermissionIdBase + 11,
},
channelChat: { // 101000 ~ 101999
// 发送好友频道聊天
ADD_FRIEND_CHANNEL_CHAT: channelPermissionIdBase + 1000,
// 发送多人频道聊天
ADD_GROUP_CHANNEL_CHAT: channelPermissionIdBase + 1001,
// 回复好友频道聊天
ADD_REPLY_FRIEND_CHANNEL_CHAT: channelPermissionIdBase + 1002,
// 回复多人频道聊天
ADD_REPLY_GROUP_CHANNEL_CHAT: channelPermissionIdBase + 1003,
// 撤回聊天消息
ROLLBACK_CHANNEL_CHAT: channelPermissionIdBase + 1004,
},
channelUser: { // 105000 ~ 105999
// 系统管理员添加频道用户
ADD_CHANNEL_USER: channelPermissionIdBase + 5001,
// 分享加入群聊
SHARE_JOIN_CHANNEL: channelPermissionIdBase + 5002,
// 添加频道普通身份用户
ADD_CHANNEL_USER_NORMAL: channelPermissionIdBase + 5003,
// 批量添加频道普通身份用户
ADD_CHANNEL_USER_LIST_NORMAL: channelPermissionIdBase + 5004,
// 添加频道管理员身份用户
ADD_CHANNEL_USER_ADMIN: channelPermissionIdBase + 5005,
// 删除频道用户
DELETE_CHANNEL_USER: channelPermissionIdBase + 5006,
// 更新频道用户角色为管理员
UPDATE_CHANNEL_USER_ROLE_ADMIN: channelPermissionIdBase + 5007,
// 更新频道用户角色为普通用户
UPDATE_CHANNEL_USER_ROLE_NORMAL: channelPermissionIdBase + 5008,
// 获取所有频道列表的用户
GET_CHANNEL_LIST_USER_LIST: channelPermissionIdBase + 5009,
// 获取某个频道的用户列表
GET_CHANNEL_USER_LIST: channelPermissionIdBase + 5010,
// 修改频道是否置顶
UPDATE_CHANNEL_TOP: channelPermissionIdBase + 5011,
// 修改频道是否拉黑
UPDATE_CHANNEL_BLACK: channelPermissionIdBase + 5012,
// 退出频道
EXIT_CHANNEL: channelPermissionIdBase + 5013,
}
}
// 企业权限 300000 - 399999
let companyPermission = {
company: { // 300000 ~ 300999
// 添加企业
ADD_COMPANY: companyPermissionIdBase + 1,
// 获取企业
GET_COMPANY: companyPermissionIdBase + 2,
}
}
// 用户权限 600000 - 699999
let userPermission = {
user: { // 600000 ~ 600999
// 搜索用户
SEARCH_USER_BY_NAME: userPermissionIdBase + 1,
// 搜索用户通过id
SEARCH_USER_BY_ID: userPermissionIdBase + 2,
// 更新用户头像
UPDATE_USER_AVATAR: userPermissionIdBase + 3,
// 绑定邮箱
BIND_EMAIL: userPermissionIdBase + 4
},
userApply: { // 601000 ~ 601999
// 添加好友申请
ADD_USER_FRIEND_APPLY: userPermissionIdBase + 1000,
// 通过好友申请
PASS_USER_FRIEND: userPermissionIdBase + 1001,
// 拒绝好友申请
REJECT_USER_FRIEND: userPermissionIdBase + 1002,
// 获取自己收到的用户好友申请列表
GET_USER_FRIEND_OTHER_APPLY_LIST: userPermissionIdBase + 1003,
// 获取自己发出的用户好友申请列表
GET_USER_FRIEND_SELF_APPLY_LIST: userPermissionIdBase + 1004,
},
userFriend: { // 602000 ~ 602999
// 删除好友
DELETE_USER_FRIEND: userPermissionIdBase + 2000,
// 更新好友信息备注
UPDATE_USER_FRIEND_REMARK: userPermissionIdBase + 2001,
// 更新好友名称备注
UPDATE_USER_FRIEND_RENAME: userPermissionIdBase + 2002,
// 获取用户好友列表
GET_USER_FRIEND_LIST: userPermissionIdBase + 2003,
// 关注好友
UPDATE_USER_FRIEND_SPECIAL: userPermissionIdBase + 2004,
},
userConfig: { // 603000 ~ 603999
// 获取用户配置
GET_USER_CONFIG: userPermissionIdBase + 3000,
// 更新用户通用设置
UPDATE_USER_CONFIG_NORMAL: userPermissionIdBase + 3001,
// 更新用户皮肤设置
UPDATE_USER_CONFIG_SKIN: userPermissionIdBase + 3002,
// 更新用户账号设置
UPDATE_USER_CONFIG_ACCOUNT: userPermissionIdBase + 3003,
// 更新用户消息设置
UPDATE_USER_CONFIG_MESSAGE: userPermissionIdBase + 3004,
// 更新用户权限设置
UPDATE_USER_CONFIG_AUTHORITY: userPermissionIdBase + 3005,
// 更新用户其他设置
UPDATE_USER_CONFIG_OTHER: userPermissionIdBase + 3006,
},
userRead: { // 604000 ~ 604999
// 更新频道文件/媒体/聊天消息已读记录
UPDATE_CHANNEL_MUTIL_READ: userPermissionIdBase + 4000,
// 更新频道聊天消息已读记录
UPDATE_CHANNEL_CHAT_READ: userPermissionIdBase + 4001,
// 更新频道媒体消息已读记录
UPDATE_CHANNEL_MEDIA_READ: userPermissionIdBase + 4002,
// 更新频道文件消息已读记录
UPDATE_CHANNEL_FILE_READ: userPermissionIdBase + 4003,
// 新增申请消息已读记录
UPDATE_USER_FRIEND_APPLY_READ: userPermissionIdBase + 4004,
// 新增通过申请消息已读记录
UPDATE_USER_FRIEND_APPLY_PASS_READ: userPermissionIdBase + 4005,
// 新增拒绝申请消息已读记录
UPDATE_USER_FRIEND_APPLY_REJECT_READ: userPermissionIdBase + 4006,
},
userTag: { // 605000 ~ 605999
// 添加频道分组标签
ADD_CHANNEL_TAG: userPermissionIdBase + 5000,
// 添加好友分组标签
ADD_FRIEND_TAG: userPermissionIdBase + 5001,
// 添加资源库分组标签
ADD_CLOUD_TAG: userPermissionIdBase + 5002,
// 获取频道分组标签列表
GET_CHANNEL_TAG_LIST: userPermissionIdBase + 5003,
// 获取好友分组标签列表
GET_FRIEND_TAG_LIST: userPermissionIdBase + 5004,
// 获取资源库分组标签列表
GET_CLOUD_TAG_LIST: userPermissionIdBase + 5005,
// 删除标签
DELETE_TAG: userPermissionIdBase + 5006,
},
userRegister: { // 606000 ~ 606999
},
userLogin: { // 607000 ~ 607999
},
userLogout: { // 608000 ~ 608999
},
}
// 配置权限 700000 - 799999
const configPermission = {
}
addPerfix(channelPermission.channel, channelPerfix)
addPerfix(channelPermission.channelChat, channelChatPerfix)
addPerfix(channelPermission.channelUser, channelUserPerfix)
addPerfix(companyPermission.company, companyPerfix)
addPerfix(userPermission.user, userPerfix)
addPerfix(userPermission.userApply, userApplyPerfix)
addPerfix(userPermission.userFriend, userFriendPerfix)
addPerfix(userPermission.userConfig, userConfigPerfix)
addPerfix(userPermission.userRead, userReadPerfix)
addPerfix(userPermission.userRegister, userRegisterPerfix)
addPerfix(userPermission.userLogin, userLoginPerfix)
addPerfix(userPermission.userLogout, userLogoutPerfix)
addPerfix(userPermission.userTag, userTagPerfix)
module.exports = {
systemPermission,
channelPermission,
companyPermission,
userPermission,
configPermission,
systemPerfix,
channelPerfix,
channelChatPerfix,
companyPerfix,
userPerfix,
userApplyPerfix,
userFriendPerfix,
userConfigPerfix,
userReadPerfix,
userRegisterPerfix,
userLoginPerfix,
userLogoutPerfix,
userTagPerfix,
}

58
src/role/role.js Normal file
View File

@ -0,0 +1,58 @@
const {
channelPermission,
userPermission,
companyPermission,
configPermission,
} = require('./permission');
const {
userNormalPermissions,
userAdminPermissions,
} = require('./accountRole')
const {
userChannelCreatorPermissions,
userChannelAdminPermissions,
userChannelNormalPermissions,
} = require('./channelRole')
/**
* 获取所有权限
* @returns
*/
const getAllPermissionsMap = function(){
let returnPermissionMap = {};
// 频道权限
returnPermissionMap = Object.assign(returnPermissionMap, channelPermission.channel)
returnPermissionMap = Object.assign(returnPermissionMap, channelPermission.channelChat)
returnPermissionMap = Object.assign(returnPermissionMap, channelPermission.channelUser)
// 企业权限
returnPermissionMap = Object.assign(returnPermissionMap, companyPermission.company)
// 用户权限
returnPermissionMap = Object.assign(returnPermissionMap, userPermission.user)
returnPermissionMap = Object.assign(returnPermissionMap, userPermission.userFriend)
returnPermissionMap = Object.assign(returnPermissionMap, userPermission.userApply)
returnPermissionMap = Object.assign(returnPermissionMap, userPermission.userConfig)
returnPermissionMap = Object.assign(returnPermissionMap, userPermission.userRead)
returnPermissionMap = Object.assign(returnPermissionMap, userPermission.userLogin)
returnPermissionMap = Object.assign(returnPermissionMap, userPermission.userLogout)
returnPermissionMap = Object.assign(returnPermissionMap, userPermission.userRegister)
returnPermissionMap = Object.assign(returnPermissionMap, userPermission.userTag)
// 配置权限
return returnPermissionMap;
}
module.exports = {
userNormalPermissions,
userAdminPermissions,
userChannelCreatorPermissions,
userChannelAdminPermissions,
userChannelNormalPermissions,
getAllPermissionsMap
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,254 @@
const { fields } = require('../../tables/tl_channel')
const TlChannelDao = require('../../dao/tl_channel_dao')
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");
/**
* addInfo 接口
* @param {*} data
*/
const addInfo = async function({
companyId, name, type, flag = 0,
}){
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
if(!name){
tlConsoleError(TableName, "请求service参数name为空")
return {}
}
if(flag == null || flag == undefined){
tlConsoleError(TableName, "请求service参数flag为空")
return {}
}
if(!type){
tlConsoleError(TableName, "请求service参数type为空")
return {}
}
if(![
TlChannelType.GROUP,
TlChannelType.FRIEND,
].includes(type)){
tlConsoleError(TableName, "请求service参数type不合法")
return {}
}
const info = await TlChannelDao.addInfo({
[TlChannelDef.companyId]: companyId,
[TlChannelDef.name]: name,
[TlChannelDef.type]: type,
[TlChannelDef.flag]: flag,
[TlChannelDef.status]: TlChannelStatus.NORMAL,
})
if(info == null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* getInfoById 接口
* @param {*} companyId
* @param {*} id
*/
const getInfoById = async function({companyId, id}){
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
const info = await TlChannelDao.getInfo({
[TlChannelDef.companyId]: companyId,
[TlChannelDef.id]: id,
})
if(info == null){
return {}
}
return info
}
/**
* getListByIdList 接口
* @param {*} companyId
* @param {*} idList
* @param {*} fields
*/
const getListByIdList = async function({companyId, idList}, fields){
if(!idList){
tlConsoleError(TableName, "请求service参数idList为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
const list = await TlChannelDao.getList({
[TlChannelDef.companyId]: companyId,
[TlChannelDef.id]: idList
}, fields, [
[TlChannelDef.createdAt, "DESC"]
])
if(list == null){
return []
}
return list
}
/**
* getListByIdListForPage 接口
* @param {*} companyId
* @param {*} idList
* @param {*} fields
* @param {*} page
* @param {*} pageSize
*/
const getListByIdListForPage = async function({companyId, idList}, fields, page, pageSize){
if(!idList){
tlConsoleError(TableName, "请求service参数idList为空")
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 TlChannelDao.getListForPage({
[TlChannelDef.companyId]: companyId,
[TlChannelDef.id]: idList
}, fields, [
[TlChannelDef.createdAt, "DESC"]
], page, pageSize)
if(list == null){
return []
}
return list
}
/**
* updateInfoById 接口
* @param {*} companyId
* @param {*} id
* @param {*} data
*/
const updateInfoById = async function({companyId, id}, 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 TlChannelDao.updateInfo({
[TlChannelDef.companyId]: companyId,
[TlChannelDef.id]: id
}, data)
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* deleteInfoById 接口
* @param {*} companyId
* @param {*} id
*/
const deleteInfoById = async function({companyId, id}){
// 参数校验
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
const info = await TlChannelDao.deleteInfo({
[TlChannelDef.companyId]: companyId,
[TlChannelDef.id]: id
})
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
module.exports = {
addInfo,
updateInfoById,
deleteInfoById,
getInfoById,
getListByIdList,
getListByIdListForPage
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,267 @@
const { fields } = require('../../tables/tl_company')
const TlCompanyDao = require('../../dao/tl_company_dao')
const TlCompanyDef = fields.Def
const TableName = fields.Name
const TableFields = Object.keys(fields.Def).map(key => fields.Def[key])
const { tlConsoleError, tlConsole } = require("../../../src/utils/utils");
/**
* 添加角色
* @param {*} data
*/
const addInfo = async function ({
name, address, phone, email, website, logo, description, code
}) {
// 参数校验
if (!name) {
tlConsoleError(TableName, "请求service参数name为空")
return {}
}
if (!address) {
tlConsoleError(TableName, "请求service参数address为空")
return {}
}
if (!phone) {
tlConsoleError(TableName, "请求service参数phone为空")
return {}
}
if (!email) {
tlConsoleError(TableName, "请求service参数email为空")
return {}
}
if (!website) {
tlConsoleError(TableName, "请求service参数website为空")
return {}
}
if (!logo) {
tlConsoleError(TableName, "请求service参数logo为空")
return {}
}
if (!description) {
tlConsoleError(TableName, "请求service参数description为空")
return {}
}
const info = await TlCompanyDao.addInfo({
[TlCompanyDef.name]: name,
[TlCompanyDef.address]: address,
[TlCompanyDef.phone]: phone,
[TlCompanyDef.email]: email,
[TlCompanyDef.website]: website,
[TlCompanyDef.logo]: logo,
[TlCompanyDef.code]: code,
[TlCompanyDef.description]: description
});
if (info === null) {
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* 删除企业
* @param {*} id
*/
const deleteInfoById = async function ({ id }) {
// 参数校验
if (!id) {
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
const info = await TlCompanyDao.deleteInfo({
[TlCompanyDef.id]: id
});
if (info === null) {
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* 更新企业
* @param {*} data
* @param {*} id
*/
const updateInfoById = async function ({ id }, data) {
// 参数校验
if (Object.keys(data).length === 0) {
tlConsoleError(TableName, "请求service参数为空")
return {}
}
if (!id) {
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
const info = await TlCompanyDao.updateInfo({
[TlCompanyDef.id]: id
}, data);
if (info === null) {
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* 获取企业列表
* @param {*} fields
*/
const getList = async function ({ }, fields) {
const infoList = await TlCompanyDao.getList({
}, fields, [
[TlCompanyDef.createdAt, "DESC"]
]);
if (infoList === null) {
return []
}
return infoList
}
/**
* 获取企业列表
* @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 infoList = await TlCompanyDao.getListForPage({
}, fields, [
[TlCompanyDef.createdAt, "DESC"]
], page, pageSize);
if (infoList === null) {
return []
}
return infoList
}
/**
* 获取企业信息
* @param {*} id
* @param {*} fields
*/
const getInfoById = async function ({ id }, fields) {
// 参数校验
if (!id) {
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
const info = await TlCompanyDao.getInfo({
[TlCompanyDef.id]: id
}, fields)
if (info === null) {
return {}
}
return info
}
/**
* 获取企业信息
* @param {*} name
* @param {*} fields
*/
const getInfoByName = async function ({ name }, fields) {
// 参数校验
if (!name) {
tlConsoleError(TableName, "请求service参数name为空")
return {}
}
const info = await TlCompanyDao.getInfo({
[TlCompanyDef.name]: name
}, fields)
if (info === null) {
return {}
}
return info
}
/**
* 通过企业编码获取企业信息
* @param {*} code
* @param {*} fields
* @returns
*/
const getInfoByCode = async function ({ code }, fields) {
// 参数校验
if (!code) {
tlConsoleError(TableName, "请求service参数code为空")
return {}
}
const info = await TlCompanyDao.getInfo({
[TlCompanyDef.code]: code
}, fields)
if (info === null) {
return {}
}
return info
}
module.exports = {
addInfo,
deleteInfoById,
updateInfoById,
getInfoById,
getInfoByName,
getInfoByCode,
getList,
getListForPage
}

View File

@ -0,0 +1,344 @@
const { fields } = require('../../tables/tl_role')
const TlRoleDao = require('../../dao/tl_role_dao')
const TlRoleDef = fields.Def
const TlRoleType = fields.Type
const TableName = fields.Name
const TableFields = Object.keys(fields.Def).map(key => fields.Def[key])
const { tlConsoleError, tlConsole } = require("../../../src/utils/utils");
/**
* 添加角色
* @param {*} data
*/
const addInfo = async function({
companyId, name, key, permissionIdList, description, flag, type
}){
// 参数校验
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
if(!key){
tlConsoleError(TableName, "请求service参数key为空")
return {}
}
if(!name){
tlConsoleError(TableName, "请求service参数name为空")
return {}
}
if(!permissionIdList){
tlConsoleError(TableName, "请求service参数permissionIdList为空")
return {}
}
if(!description){
tlConsoleError(TableName, "请求service参数description为空")
return {}
}
if(flag === undefined || flag === null){
tlConsoleError(TableName, "请求service参数flag为空")
return {}
}
if(!type){
tlConsoleError(TableName, "请求service参数type为空")
return {}
}
if(![
TlRoleType.ADMIN_USER,
TlRoleType.NORMAL_USER,
TlRoleType.TEST_USER,
TlRoleType.CHANNEL_NORMAL_USER,
TlRoleType.CHANNEL_ADMIN_USER,
TlRoleType.CHANNEL_CREATOR_USER,
].includes(type)){
tlConsoleError(TableName, "请求service参数type不合法")
return {}
}
const exist = await TlRoleDao.getInfo({
[TlRoleDef.companyId]: companyId,
[TlRoleDef.type]: type,
[TlRoleDef.name]: name
})
if(exist !== null){
tlConsoleError(TableName, type + ' 类型下' + "角色名称已存在")
return {}
}
const info = await TlRoleDao.addInfo({
[TlRoleDef.companyId]: companyId,
[TlRoleDef.name]: name,
[TlRoleDef.type]: type,
[TlRoleDef.permissionIdList]: permissionIdList,
[TlRoleDef.key]: key,
[TlRoleDef.description]: description,
[TlRoleDef.flag]: flag
})
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* 删除角色
* @param {*} id
* @param {*} companyId
*/
const deleteInfoById = async function({companyId, id}){
// 参数校验
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
const info = await TlRoleDao.deleteInfo({
[TlRoleDef.companyId]: companyId,
[TlRoleDef.id]: id
})
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* 更新角色
* @param {*} data
* @param {*} companyId
* @param {*} id
*/
const updateInfoById = async function({companyId, id}, data){
// 参数校验
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求service参数为空")
return {}
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
const info = await TlRoleDao.updateInfo({
[TlRoleDef.companyId]: companyId,
[TlRoleDef.id]: id
}, data)
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* 获取角色列表
* @param {*} companyId
* @param {*} fields
*/
const getList = async function({companyId}, fields){
// 参数校验
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
const infoList = await TlRoleDao.getList({
[TlRoleDef.companyId]: companyId
}, fields, [
[TlRoleDef.createdAt, "DESC"]
])
if(infoList === null){
return []
}
return infoList
}
/**
* 获取角色列表
* @param {*} companyId
* @param {*} fields
* @param {*} page
* @param {*} pageSize
*/
const getListForPage = 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 infoList = await TlRoleDao.getListForPage({
[TlRoleDef.companyId]: companyId
}, fields, [
[TlRoleDef.createdAt, "DESC"]
], page, pageSize)
if(infoList === null){
return []
}
return infoList
}
/**
* 获取角色信息
* @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 TlRoleDao.getInfo({
[TlRoleDef.companyId]: companyId,
[TlRoleDef.id]: id
}, fields)
if(info === null){
return {}
}
return info
}
/**
* 通过名称获取角色信息
* @param {*} companyId
* @param {*} name
* @param {*} fields
*/
const getListByName = async function({companyId, name}, fields){
// 参数校验
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!name){
tlConsoleError(TableName, "请求service参数name为空")
return []
}
const list = await TlRoleDao.getList({
[TlRoleDef.companyId]: companyId,
[TlRoleDef.name]: name
}, fields)
if(list === null){
return []
}
return list
}
/**
* 获取角色信息
* @param {*} companyId
* @param {*} name
* @param {*} fields
*/
const getInfoByTypeAndName = async function({companyId, type, name}, fields){
// 参数校验
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
if(!name){
tlConsoleError(TableName, "请求service参数name为空")
return {}
}
if(!type){
tlConsoleError(TableName, "请求service参数type为空")
return {}
}
const info = await TlRoleDao.getInfo({
[TlRoleDef.companyId]: companyId,
[TlRoleDef.name]: name,
[TlRoleDef.type]: type
}, fields)
if(info === null){
return {}
}
return info
}
module.exports = {
addInfo,
deleteInfoById,
updateInfoById,
getInfoById,
getInfoByTypeAndName,
getList,
getListForPage,
getListByName,
}

View File

@ -0,0 +1,695 @@
const { fields } = require('../../tables/tl_user_apply')
const TlUserApplyDao = require('../../dao/tl_user_apply_dao')
const TlUserApplyDef = fields.Def
const TlUserApplyStatus = fields.Status
const TlUserApplyType = fields.Type
const TableName = fields.Name
const TableFields = Object.keys(fields.Def).map(key => fields.Def[key])
const { tlConsoleError, tlConsole } = require("../../../src/utils/utils");
/**
* addInfo 接口
* @param {*} data
*/
const addInfo = async function({
companyId, userId, targetId, type, origin, remark, status, flag = 0
}){
// 参数校验
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return {}
}
if(!targetId){
tlConsoleError(TableName, "请求service参数targetId为空")
return {}
}
if(!type){
tlConsoleError(TableName, "请求service参数type为空")
return {}
}
if(![
TlUserApplyType.FRIEND,
TlUserApplyType.GROUP,
].includes(type)){
tlConsoleError(TableName, "请求service参数type不合法")
return {}
}
if(!status){
tlConsoleError(TableName, "请求service参数status为空")
return {}
}
if(![
TlUserApplyStatus.BLACK,
TlUserApplyStatus.PASS,
TlUserApplyStatus.REJECT,
TlUserApplyStatus.WAIT,
].includes(status)){
tlConsoleError(TableName, "请求service参数status不合法")
return {}
}
if(!origin){
tlConsoleError(TableName, "请求service参数origin为空")
return {}
}
if(flag === null || flag === undefined){
tlConsoleError(TableName, "请求service参数flag为空")
return {}
}
const info = await TlUserApplyDao.addInfo({
[TlUserApplyDef.companyId]: companyId,
[TlUserApplyDef.userId]: userId,
[TlUserApplyDef.targetId]: targetId,
[TlUserApplyDef.type]: type,
[TlUserApplyDef.status]: status,
[TlUserApplyDef.origin]: origin,
[TlUserApplyDef.remark]: remark,
[TlUserApplyDef.flag]: flag
})
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* getInfoById 接口
* @param {*} companyId
* @param {*} id
* @param {*} fields
*/
const getInfoById = async function({companyId, id}, fields){
// 参数校验
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
const info = await TlUserApplyDao.getInfo({
[TlUserApplyDef.companyId]: companyId,
[TlUserApplyDef.id]: id
}, fields)
if(info === null){
return {}
}
return info
}
/**
* getInfoByUserId 接口
* @param {*} companyId
* @param {*} userId
* @param {*} fields
* @returns
*/
const getListByUserId = async function({companyId, userId}, fields){
// 参数校验
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
const list = await TlUserApplyDao.getList({
[TlUserApplyDef.companyId]: companyId,
[TlUserApplyDef.userId]: userId
}, fields, [
[TlUserApplyDef.createdAt, 'DESC']
])
if(list === null){
return []
}
return list
}
/**
* getInfoByUserId 接口
* @param {*} companyId
* @param {*} userId
* @param {*} fields
* @param {*} page
* @param {*} pageSize
* @returns
*/
const getListByUserIdForPage = async function({companyId, userId}, fields, page, pageSize){
// 参数校验
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
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 TlUserApplyDao.getListForPage({
[TlUserApplyDef.companyId]: companyId,
[TlUserApplyDef.userId]: userId
}, fields, [
[TlUserApplyDef.createdAt, 'DESC']
], page, pageSize)
if(list === null){
return []
}
return list
}
/**
* getListByUserIdAndType 接口
* @param {*} companyId
* @param {*} userId
* @param {*} type
* @param {*} fields
* @returns
*/
const getListByUserIdAndType = async function({companyId, userId, type}, fields){
// 参数校验
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!type){
tlConsoleError(TableName, "请求service参数type为空")
return []
}
const list = await TlUserApplyDao.getList({
[TlUserApplyDef.companyId]: companyId,
[TlUserApplyDef.userId]: userId,
[TlUserApplyDef.type]: type
}, fields, [
[TlUserApplyDef.createdAt, 'DESC']
])
if(list === null){
return []
}
return list
}
/**
* getListByUserIdAndType 接口
* @param {*} companyId
* @param {*} userId
* @param {*} type
* @param {*} fields
* @param {*} page
* @param {*} pageSize
* @returns
*/
const getListByUserIdAndTypeForPage = async function({companyId, userId, type}, fields, page, pageSize){
// 参数校验
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!type){
tlConsoleError(TableName, "请求service参数type为空")
return []
}
const list = await TlUserApplyDao.getList({
[TlUserApplyDef.companyId]: companyId,
[TlUserApplyDef.userId]: userId,
[TlUserApplyDef.type]: type
}, fields, [
[TlUserApplyDef.createdAt, 'DESC']
], page, pageSize)
if(list === null){
return []
}
return list
}
/**
* getListByUserIdAndTargetIdAndStatuAndType 接口
* @param {*} companyId
* @param {*} userId
* @param {*} type
* @param {*} status
* @param {*} targetId
* @param {*} fields
* @returns
*/
const getListByUserIdAndTargetIdAndStatuAndType = async function({companyId, userId, targetId, status, type}, fields){
// 参数校验
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!type){
tlConsoleError(TableName, "请求service参数type为空")
return []
}
if(!status){
tlConsoleError(TableName, "请求service参数status为空")
return []
}
if(!targetId){
tlConsoleError(TableName, "请求service参数targetId为空")
return []
}
const list = await TlUserApplyDao.getList({
[TlUserApplyDef.companyId]: companyId,
[TlUserApplyDef.userId]: userId,
[TlUserApplyDef.targetId]: targetId,
[TlUserApplyDef.status]: status,
[TlUserApplyDef.type]: type
}, fields, [
[TlUserApplyDef.createdAt, 'DESC']
])
if(list === null){
return []
}
return list
}
/**
* getListByUserIdAndTargetIdAndStatuAndTypeForPage 接口
* @param {*} companyId
* @param {*} userId
* @param {*} type
* @param {*} status
* @param {*} targetId
* @param {*} fields
* @param {*} page
* @param {*} pageSize
* @returns
*/
const getListByUserIdAndTargetIdAndStatuAndTypeForPage = async function({
companyId, userId, targetId, status, type
}, fields, page, pageSize){
// 参数校验
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!type){
tlConsoleError(TableName, "请求service参数type为空")
return []
}
if(!status){
tlConsoleError(TableName, "请求service参数status为空")
return []
}
if(!targetId){
tlConsoleError(TableName, "请求service参数targetId为空")
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 TlUserApplyDao.getListForPage({
[TlUserApplyDef.companyId]: companyId,
[TlUserApplyDef.userId]: userId,
[TlUserApplyDef.targetId]: targetId,
[TlUserApplyDef.status]: status,
[TlUserApplyDef.type]: type
}, fields, [
[TlUserApplyDef.createdAt, 'DESC']
], page, pageSize)
if(list === null){
return []
}
return list
}
/**
* getListByTargetIdAndType 接口
* @param {*} companyId
* @param {*} targetId
* @param {*} type
* @param {*} fields
* @returns
*/
const getListByTargetIdAndType = async function({companyId, targetId, type}, fields){
// 参数校验
if(!targetId){
tlConsoleError(TableName, "请求service参数targetId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
const list = await TlUserApplyDao.getList({
[TlUserApplyDef.companyId]: companyId,
[TlUserApplyDef.targetId]: targetId,
[TlUserApplyDef.type]: type
}, fields, [
[TlUserApplyDef.createdAt, 'DESC']
])
if(list === null){
return []
}
return list
}
/**
* getListByTargetIdAndTypeForPage 接口
* @param {*} companyId
* @param {*} targetId
* @param {*} type
* @param {*} fields
* @param {*} page
* @param {*} pageSize
* @returns
*/
const getListByTargetIdAndTypeForPage = async function({companyId, targetId, type}, fields, page, pageSize){
// 参数校验
if(!targetId){
tlConsoleError(TableName, "请求service参数targetId为空")
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 TlUserApplyDao.getListForPage({
[TlUserApplyDef.companyId]: companyId,
[TlUserApplyDef.targetId]: targetId,
[TlUserApplyDef.type]: type
}, fields, [
[TlUserApplyDef.createdAt, 'DESC']
], page, pageSize)
if(list === null){
return []
}
return list
}
/**
* updateInfoById 接口
* @param {*} companyId
* @param {*} id
* @param {*} data
*/
const updateInfoById = async function({companyId, id}, 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 TlUserApplyDao.updateInfo({
[TlUserApplyDef.companyId]: companyId,
[TlUserApplyDef.id]: id
}, data)
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* deleteInfoById 接口
* @param {*} companyId
* @param {*} id
*/
const deleteInfoById = async function({companyId, id}){
// 参数校验
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
const info = await TlUserApplyDao.deleteInfo({
[TlUserApplyDef.companyId]: companyId,
[TlUserApplyDef.id]: id
})
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* getListByIdList 接口
* @param {*} companyId
* @param {*} idList
* @param {*} fields
*/
const getListByIdList = async function({companyId, idList}, fields){
// 参数校验
if(!idList){
tlConsoleError(TableName, "请求service参数idList为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
const list = await TlUserApplyDao.getList({
[TlUserApplyDef.companyId]: companyId,
[TlUserApplyDef.id]: idList
}, fields, [
[TlUserApplyDef.createdAt, 'DESC']
])
if(list === null){
return []
}
return list
}
/**
* getListByIdListForPage 接口
* @param {*} companyId
* @param {*} idList
* @param {*} fields
* @param {*} page
* @param {*} pageSize
*/
const getListByIdListForPage = async function({companyId, idList}, fields, page, pageSize){
// 参数校验
if(!idList){
tlConsoleError(TableName, "请求service参数idList为空")
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 TlUserApplyDao.getListForPage({
[TlUserApplyDef.companyId]: companyId,
[TlUserApplyDef.id]: idList
}, fields, [
[TlUserApplyDef.createdAt, 'DESC']
], page, pageSize)
if(list === null){
return []
}
return list
}
module.exports = {
addInfo,
updateInfoById,
deleteInfoById,
getInfoById,
getListByIdList,
getListByIdListForPage,
getListByUserId,
getListByUserIdForPage,
getListByTargetIdAndType,
getListByTargetIdAndTypeForPage,
getListByUserIdAndType,
getListByUserIdAndTypeForPage,
getListByUserIdAndTargetIdAndStatuAndType,
getListByUserIdAndTargetIdAndStatuAndTypeForPage
}

View File

@ -0,0 +1,332 @@
const { Op } = require('sequelize')
const moment = require('moment')
const { fields } = require('../../tables/tl_user_auth')
const TlUserAuthDao = require('../../dao/tl_user_auth_dao')
const TlUserAuthDef = fields.Def
const TlUserAuthType = fields.Type
const TableName = fields.Name
const TableFields = Object.keys(fields.Def).map(key => fields.Def[key])
const { tlConsoleError, tlConsole } = require("../../utils/utils");
/**
* addInfo 接口
* @param {*} data
*/
const addInfo = async function({
key, type, code
}){
// 参数校验
if(!key){
tlConsoleError(TableName, "请求service参数key为空")
return {}
}
if(!type){
tlConsoleError(TableName, "请求service参数type为空")
return {}
}
if(![
TlUserAuthType.EMAIL_REGISTER_CODE,
TlUserAuthType.PHONE_LOGIN_CODE,
TlUserAuthType.PHONE_REGISTER_CODE,
].includes(type)){
tlConsoleError(TableName, "请求service参数type不合法")
return {}
}
if(!code){
tlConsoleError(TableName, "请求service参数code为空")
return {}
}
const info = await TlUserAuthDao.addInfo({
[TlUserAuthDef.key]: key,
[TlUserAuthDef.type]: type,
[TlUserAuthDef.code]: code
})
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* getInfoById 接口
* @param {*} id
* @param {*} fields
*/
const getInfoById = async function({id}, fields){
// 参数校验
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
const info = await TlUserAuthDao.getInfo({
[TlUserAuthDef.id]: id
}, fields)
if(info === null){
return {}
}
return info
}
/**
* updateInfoById 接口
* @param {*} id
* @param {*} data
*/
const updateInfoById = async function({id}, data){
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求service参数为空")
return {}
}
// 参数校验
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
const info = await TlUserAuthDao.updateInfo({
[TlUserAuthDef.id]: id
}, data)
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* deleteInfoById 接口
* @param {*} id
*/
const deleteInfoById = async function({id}){
// 参数校验
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
const info = await TlUserAuthDao.deleteInfo({
[TlUserAuthDef.id]: id
})
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* getListByIdList 接口
* @param {*} idList
* @param {*} fields
*/
const getListByIdList = async function({idList}, fields){
// 参数校验
if(!idList){
tlConsoleError(TableName, "请求service参数idList为空")
return []
}
const list = await TlUserAuthDao.getList({
[TlUserAuthDef.id]: idList
}, fields, [
[TlUserAuthDef.createdAt, 'DESC']
])
if(list === null){
return []
}
return list
}
/**
* getListByIdListForPage 接口
* @param {*} idList
* @param {*} fields
* @param {*} page
* @param {*} pageSize
*/
const getListByIdListForPage = async function({idList}, fields, page, pageSize){
// 参数校验
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 []
}
if(pageSize > 1000){
tlConsoleError(TableName, "请求service参数pageSize过大")
return []
}
const list = await TlUserAuthDao.getListForPage({
[TlUserAuthDef.id]: idList
}, fields, [
[TlUserAuthDef.createdAt, 'DESC']
], page, pageSize)
if(list === null){
return []
}
return list
}
/**
* getCountByKey 接口
* @param {*} key
*/
const getCountByKey = async function({key}){
// 参数校验
if(!key){
tlConsoleError(TableName, "请求service参数key为空")
return 0
}
const count = await TlUserAuthDao.getCount({
[TlUserAuthDef.key]: key
})
if(count === null){
return 0
}
return count
}
/**
* getDayCountByType 接口
* @param {*} type
*/
const getDayCountByType = async function({type}){
// 参数校验
if(!type){
tlConsoleError(TableName, "请求service参数type为空")
return 0
}
const count = await TlUserAuthDao.getCount({
[TlUserAuthDef.type]: type,
[TlUserAuthDef.createdAt]: {
[Op.gte]: moment().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
[Op.lte]: moment().endOf('day').format('YYYY-MM-DD HH:mm:ss')
}
})
if(count === null){
return 0
}
return count
}
/**
* getCountByTypeAndKey 接口
* @param {*} type
* @param {*} key
*/
const getCountByTypeAndKey = async function({type, key}){
// 参数校验
if(!type){
tlConsoleError(TableName, "请求service参数type为空")
return 0
}
if(!key){
tlConsoleError(TableName, "请求service参数key为空")
return 0
}
const count = await TlUserAuthDao.getCount({
[TlUserAuthDef.type]: type,
[TlUserAuthDef.key]: key
})
if(count === null){
return 0
}
return count
}
/**
* getDayCountByTypeAndKey 接口
* @param {*} type
* @param {*} key
*/
const getDayCountByTypeAndKey = async function({type, key}){
// 参数校验
if(!type){
tlConsoleError(TableName, "请求service参数type为空")
return 0
}
if(!key){
tlConsoleError(TableName, "请求service参数key为空")
return 0
}
const count = await TlUserAuthDao.getCount({
[TlUserAuthDef.type]: type,
[TlUserAuthDef.key]: key,
[TlUserAuthDef.createdAt]: {
[Op.gte]: moment().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
[Op.lte]: moment().endOf('day').format('YYYY-MM-DD HH:mm:ss')
}
})
if(count === null){
return 0
}
return count
}
module.exports = {
addInfo,
updateInfoById,
deleteInfoById,
getInfoById,
getCountByKey,
getCountByTypeAndKey,
getDayCountByTypeAndKey,
getDayCountByType,
getListByIdList,
getListByIdListForPage
}

View File

@ -0,0 +1,373 @@
const { fields } = require('../../tables/tl_user_config')
const TlUserConfigDao = require('../../dao/tl_user_config_dao')
const TlUserConfigDef = fields.Def
const TableName = fields.Name
const TableFields = Object.keys(fields.Def).map(key => fields.Def[key])
const { tlConsoleError, tlConsole } = require("../../../src/utils/utils");
/**
* 添加用户配置
* @param {*} data
*/
const addInfo = async function({
companyId, userId, normal, account, message, skin, authority, other,
}){
// 参数校验
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return {}
}
if(!normal){
tlConsoleError(TableName, "请求service参数normal为空")
return {}
}
if(!account){
tlConsoleError(TableName, "请求service参数account为空")
return {}
}
if(!message){
tlConsoleError(TableName, "请求service参数message为空")
return {}
}
if(!skin){
tlConsoleError(TableName, "请求service参数skin为空")
return {}
}
if(!authority){
tlConsoleError(TableName, "请求service参数authority为空")
return {}
}
if(!other){
tlConsoleError(TableName, "请求service参数other为空")
return {}
}
const exist = await TlUserConfigDao.getInfo({
[TlUserConfigDef.companyId]: companyId,
[TlUserConfigDef.userId]: userId
})
if(exist !== null){
tlConsoleError(TableName, "用户配置已存在")
return {}
}
const info = await TlUserConfigDao.addInfo({
[TlUserConfigDef.companyId]: companyId,
[TlUserConfigDef.userId]: userId,
[TlUserConfigDef.normal]: normal,
[TlUserConfigDef.account]: account,
[TlUserConfigDef.message]: message,
[TlUserConfigDef.skin]: skin,
[TlUserConfigDef.authority]: authority,
[TlUserConfigDef.other]: other
})
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* 添加默认用户配置
* @param {*} companyId
* @param {*} userId
*/
const addDefaultInfo = async function({companyId, userId}){
return await addInfo({
companyId: companyId,
userId: userId,
normal: JSON.stringify({
windowSizeDefault: false,
windowSizeFull: false,
fontSize: '小',
sidebarChannelOpen: true,
sidebarContactOpen: true,
sidebarCloudOpen: true,
sidebarSettingOpen: true,
sidebarMeetingOpen: true,
sidebarP2pChannelOpen: true,
sidebarCutPasteOpen: true,
sidebarDatesOpen: true,
sidebarDocumentOpen: true,
homePage: 'channel',
}),
account: JSON.stringify({
allowLoginMore: false,
loginRemoteNotify: false,
notAcceptFriendApply: false,
autoPassFriendApply: false,
fileSaveToServer: true,
fileSaveToAlyOss: false,
fileSaveToTxOss: true,
}),
message: JSON.stringify({
webNotify: false,
messageDot: true,
friendMessageSound: false,
friendMessageVibrate: false,
friendMessagePreview: false,
friendCallSound: false,
friendCallVibrate: false,
groupMessageSound: false,
groupMessageVibrate: false,
groupMessagePreview: false,
groupCallSound: false,
groupCallVibrate: false,
}),
skin: JSON.stringify({
global: 'light',
}),
authority: JSON.stringify({
acceptFriendAudioInvite: false,
acceptFriendVideoInvite: false,
acceptFriendScreenInvite: false,
acceptFriendInviteGroup: false
}),
other: JSON.stringify({
// 我的文件视图模式
cloudSelfViewMode: 'list',
// 我的收藏视图模式
cloudCollectionViewMode: 'list',
// 我的回收小站视图模式
cloudRecycleViewMode: 'list',
// 群聊文件视图模式
cloudGroupViewMode: 'list',
// 中继服务器
turnServer: true,
// 自定义wss
customWss: '',
})
})
}
/**
* 删除用户配置
* @param {*} id
* @param {*} companyId
*/
const deleteInfoById = async function({companyId, id}){
// 参数校验
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
const info = await TlUserConfigDao.deleteInfo({
[TlUserConfigDef.companyId]: companyId,
[TlUserConfigDef.id]: id
})
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* 更新用户配置
* @param {*} data
* @param {*} companyId
* @param {*} id
*/
const updateInfoById = async function({companyId, id}, data){
// 参数校验
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求service参数为空")
return {}
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
const info = await TlUserConfigDao.updateInfo({
[TlUserConfigDef.companyId]: companyId,
[TlUserConfigDef.id]: id
}, data)
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* 获取用户配置列表
* @param {*} companyId
* @param {*} fields
*/
const getList = async function({companyId}, fields){
// 参数校验
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
const infoList = await TlUserConfigDao.getList({
[TlUserConfigDef.companyId]: companyId
}, fields, [
[TlUserConfigDef.createdAt, 'DESC']
])
if(infoList === null){
return []
}
return infoList
}
/**
* 获取用户配置列表
* @param {*} companyId
* @param {*} fields
* @param {*} page
* @param {*} pageSize
*/
const getListForPage = 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 infoList = await TlUserConfigDao.getListForPage({
[TlUserConfigDef.companyId]: companyId
}, fields, [
[TlUserConfigDef.createdAt, 'DESC']
], page, pageSize)
if(infoList === null){
return []
}
return infoList
}
/**
* 获取用户配置信息
* @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 TlUserConfigDao.getInfo({
[TlUserConfigDef.companyId]: companyId,
[TlUserConfigDef.id]: id
}, fields)
if(info === null){
return {}
}
return info
}
/**
* 获取用户配置信息
* @param {*} companyId
* @param {*} userId
* @param {*} fields
*/
const getInfoByUserId = async function({companyId, userId}, fields){
// 参数校验
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return {}
}
const info = await TlUserConfigDao.getInfo({
[TlUserConfigDef.companyId]: companyId,
[TlUserConfigDef.userId]: userId
}, fields)
if(info === null){
return {}
}
return info
}
module.exports = {
addInfo,
deleteInfoById,
updateInfoById,
getInfoById,
getInfoByUserId,
addDefaultInfo,
getList,
getListForPage
}

View File

@ -0,0 +1,381 @@
const { Op } = require('sequelize')
const moment = require('moment')
const { fields } = require('../../tables/tl_user_finger_print')
const TlUserFingerPrintDao = require('../../dao/tl_user_finger_print_dao')
const TlUserFingerPrintDef = fields.Def
const TableName = fields.Name
const TableFields = Object.keys(fields.Def).map(key => fields.Def[key])
const { tlConsoleError, tlConsole } = require("../../utils/utils");
/**
* addInfo 接口
* @param {*} data
*/
const addInfo = async function({
userId, fingerPrint
}){
// 参数校验
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return {}
}
if(!fingerPrint){
tlConsoleError(TableName, "请求service参数fingerPrint为空")
return {}
}
const info = await TlUserFingerPrintDao.addInfo({
[TlUserFingerPrintDef.user_id]: userId,
[TlUserFingerPrintDef.finger_print]: fingerPrint,
})
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* addInfoList 接口
* @param {*} userId
* @param {*} dataList
*/
const addInfoList = async function({
userId, dataList
}){
// 参数校验
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return {}
}
if(!dataList){
tlConsoleError(TableName, "请求service参数dataList为空")
return {}
}
let addDataList = []
for(let i = 0; i < dataList.length; i++){
const fingerPrint = dataList[i]
if(!fingerPrint){
tlConsoleError(TableName, "请求service参数fingerPrint为空")
return {}
}
addDataList.push({
[TlUserFingerPrintDef.user_id]: userId,
[TlUserFingerPrintDef.finger_print]: fingerPrint,
})
}
const list = await TlUserFingerPrintDao.addList(addDataList)
if(list === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return list
}
/**
* getInfoById 接口
* @param {*} id
* @param {*} fields
*/
const getInfoById = async function({id}, fields){
// 参数校验
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
const info = await TlUserFingerPrintDao.getInfo({
[TlUserFingerPrintDef.id]: id
}, fields)
if(info === null){
return {}
}
return info
}
/**
* updateInfoById 接口
* @param {*} id
* @param {*} data
*/
const updateInfoById = async function({id}, data){
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求service参数为空")
return {}
}
// 参数校验
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
const info = await TlUserFingerPrintDao.updateInfo({
[TlUserFingerPrintDef.id]: id
}, data)
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* deleteInfoById 接口
* @param {*} id
*/
const deleteInfoById = async function({id}){
// 参数校验
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
const info = await TlUserFingerPrintDao.deleteInfo({
[TlUserFingerPrintDef.id]: id
})
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* getInfoByUserIdAndFingerPrint 接口
* @param {*} userId
* @param {*} fingerPrint
* @param {*} fields
*/
const getInfoByUserIdAndFingerPrint = async function({fingerPrint, userId}, fields){
// 参数校验
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return {}
}
if(!fingerPrint){
tlConsoleError(TableName, "请求service参数fingerPrint为空")
return {}
}
const info = await TlUserFingerPrintDao.getInfo({
[TlUserFingerPrintDef.finger_print]: fingerPrint,
[TlUserFingerPrintDef.user_id]: userId
}, fields, [
[TlUserFingerPrintDef.createdAt, 'DESC']
])
if(info === null){
return {}
}
return info
}
/**
* getListByUserId 接口
* @param {*} userId
* @param {*} fields
*/
const getListByUserId = async function({userId}, fields){
// 参数校验
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return []
}
const list = await TlUserFingerPrintDao.getList({
[TlUserFingerPrintDef.user_id]: userId
}, fields, [
[TlUserFingerPrintDef.createdAt, 'DESC']
])
if(list === null){
return []
}
return list
}
/**
* getListByUserIdForPage 接口
* @param {*} userId
* @param {*} fields
* @param {*} page
* @param {*} pageSize
*/
const getListByUserIdForPage = async function({userId}, fields, page, pageSize){
// 参数校验
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
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 TlUserFingerPrintDao.getListForPage({
[TlUserFingerPrintDef.user_id]: userId
}, fields, [
[TlUserFingerPrintDef.createdAt, 'DESC']
], page, pageSize)
if(list === null){
return []
}
return list
}
/**
* getListByIdList 接口
* @param {*} idList
* @param {*} fields
*/
const getListByIdList = async function({idList}, fields){
// 参数校验
if(!idList){
tlConsoleError(TableName, "请求service参数idList为空")
return []
}
const list = await TlUserFingerPrintDao.getList({
[TlUserFingerPrintDef.id]: idList
}, fields, [
[TlUserFingerPrintDef.createdAt, 'DESC']
])
if(list === null){
return []
}
return list
}
/**
* getListByIdListForPage 接口
* @param {*} idList
* @param {*} fields
* @param {*} page
* @param {*} pageSize
*/
const getListByIdListForPage = async function({idList}, fields, page, pageSize){
// 参数校验
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 []
}
if(pageSize > 1000){
tlConsoleError(TableName, "请求service参数pageSize过大")
return []
}
const list = await TlUserFingerPrintDao.getListForPage({
[TlUserFingerPrintDef.id]: idList
}, fields, [
[TlUserFingerPrintDef.createdAt, 'DESC']
], page, pageSize)
if(list === null){
return []
}
return list
}
/**
* getCountByFingerPrint 接口
* @param {*} fingerPrint
*/
const getCountByFingerPrint = async function({fingerPrint}){
// 参数校验
if(!fingerPrint){
tlConsoleError(TableName, "请求service参数fingerPrint为空")
return 0
}
const count = await TlUserFingerPrintDao.getCount({
[TlUserFingerPrintDef.finger_print]: fingerPrint
})
if(count === null){
return 0
}
return count
}
module.exports = {
addInfo,
addInfoList,
updateInfoById,
deleteInfoById,
getInfoById,
getInfoByUserIdAndFingerPrint,
getCountByFingerPrint,
getListByIdList,
getListByIdListForPage,
getListByUserId,
getListByUserIdForPage
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,677 @@
const { fields } = require('../../tables/tl_user_read')
const TlUserReadDao = require('../../dao/tl_user_read_dao')
const TlUserReadDef = fields.Def
const TlUserReadType = fields.Type
const TableName = fields.Name
const TableFields = Object.keys(fields.Def).map(key => fields.Def[key])
const { tlConsoleError, tlConsole } = require("../../../src/utils/utils");
/**
* addInfo 接口
* @param {*} data
*/
const addInfo = async function({
companyId, channelId, userId, type, latestReadId, recordId
}){
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return {}
}
if(!type){
tlConsoleError(TableName, "请求service参数type为空")
return {}
}
if(![
TlUserReadType.CHAT,
TlUserReadType.MEDIA,
TlUserReadType.FILE,
TlUserReadType.FRIEND_APPLY,
TlUserReadType.FRIEND_APPLY_PASS,
TlUserReadType.FRIEND_APPLY_REJECT,
].includes(type)){
tlConsoleError(TableName, "请求service参数type不合法")
return {}
}
if([
TlUserReadType.CHAT,
TlUserReadType.MEDIA,
TlUserReadType.FILE,
].includes[type]){
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return {}
}
if(!latestReadId){
tlConsoleError(TableName, "请求service参数latestChatId为空")
return {}
}
}
if([
TlUserReadType.FRIEND_APPLY,
TlUserReadType.FRIEND_APPLY_PASS,
TlUserReadType.FRIEND_APPLY_REJECT,
].includes[type]){
if(!recordId){
tlConsoleError(TableName, "请求service参数recordId为空")
return {}
}
}
if(!recordId){
recordId = 0
}
if(!latestReadId) {
latestReadId = 0
}
if(!channelId){
channelId = 0
}
const info = await TlUserReadDao.addInfo({
[TlUserReadDef.companyId] : companyId,
[TlUserReadDef.channelId] : channelId,
[TlUserReadDef.userId] : userId,
[TlUserReadDef.type] : type,
[TlUserReadDef.latestReadId] : latestReadId,
[TlUserReadDef.recordId] : recordId,
})
if(info == null){
tlConsoleError(TableName, "请求service参数为空")
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 TlUserReadDao.getInfo({
[TlUserReadDef.companyId] : companyId,
[TlUserReadDef.id] : id,
}, fields)
if(info == null){
return {}
}
return info
}
/**
* getListByUserId 接口
* @param {*} companyId
* @param {*} userId
* @param {*} fields
*/
const getListByUserId = async function({companyId, userId}, fields){
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
const list = await TlUserReadDao.getList({
[TlUserReadDef.companyId]: companyId,
[TlUserReadDef.userId]: userId,
}, fields, [
[TlUserReadDef.createdAt, "DESC"]
])
if(list == null){
return []
}
return list
}
/**
* getListByUserIdForPage 接口
* @param {*} companyId
* @param {*} userId
* @param {*} fields
* @param {*} page
* @param {*} pageSize
*/
const getListByUserIdForPage = async function({companyId, userId}, fields, page, pageSize){
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
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 TlUserReadDao.getListForPage({
[TlUserReadDef.companyId]: companyId,
[TlUserReadDef.userId]: userId,
}, fields, [
[TlUserReadDef.createdAt, "DESC"]
], page, pageSize)
if(list == null){
return []
}
return list
}
/**
* getListByUserIdTypeList 接口
* @param {*} companyId
* @param {*} userId
* @param {*} typeList
* @param {*} fields
*/
const getListByUserIdTypeList = async function({companyId, userId, typeList}, fields){
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!typeList){
tlConsoleError(TableName, "请求service参数typeList为空")
return []
}
const list = await TlUserReadDao.getList({
[TlUserReadDef.companyId]: companyId,
[TlUserReadDef.userId]: userId,
[TlUserReadDef.type]: typeList,
}, fields, [
[TlUserReadDef.createdAt, "DESC"]
])
if(list == null){
return []
}
return list
}
/**
* getListByUserIdTypeListForPage 接口
* @param {*} companyId
* @param {*} userId
* @param {*} typeList
* @param {*} fields
* @param {*} page
* @param {*} pageSize
*/
const getListByUserIdTypeListForPage = async function({companyId, userId, typeList}, fields, page, pageSize){
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!typeList){
tlConsoleError(TableName, "请求service参数typeList为空")
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 TlUserReadDao.getListForPage({
[TlUserReadDef.companyId]: companyId,
[TlUserReadDef.userId]: userId,
[TlUserReadDef.type]: typeList,
}, fields, [
[TlUserReadDef.createdAt, "DESC"]
], page, pageSize)
if(list == null){
return []
}
return list
}
/**
* 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 TlUserReadDao.getList({
[TlUserReadDef.companyId]: companyId,
[TlUserReadDef.channelId]: channelId,
}, fields, [
[TlUserReadDef.createdAt, "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 TlUserReadDao.getListForPage({
[TlUserReadDef.companyId]: companyId,
[TlUserReadDef.channelId]: channelId,
}, fields, [
[TlUserReadDef.createdAt, "DESC"]
], page, pageSize)
if(list == null){
return []
}
return list
}
/**
* getListByChannelUserId 接口
* @param {*} companyId
* @param {*} channelId
* @param {*} userId
* @param {*} fields
*/
const getListByChannelUserId = async function({companyId, channelId, userId}, fields){
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return []
}
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
const list = await TlUserReadDao.getList({
[TlUserReadDef.companyId]: companyId,
[TlUserReadDef.channelId]: channelId,
[TlUserReadDef.userId]: userId,
}, fields, [
[TlUserReadDef.createdAt, "DESC"]
])
if(list == null){
return []
}
return list
}
/**
* getListByChannelUserIdForPage 接口
* @param {*} companyId
* @param {*} channelId
* @param {*} userId
* @param {*} fields
* @param {*} page
* @param {*} pageSize
*/
const getListByChannelUserIdForPage = async function({companyId, channelId, userId}, fields, page, pageSize){
if(!channelId){
tlConsoleError(TableName, "请求service参数channelId为空")
return []
}
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
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 TlUserReadDao.getListForPage({
[TlUserReadDef.companyId]: companyId,
[TlUserReadDef.channelId]: channelId,
[TlUserReadDef.userId]: userId,
}, fields, [
[TlUserReadDef.createdAt, "DESC"]
], page, pageSize)
if(list == null){
return []
}
return list
}
/**
* updateInfoById 接口
* @param {*} companyId
* @param {*} id
* @param {*} data
*/
const updateInfoById = async function({companyId, id}, data){
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求service参数data为空")
return {}
}
const info = await TlUserReadDao.updateInfo({
[TlUserReadDef.companyId]: companyId,
[TlUserReadDef.id]: id,
}, data)
if(info == null){
return {}
}
return info
}
/**
* updateInfoByUserId 接口
* @param {*} companyId
* @param {*} userId
* @param {*} data
*/
const updateInfoByUserId = async function({companyId, userId}, data){
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return {}
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
if(Object.keys(data).length === 0){
tlConsoleError(TableName, "请求service参数data为空")
return {}
}
const info = await TlUserReadDao.updateInfo({
[TlUserReadDef.companyId]: companyId,
[TlUserReadDef.userId]: userId,
}, data)
if(info == null){
return {}
}
return info
}
/**
* deleteInfoById 接口
* @param {*} companyId
* @param {*} id
*/
const deleteInfoById = async function({companyId, id}){
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
const info = await TlUserReadDao.deleteInfo({
[TlUserReadDef.companyId]: companyId,
[TlUserReadDef.id]: id,
})
if(info == null){
return {}
}
return info
}
/**
* getListByUserIdTypeListAndChannelIdList 接口
* @param {*} companyId
* @param {*} userId
* @param {*} typeList
* @param {*} channelIdList
* @param {*} fields
*/
const getListByUserIdTypeListAndChannelIdList = async function({companyId, userId, typeList, channelIdList}, fields){
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!typeList){
tlConsoleError(TableName, "请求service参数typeList为空")
return []
}
if(!channelIdList){
tlConsoleError(TableName, "请求service参数channelIdList为空")
return []
}
if(channelIdList.length === 0){
tlConsoleError(TableName, "请求service参数channelIdList为空")
return []
}
const list = await TlUserReadDao.getList({
[TlUserReadDef.companyId]: companyId,
[TlUserReadDef.userId]: userId,
[TlUserReadDef.type]: typeList,
[TlUserReadDef.channelId]: channelIdList,
}, fields, [
[TlUserReadDef.createdAt, "DESC"]
])
if(list == null){
return []
}
return list
}
module.exports = {
addInfo,
getInfoById,
updateInfoById,
updateInfoByUserId,
deleteInfoById,
getListByUserId,
getListByUserIdForPage,
getListByChannelId,
getListByChannelIdForPage,
getListByChannelUserId,
getListByChannelUserIdForPage,
getListByUserIdTypeList,
getListByUserIdTypeListForPage,
getListByUserIdTypeListAndChannelIdList,
}

View File

@ -0,0 +1,466 @@
const { fields } = require('../../tables/tl_user')
const TlUserDao = require('../../dao/tl_user_dao')
const TlUserDef = fields.Def
const TableName = fields.Name
const TableFields = Object.keys(fields.Def).map(key => fields.Def[key])
const { tlConsoleError, tlConsole } = require("../../../src/utils/utils");
const { get } = require('request')
/**
* addInfo 接口
* @param {*} data
*/
const addInfo = async function({
companyId, name, password, roleId, salt, mobile, email, avatarUrl,
wchatName, wchatOpenId, wchatUnionId, wchatAvatarUrl, flag,
}){
// 参数校验
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
if(!name){
tlConsoleError(TableName, "请求service参数name为空")
return {}
}
if(!password){
tlConsoleError(TableName, "请求service参数password为空")
return {}
}
if(!roleId){
tlConsoleError(TableName, "请求service参数roleId为空")
return {}
}
if(!salt){
tlConsoleError(TableName, "请求service参数salt为空")
return {}
}
if(!mobile){
mobile = ""
}
if(!email){
email = ""
}
if(!avatarUrl){
avatarUrl = ""
}
if(!wchatName){
wchatName = ""
}
if(!wchatOpenId){
wchatOpenId = ""
}
if(!wchatUnionId){
wchatUnionId = ""
}
if(!wchatAvatarUrl){
wchatAvatarUrl = ""
}
if(!flag){
flag = 0
}
const info = await TlUserDao.addInfo({
[TlUserDef.companyId]: companyId,
[TlUserDef.name]: name,
[TlUserDef.password]: password,
[TlUserDef.roleId]: roleId,
[TlUserDef.salt]: salt,
[TlUserDef.mobile]: mobile,
[TlUserDef.email]: email,
[TlUserDef.avatarUrl]: avatarUrl,
[TlUserDef.wchatName]: wchatName,
[TlUserDef.wchatOpenId]: wchatOpenId,
[TlUserDef.wchatUnionId]: wchatUnionId,
[TlUserDef.wchatAvatarUrl]: wchatAvatarUrl,
[TlUserDef.flag]: flag,
})
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* getInfoById 接口
* @param {*} companyId
* @param {*} id
* @param {*} fields
* @returns
*/
const getInfoById = async function({companyId, id}, fields){
// 参数校验
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
const info = await TlUserDao.getInfo({
[TlUserDef.companyId]: companyId,
[TlUserDef.id]: id
}, fields)
if(info === null){
return {}
}
return info
}
/**
* getInfoByName 接口
* @param {*} name
* @param {*} companyId
* @param {*} fields
* @returns
*/
const getInfoByName = async function({companyId, name}, fields){
// 参数校验
if(!name){
tlConsoleError(TableName, "请求service参数name为空")
return {}
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
const info = await TlUserDao.getInfo({
[TlUserDef.companyId]: companyId,
[TlUserDef.name]: name
}, fields)
if(info === null){
return {}
}
return info
}
/**
* getInfoByNameForLogin 接口
* @param {*} name
* @param {*} fields
* @returns
*/
const getInfoByNameForLogin = async function({name}, fields){
// 参数校验
if(!name){
tlConsoleError(TableName, "请求service参数name为空")
return {}
}
const info = await TlUserDao.getInfo({
[TlUserDef.name]: name
}, fields)
if(info === null){
return {}
}
return info
}
/**
* getInfoByMobile 接口
* @param {*} mobile
* @param {*} companyId
* @param {*} fields
* @returns
*/
const getInfoByMobile = async function({companyId, mobile}, fields){
// 参数校验
if(!mobile){
tlConsoleError(TableName, "请求service参数mobile为空")
return {}
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
const info = await TlUserDao.getInfo({
[TlUserDef.companyId]: companyId,
[TlUserDef.mobile]: mobile
}, fields)
if(info === null){
return {}
}
return info
}
/**
* getInfoByMobileForLogin 接口
* @param {*} mobile
* @param {*} fields
* @returns
*/
const getInfoByMobileForLogin = async function({mobile}, fields){
// 参数校验
if(!mobile){
tlConsoleError(TableName, "请求service参数mobile为空")
return {}
}
const info = await TlUserDao.getInfo({
[TlUserDef.mobile]: mobile
}, fields)
if(info === null){
return {}
}
return info
}
/**
* getInfoByEmail 接口
* @param {*} email
* @param {*} companyId
* @param {*} fields
* @returns
*/
const getInfoByEmail = async function({companyId, email}, fields){
// 参数校验
if(!email){
tlConsoleError(TableName, "请求service参数email为空")
return {}
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
const info = await TlUserDao.getInfo({
[TlUserDef.companyId]: companyId,
[TlUserDef.email]: email
}, fields)
if(info === null){
return {}
}
return info
}
/**
* getInfoByEmailForLogin 接口
* @param {*} email
* @param {*} fields
* @returns
*/
const getInfoByEmailForLogin = async function({email}, fields){
// 参数校验
if(!email){
tlConsoleError(TableName, "请求service参数email为空")
return {}
}
const info = await TlUserDao.getInfo({
[TlUserDef.email]: email
}, fields)
if(info === null){
return {}
}
return info
}
/**
* updateInfoById 接口
* @param {*} companyId
* @param {*} id
* @param {*} data
*/
const updateInfoById = async function({companyId, id}, 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 TlUserDao.updateInfo({
[TlUserDef.companyId]: companyId,
[TlUserDef.id]: id
}, data)
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* deleteInfoById 接口
* @param {*} companyId
* @param {*} id
*/
const deleteInfoById = async function({companyId, id}){
// 参数校验
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
const info = await TlUserDao.deleteInfo({
[TlUserDef.companyId]: companyId,
[TlUserDef.id]: id
})
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* getListByIdList 接口
* @param {*} companyId
* @param {*} idList
* @param {*} fields
*/
const getListByIdList = async function({companyId, idList}, fields){
// 参数校验
if(!idList){
tlConsoleError(TableName, "请求service参数idList为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
const list = await TlUserDao.getList({
[TlUserDef.companyId]: companyId,
[TlUserDef.id]: idList
}, fields, [
[TlUserDef.createdAt, "DESC"]
])
if(list === null){
return []
}
return list
}
/**
* getListByIdListForPage 接口
* @param {*} companyId
* @param {*} idList
* @param {*} fields
* @param {*} page
* @param {*} pageSize
*/
const getListByIdListForPage = async function({companyId, idList}, fields, page, pageSize){
// 参数校验
if(!idList){
tlConsoleError(TableName, "请求service参数idList为空")
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 TlUserDao.getListForPage({
[TlUserDef.companyId]: companyId,
[TlUserDef.id]: idList
}, fields, [
[TlUserDef.createdAt, "DESC"]
], page, pageSize)
if(list === null){
return []
}
return list
}
module.exports = {
addInfo,
updateInfoById,
deleteInfoById,
getInfoByName,
getInfoById,
getInfoByMobile,
getInfoByEmail,
getInfoByNameForLogin,
getInfoByMobileForLogin,
getInfoByEmailForLogin,
getListByIdList,
getListByIdListForPage
}

View File

@ -0,0 +1,223 @@
const {
tlResponseArgsError, tlResponseForbidden, tlResponseSvrError,
tlResponseTimeout, tlResponseNotFound, tlResponseSuccess,
tlConsole, tlConsoleError
} = require('../../utils/utils')
const uuid = require('uuid')
const cache = require('../../utils/cache/cache')
const {
USER_KEYS
} = require('../../utils/cache/cache_key')
/**
* 通过token获取用户信息
* @param {*} token
*/
const getUserInfoByToken = async function({token}){
if(!token){
return {}
}
let info = await cache.getLoginInfo({token})
if(!info){
return {}
}
try{
info = JSON.parse(info)
}catch(e){
tlConsoleError(e)
info = null
}
return info
}
/**
* 通过token设置用户信息
* @param {*} token
* @param {*} info
* @param {*} isLogin
* @param {*} isWebsite
*/
const setUserInfoByToken = async function({
token, info, isLogin = true, isWebsite = false
}){
if(!token){
return {}
}
let jsonInfo = null;
try{
jsonInfo = JSON.stringify(info)
}catch(e){
tlConsoleError(e)
}
if(!jsonInfo){
return false
}
let loginUserId = info.loginUserId
if(isLogin){
// 设置userId在线状态
await cache.setLoginStatus({
userId: loginUserId,
status: 1,
isWebsite
})
// 设置token登录态
return await cache.setLoginInfo({
token, loginInfo: jsonInfo, isWebsite
})
}else{
// 设置userId在线状态
await cache.setLoginStatus({
userId: loginUserId,
status: 0,
isWebsite
})
// 设置token登录态
return await cache.setLoginInfo({
token, loginInfo: '', isWebsite
})
}
}
/**
* 通过userIdList获取登录状态
* @param {*} userIdList
*/
const getUserLoginStatusByIdList = async function({userIdList}){
if(!userIdList || userIdList.length === 0){
return {}
}
let statusMap = {}
let resultList = await cache.getLoginStatusList({userIdList})
resultList.forEach((status, index) => {
if(parseInt(status) === 1){
status = 1
}else{
status = 0
}
statusMap[parseInt(userIdList[index])] = status
})
return statusMap
}
/**
* 设置登录用户频道权限
* @param {*} userId
* @param {*} channelRoleMap
* @returns
*/
const setUserChannelRoleMap = async function({userId, channelRoleMap}){
return await cache.setUserChannelRoleMap({userId, channelRoleMap})
}
/**
* 更新登录用户频道权限
* @param {*} userId
* @param {*} channelRoleMap
*/
const updateUserChannelRoleMap = async function({userId, channelRoleMap}){
return await cache.updateUserChannelRoleMap({userId, channelRoleMap})
}
/**
* 批量更新登录用户频道权限
* @param {*} userIdList
* @param {*} channelRoleMap
*/
const batchUpdateUserChannelRoleMap = async function({userIdList, channelRoleMap}){
return await cache.batchUpdateUserChannelRoleMap({userIdList, channelRoleMap})
}
/**
* 获取登录用户所有频道权限
* @param {*} userId
* @param {*} channelId
* @returns
*/
const getUserChannelRoleMap = async function({userId}){
return await cache.getUserChannelRoleMap({userId})
}
/**
* 获取登录用户频道权限
* @param {*} userId
* @param {*} channelId
* @returns
*/
const getUserChannelRole = async function({userId, channelId}){
return await cache.getUserChannelRole({userId, channelId})
}
/**
* 设置邮箱验证码
* @param {*} email
* @param {*} code
*/
const setEmailCode = async function({email, code}){
return await cache.setEmailCode({email, code})
}
/**
* 获取邮箱验证码
* @param {*} email
*/
const getEmailCode = async function({email}){
return await cache.getEmailCode({email})
}
/**
* 设置手机号验证码
* @param {*} mobile
* @param {*} code
*/
const setMobileCode = async function({mobile, code}){
return await cache.setPhoneCode({mobile, code})
}
/**
* 获取手机号验证码
* @param {*} mobile
*/
const getMobileCode = async function({mobile}){
return await cache.getPhoneCode({mobile})
}
/**
* 生成token
*/
const generateLoginToken = function(){
return uuid.v4()
}
module.exports = {
getUserInfoByToken,
setUserInfoByToken,
generateLoginToken,
getUserLoginStatusByIdList,
setEmailCode,
getEmailCode,
setMobileCode,
getMobileCode,
setUserChannelRoleMap,
getUserChannelRoleMap,
getUserChannelRole,
updateUserChannelRoleMap,
batchUpdateUserChannelRoleMap
}

View File

@ -0,0 +1,365 @@
const { Op } = require('sequelize')
const moment = require('moment')
const { fields } = require('../../tables/tl_user_tag')
const TlUserTagDao = require('../../dao/tl_user_tag_dao')
const TlUserTagDef = fields.Def
const TlUserTagType = fields.Type
const TableName = fields.Name
const TableFields = Object.keys(fields.Def).map(key => fields.Def[key])
const { tlConsoleError, tlConsole } = require("../../utils/utils");
/**
* addInfo 接口
* @param {*} data
*/
const addInfo = async function({
name, type, userId, companyId
}){
// 参数校验
if(!name){
tlConsoleError(TableName, "请求service参数name为空")
return {}
}
if(!type){
tlConsoleError(TableName, "请求service参数type为空")
return {}
}
if(![
TlUserTagType.CHANNEL,
TlUserTagType.CLOUD,
TlUserTagType.FRIEND,
].includes(type)){
tlConsoleError(TableName, "请求service参数type不合法")
return {}
}
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return {}
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
const info = await TlUserTagDao.addInfo({
[TlUserTagDef.name]: name,
[TlUserTagDef.type]: type,
[TlUserTagDef.userId]: userId,
[TlUserTagDef.companyId]: companyId
})
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* getInfoById 接口
* @param {*} id
* @param {*} fields
* @param {*} companyId
*/
const getInfoById = async function({id, companyId}, fields){
// 参数校验
if(!id){
tlConsoleError(TableName, "请求service参数id为空")
return {}
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return {}
}
const info = await TlUserTagDao.getInfo({
[TlUserTagDef.id]: id
}, fields)
if(info === null){
return {}
}
return info
}
/**
* updateInfoById 接口
* @param {*} id
* @param {*} data
* @param {*} companyId
*/
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 TlUserTagDao.updateInfo({
[TlUserTagDef.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 TlUserTagDao.deleteInfo({
[TlUserTagDef.id]: id,
[TlUserTagDef.companyId]: companyId
})
if(info === null){
tlConsoleError(TableName, "请求dao异常")
return {}
}
return info
}
/**
* getListByIdList 接口
* @param {*} idList
* @param {*} companyId
* @param {*} fields
*/
const getListByIdList = async function({idList, companyId}, fields){
// 参数校验
if(!idList){
tlConsoleError(TableName, "请求service参数idList为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
const list = await TlUserTagDao.getList({
[TlUserTagDef.id]: idList,
[TlUserTagDef.companyId]: companyId
}, fields, [
[TlUserTagDef.createdAt, 'DESC']
])
if(list === null){
return []
}
return list
}
/**
* getListByIdListForPage 接口
* @param {*} idList
* @param {*} companyId
* @param {*} fields
* @param {*} page
* @param {*} pageSize
*/
const getListByIdListForPage = async function({idList, companyId}, fields, page, pageSize){
// 参数校验
if(!idList){
tlConsoleError(TableName, "请求service参数idList为空")
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 TlUserTagDao.getListForPage({
[TlUserTagDef.id]: idList
}, fields, [
[TlUserTagDef.createdAt, 'DESC']
], page, pageSize)
if(list === null){
return []
}
return list
}
/**
* getListByUserIdAndType 接口
* @param {*} companyId
* @param {*} userId
* @param {*} type
* @param {*} fields
*/
const getListByUserIdAndType = async function({ companyId, userId, type }, fields){
// 参数校验
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return []
}
if(!type){
tlConsoleError(TableName, "请求service参数type为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
const list = await TlUserTagDao.getList({
[TlUserTagDef.companyId]: companyId,
[TlUserTagDef.userId]: userId,
[TlUserTagDef.type]: type
}, fields, [
[TlUserTagDef.createdAt, 'DESC']
])
if(list === null){
return []
}
return list
}
/**
* getListByUserIdAndTypeForPage 接口
* @param {*} companyId
* @param {*} userId
* @param {*} type
* @param {*} fields
* @param {*} page
* @param {*} pageSize
*/
const getListByUserIdAndTypeForPage = async function({ companyId, userId, type }, fields, page, pageSize){
// 参数校验
if(!userId){
tlConsoleError(TableName, "请求service参数userId为空")
return []
}
if(!companyId){
tlConsoleError(TableName, "请求service参数companyId为空")
return []
}
if(!type){
tlConsoleError(TableName, "请求service参数type为空")
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 TlUserTagDao.getListForPage({
[TlUserTagDef.companyId]: companyId,
[TlUserTagDef.userId]: userId,
[TlUserTagDef.type]: type
}, fields, [
[TlUserTagDef.createdAt, 'DESC']
], page, pageSize)
if(list === null){
return []
}
return list
}
module.exports = {
addInfo,
updateInfoById,
deleteInfoById,
getInfoById,
getListByIdList,
getListByIdListForPage,
getListByUserIdAndType,
getListByUserIdAndTypeForPage
}

65
src/socket/connect.js Normal file
View File

@ -0,0 +1,65 @@
const socketCount = require("./handler/count");
const socketExit = require("./handler/exit");
const socketHeartbeat = require("./handler/heartbeat");
const socketDisConnect = require("./handler/disconnect");
const socketChannelChat = require("./handler/channel_chat");
const socketChannelChatRollback = require("./handler/channel_chat_rollback");
const socketContactApply = require('./handler/contact_apply')
const socketContactApplyPass = require('./handler/contact_apply_pass')
const socketContactApplyReject = require('./handler/contact_apply_reject')
const socketAuth = require("./handler/auth");
const {socketServerEvent} = require("./event");
module.exports = (io, socket) => {
// 登陆态校验
socketAuth.auth(io, socket)
// 断开连接
socket.on(socketServerEvent.disconnect, (data)=>{
socketDisConnect.disconnect(io, socket, data)
});
// 在线人数统计
socket.on(socketServerEvent.count, (data) => {
socketCount.count(io, socket, data)
});
// 退出房间
socket.on(socketServerEvent.exit, (data) => {
socketExit.exit(io, socket, data)
});
// 心跳
socket.on(socketServerEvent.heartbeat, (data) => {
socketHeartbeat.heartbeat(io, socket, data)
});
// 广播聊天消息
socket.on(socketServerEvent.channelChat, (data) => {
socketChannelChat.channelChat(io, socket, data)
})
// 广播聊天消息撤回
socket.on(socketServerEvent.channelChatRollback, (data) => {
socketChannelChatRollback.channelChatRollback(io, socket, data)
})
// 广播好友申请消息
socket.on(socketServerEvent.contactApply, (data) => {
socketContactApply.contactApply(io, socket, data)
})
// 通过好友申请
socket.on(socketServerEvent.contactApplyPass, (data) => {
socketContactApplyPass.contactApplyPass(io, socket, data)
})
// 拒绝好友申请
socket.on(socketServerEvent.contactApplyReject, (data) => {
socketContactApplyReject.contactApplyReject(io, socket, data)
})
// 触发一次count
socketCount.count(io, socket, {})
}

6
src/socket/event.js Normal file
View File

@ -0,0 +1,6 @@
const socketServerEvent = require('./event/server_event');
const socketClientEvent = require('./event/client_event');
module.exports = {
socketClientEvent, socketServerEvent
}

View File

@ -0,0 +1,27 @@
/**
* 客户端监听事件
* event事件名称
*/
module.exports = {
// 创建房间
created : "created",
// 加入房间
joined : "joined",
// 退出
exit : "exit",
// 人数
count : "count",
// 心跳
heartbeat : "heartbeat",
// 广播聊天消息
channelChat: "channelChat",
// 广播聊天消息撤回
channelChatRollback: "channelChatRollback",
// 广播好友申请
contactApply: "contactApply",
// 通过好友申请
contactApplyPass: "contactApplyPass",
// 拒绝好友申请
contactApplyReject: "contactApplyReject",
}

View File

@ -0,0 +1,30 @@
/**
* 服务端监听事件
* event事件名称
*/
module.exports = {
// socket连接
connection : "connection",
// socket断开连接
disconnect : "disconnect",
// 在线人数
count : "count",
// 退出
exit : "exit",
// 加入/创建房间
createAndJoin : "createAndJoin",
// 心跳
heartbeat : "heartbeat",
// 广播聊天消息
channelChat: "channelChat",
// 广播聊天消息撤回
channelChatRollback: "channelChatRollback",
// 广播好友申请
contactApply: "contactApply",
// 通过好友申请
contactApplyPass: "contactApplyPass",
// 拒绝好友申请
contactApplyReject: "contactApplyReject",
}

View File

@ -0,0 +1,45 @@
const {socketClientEvent} = require("../event");
const userSessionService = require('../../service/user/tl_user_session_service')
const cache = require('../../utils/cache/cache')
/**
* 登陆态校验
* @param {*} io socketio对象
* @param {*} socket 单个socket连接
* @returns
*/
async function auth(io, socket){
const { token } = socket.handshake.query;
if(!token){
return
}
const {
loginUserId, loginUserCompanyId, logniTime
} = await userSessionService.getUserInfoByToken({token})
if(!loginUserId){
return
}
// 更新socketId和userId的映射关系
await cache.setUserIdSocketIdMap({
companyId: loginUserCompanyId,
userId: loginUserId,
socketId: socket.id
})
// 加入个人房间
socket.join(loginUserId)
// 设置token
socket.token = token
return
}
module.exports = {
auth
}

View File

@ -0,0 +1,72 @@
const {socketClientEvent} = require("../event");
const userSessionService = require('../../service/user/tl_user_session_service')
const channelUserService = require('../../service/channel/tl_channel_user_service')
const { fields: channelUserFields } = require('../../tables/tl_channel_user')
const { Def: TlChannelUserDef } = channelUserFields
/**
* 广播聊天消息
* @param {*} io socketio对象
* @param {*} socket 单个socket连接
* @param {*} data event参数
* @returns
*/
async function channelChat(io, socket, data){
let channel = data.channel
let messageInfo = data.messageInfo
let to = data.to
const token = socket.token;
if(!channel){
return
}
const {
loginUserId, loginUserCompanyId
} = await userSessionService.getUserInfoByToken({token})
if(!loginUserId){
return
}
// 指定人,无须频道广播
if (to){
const toClient = io.sockets.connected[to]
if (toClient){
toClient.emit(socketClientEvent.channelChat, {
channel: data.channel,
messageInfo: messageInfo,
from: socket.id,
})
}
return
}
// 拿到当前频道下的所有用户socketid,进行广播
const channelUserList = await channelUserService.getListByChannelId({
channelId: channel,
companyId: loginUserCompanyId
}, [
TlChannelUserDef.userId
])
const userIds = channelUserList.map(item => item[TlChannelUserDef.userId])
// 广播给频道内的所有用户
for(let userId of userIds){
if(userId === loginUserId){
continue
}
io.sockets.in(userId).emit(socketClientEvent.channelChat, {
channel: data.channel,
messageInfo: messageInfo,
from: socket.id,
})
}
}
module.exports = {
channelChat
}

View File

@ -0,0 +1,75 @@
const {socketClientEvent} = require("../event");
const userSessionService = require('../../service/user/tl_user_session_service')
const channelUserService = require('../../service/channel/tl_channel_user_service')
const { fields: channelUserFields } = require('../../tables/tl_channel_user')
const { Def: TlChannelUserDef } = channelUserFields
/**
* 广播聊天消息撤回
* @param {*} io socketio对象
* @param {*} socket 单个socket连接
* @param {*} data event参数
* @returns
*/
async function channelChatRollback(io, socket, data){
let channel = data.channel
let messageId = data.messageId
let rollbackMessage = data.rollbackMessage
let to = data.to
const token = socket.token;
if(!channel){
return
}
const {
loginUserId, loginUserCompanyId
} = await userSessionService.getUserInfoByToken({token})
if(!loginUserId){
return
}
// 指定人,无须频道广播
if (to){
const toClient = io.sockets.connected[to]
if (toClient){
toClient.emit(socketClientEvent.channelChatRollback, {
channel: data.channel,
messageId: messageId,
from: socket.id,
rollbackMessage: rollbackMessage,
})
}
return
}
// 拿到当前频道下的所有用户socketid,进行广播
const channelUserList = await channelUserService.getListByChannelId({
channelId: channel,
companyId: loginUserCompanyId
}, [
TlChannelUserDef.userId
])
const userIds = channelUserList.map(item => item[TlChannelUserDef.userId])
// 广播给频道内的所有用户
for(let userId of userIds){
if(userId === loginUserId){
continue
}
io.sockets.in(userId).emit(socketClientEvent.channelChatRollback, {
channel: data.channel,
messageId: messageId,
from: socket.id,
rollbackMessage: rollbackMessage,
})
}
}
module.exports = {
channelChatRollback
}

View File

@ -0,0 +1,56 @@
const {socketClientEvent} = require("../event");
const userSessionService = require('../../service/user/tl_user_session_service')
const channelUserService = require('../../service/channel/tl_channel_user_service')
const { fields: channelUserFields } = require('../../tables/tl_channel_user')
const { Def: TlChannelUserDef } = channelUserFields
/**
* 广播好友申请消息
* @param {*} io socketio对象
* @param {*} socket 单个socket连接
* @param {*} data event参数
* @returns
*/
async function contactApply(io, socket, data){
let userId = data.userId
let applyInfo = data.applyInfo
let to = data.to
const token = socket.token;
if(!userId){
return
}
const {
loginUserId, loginUsername
} = await userSessionService.getUserInfoByToken({token})
if(!loginUserId){
return
}
// 指定人,无须频道广播
if (to){
const toClient = io.sockets.connected[to]
if (toClient){
toClient.emit(socketClientEvent.contactApply, {
fromUsername: loginUsername,
applyInfo: applyInfo,
from: socket.id,
})
}
return
}
io.sockets.in(userId).emit(socketClientEvent.contactApply, {
fromUsername: loginUsername,
applyInfo: applyInfo,
from: socket.id,
})
}
module.exports = {
contactApply
}

View File

@ -0,0 +1,56 @@
const {socketClientEvent} = require("../event");
const userSessionService = require('../../service/user/tl_user_session_service')
const channelUserService = require('../../service/channel/tl_channel_user_service')
const { fields: channelUserFields } = require('../../tables/tl_channel_user')
const { Def: TlChannelUserDef } = channelUserFields
/**
* 广播好友通过申请消息
* @param {*} io socketio对象
* @param {*} socket 单个socket连接
* @param {*} data event参数
* @returns
*/
async function contactApplyPass(io, socket, data){
let userId = data.userId
let passInfo = data.passInfo
let to = data.to
const token = socket.token;
if(!userId){
return
}
const {
loginUserId, loginUsername
} = await userSessionService.getUserInfoByToken({token})
if(!loginUserId){
return
}
// 指定人,无须频道广播
if (to){
const toClient = io.sockets.connected[to]
if (toClient){
toClient.emit(socketClientEvent.contactApplyPass, {
fromUsername: loginUsername,
passInfo: passInfo,
from: socket.id,
})
}
return
}
io.sockets.in(userId).emit(socketClientEvent.contactApplyPass, {
fromUsername: loginUsername,
passInfo: passInfo,
from: socket.id,
})
}
module.exports = {
contactApplyPass
}

View File

@ -0,0 +1,56 @@
const {socketClientEvent} = require("../event");
const userSessionService = require('../../service/user/tl_user_session_service')
const channelUserService = require('../../service/channel/tl_channel_user_service')
const { fields: channelUserFields } = require('../../tables/tl_channel_user')
const { Def: TlChannelUserDef } = channelUserFields
/**
* 广播好友申请拒绝消息
* @param {*} io socketio对象
* @param {*} socket 单个socket连接
* @param {*} data event参数
* @returns
*/
async function contactApplyReject(io, socket, data){
let userId = data.userId
let rejectInfo = data.rejectInfo
let to = data.to
const token = socket.token;
if(!userId){
return
}
const {
loginUserId, loginUsername
} = await userSessionService.getUserInfoByToken({token})
if(!loginUserId){
return
}
// 指定人,无须频道广播
if (to){
const toClient = io.sockets.connected[to]
if (toClient){
toClient.emit(socketClientEvent.contactApplyReject, {
fromUsername: loginUsername,
rejectInfo: rejectInfo,
from: socket.id,
})
}
return
}
io.sockets.in(userId).emit(socketClientEvent.contactApplyReject, {
fromUsername: loginUsername,
rejectInfo: rejectInfo,
from: socket.id,
})
}
module.exports = {
contactApplyReject
}

View File

@ -0,0 +1,21 @@
const {socketClientEvent} = require("../event");
/**
* 在线人数统计广播
* @param {*} io socketio对象
* @param {*} socket 单个socket连接
* @param {*} data event参数
* @returns
*/
async function count(io, socket, data){
let allManCount = Object.keys(io.sockets.connected).length || 0;
io.sockets.emit(socketClientEvent.count, {
mc : allManCount
})
}
module.exports = {
count
}

View File

@ -0,0 +1,21 @@
const socketCount = require("./count");
const {socketClientEvent} = require("../event");
/**
* 断开连接的操作
* @param {*} io socketio对象
* @param {*} socket 单个socket连接
* @param {*} data event参数
*/
async function disconnect(io, socket, data){
socket.broadcast.emit(socketClientEvent.exit, {
from : socket.id,
});
socketCount.count(io, socket, data);
}
module.exports = {
disconnect
}

View File

@ -0,0 +1,30 @@
const socketCount = require("./count");
const {socketClientEvent} = require("../event");
/**
* 退出房间
* @param {*} io socketio对象
* @param {*} socket 单个socket连接
* @param {*} data event参数
* @returns
*/
async function exit(io, socket, data){
socket.leave(room);
const clientsInRoom = io.sockets.adapter.rooms[room];
if (clientsInRoom) {
let otherSocketIds = Object.keys(clientsInRoom.sockets);
for (let i = 0; i < otherSocketIds.length; i++) {
let otherSocket = io.sockets.connected[otherSocketIds[i]];
otherSocket.emit(socketClientEvent.exit, data);
}
}
socketCount.count(io, socket, data);
}
module.exports = {
exit
}

View File

@ -0,0 +1,19 @@
const {socketClientEvent} = require("../event");
/**
* 心跳
* @param {*} io socketio对象
* @param {*} socket 单个socket连接
* @param {*} data event参数
* @returns
*/
async function heartbeat(io, socket, data){
socket.emit(socketClientEvent.heartbeat, {
status : "ok"
})
}
module.exports = {
heartbeat
}

33
src/socket/index.js Normal file
View File

@ -0,0 +1,33 @@
const connect = require("./connect");
const {socketServerEvent} = require("./event");
const {
tlConsole
} = require("./../utils/utils");
/**
* socket事件初始化入口
* @param {*} io
* @returns
*/
async function execute(io) {
if (io === undefined || io === null) {
tlConsole("io is null")
return;
}
io.sockets.on(socketServerEvent.connection, function (socket) {
if(socket.id === undefined || socket.id === null || socket.id === 0 || socket.id === "0"){
socket.emit("tips", {
to: socket.id,
msg: "非法连接"
});
return
}
connect(io, socket)
});
}
module.exports = {
execute
}

102
src/tables/db.js Normal file
View File

@ -0,0 +1,102 @@
const sequelizeObj = require('sequelize');
const fs = require('fs');
const { tlConsole } = require("../../src/utils/utils");
const { get_env_config } = require("../../conf/env_config");
const { resolve } = require('path');
const conf = get_env_config();
//db connect retry times
let connectRetryTimes = 0;
// 连接对象缓存
let dbClientInstance = null
/**
* 获取数据库连接对象
* @returns
*/
const getDbClient = function() {
if(dbClientInstance != null){
return dbClientInstance
}
const options = {
"dialect": "mysql",
"host": conf.db_mysql_host,
"port": conf.db_mysql_port,
"logging": false,
"pool": {
"max": 20,
"min": 5,
"acquire": 30000,
"idle": 10000
},
"timezone": "+08:00",
"define": {
"freezeTableName": true,
"underscored": true,
"charset": "utf8",
"collate": "utf8_general_ci",
"timestamps": false,
"paranoid": true
}
}
dbClientInstance = new sequelizeObj(
conf.db_mysql_dbName, conf.db_mysql_user, conf.db_mysql_password, options
);
tlConsole("db init done ...")
return dbClientInstance
}
/**
* 初始化数据库
* @returns
*/
const dbInit = async function(){
let dbclient = getDbClient()
try {
await dbclient.authenticate();
tlConsole('db connect ok ... ');
let files = fs.readdirSync(__dirname);
for (let f of files) {
if (f[0] == '.' || f == 'db.js') continue;
try {
let fn = require('./' + f).model;
if (typeof fn == 'function') {
fn(dbclient, sequelizeObj);
}
} catch (e) {
tlConsole(e);
}
}
try {
await dbclient.sync({ force: false });
tlConsole("db sync ok ...");
} catch (e) {
tlConsole("db sync err : ",e);
}
} catch (e) {
if(connectRetryTimes++ < 8){
tlConsole('db connect err, retrying ... ',e.message);
await new Promise(resolve => setTimeout(resolve, connectRetryTimes * 3000));
await dbInit();
return;
}
tlConsole('db connect err ',e);
}
}
module.exports = {
dbClient: getDbClient(),
dbInit
}

79
src/tables/tl_channel.js Normal file
View File

@ -0,0 +1,79 @@
const tl_channel_fields = {
Name: 'tl_channel',
Description: '频道表,主要定义单聊,群聊等创建的各种频道记录',
Def: {
id : 'id',
companyId : 'company_id',
flag : 'flag',
name : 'name',
status: 'status',
type: 'type',
createdAt : 'createdAt',
updatedAt : 'updatedAt',
deletedAt : 'deletedAt',
},
Type: {
GROUP : 1, // 群聊
FRIEND : 2, // 好友
},
Status: {
NORMAL: 1, //正常
}
}
const tl_channel_model = function(DataTypes){
return {
model : {
id: {
type: DataTypes.INTEGER,
comment: '频道id',
primaryKey: true,
autoIncrement: true
},
company_id: {
type: DataTypes.INTEGER,
comment: '企业id'
},
flag: {
type: DataTypes.INTEGER,
comment: '标志位',
defaultValue: 0,
},
name : {
type: DataTypes.STRING(64),
comment: '频道名称'
},
type: {
type: DataTypes.INTEGER,
comment: '频道类型',
},
status: {
type: DataTypes.INTEGER,
comment: '频道状态',
defaultValue: tl_channel_fields.Status.NORMAL
},
},
options : {
timestamps: true,
comment: '频道记录表',
indexes: [{
name: 'created_at_index',
method: 'BTREE',
fields: ['created_at']
}]
}
}
}
module.exports = {
model: function(sequelize, DataTypes){
return {
TlChannel: sequelize.define(
'tl_channel',
tl_channel_model(DataTypes).model,
tl_channel_model(DataTypes).options
)
}
},
fields: tl_channel_fields
}

View File

@ -0,0 +1,129 @@
const tl_channel_chat_fields = {
Name: 'tl_channel_chat',
Description: '频道聊天记录表,所有企业,用户的单聊,群聊聊天记录表',
Def: {
id : 'id',
companyId : 'company_id',
channelId : 'channel_id',
type : 'type',
flag : 'flag',
message : 'message',
other : 'other',
fromUserId : 'from_user_id',
fromUserName : 'from_user_name',
toUserId : 'to_user_id',
toUserName : 'to_user_name',
messageTimeStamp : 'message_ts',
messageVersion : 'message_version',
createdAt : 'createdAt',
updatedAt : 'updatedAt',
deletedAt : 'deletedAt',
},
Flag: {
IS_ROLL_BACK: 0x1, //是否撤回
IS_REAL_TEXT: 0x2, // 是否是富文本
IS_REPLAY: 0x4, // 是否是回复
IS_AT_USER: 0x8, // 是否是@用户
IS_AT_ALL: 0x10, // 是否是@所有人
},
Other: {
ip: 'ip', // ip地址
replyToMessageId: 'reply_to_message_id', // 回复消息id
replyToMessageType: 'reply_to_message_type', // 回复消息类型
atUserId: 'at_user_id', // at用户id
atUserName: 'at_user_name', // at用户昵称
},
Type : {
FRIEND : 'friend', // 好友消息
GROUP : 'group', // 群消息
SYSTEM : 'system', // 系统消息
},
}
const tl_channel_chat_model = function(DataTypes){
return {
model : {
id: {
type: DataTypes.INTEGER,
comment: '聊天记录id',
primaryKey: true,
autoIncrement: true
},
company_id: {
type: DataTypes.INTEGER,
comment: '企业id'
},
channel_id : {
type: DataTypes.INTEGER,
comment: '频道id'
},
type : {
type: DataTypes.STRING(8),
comment: '消息类型'
},
flag: {
type: DataTypes.INTEGER,
comment: '标志位',
defaultValue: 0,
},
message: {
type: DataTypes.STRING(8192),
comment: '消息内容'
},
other: {
type: DataTypes.TEXT,
comment: '其他信息, json格式'
},
from_user_id: {
type: DataTypes.INTEGER,
comment: '发送用户id'
},
from_user_name:{
type: DataTypes.STRING(64),
comment: '发送用户昵称'
},
to_user_id: {
type: DataTypes.INTEGER,
comment: '接收用户id'
},
to_user_name: {
type: DataTypes.STRING(64),
comment: '接收用户昵称'
},
message_ts: {
type: DataTypes.BIGINT,
comment: '消息时间戳'
},
message_version: {
type: DataTypes.STRING(8),
comment: '消息版本'
},
},
options : {
timestamps: true,
comment: '聊天记录表',
indexes: [{
name: 'created_at_index',
method: 'BTREE',
fields: ['created_at']
}, {
name: 'message_ts_index',
method: 'BTREE',
fields: ['message_ts']
}]
}
}
}
module.exports = {
model: function(sequelize, DataTypes){
return {
TlChannelChat: sequelize.define(
'tl_channel_chat',
tl_channel_chat_model(DataTypes).model,
tl_channel_chat_model(DataTypes).options
)
}
},
fields: tl_channel_chat_fields
}

View File

@ -0,0 +1,96 @@
const tl_channel_user_fields = {
Name: 'tl_channel_user',
Description: '频道用户表,主要定义单聊,群聊等创建的各种频道中的用户信息',
Def: {
id : 'id',
companyId : 'company_id',
channelId : 'channel_id',
userId : 'user_id',
flag : 'flag',
roleId : 'role_id',
type: 'type',
status : 'status',
createdAt : 'createdAt',
updatedAt : 'updatedAt',
deletedAt : 'deletedAt',
},
Type: {
GROUP : 1, // 群聊
FRIEND : 2, // 好友
},
Status: {
NORMAL: 1, //正常
BLACK: 2, // 黑名单
},
Flag: {
IS_SET_TOP: 1, // 置顶
IS_SET_BLACK: 2, // 拉黑
IS_SET_HIDDEN: 3, // 不显示
IS_SET_MUTE: 4, // 静音/免打扰
}
}
const tl_channel_user_model = function(DataTypes){
return {
model : {
id: {
type: DataTypes.INTEGER,
comment: '频道用户记录id',
primaryKey: true,
autoIncrement: true
},
company_id: {
type: DataTypes.INTEGER,
comment: '企业id'
},
channel_id : {
type: DataTypes.INTEGER,
comment: '频道id'
},
type: {
type: DataTypes.INTEGER,
comment: '频道类型',
},
user_id: {
type: DataTypes.INTEGER,
comment: '用户id'
},
flag: {
type: DataTypes.INTEGER,
comment: '标志位',
defaultValue: 0,
},
role_id: {
type: DataTypes.INTEGER,
comment: '角色id'
},
status: {
type: DataTypes.INTEGER,
comment: '群聊用户状态',
defaultValue: tl_channel_user_fields.Status.NORMAL
}
},
options : {
timestamps: true,
comment: '频道用户记录表',
indexes: [{
name: 'created_at_index',
method: 'BTREE',
fields: ['created_at']
}]
}
}
}
module.exports = {
model: function(sequelize, DataTypes){
return {
TlChannelUser: sequelize.define(
'tl_channel_user',
tl_channel_user_model(DataTypes).model,
tl_channel_user_model(DataTypes).options
)
}
},
fields: tl_channel_user_fields
}

100
src/tables/tl_company.js Normal file
View File

@ -0,0 +1,100 @@
const tl_company_fields = {
Name: 'tl_company',
Description: '企业信息表',
Def: {
id : 'id',
code: 'code',
name : 'name',
address : 'address',
phone : 'phone',
email : 'email',
website : 'website',
logo : 'logo',
description : 'description',
flag : 'flag',
content : 'content',
createdAt : 'createdAt',
updatedAt : 'updatedAt',
deletedAt : 'deletedAt',
},
Flag: {
IS_PASS_AUTH: 0x1, //是否通过认证
IS_EXPIRED: 0x2, //是否过期
},
}
const tl_company_model = function(DataTypes){
return {
model : {
id: {
type: DataTypes.INTEGER,
comment: '企业id',
primaryKey: true,
autoIncrement: true
},
code: {
type: DataTypes.STRING(60),
comment: '企业唯一编码'
},
name: {
type: DataTypes.STRING(20),
comment: '企业名称'
},
address: {
type: DataTypes.STRING(256),
comment: '企业地址'
},
phone: {
type: DataTypes.STRING(20),
comment: '企业电话'
},
email: {
type: DataTypes.STRING(48),
comment: '企业邮箱'
},
website: {
type: DataTypes.STRING(48),
comment: '企业网址'
},
logo: {
type: DataTypes.STRING(256),
comment: '企业logo'
},
description: {
type: DataTypes.STRING(256),
comment: '企业描述'
},
flag: {
type: DataTypes.INTEGER,
comment: '标志位',
defaultValue: 0,
},
content: {
type: DataTypes.TEXT,
comment: '详细信息'
},
},
options : {
timestamps: true,
comment: '企业信息表',
indexes: [{
name: 'created_at_index',
method: 'BTREE',
fields: ['created_at']
}]
}
}
}
module.exports = {
model: function(sequelize, DataTypes){
return {
TlCompany: sequelize.define(
'tl_company',
tl_company_model(DataTypes).model,
tl_company_model(DataTypes).options
)
}
},
fields: tl_company_fields
}

157
src/tables/tl_role.js Normal file
View File

@ -0,0 +1,157 @@
const role = require('../role/role');
const tl_role_fields = {
Name: 'tl_role',
Description: '角色表,定义各种角色,包括企业角色,系统角色,管理员角色等',
Def : {
id : 'id',
companyId : 'company_id',
name : 'name',
key: 'key',
flag : 'flag',
type: 'type',
description : 'description',
permissionIdList: 'permission_id_list',
createdAt : 'createdAt',
updatedAt : 'updatedAt',
deletedAt : 'deletedAt',
},
Type: {
NORMAL_USER: 1, // 普通用户角色
ADMIN_USER: 2, // 管理员角色
TEST_USER: 3, // 测试演示用户角色
CHANNEL_CREATOR_USER: 4, // 频道群主角色
CHANNEL_ADMIN_USER: 5, // 频道管理员角色
CHANNEL_NORMAL_USER: 6, // 频道普通用户角色
WEBSITE_USER: 7, // 官网用户角色
}
}
const tl_role_model = function(DataTypes){
return {
model : {
id: {
type: DataTypes.INTEGER,
comment: '角色记录id',
primaryKey: true,
autoIncrement: true
},
company_id: {
type: DataTypes.INTEGER,
comment: '企业id'
},
key: {
type: DataTypes.STRING(20),
comment: '角色key'
},
type: {
type: DataTypes.INTEGER,
comment: '角色类型',
},
name: {
type: DataTypes.STRING(20),
comment: '角色名称'
},
description: {
type: DataTypes.STRING(256),
comment: '角色描述'
},
permission_id_list: {
type: DataTypes.TEXT,
comment: '权限id列表',
},
flag: {
type: DataTypes.INTEGER,
comment: '标志位',
defaultValue: 0,
},
},
options : {
timestamps: true,
comment: '用户角色表',
indexes: [{
name: 'created_at_index',
method: 'BTREE',
fields: ['created_at']
}]
}
}
}
const tl_inner_role = {
user: {
normal : {
id : 1,
key: 'normal',
name : '普通角色',
type: tl_role_fields.Type.NORMAL_USER,
permissionIdList : JSON.stringify(
role.userNormalPermissions()
),
description : '普通角色用户',
flag : 0,
},
admin : {
id : 2,
key: 'admin',
name : '管理员',
type: tl_role_fields.Type.ADMIN_USER,
permissionIdList : JSON.stringify(
role.userAdminPermissions()
),
description : '管理员角色用户',
flag : 0,
},
},
channel : {
creator : {
id : 10000,
key: 'creator',
name : '群主',
type: tl_role_fields.Type.CHANNEL_CREATOR_USER,
permissionIdList : JSON.stringify(
role.userChannelCreatorPermissions()
),
description : '频道创建者',
flag : 0,
},
admin : {
id : 10001,
key: 'admin',
name : '管理员',
type: tl_role_fields.Type.CHANNEL_ADMIN_USER,
permissionIdList : JSON.stringify(
role.userChannelAdminPermissions()
),
description : '频道管理员',
flag : 0,
},
member : {
id : 10002,
key: 'member',
name : '成员',
type: tl_role_fields.Type.CHANNEL_NORMAL_USER,
permissionIdList : JSON.stringify(
role.userChannelNormalPermissions()
),
description : '频道成员',
flag : 0,
},
},
}
module.exports = {
model: function(sequelize, DataTypes){
return {
TlRole: sequelize.define(
'tl_role',
tl_role_model(DataTypes).model,
tl_role_model(DataTypes).options
)
}
},
fields: tl_role_fields,
inner: tl_inner_role
}

115
src/tables/tl_user.js Normal file
View File

@ -0,0 +1,115 @@
const tl_user_fields = {
Name: 'tl_user',
Description : '用户表,系统平台所有用户都在这个表',
Def : {
id : 'id',
companyId : 'company_id',
name : 'name',
password : 'password',
salt : 'salt',
email : 'email',
mobile : 'mobile',
avatarUrl : 'avatar_url',
roleId : 'role_id',
wchatName : 'wchat_name',
wchatOpenId : 'wchat_open_id',
wchatUnionId : 'wchat_union_id',
wchatAvatarUrl : 'wchat_avatar_url',
flag : 'flag',
createdAt : 'createdAt',
updatedAt : 'updatedAt',
deletedAt : 'deletedAt',
},
Flag: {
IS_PASS_AUTH: 0x1, //是否通过认证
IS_EXPIRED: 0x2, //是否过期
},
}
const tl_user_model = function(DataTypes){
return {
model : {
id: {
type: DataTypes.INTEGER,
comment: '用户id',
primaryKey: true,
autoIncrement: true
},
company_id: {
type: DataTypes.INTEGER,
comment: '企业id'
},
name: {
type: DataTypes.STRING(20),
comment: '用户名称'
},
password: {
type: DataTypes.STRING(64),
comment: '用户密码'
},
salt: {
type: DataTypes.STRING(32),
comment: '用户密码盐'
},
email: {
type: DataTypes.STRING(64),
comment: '用户邮箱'
},
mobile: {
type: DataTypes.STRING(11),
comment: '用户手机号'
},
avatar_url: {
type: DataTypes.STRING(255),
comment: '头像地址-对应oss-key'
},
role_id : {
type: DataTypes.INTEGER,
comment: '角色id'
},
wchat_name: {
type: DataTypes.STRING(64),
comment: '微信昵称'
},
wchat_open_id: {
type: DataTypes.STRING(64),
comment: '微信open_id'
},
wchat_union_id: {
type: DataTypes.STRING(64),
comment: '微信union_id'
},
wchat_avatar_url: {
type: DataTypes.STRING(255),
comment: '微信头像地址'
},
flag: {
type: DataTypes.INTEGER,
comment: '标志位',
defaultValue: 0,
}
},
options : {
timestamps: true,
comment: '用户表',
indexes: [{
name: 'created_at_index',
method: 'BTREE',
fields: ['created_at']
}]
}
}
}
module.exports = {
model: function(sequelize, DataTypes){
return {
TlUser: sequelize.define(
'tl_user',
tl_user_model(DataTypes).model,
tl_user_model(DataTypes).options
)
}
},
fields: tl_user_fields
}

107
src/tables/tl_user_apply.js Normal file
View File

@ -0,0 +1,107 @@
const tl_user_apply_fields = {
Name: 'tl_user_apply',
Description: '用户申请表, 主要定义用户各种申请记录,如好友申请,加群申请等',
Def: {
id : 'id',
companyId : 'company_id',
userId : 'user_id',
targetId: 'target_id',
type : 'type',
status : 'status',
origin: 'origin',
remark: 'remark',
flag: 'flag',
createdAt : 'createdAt',
updatedAt : 'updatedAt',
deletedAt : 'deletedAt',
},
Flag: {
},
Type: {
FRIEND: 1, //好友申请
GROUP: 2, //群申请
},
Status: {
WAIT: 1, //等待验证
PASS: 2, //通过
REJECT: 3, //拒绝
BLACK: 4, //黑名单
},
Origin: {
SEARCH_NAME: '1', //搜索用户名添加
SEARCH_PHONE: '2', //搜索手机号添加
SEARCH_EMAIL: '3', //搜索邮箱添加
INVITE_QR: '4', //二维码邀请添加
INVITE_LINK: '5', //链接邀请添加
}
}
const tl_user_apply_model = function(DataTypes){
return {
model : {
id: {
type: DataTypes.INTEGER,
comment: '申请id',
primaryKey: true,
autoIncrement: true
},
company_id: {
type: DataTypes.INTEGER,
comment: '企业id'
},
flag: {
type: DataTypes.INTEGER,
comment: '标志位',
defaultValue: 0,
},
origin:{
type: DataTypes.STRING,
comment: '申请来源'
},
user_id: {
type: DataTypes.INTEGER,
comment: '申请记录所属用户id'
},
target_id: {
type: DataTypes.INTEGER,
comment: '申请目标id'
},
remark:{
type: DataTypes.STRING,
comment: '申请备注'
},
type: {
type: DataTypes.INTEGER,
comment: '申请类型'
},
status: {
type: DataTypes.INTEGER,
comment: '申请状态',
defaultValue: tl_user_apply_fields.Status.WAIT
}
},
options : {
timestamps: true,
comment: '用户申请记录表',
indexes: [{
name: 'created_at_index',
method: 'BTREE',
fields: ['created_at']
}]
}
}
}
module.exports = {
model: function(sequelize, DataTypes){
return {
TlUserApply: sequelize.define(
'tl_user_apply',
tl_user_apply_model(DataTypes).model,
tl_user_apply_model(DataTypes).options
)
}
},
fields: tl_user_apply_fields
}

View File

@ -0,0 +1,65 @@
const tl_user_auth_fields = {
Name: 'tl_user_auth',
Description: '用户认证表, 主要定义用户各种认证记录,如邮箱认证,手机号认证等',
Def: {
id : 'id',
key: 'key',
type : 'type',
code : 'code',
createdAt : 'createdAt',
updatedAt : 'updatedAt',
deletedAt : 'deletedAt',
},
Type: {
EMAIL_REGISTER_CODE: 1,
PHONE_REGISTER_CODE: 2,
PHONE_LOGIN_CODE: 3,
},
}
const tl_user_auth_model = function(DataTypes){
return {
model : {
id: {
type: DataTypes.INTEGER,
comment: '认证id',
primaryKey: true,
autoIncrement: true
},
key: {
type: DataTypes.STRING,
comment: '认证key'
},
code: {
type: DataTypes.STRING(16),
comment: '认证code'
},
type: {
type: DataTypes.INTEGER,
comment: '认证类型'
},
},
options : {
timestamps: true,
comment: '用户认证记录表',
indexes: [{
name: 'created_at_index',
method: 'BTREE',
fields: ['created_at']
}]
}
}
}
module.exports = {
model: function(sequelize, DataTypes){
return {
TlUserAuth: sequelize.define(
'tl_user_auth',
tl_user_auth_model(DataTypes).model,
tl_user_auth_model(DataTypes).options
)
}
},
fields: tl_user_auth_fields
}

View File

@ -0,0 +1,116 @@
const tl_user_config_fields = {
Name: 'tl_user_config',
Description: '用户配置表',
Def: {
id : 'id',
companyId : 'company_id',
userId : 'user_id',
normal: 'normal',
account: 'account',
message: 'message',
skin: 'skin',
authority: 'authority',
other: 'other',
createdAt : 'createdAt',
updatedAt : 'updatedAt',
deletedAt : 'deletedAt',
},
Account: {
},
Normal: {
},
Message: { // 消息设置
// 网页通知
webNotify: 'webNotify',
// 消息红点
messageDot: 'messageDot',
},
Authority: { // 权限设置
},
Skin: {
},
Other: {
// 中继服务
turnServer: 'turnServer',
// 自定义wss服务地址
customWss: 'customWss',
}
}
const tl_user_config_model = function(DataTypes){
return {
model : {
id: {
type: DataTypes.INTEGER,
comment: '用户配置id',
primaryKey: true,
autoIncrement: true
},
company_id: {
type: DataTypes.INTEGER,
comment: '企业id'
},
user_id:{
type: DataTypes.INTEGER,
comment: '用户id',
defaultValue: 0
},
account: {
type: DataTypes.TEXT,
comment: '账户设置',
defaultValue: ''
},
message: {
type: DataTypes.TEXT,
comment: '消息设置',
defaultValue: ''
},
skin: {
type: DataTypes.TEXT,
comment: '皮肤设置',
defaultValue: ''
},
authority: {
type: DataTypes.TEXT,
comment: '权限设置',
defaultValue: ''
},
normal: {
type: DataTypes.TEXT,
comment: '通用设置',
defaultValue: ''
},
other: {
type: DataTypes.TEXT,
comment: '其他设置',
defaultValue: ''
},
},
options : {
timestamps: true,
comment: '用户配置表',
indexes: [{
name: 'created_at_index',
method: 'BTREE',
fields: ['created_at']
}]
}
}
}
module.exports = {
model: function(sequelize, DataTypes){
return {
TlUserConfig: sequelize.define(
'tl_user_config',
tl_user_config_model(DataTypes).model,
tl_user_config_model(DataTypes).options
)
}
},
fields: tl_user_config_fields
}

View File

@ -0,0 +1,55 @@
const tl_user_finger_print_fields = {
Name: 'tl_user_finger_print',
Description: '用户登录指纹表, 主要存储用户相关指纹,用于登录身份认证等',
Def: {
id : 'id',
user_id: 'user_id',
finger_print: 'finger_print',
createdAt : 'createdAt',
updatedAt : 'updatedAt',
deletedAt : 'deletedAt',
},
}
const tl_user_finger_print_model = function(DataTypes){
return {
model : {
id: {
type: DataTypes.INTEGER,
comment: '主键',
primaryKey: true,
autoIncrement: true
},
user_id: {
type: DataTypes.INTEGER,
comment: '用户id'
},
finger_print: {
type: DataTypes.STRING,
comment: '指纹'
},
},
options : {
timestamps: true,
comment: '用户登录指纹表',
indexes: [{
name: 'created_at_index',
method: 'BTREE',
fields: ['created_at']
}]
}
}
}
module.exports = {
model: function(sequelize, DataTypes){
return {
TlUserFingerPrint: sequelize.define(
'tl_user_finger_print',
tl_user_finger_print_model(DataTypes).model,
tl_user_finger_print_model(DataTypes).options
)
}
},
fields: tl_user_finger_print_fields
}

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