Compare commits

..

50 Commits

Author SHA1 Message Date
Xinwei Xiong ab406bea3d Merge pull request #543 from hanzhixiao/fix/v3-error2
fix conflict
2023-07-13 10:39:35 +00:00
‘hanzhixiao’ 4bd97149c3 fix conflict
Signed-off-by: ‘hanzhixiao’ <‘709674996@qq.com’>
2023-07-13 18:37:59 +08:00
‘hanzhixiao’ fda6cd5354 fix conflict
Signed-off-by: ‘hanzhixiao’ <‘709674996@qq.com’>
2023-07-13 18:30:18 +08:00
Xinwei Xiong c6203c825f Merge pull request #542 from hanzhixiao/fix/v3-error
Fix/v3 error
2023-07-13 10:26:27 +00:00
‘hanzhixiao’ 90d226c290 fix conflict
Signed-off-by: ‘hanzhixiao’ <‘709674996@qq.com’>
2023-07-13 18:21:42 +08:00
‘hanzhixiao’ 25eabde3f6 fix conflict
Signed-off-by: ‘hanzhixiao’ <‘709674996@qq.com’>
2023-07-13 18:20:11 +08:00
‘hanzhixiao’ 02e6b7ec18 fix conflict
Signed-off-by: ‘hanzhixiao’ <‘709674996@qq.com’>
2023-07-13 18:20:03 +08:00
‘hanzhixiao’ be7d785f1d fix conflict
Signed-off-by: ‘hanzhixiao’ <‘709674996@qq.com’>
2023-07-13 18:17:27 +08:00
Xinwei Xiong ccf2cdaab2 Merge pull request #540 from cubxxw/fix/copy
feat: add test file
2023-07-13 10:09:16 +00:00
Xinwei Xiong(cubxxw-openim) 99dc701ff6 feat: script and make build
Signed-off-by: Xinwei Xiong(cubxxw-openim) <3293172751nss@gmail.com>
2023-07-13 17:37:51 +08:00
Xinwei Xiong 8fbc7e8116 Merge pull request #539 from plutoyty/main
url to uri
2023-07-13 09:33:37 +00:00
pluto 4066726221 Merge branch 'OpenIMSDK:main' into main 2023-07-13 17:22:39 +08:00
withchao 53048951ec Merge pull request #538 from withchao/main
fix: minio auto make bucket
2023-07-13 09:19:30 +00:00
plutoyty 772cb859fa url to uri 2023-07-13 17:18:14 +08:00
withchao 81bcd86304 fix: minio auto make bucket 2023-07-13 17:10:48 +08:00
pluto b0b7d6fe7f Merge branch 'OpenIMSDK:main' into main 2023-07-13 17:08:00 +08:00
Xinwei Xiong(cubxxw-openim) 6ecf253ef6 feat: add copy
Signed-off-by: Xinwei Xiong(cubxxw-openim) <3293172751nss@gmail.com>
2023-07-13 17:07:45 +08:00
Xinwei Xiong(cubxxw-openim) fd3c19d6a5 feat: add test file
Signed-off-by: Xinwei Xiong(cubxxw-openim) <3293172751nss@gmail.com>
2023-07-13 17:07:45 +08:00
Gordon ce33b79915 fix: conflict resolve main (#537)
* statistics user register

* refactor: router change

* minio init

* UserRegisterCount

* push use local conn

* refactor: user pb update

* remove online push close grpc conn

* refactor: user pb update

* refactor:pb file

* msgs statistics

* msgs statistics

* revoke userID

* refactor: errcode update

* active user

* active user

* active user

* refactor: errcode update

* feat: conn update token

* active user

* active user

* feat: conn update token

* active user

* feat: conn update token

* feat: conn update token

* feat: conn update token

* add tx_oss cos

* active user

* active user

* group create

* group create

* feat: group notification show to conversation

* feat: group notification show to conversation

* group active

* user active

* sendNotificationWithName

* withname

* privateChat

* a2r call option

* grpc with detail return error

* change log error

* chain unary interceptor

* api nil slice map

* fix sync has read

* fix: text update

* fix: update add model

* set conversations update

* set privateChat

* fix: content update

* remove unuse rpc

* msgDestruct

* cron use rpc mw

* set IsMsgDestruct

* msg destruct

* msgDestruct

* s3 minio, cos, oss support

* feat: add implement of GetUsersOnlineStatus, #472 (#477)

* s3 minio, cos, oss support

* s3 route

* remove extendMsg code

* s3 route

* remove unuse code

* s3 pb

* s3 pb

* s3 pb

* s3 presigned put

* s3 presigned test

* s3 presigned test

* s3 presigned test

* s3 presigned test

* s3 presigned test

* s3 presigned test

* s3 presigned test

* s3 presigned test

* Update .gitignore (#482)

* s3 debug log

* s3 debug log

* cron add log and fix cron

* add log

* cron

* s3 config

* fix kick user bug

* s3 cos

* add kick log

* s3 cos test

* s3 cos test

* s3 cos test

* kick user log

* kickuserlog

* s3 cos copy

* s3 cos copy

* s3 url

* s3 url

* s3 AccessURL

* log

* s3 InitiateMultipartUpload add ExpireTime

* feat: regenerate pb file

* feat: regenerate pb file

* Revert "feat: regenerate pb file"

This reverts commit 434f22564a.

* Delete .idea directory

* feat: regenerate pb file

* fix: remove import C

* fix: add msg transfer main file

* fix: get user online status fix

---------

Co-authored-by: withchao <993506633@qq.com>
Co-authored-by: wangchuxiao <wangchuxiao97@outlook.com>
Co-authored-by: BanTanger <88583317+BanTanger@users.noreply.github.com>
Co-authored-by: withchao <48119764+withchao@users.noreply.github.com>
Co-authored-by: Alan <68671759+hanzhixiao@users.noreply.github.com>
2023-07-13 16:51:52 +08:00
pluto 2388f93cfb Merge branch 'OpenIMSDK:main' into main 2023-07-13 15:46:37 +08:00
WangchuXiao 4cacc3f621 fix bug: friend, args error (#534)
* fix bug: args error

* fix bug: args error

* fix bug: add friend need update both request

* fix bug: add friend need update both request
2023-07-13 15:26:25 +08:00
Gordon e5ab278be5 fix: get user online status #472 (#527)
* statistics user register

* refactor: router change

* minio init

* UserRegisterCount

* push use local conn

* refactor: user pb update

* remove online push close grpc conn

* refactor: user pb update

* refactor:pb file

* msgs statistics

* msgs statistics

* revoke userID

* refactor: errcode update

* active user

* active user

* active user

* refactor: errcode update

* feat: conn update token

* active user

* active user

* feat: conn update token

* active user

* feat: conn update token

* feat: conn update token

* feat: conn update token

* add tx_oss cos

* active user

* active user

* group create

* group create

* feat: group notification show to conversation

* feat: group notification show to conversation

* group active

* user active

* sendNotificationWithName

* withname

* privateChat

* a2r call option

* grpc with detail return error

* change log error

* chain unary interceptor

* api nil slice map

* fix sync has read

* fix: text update

* fix: update add model

* set conversations update

* set privateChat

* fix: content update

* remove unuse rpc

* msgDestruct

* cron use rpc mw

* set IsMsgDestruct

* msg destruct

* msgDestruct

* s3 minio, cos, oss support

* feat: add implement of GetUsersOnlineStatus, #472 (#477)

* s3 minio, cos, oss support

* s3 route

* remove extendMsg code

* s3 route

* remove unuse code

* s3 pb

* s3 pb

* s3 pb

* s3 presigned put

* s3 presigned test

* s3 presigned test

* s3 presigned test

* s3 presigned test

* s3 presigned test

* s3 presigned test

* s3 presigned test

* s3 presigned test

* Update .gitignore (#482)

* s3 debug log

* s3 debug log

* cron add log and fix cron

* add log

* cron

* s3 config

* fix kick user bug

* s3 cos

* add kick log

* s3 cos test

* s3 cos test

* s3 cos test

* kick user log

* kickuserlog

* s3 cos copy

* s3 cos copy

* s3 url

* s3 url

* s3 AccessURL

* log

* s3 InitiateMultipartUpload add ExpireTime

* feat: regenerate pb file

* feat: regenerate pb file

* Revert "feat: regenerate pb file"

This reverts commit 434f22564a.

* Delete .idea directory

* feat: regenerate pb file

* fix: remove import C

* fix: add msg transfer main file

* fix: get user online status fix

---------

Co-authored-by: withchao <993506633@qq.com>
Co-authored-by: wangchuxiao <wangchuxiao97@outlook.com>
Co-authored-by: BanTanger <88583317+BanTanger@users.noreply.github.com>
Co-authored-by: withchao <48119764+withchao@users.noreply.github.com>
Co-authored-by: Alan <68671759+hanzhixiao@users.noreply.github.com>
2023-07-13 15:17:05 +08:00
Alan 0b306d996d all back-office api (#533)
* fix conflict

Signed-off-by: ‘hanzhixiao’ <‘709674996@qq.com’>

* all Back-office management api

Signed-off-by: ‘hanzhixiao’ <‘709674996@qq.com’>

---------

Signed-off-by: ‘hanzhixiao’ <‘709674996@qq.com’>
Co-authored-by: ‘hanzhixiao’ <‘709674996@qq.com’>
2023-07-13 15:11:33 +08:00
pluto 5e92c76136 Merge branch 'OpenIMSDK:main' into main 2023-07-13 12:27:20 +08:00
pluto 058e2eee32 add MongoDB,Redis,Kafka retry mechanism (#518) 2023-07-13 12:26:09 +08:00
Xinwei Xiong 7bf8a898e2 feat: add scripts (#525) 2023-07-13 11:37:23 +08:00
pluto eb7953cacb cicd: update openim-ci.yml (#528) 2023-07-13 10:30:25 +08:00
pluto 59f948bde2 Merge branch 'OpenIMSDK:main' into main 2023-07-13 10:14:40 +08:00
skiffer-git b46f3410ad Add feature: Replace apiURL (in config.yaml) with an external IP address 2023-07-12 22:07:25 +08:00
skiffer-git 62cd1dace0 Merge remote-tracking branch 'origin/main' 2023-07-12 21:33:25 +08:00
skiffer-git 95ec99daf0 fix bug ContentType is wrong range for Check 2023-07-12 21:33:11 +08:00
pluto df38875d88 Merge branch 'OpenIMSDK:main' into main 2023-07-12 20:58:37 +08:00
Xinwei Xiong 135dc7b359 feat: add scripts (#515)
* feat: add scripts

Signed-off-by: Xinwei Xiong(cubxxw-openim) <3293172751nss@gmail.com>

* build: Infrastructure, openimv3.0.0

Signed-off-by: Xinwei Xiong(cubxxw-openim) <3293172751nss@gmail.com>

* feat: add code (#519)

---------

Signed-off-by: Xinwei Xiong(cubxxw-openim) <3293172751nss@gmail.com>
2023-07-12 20:46:34 +08:00
plutoyty d41f2a7aef Add retry mechanism to mongoDB, Redis, Kafka 2023-07-12 20:21:52 +08:00
plutoyty 40b26f9a2f Merge remote-tracking branch 'origin/main' into add-new-feature-#484 2023-07-12 19:29:12 +08:00
pluto 2cca8b8927 Merge branch 'OpenIMSDK:main' into main 2023-07-12 19:27:50 +08:00
Xinwei Xiong 1b5eb4a5c0 feat: add scripts (#514) 2023-07-12 19:21:55 +08:00
plutoyty 9ac47e3423 Merge remote-tracking branch 'origin/main' into add-new-feature-#484
# Conflicts:
#	pkg/common/db/unrelation/extend_msg.go
2023-07-12 19:16:48 +08:00
pluto 568e6a8e86 Merge branch 'OpenIMSDK:main' into main 2023-07-12 19:16:04 +08:00
plutoyty 35b1f75036 Add retry mechanism to mongoDB, Redis, Kafka 2023-07-12 19:15:39 +08:00
pluto 496d178313 Merge branch 'OpenIMSDK:main' into main 2023-07-12 15:34:47 +08:00
pluto 1fe6423593 Merge branch 'OpenIMSDK:main' into main 2023-07-12 15:28:38 +08:00
plutoyty a735a70a7b Remove .idea directory and add it to .gitignore 2023-07-12 12:05:32 +08:00
plutoyty 2f5bcf1cf7 For 'add database retry' add test
Signed-off-by: plutoyty <2631223275@qq.com>
2023-07-12 11:53:22 +08:00
plutoyty 6bc369ed00 For "add database retry" add test 2023-07-12 11:43:30 +08:00
plutoyty 66f6e3d604 Merge remote-tracking branch 'origin/main' into add-new-feature-#484 2023-07-12 11:39:28 +08:00
pluto 4d2bd1a1c5 Merge branch 'OpenIMSDK:main' into main 2023-07-12 11:37:54 +08:00
plutoyty 2693db218a For "add database retry" add test 2023-07-12 11:35:06 +08:00
pluto 51314729fc Merge branch 'OpenIMSDK:main' into main 2023-07-12 09:57:32 +08:00
杨腾宇 2b041d8f6a Add database retry 2023-07-11 17:34:39 +08:00
120 changed files with 3765 additions and 767 deletions
+31
View File
@@ -0,0 +1,31 @@
# Ignore files and directories starting with a dot
# Ignore specific files
.dockerignore
# Ignore build artifacts
_output/
logs/
# Ignore non-essential documentation
README.md
README-zh_CN.md
CONTRIBUTING.md
CHANGELOG/
# LICENSE
# Ignore testing and linting configuration
.golangci.yml
# Ignore deployment-related files
docker-compose.yaml
deployments/
# Ignore assets
assets/
# Ignore components
components/
# Ignore tools and scripts
.github/
+1
View File
@@ -1,4 +1,5 @@
USER=root USER=root
PASSWORD=openIM123 PASSWORD=openIM123
MINIO_ENDPOINT=http://127.0.0.1:10005 MINIO_ENDPOINT=http://127.0.0.1:10005
API_URL=http://127.0.0.1:10002/object/
DATA_DIR=./ DATA_DIR=./
+36
View File
@@ -0,0 +1,36 @@
name: OpenIM Build Docker Images
on:
push:
tags:
- v*
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
bin:
- ssserver
- sslocal
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Login to GitHub Container Registry
uses: docker/login-action@v2
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Docker metadata
id: metadata
uses: docker/metadata-action@v4
with:
images: ghcr.io/${{ github.repository_owner }}/openim-${{ matrix.bin }}
- name: Build and release Docker images
uses: docker/build-push-action@v3
with:
platforms: linux/386,linux/amd64,linux/arm64/v8
target: ${{ matrix.bin }}
tags: ${{ steps.metadata.outputs.tags }}
push: true
+1 -1
View File
@@ -45,7 +45,7 @@ jobs:
# args: --timeout=30m --config=/my/path/.golangci.yml --issues-exit-code=0 # args: --timeout=30m --config=/my/path/.golangci.yml --issues-exit-code=0
# Optional: show only new issues if it's a pull request. The default value is `false`. # Optional: show only new issues if it's a pull request. The default value is `false`.
only-new-issues: true # only-new-issues: true
# Optional:The mode to install golangci-lint. It can be 'binary' or 'goinstall'. # Optional:The mode to install golangci-lint. It can be 'binary' or 'goinstall'.
install-mode: "goinstall" install-mode: "goinstall"
+2 -20
View File
@@ -66,6 +66,7 @@ jobs:
run: | run: |
make format make format
echo "Run go format successfully" echo "Run go format successfully"
continue-on-error: true
# - name: Generate all necessary files, such as error code files # - name: Generate all necessary files, such as error code files
# run: | # run: |
@@ -82,7 +83,7 @@ jobs:
- name: Build source code for host platform - name: Build source code for host platform
run: | run: |
make multiarch make build
echo "Build source code for host platform successfully" echo "Build source code for host platform successfully"
# - name: Collect Test Coverage File # - name: Collect Test Coverage File
@@ -131,22 +132,3 @@ jobs:
# - name: Test docker image # - name: Test docker image
# run: | # run: |
# docker build -t openim:ci-build . # docker build -t openim:ci-build .
# goreleaser-test:
# runs-on: ubuntu-20.04
# steps:
# - name: Checkout
# uses: actions/checkout@v3
# with:
# fetch-depth: 0
# - name: Set up Go
# uses: actions/setup-go@v3
# with:
# go-version: ${{ env.GO_VERSION }}
# - name: Run GoReleaser
# uses: goreleaser/goreleaser-action@v4
# with:
# version: latest
# args: release --clean --skip-publish --snapshot
+37
View File
@@ -0,0 +1,37 @@
name: goreleaser
on:
push:
# run only against tags
tags:
- '*'
permissions:
contents: write
# packages: write
# issues: write
jobs:
goreleaser:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- run: git fetch --force --tags
- uses: actions/setup-go@v4
with:
go-version: stable
# More assembly might be required: Docker logins, GPG, etc. It all depends
# on your needs.
- uses: goreleaser/goreleaser-action@v4
with:
# either 'goreleaser' (default) or 'goreleaser-pro':
distribution: goreleaser
version: latest
args: release --clean
env:
GITHUB_TOKEN: ${{ secrets.BOT_GITHUB_TOKEN }}
# Your GoReleaser Pro key, if you are using the 'goreleaser-pro'
# distribution:
# GORELEASER_KEY: ${{ secrets.GORELEASER_KEY }}
+1 -2
View File
@@ -163,7 +163,6 @@ go.work
# User-specific stuff # User-specific stuff
.idea/ .idea/
.idea
.idea/**/workspace.xml .idea/**/workspace.xml
.idea/**/tasks.xml .idea/**/tasks.xml
.idea/**/usage.statistics.xml .idea/**/usage.statistics.xml
@@ -353,7 +352,6 @@ cscope.po.out
*testsdir *testsdir
*testsfile *testsfile
*testsfiles *testsfiles
*test
*testdir *testdir
*testfile *testfile
*testfiles *testfiles
@@ -391,3 +389,4 @@ Sessionx.vim
[._]*.un~ [._]*.un~
# End of https://www.toptal.com/developers/gitignore/api/go,git,vim,tags,test,emacs,backup,jetbrains # End of https://www.toptal.com/developers/gitignore/api/go,git,vim,tags,test,emacs,backup,jetbrains
.idea
+665 -57
View File
@@ -1,10 +1,27 @@
# Copyright © 2023 OpenIMSDK open source community. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This file contains all available configuration options
# with their default values.
# options for analysis running # options for analysis running
run: run:
# default concurrency is a available CPU number # default concurrency is a available CPU number
concurrency: 4 concurrency: 4
# timeout for analysis, e.g. 30s, 5m, default is 1m # timeout for analysis, e.g. 30s, 5m, default is 1m
timeout: 1m timeout: 5m
# exit code when at least one issue was found, default is 1 # exit code when at least one issue was found, default is 1
issues-exit-code: 1 issues-exit-code: 1
@@ -12,10 +29,36 @@ run:
# include test files or not, default is true # include test files or not, default is true
tests: true tests: true
# list of build tags, all linters use it. Default is empty list.
build-tags:
- mytag
# which dirs to skip: issues from them won't be reported;
# can use regexp here: generated.*, regexp is applied on full path;
# default value is empty list, but default dirs are skipped independently
# from this option's value (see skip-dirs-use-default).
# "/" will be replaced by current OS file path separator to properly work
# on Windows.
skip-dirs:
- util
- .*~
- api/swagger/docs
- server/docs
# default is true. Enables skipping of directories: # default is true. Enables skipping of directories:
# vendor$, third_party$, testdata$, examples$, Godeps$, builtin$ # vendor$, third_party$, testdata$, examples$, Godeps$, builtin$
skip-dirs-use-default: true skip-dirs-use-default: true
# which files to skip: they will be analyzed, but issues from them
# won't be reported. Default value is empty list, but there is
# no need to include all autogenerated files, we confidently recognize
# autogenerated files. If it's not please let us know.
# "/" will be replaced by current OS file path separator to properly work
# on Windows.
skip-files:
- ".*\\.my\\.go$"
- _test.go
# by default isn't set. If set we pass it to "go list -mod={option}". From "go help modules": # by default isn't set. If set we pass it to "go list -mod={option}". From "go help modules":
# If invoked with -mod=readonly, the go command is disallowed from the implicit # If invoked with -mod=readonly, the go command is disallowed from the implicit
# automatic updating of go.mod described above. Instead, it fails when any changes # automatic updating of go.mod described above. Instead, it fails when any changes
@@ -30,6 +73,7 @@ run:
# If false (default) - golangci-lint acquires file lock on start. # If false (default) - golangci-lint acquires file lock on start.
allow-parallel-runners: true allow-parallel-runners: true
# output configuration options # output configuration options
output: output:
# colored-line-number|line-number|json|tab|checkstyle|code-climate, default is "colored-line-number" # colored-line-number|line-number|json|tab|checkstyle|code-climate, default is "colored-line-number"
@@ -44,9 +88,26 @@ output:
# make issues output unique by line, default is true # make issues output unique by line, default is true
uniq-by-line: true uniq-by-line: true
# add a prefix to the output file references; default is no prefix
path-prefix: ""
# sorts results by: filepath, line and column
sort-results: true
# all available settings of specific linters # all available settings of specific linters
linters-settings: linters-settings:
bidichk:
# The following configurations check for all mentioned invisible unicode
# runes. It can be omitted because all runes are enabled by default.
left-to-right-embedding: true
right-to-left-embedding: true
pop-directional-formatting: true
left-to-right-override: true
right-to-left-override: true
left-to-right-isolate: true
right-to-left-isolate: true
first-strong-isolate: true
pop-directional-isolate: true
dogsled: dogsled:
# checks assignments with too many blank identifiers; default is 2 # checks assignments with too many blank identifiers; default is 2
max-blank-identifiers: 2 max-blank-identifiers: 2
@@ -62,47 +123,217 @@ linters-settings:
# default is false: such cases aren't reported by default. # default is false: such cases aren't reported by default.
check-blank: false check-blank: false
# [deprecated] comma-separated list of pairs of the form pkg:regex
# the regex is used to ignore names within pkg. (default "fmt:.*").
# see https://github.com/kisielk/errcheck#the-deprecated-method for details
#ignore: GenMarkdownTree,os:.*,BindPFlags,WriteTo,Help
#ignore: (os\.)?std(out|err)\..*|.*Close|.*Flush|os\.Remove(All)?|.*print(f|ln)?|os\.(Un)?Setenv
# path to a file containing a list of functions to exclude from checking # path to a file containing a list of functions to exclude from checking
# see https://github.com/kisielk/errcheck#excluding-functions for details # see https://github.com/kisielk/errcheck#excluding-functions for details
#exclude: errcheck.txt #exclude: errcheck.txt
errorlint:
# Check whether fmt.Errorf uses the %w verb for formatting errors. See the readme for caveats
errorf: true
# Check for plain type assertions and type switches
asserts: true
# Check for plain error comparisons
comparison: true
exhaustive: exhaustive:
# check switch statements in generated files also
check-generated: false
# indicates that switch statements are to be considered exhaustive if a # indicates that switch statements are to be considered exhaustive if a
# 'default' case is present, even if all enum members aren't listed in the # 'default' case is present, even if all enum members aren't listed in the
# switch # switch
default-signifies-exhaustive: false default-signifies-exhaustive: false
# enum members matching the supplied regex do not have to be listed in
# switch statements to satisfy exhaustiveness
ignore-enum-members: ""
# consider enums only in package scopes, not in inner scopes
package-scope-only: false
exhaustivestruct:
struct-patterns:
- '*.Test'
- '*.Test2'
- '*.Embedded'
- '*.External'
# forbidigo:
# # Forbid the following identifiers (identifiers are written using regexp):
# forbid:
# - ^print.*$
# - 'fmt\.Print.*'
# - fmt.Println.* # too much log noise
# - ginkgo\\.F.* # these are used just for local development
# # Exclude godoc examples from forbidigo checks. Default is true.
# exclude_godoc_examples: false
funlen: funlen:
lines: 150 lines: 150
statements: 40 statements: 50
gci:
# put imports beginning with prefix after 3rd-party packages;
# only support one prefix
# if not set, use goimports.local-prefixes
prefix: github.com/OpenIMSDK/OpenKF
gocognit: gocognit:
# minimal code complexity to report, 30 by default (but we recommend 10-20) # minimal code complexity to report, 30 by default (but we recommend 10-20)
min-complexity: 30 min-complexity: 30
nestif:
# minimal complexity of if statements to report, 5 by default
min-complexity: 4
goconst: goconst:
# minimal length of string constant, 3 by default # minimal length of string constant, 3 by default
min-len: 5 min-len: 3
# minimal occurrences count to trigger, 3 by default # minimal occurrences count to trigger, 3 by default
min-occurrences: 5 min-occurrences: 3
# ignore test files, false by default
ignore-tests: false
# look for existing constants matching the values, true by default
match-constant: true
# search also for duplicated numbers, false by default
numbers: false
# minimum value, only works with goconst.numbers, 3 by default
min: 3
# maximum value, only works with goconst.numbers, 3 by default
max: 3
# ignore when constant is not used as function argument, true by default
ignore-calls: true
gocritic:
# Which checks should be enabled; can't be combined with 'disabled-checks';
# See https://go-critic.github.io/overview#checks-overview
# To check which checks are enabled run `GL_DEBUG=gocritic golangci-lint run`
# By default list of stable checks is used.
enabled-checks:
#- rangeValCopy
- nestingreduce
- truncatecmp
- unnamedresult
- ruleguard
# Which checks should be disabled; can't be combined with 'enabled-checks'; default is empty
disabled-checks:
- regexpMust
- ifElseChain
#- exitAfterDefer
# Enable multiple checks by tags, run `GL_DEBUG=gocritic golangci-lint run` to see all tags and checks.
# Empty list by default. See https://github.com/go-critic/go-critic#usage -> section "Tags".
enabled-tags:
- performance
disabled-tags:
- experimental
# Settings passed to gocritic.
# The settings key is the name of a supported gocritic checker.
# The list of supported checkers can be find in https://go-critic.github.io/overview.
settings:
captLocal: # must be valid enabled check name
# whether to restrict checker to params only (default true)
paramsOnly: true
elseif:
# whether to skip balanced if-else pairs (default true)
skipBalanced: true
hugeParam:
# size in bytes that makes the warning trigger (default 80)
sizeThreshold: 80
nestingReduce:
# min number of statements inside a branch to trigger a warning (default 5)
bodyWidth: 5
rangeExprCopy:
# size in bytes that makes the warning trigger (default 512)
sizeThreshold: 512
# whether to check test functions (default true)
skipTestFuncs: true
rangeValCopy:
# size in bytes that makes the warning trigger (default 128)
sizeThreshold: 32
# whether to check test functions (default true)
skipTestFuncs: true
ruleguard:
# path to a gorules file for the ruleguard checker
rules: ''
truncateCmp:
# whether to skip int/uint/uintptr types (default true)
skipArchDependent: true
underef:
# whether to skip (*x).method() calls where x is a pointer receiver (default true)
skipRecvDeref: true
unnamedResult:
# whether to check exported functions
checkExported: true
gocyclo: gocyclo:
# minimal code complexity to report, 30 by default (but we recommend 10-20) # minimal code complexity to report, 30 by default (but we recommend 10-20)
min-complexity: 30 min-complexity: 30
cyclop:
# the maximal code complexity to report
max-complexity: 50
# the maximal average package complexity. If it's higher than 0.0 (float) the check is enabled (default 0.0)
package-average: 0.0
# should ignore tests (default false)
skip-tests: false
godot: godot:
# check all top-level comments, not only declarations # comments to be checked: `declarations`, `toplevel`, or `all`
check-all: false scope: declarations
# list of regexps for excluding particular comment lines from check
exclude:
# example: exclude comments which contain numbers
# - '[0-9]+'
# check that each sentence starts with a capital letter
capital: false
godox: godox:
# report any comments starting with keywords, this is useful for TODO or FIXME comments that # report any comments starting with keywords, this is useful for TODO or FIXME comments that
# might be left in the code accidentally and should be resolved before merging # might be left in the code accidentally and should be resolved before merging
keywords: # default keywords are TODO, BUG, and FIXME, these can be overwritten by this setting keywords: # default keywords are TODO, BUG, and FIXME, these can be overwritten by this setting
#- TODO
- BUG
- FIXME
#- NOTE
- OPTIMIZE # marks code that should be optimized before merging - OPTIMIZE # marks code that should be optimized before merging
- HACK # marks hack-arounds that should be removed before merging - HACK # marks hack-arounds that should be removed before merging
gofmt: gofmt:
# simplify code: gofmt with `-s` option, true by default # simplify code: gofmt with `-s` option, true by default
simplify: true simplify: true
gofumpt:
# Select the Go version to target. The default is `1.18`.
lang-version: "1.20"
# Choose whether or not to use the extra rules that are disabled
# by default
extra-rules: false
goheader:
values:
const:
# define here const type values in format k:v, for example:
# COMPANY: MY COMPANY
regexp:
# define here regexp type values, for example
# AUTHOR: .*@mycompany\.com
template: # |-
# put here copyright header template for source code files, for example:
# Note: {{ YEAR }} is a builtin value that returns the year relative to the current machine time.
#
# {{ AUTHOR }} {{ COMPANY }} {{ YEAR }}
# SPDX-License-Identifier: Apache-2.0
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
template-path:
# also as alternative of directive 'template' you may put the path to file with the template source
goimports: goimports:
# put imports beginning with prefix after 3rd-party packages; # put imports beginning with prefix after 3rd-party packages;
# it's a comma-separated list of prefixes # it's a comma-separated list of prefixes
local-prefixes: github.com/org/project local-prefixes: github.com/OpenIMSDK/OpenKF
golint: golint:
# minimal confidence for issues, default is 0.8 # minimal confidence for issues, default is 0.8
min-confidence: 0.9 min-confidence: 0.9
@@ -111,16 +342,91 @@ linters-settings:
mnd: mnd:
# the list of enabled checks, see https://github.com/tommy-muehle/go-mnd/#checks for description. # the list of enabled checks, see https://github.com/tommy-muehle/go-mnd/#checks for description.
checks: argument,case,condition,operation,return,assign checks: argument,case,condition,operation,return,assign
# ignored-numbers: 1000
# ignored-files: magic_.*.go
# ignored-functions: math.*
gomoddirectives:
# Allow local `replace` directives. Default is false.
replace-local: true
# List of allowed `replace` directives. Default is empty.
replace-allow-list:
- google.golang.org/grpc
# Allow to not explain why the version has been retracted in the `retract` directives. Default is false.
retract-allow-no-explanation: false
# Forbid the use of the `exclude` directives. Default is false.
exclude-forbidden: false
gomodguard: gomodguard:
allowed: allowed:
modules: # List of allowed modules modules:
- gorm.io/gen # List of allowed modules
- gorm.io/gorm
- gorm.io/driver/mysql
- k8s.io/klog
# - gopkg.in/yaml.v2 # - gopkg.in/yaml.v2
domains: # List of allowed module domains domains: # List of allowed module domains
# - golang.org - google.golang.org
- gopkg.in
- golang.org
- github.com
- go.uber.org
- go.etcd.io
blocked:
versions:
- github.com/MakeNowJust/heredoc:
version: "> 2.0.9"
reason: "use the latest version"
local_replace_directives: false # Set to true to raise lint issues for packages that are loaded from a local path via replace directive
gosec:
# To select a subset of rules to run.
# Available rules: https://github.com/securego/gosec#available-rules
includes:
- G401
- G306
- G101
# To specify a set of rules to explicitly exclude.
# Available rules: https://github.com/securego/gosec#available-rules
excludes:
- G204
# Exclude generated files
exclude-generated: true
# Filter out the issues with a lower severity than the given value. Valid options are: low, medium, high.
severity: "low"
# Filter out the issues with a lower confidence than the given value. Valid options are: low, medium, high.
confidence: "low"
# To specify the configuration of rules.
# The configuration of rules is not fully documented by gosec:
# https://github.com/securego/gosec#configuration
# https://github.com/securego/gosec/blob/569328eade2ccbad4ce2d0f21ee158ab5356a5cf/rules/rulelist.go#L60-L102
config:
G306: "0600"
G101:
pattern: "(?i)example"
ignore_entropy: false
entropy_threshold: "80.0"
per_char_threshold: "3.0"
truncate: "32"
gosimple:
# Select the Go version to target. The default is '1.13'.
go: "1.20"
# https://staticcheck.io/docs/options#checks
checks: [ "all" ]
govet: govet:
# report about shadowed variables # report about shadowed variables
check-shadowing: true check-shadowing: true
# settings per analyzer
settings:
printf: # analyzer name, run `go tool vet help` to see all analyzers
funcs: # run `go tool vet help printf` to see available settings for `printf` analyzer
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf
# enable or disable analyzers by name # enable or disable analyzers by name
enable: enable:
- atomicalign - atomicalign
@@ -128,17 +434,69 @@ linters-settings:
disable: disable:
- shadow - shadow
disable-all: false disable-all: false
depguard: # depguard:
list-type: blacklist # list-type: blacklist
include-go-root: false # include-go-root: false
packages: # packages:
packages-with-error-message: # - github.com/Sirupsen/logrus
# packages-with-error-message:
# # specify an error message to output when a blacklisted package is used
# - github.com/Sirupsen/logrus: "logging is allowed only by logutils.Log"
ifshort:
# Maximum length of variable declaration measured in number of lines, after which linter won't suggest using short syntax.
# Has higher priority than max-decl-chars.
max-decl-lines: 1
# Maximum length of variable declaration measured in number of characters, after which linter won't suggest using short syntax.
max-decl-chars: 30
importas:
# if set to `true`, force to use alias.
no-unaliased: true
# List of aliases
alias:
# using `servingv1` alias for `knative.dev/serving/pkg/apis/serving/v1` package
- pkg: knative.dev/serving/pkg/apis/serving/v1
alias: servingv1
# using `autoscalingv1alpha1` alias for `knative.dev/serving/pkg/apis/autoscaling/v1alpha1` package
- pkg: knative.dev/serving/pkg/apis/autoscaling/v1alpha1
alias: autoscalingv1alpha1
# You can specify the package path by regular expression,
# and alias by regular expression expansion syntax like below.
# see https://github.com/julz/importas#use-regular-expression for details
- pkg: knative.dev/serving/pkg/apis/(\w+)/(v[\w\d]+)
alias: $1$2
# using `jwt` alias for `github.com/appleboy/gin-jwt/v2` package
jwt: github.com/appleboy/gin-jwt/v2
ireturn:
# ireturn allows using `allow` and `reject` settings at the same time.
# Both settings are lists of the keywords and regular expressions matched to interface or package names.
# keywords:
# - `empty` for `interface{}`
# - `error` for errors
# - `stdlib` for standard library
# - `anon` for anonymous interfaces
# By default, it allows using errors, empty interfaces, anonymous interfaces,
# and interfaces provided by the standard library.
allow:
- anon
- error
- empty
- stdlib
# You can specify idiomatic endings for interface
- (or|er)$
# Reject patterns
reject:
- github.com\/user\/package\/v4\.Type
lll: lll:
# max line length, lines longer will be reported. Default is 120. # max line length, lines longer will be reported. Default is 120.
# '\t' is counted as 1 character by default, and can be changed with the tab-width option # '\t' is counted as 1 character by default, and can be changed with the tab-width option
line-length: 120 line-length: 240
# tab width in spaces. Default to 1. # tab width in spaces. Default to 1.
tab-width: 1 tab-width: 4
maligned: maligned:
# print struct with more effective memory layout or not, false by default # print struct with more effective memory layout or not, false by default
suggest-new: true suggest-new: true
@@ -152,6 +510,37 @@ linters-settings:
nakedret: nakedret:
# make an issue if func has more lines of code than this setting and it has naked returns; default is 30 # make an issue if func has more lines of code than this setting and it has naked returns; default is 30
max-func-lines: 30 max-func-lines: 30
nestif:
# minimal complexity of if statements to report, 5 by default
min-complexity: 4
nilnil:
# By default, nilnil checks all returned types below.
checked-types:
- ptr
- func
- iface
- map
- chan
nlreturn:
# size of the block (including return statement that is still "OK")
# so no return split required.
block-size: 1
nolintlint:
# Disable to ensure that all nolint directives actually have an effect. Default is true.
allow-unused: false
# Disable to ensure that nolint directives don't have a leading space. Default is true.
allow-leading-space: true
# Exclude following linters from requiring an explanation. Default is [].
allow-no-explanation: [ ]
# Enable to require an explanation of nonzero length after each nolint directive. Default is false.
require-explanation: false
# Enable to require nolint directives to mention the specific linter being suppressed. Default is false.
require-specific: true
prealloc: prealloc:
# XXX: we don't recommend using this linter before doing performance profiling. # XXX: we don't recommend using this linter before doing performance profiling.
# For most programs usage of prealloc will be a premature optimization. # For most programs usage of prealloc will be a premature optimization.
@@ -161,17 +550,97 @@ linters-settings:
simple: true simple: true
range-loops: true # Report preallocation suggestions on range loops, true by default range-loops: true # Report preallocation suggestions on range loops, true by default
for-loops: false # Report preallocation suggestions on for loops, false by default for-loops: false # Report preallocation suggestions on for loops, false by default
nolintlint:
# Enable to ensure that nolint directives are all used. Default is true. promlinter:
allow-unused: false # Promlinter cannot infer all metrics name in static analysis.
# Disable to ensure that nolint directives don't have a leading space. Default is true. # Enable strict mode will also include the errors caused by failing to parse the args.
allow-leading-space: true strict: false
# Exclude following linters from requiring an explanation. Default is []. # Please refer to https://github.com/yeya24/promlinter#usage for detailed usage.
allow-no-explanation: [] disabled-linters:
# Enable to require an explanation of nonzero length after each nolint directive. Default is false. # - "Help"
require-explanation: true # - "MetricUnits"
# Enable to require nolint directives to mention the specific linter being suppressed. Default is false. # - "Counter"
require-specific: true # - "HistogramSummaryReserved"
# - "MetricTypeInName"
# - "ReservedChars"
# - "CamelCase"
# - "lintUnitAbbreviations"
predeclared:
# comma-separated list of predeclared identifiers to not report on
ignore: ""
# include method names and field names (i.e., qualified names) in checks
q: false
rowserrcheck:
packages:
- github.com/jmoiron/sqlx
revive:
# see https://github.com/mgechev/revive#available-rules for details.
ignore-generated-header: true
severity: warning
rules:
- name: indent-error-flow
severity: warning
staticcheck:
# Select the Go version to target. The default is '1.13'.
go: "1.16"
# https://staticcheck.io/docs/options#checks
checks: [ "all" ]
stylecheck:
# Select the Go version to target. The default is '1.13'.
go: "1.16"
# https://staticcheck.io/docs/options#checks
checks: [ "all", "-ST1000", "-ST1003", "-ST1016", "-ST1020", "-ST1021", "-ST1022" ]
# https://staticcheck.io/docs/options#dot_import_whitelist
dot-import-whitelist:
- fmt
# https://staticcheck.io/docs/options#initialisms
initialisms: [ "ACL", "API", "ASCII", "CPU", "CSS", "DNS", "EOF", "GUID", "HTML", "HTTP", "HTTPS", "ID", "IP", "JSON", "QPS", "RAM", "RPC", "SLA", "SMTP", "SQL", "SSH", "TCP", "TLS", "TTL", "UDP", "UI", "GID", "UID", "UUID", "URI", "URL", "UTF8", "VM", "XML", "XMPP", "XSRF", "XSS" ]
# https://staticcheck.io/docs/options#http_status_code_whitelist
http-status-code-whitelist: [ "200", "400", "404", "500" ]
tagliatelle:
# check the struck tag name case
case:
# use the struct field name to check the name of the struct tag
use-field-name: true
rules:
# any struct tag type can be used.
# support string case: `camel`, `pascal`, `kebab`, `snake`, `goCamel`, `goPascal`, `goKebab`, `goSnake`, `upper`, `lower`
json: camel
yaml: camel
xml: camel
bson: camel
avro: snake
mapstructure: kebab
testpackage:
# regexp pattern to skip files
skip-regexp: (id|export|internal)_test\.go
thelper:
# The following configurations enable all checks. It can be omitted because all checks are enabled by default.
# You can enable only required checks deleting unnecessary checks.
test:
first: true
name: true
begin: true
benchmark:
first: true
name: true
begin: true
tb:
first: true
name: true
begin: true
tenv:
# The option `all` will run against whole test files (`_test.go`) regardless of method/function signatures.
# By default, only methods that take `*testing.T`, `*testing.B`, and `testing.TB` as arguments are checked.
all: false
unparam: unparam:
# Inspect exported functions, default is false. Set to true if no external program/library imports your code. # Inspect exported functions, default is false. Set to true if no external program/library imports your code.
# XXX: if you enable this setting, unparam will report a lot of false-positives in text editors: # XXX: if you enable this setting, unparam will report a lot of false-positives in text editors:
@@ -187,6 +656,24 @@ linters-settings:
whitespace: whitespace:
multi-if: false # Enforces newlines (or comments) after every multi-line if statement multi-if: false # Enforces newlines (or comments) after every multi-line if statement
multi-func: false # Enforces newlines (or comments) after every multi-line function signature multi-func: false # Enforces newlines (or comments) after every multi-line function signature
wrapcheck:
# An array of strings that specify substrings of signatures to ignore.
# If this set, it will override the default set of ignored signatures.
# See https://github.com/tomarrell/wrapcheck#configuration for more information.
ignoreSigs:
- .Errorf(
- errors.New(
- errors.Unwrap(
- .Wrap(
- .Wrapf(
- .WithMessage(
- .WithMessagef(
- .WithStack(
ignorePackageGlobs:
- encoding/*
- github.com/pkg/*
wsl: wsl:
# If true append is only allowed to be cuddled if appending value is # If true append is only allowed to be cuddled if appending value is
# matching variables, fields or types on line above. Default is true. # matching variables, fields or types on line above. Default is true.
@@ -194,6 +681,8 @@ linters-settings:
# Allow calls and assignments to be cuddled as long as the lines have any # Allow calls and assignments to be cuddled as long as the lines have any
# matching variables, fields or types. Default is true. # matching variables, fields or types. Default is true.
allow-assign-and-call: true allow-assign-and-call: true
# Allow assignments to be cuddled with anything. Default is false.
allow-assign-and-anything: false
# Allow multiline assignments to be cuddled. Default is true. # Allow multiline assignments to be cuddled. Default is true.
allow-multiline-assign: true allow-multiline-assign: true
# Allow declarations (var) to be cuddled. # Allow declarations (var) to be cuddled.
@@ -206,65 +695,181 @@ linters-settings:
force-err-cuddling: false force-err-cuddling: false
# Allow leading comments to be separated with empty liens # Allow leading comments to be separated with empty liens
allow-separated-leading-comment: false allow-separated-leading-comment: false
makezero:
# Allow only slices initialized with a length of zero. Default is false.
always: false
# The custom section can be used to define linter plugins to be loaded at runtime. See README doc
# for more info.
#custom:
# Each custom linter should have a unique name.
#example:
# The path to the plugin *.so. Can be absolute or local. Required for each custom linter
#path: /path/to/example.so
# The description of the linter. Optional, just for documentation purposes.
#description: This is an example usage of a plugin linter.
# Intended to point to the repo location of the linter. Optional, just for documentation purposes.
#original-url: github.com/golangci/example-linter
linters: linters:
# please, do not use `enable-all`: it's deprecated and will be removed soon. # please, do not use `enable-all`: it's deprecated and will be removed soon.
# inverted configuration with `enable-all` and `disable` is not scalable during updates of golangci-lint # inverted configuration with `enable-all` and `disable` is not scalable during updates of golangci-lint
# enable-all: true
disable-all: true disable-all: true
enable: enable:
- typecheck
- asciicheck
- bodyclose - bodyclose
- cyclop
- deadcode - deadcode
- depguard # - depguard
- dogsled - dogsled
- dupl - dupl
- durationcheck
- errcheck - errcheck
- errorlint
- exhaustive
- exportloopref
# - forbidigo
- funlen - funlen
- gochecknoinits # - gci
# - gochecknoinits
- gocognit
- goconst - goconst
- gocritic
- gocyclo - gocyclo
- godot
- godox
- gofmt - gofmt
- gofumpt
- goheader
- goimports - goimports
- golint - gomoddirectives
- gomodguard
- goprintffuncname - goprintffuncname
- gosec - gosec
- gosimple - gosimple
- govet - govet
- ifshort
- importas
- ineffassign - ineffassign
- interfacer
- lll - lll
- makezero
- misspell - misspell
- nakedret - nakedret
- nestif
- nilerr
- nlreturn
- noctx
- nolintlint - nolintlint
- paralleltest
- prealloc
- predeclared
- promlinter
- revive
- rowserrcheck - rowserrcheck
- scopelint - sqlclosecheck
- staticcheck - staticcheck
- structcheck - structcheck
- stylecheck - stylecheck
- typecheck - thelper
- tparallel
- unconvert - unconvert
- unparam - unparam
- unused - unused
- varcheck - varcheck
- wastedassign
- whitespace - whitespace
- asciicheck - bidichk
- gocognit - wastedassign
- godot - golint
- godox - execinquery
- maligned - nosprintfhostport
- nestif - grouper
- prealloc - decorder
- gomodguard - errchkjson
# don't enable: - maintidx
#- goerr113 #- containedctx
#- wsl #- tagliatelle
#- testpackage #- nonamedreturns
#- exhaustive (TODO: enable after next release; current release at time of writing is v1.27) #- nilnil
#- gochecknoglobals #- tenv
#- gomnd #- varnamelen
#- contextcheck
#- errname
#- ForceTypeAssert
#- nilassign
fast: false
issues: issues:
# List of regexps of issue texts to exclude, empty list by default.
# But independently from this option we use default exclude patterns,
# it can be disabled by `exclude-use-default: false`. To list all
# excluded by default patterns execute `golangci-lint run --help`
exclude:
- tools/.*
- test/.*
- third_party/.*
# Excluding configuration per-path, per-linter, per-text and per-source # Excluding configuration per-path, per-linter, per-text and per-source
exclude-rules:
- linters:
- golint
path: (internal/api/.*)\.go # exclude golint for internal/api/... files
- linters:
- revive
path: (log/.*)\.go
- linters:
- wrapcheck
path: (cmd/.*|pkg/.*)\.go
- linters:
- typecheck
#path: (pkg/storage/.*)\.go
path: (internal/.*|pkg/.*)\.go
- path: (cmd/.*|test/.*|tools/.*|internal/pump/pumps/.*)\.go
linters:
- forbidigo
- path: (cmd/[a-z]*/.*|store/.*)\.go
linters:
- dupl
- linters:
- gocritic
text: (hugeParam:|rangeValCopy:)
- path: (cmd/[a-z]*/.*)\.go
linters:
- lll
- path: (validator/.*|code/.*|validator/.*|watcher/watcher/.*)
linters:
- gochecknoinits
- path: (internal/.*/options|internal/pump|pkg/log/options.go|internal/authzserver|tools/)
linters:
- tagliatelle
- path: (pkg/app/.*)\.go
linters:
- deadcode
- unused
- varcheck
- forbidigo
# Exclude some staticcheck messages
- linters:
- staticcheck
text: "SA9003:"
# Exclude lll issues for long lines with go:generate
- linters:
- lll
source: "^//go:generate "
# Independently from option `exclude` we use default exclude patterns, # Independently from option `exclude` we use default exclude patterns,
# it can be disabled by this option. To list all # it can be disabled by this option. To list all
@@ -300,24 +905,27 @@ issues:
# Show only new issues created in git patch with set file path. # Show only new issues created in git patch with set file path.
#new-from-patch: path/to/patch/file #new-from-patch: path/to/patch/file
# Fix found issues (if it's supported by the linter)
fix: true
severity: severity:
# Default value is empty string. # Default value is empty string.
# Set the default severity for issues. If severity rules are defined and the issues # Set the default severity for issues. If severity rules are defined and the issues
# do not match or no severity is provided to the rule this will be the default # do not match or no severity is provided to the rule this will be the default
# severity applied. Severities should match the supported severity names of the # severity applied. Severities should match the supported severity names of the
# selected out format. # selected out format.
# - Code climate: https://docs.codeclimate.com/docs/issues#issue-severity # - Code climate: https://docs.codeclimate.com/docs/issues#issue-severity
# - Checkstyle: https://checkstyle.sourceforge.io/property_types.html#severity # - Checkstyle: https://checkstyle.sourceforge.io/property_types.html#severity
# - Github: https://help.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-error-message # - Github: https://help.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-error-message
default-severity: error default-severity: error
# The default value is false. # The default value is false.
# If set to true severity-rules regular expressions become case sensitive. # If set to true severity-rules regular expressions become case sensitive.
case-sensitive: false case-sensitive: false
# Default value is empty list. # Default value is empty list.
# When a list of severity rules are provided, severity information will be added to lint # When a list of severity rules are provided, severity information will be added to lint
# issues. Severity rules have the same filtering capability as exclude rules except you # issues. Severity rules have the same filtering capability as exclude rules except you
# are allowed to specify one matcher per severity rule. # are allowed to specify one matcher per severity rule.
# Only affects out formats that support setting severity information. # Only affects out formats that support setting severity information.
rules: rules:
+8 -75
View File
@@ -1,23 +1,9 @@
# Version logging for OpenIM # Version logging for OpenIM
**3.0 Major refactoring**
<!-- BEGIN MUNGE: GENERATED_TOC --> <!-- BEGIN MUNGE: GENERATED_TOC -->
- [Version logging for OpenIM](#version-logging-for-openim) - [Version logging for OpenIM](#version-logging-for-openim)
- [\[v3.0\]](#v30) - [Unreleased](#unreleased)
- [v3.0.0 - 2023-07-10](#v300---2023-07-10)
- [v2.9.0+1.839643f - 2023-07-07](#v2901839643f---2023-07-07)
- [v2.9.0+2.35f07fe - 2023-07-06](#v290235f07fe---2023-07-06)
- [v2.9.0+1.b5072b1 - 2023-07-05](#v2901b5072b1---2023-07-05)
- [v2.9.0+3.2667a3a - 2023-07-05](#v29032667a3a---2023-07-05)
- [v2.9.0+7.04818ca - 2023-07-05](#v290704818ca---2023-07-05)
- [v2.9.0 - 2023-07-04](#v290---2023-07-04) - [v2.9.0 - 2023-07-04](#v290---2023-07-04)
- [v0.0.0+1.3714b4f - 2023-07-04](#v00013714b4f---2023-07-04)
- [v0.0.0+635.8b92c90 - 2023-07-04](#v0006358b92c90---2023-07-04)
- [v0.0.0+1.78a6d03 - 2023-07-04](#v000178a6d03---2023-07-04)
- [v0.0.0+2.e057c18 - 2023-07-04](#v0002e057c18---2023-07-04)
- [v0.0.0+630.b55ac4a - 2023-07-04](#v000630b55ac4a---2023-07-04)
- [Reverts](#reverts) - [Reverts](#reverts)
- [Pull Requests](#pull-requests) - [Pull Requests](#pull-requests)
- [v2.3.3 - 2022-09-18](#v233---2022-09-18) - [v2.3.3 - 2022-09-18](#v233---2022-09-18)
@@ -32,17 +18,15 @@
- [v2.0.9 - 2022-04-29](#v209---2022-04-29) - [v2.0.9 - 2022-04-29](#v209---2022-04-29)
- [Reverts](#reverts-1) - [Reverts](#reverts-1)
- [Pull Requests](#pull-requests-2) - [Pull Requests](#pull-requests-2)
- [v2.0.8 - 2022-04-24](#v208---2022-04-24)
- [Pull Requests](#pull-requests-3)
- [v2.0.7 - 2022-04-08](#v207---2022-04-08) - [v2.0.7 - 2022-04-08](#v207---2022-04-08)
- [Pull Requests](#pull-requests-4) - [Pull Requests](#pull-requests-3)
- [v2.0.6 - 2022-04-01](#v206---2022-04-01) - [v2.0.6 - 2022-04-01](#v206---2022-04-01)
- [Pull Requests](#pull-requests-5) - [Pull Requests](#pull-requests-4)
- [v2.0.5 - 2022-03-24](#v205---2022-03-24) - [v2.0.5 - 2022-03-24](#v205---2022-03-24)
- [v2.04 - 2022-03-18](#v204---2022-03-18) - [v2.04 - 2022-03-18](#v204---2022-03-18)
- [v2.0.3 - 2022-03-11](#v203---2022-03-11) - [v2.0.3 - 2022-03-11](#v203---2022-03-11)
- [v2.0.2 - 2022-03-04](#v202---2022-03-04) - [v2.0.2 - 2022-03-04](#v202---2022-03-04)
- [Pull Requests](#pull-requests-6) - [Pull Requests](#pull-requests-5)
- [v2.0.1 - 2022-02-25](#v201---2022-02-25) - [v2.0.1 - 2022-02-25](#v201---2022-02-25)
- [v2.0.0 - 2022-02-23](#v200---2022-02-23) - [v2.0.0 - 2022-02-23](#v200---2022-02-23)
- [v1.0.7 - 2021-12-17](#v107---2021-12-17) - [v1.0.7 - 2021-12-17](#v107---2021-12-17)
@@ -54,48 +38,14 @@
- [v1.0.0 - 2021-10-28](#v100---2021-10-28) - [v1.0.0 - 2021-10-28](#v100---2021-10-28)
- [Reverts](#reverts-2) - [Reverts](#reverts-2)
<!-- END MUNGE: GENERATED_TOC --> <!-- END MUNGE: GENERATED_TOC -->
<a name="unreleased"></a> <a name="unreleased"></a>
## [v3.0] ## [Unreleased]
<a name="v3.0.0"></a>
## [v3.0.0] - 2023-07-10
<a name="v2.9.0+1.839643f"></a>
## [v2.9.0+1.839643f] - 2023-07-07
<a name="v2.9.0+2.35f07fe"></a>
## [v2.9.0+2.35f07fe] - 2023-07-06
<a name="v2.9.0+1.b5072b1"></a>
## [v2.9.0+1.b5072b1] - 2023-07-05
<a name="v2.9.0+3.2667a3a"></a>
## [v2.9.0+3.2667a3a] - 2023-07-05
<a name="v2.9.0+7.04818ca"></a>
## [v2.9.0+7.04818ca] - 2023-07-05
<a name="v2.9.0"></a> <a name="v2.9.0"></a>
## [v2.9.0] - 2023-07-04 ## [v2.9.0] - 2023-07-04
<a name="v0.0.0+1.3714b4f"></a>
## [v0.0.0+1.3714b4f] - 2023-07-04
<a name="v0.0.0+635.8b92c90"></a>
## [v0.0.0+635.8b92c90] - 2023-07-04
<a name="v0.0.0+1.78a6d03"></a>
## [v0.0.0+1.78a6d03] - 2023-07-04
<a name="v0.0.0+2.e057c18"></a>
## [v0.0.0+2.e057c18] - 2023-07-04
<a name="v0.0.0+630.b55ac4a"></a>
## [v0.0.0+630.b55ac4a] - 2023-07-04
### Reverts ### Reverts
- update etcd to v3.5.2 ([#206](https://github.com/OpenIMSDK/Open-IM-Server/issues/206)) - update etcd to v3.5.2 ([#206](https://github.com/OpenIMSDK/Open-IM-Server/issues/206))
@@ -144,11 +94,6 @@
- Merge branch 'tuoyun' - Merge branch 'tuoyun'
- Merge branch 'tuoyun' - Merge branch 'tuoyun'
- Merge branch 'tuoyun' - Merge branch 'tuoyun'
<a name="v2.0.8"></a>
## [v2.0.8] - 2022-04-24
### Pull Requests
- Merge branch 'tuoyun' - Merge branch 'tuoyun'
- Merge branch 'tuoyun' - Merge branch 'tuoyun'
@@ -216,19 +161,8 @@
- update - update
[Unreleased]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v3.0.0...HEAD [Unreleased]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.9.0...HEAD
[v3.0.0]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.9.0+1.839643f...v3.0.0 [v2.9.0]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.3.3...v2.9.0
[v2.9.0+1.839643f]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.9.0+2.35f07fe...v2.9.0+1.839643f
[v2.9.0+2.35f07fe]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.9.0+1.b5072b1...v2.9.0+2.35f07fe
[v2.9.0+1.b5072b1]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.9.0+3.2667a3a...v2.9.0+1.b5072b1
[v2.9.0+3.2667a3a]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.9.0+7.04818ca...v2.9.0+3.2667a3a
[v2.9.0+7.04818ca]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.9.0...v2.9.0+7.04818ca
[v2.9.0]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v0.0.0+1.3714b4f...v2.9.0
[v0.0.0+1.3714b4f]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v0.0.0+635.8b92c90...v0.0.0+1.3714b4f
[v0.0.0+635.8b92c90]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v0.0.0+1.78a6d03...v0.0.0+635.8b92c90
[v0.0.0+1.78a6d03]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v0.0.0+2.e057c18...v0.0.0+1.78a6d03
[v0.0.0+2.e057c18]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v0.0.0+630.b55ac4a...v0.0.0+2.e057c18
[v0.0.0+630.b55ac4a]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.3.3...v0.0.0+630.b55ac4a
[v2.3.3]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.3.2...v2.3.3 [v2.3.3]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.3.2...v2.3.3
[v2.3.2]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.3.0-rc2...v2.3.2 [v2.3.2]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.3.0-rc2...v2.3.2
[v2.3.0-rc2]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.3.0-rc1...v2.3.0-rc2 [v2.3.0-rc2]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.3.0-rc1...v2.3.0-rc2
@@ -237,8 +171,7 @@
[v2.2.0]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.1.0...v2.2.0 [v2.2.0]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.1.0...v2.2.0
[v2.1.0]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.0.10...v2.1.0 [v2.1.0]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.0.10...v2.1.0
[v2.0.10]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.0.9...v2.0.10 [v2.0.10]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.0.9...v2.0.10
[v2.0.9]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.0.8...v2.0.9 [v2.0.9]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.0.7...v2.0.9
[v2.0.8]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.0.7...v2.0.8
[v2.0.7]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.0.6...v2.0.7 [v2.0.7]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.0.6...v2.0.7
[v2.0.6]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.0.5...v2.0.6 [v2.0.6]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.0.5...v2.0.6
[v2.0.5]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.04...v2.0.5 [v2.0.5]: https://github.com/OpenIMSDK/Open-IM-Server/compare/v2.04...v2.0.5
+76 -1
View File
@@ -1,5 +1,16 @@
# Changelog # Changelog
- [Changelog](#changelog)
- [command](#command)
- [create next tag](#create-next-tag)
- [Release version logs](#release-version-logs)
- [Introduction](#introduction)
- [Naming Format](#naming-format)
- [Examples](#examples)
- [Version Modifiers](#version-modifiers)
- [Versioning Strategy](#versioning-strategy)
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
+ [https://github.com/OpenIMSDK/Open-IM-Server/releases](https://github.com/OpenIMSDK/Open-IM-Server/releases) + [https://github.com/OpenIMSDK/Open-IM-Server/releases](https://github.com/OpenIMSDK/Open-IM-Server/releases)
@@ -18,6 +29,14 @@ git commit -am "release 2.0.0"
git tag 2.0.0 git tag 2.0.0
``` ```
| Query | Description | Example |
| -------------- | ---------------------------------------------- | --------------------------- |
| `<old>..<new>` | Commit contained in `<new>` tags from `<old>`. | `$ git-chglog 1.0.0..2.0.0` |
| `<name>..` | Commit from the `<name>` to the latest tag. | `$ git-chglog 1.0.0..` |
| `..<name>` | Commit from the oldest tag to `<name>`. | `$ git-chglog ..2.0.0` |
| `<name>` | Commit contained in `<name>`. | `$ git-chglog 1.0.0` |
## Release version logs ## Release version logs
+ [OpenIM CHANGELOG-V1.0](CHANGELOG-1.0.md) + [OpenIM CHANGELOG-V1.0](CHANGELOG-1.0.md)
@@ -26,4 +45,60 @@ git tag 2.0.0
+ [OpenIM CHANGELOG-V2.2](CHANGELOG-2.2.md) + [OpenIM CHANGELOG-V2.2](CHANGELOG-2.2.md)
+ [OpenIM CHANGELOG-V2.3](CHANGELOG-2.3.md) + [OpenIM CHANGELOG-V2.3](CHANGELOG-2.3.md)
+ [OpenIM CHANGELOG-V2.9](CHANGELOG-2.9.md) + [OpenIM CHANGELOG-V2.9](CHANGELOG-2.9.md)
+ [OpenIM CHANGELOG-V3.0](CHANGELOG-3.0.md) + [OpenIM CHANGELOG-V3.0](CHANGELOG-3.0.md)
## Introduction
In both the open-source and closed-source software development communities, it is important to follow a consistent and understandable versioning scheme for software projects. This ensures clear communication of changes, compatibility, and stability across different releases. One widely adopted naming convention is the Semantic Versioning 2.0.0.
## Naming Format
The most common format for version numbers is as follows:
```
major.minor[.patch[.build]]
```
Let's take a closer look at each component:
1. **Major Version**: This is the first number in the versioning scheme and indicates significant changes that may not be backward compatible (specific to each project).
2. **Minor Version**: The second number signifies the addition of new features while maintaining backward compatibility.
3. **Patch Version**: The third number represents bug fixes or code optimizations without introducing new features. It is generally backward compatible.
4. **Build Version**: Typically an automatically generated number that increments with each code commit.
## Examples
Here are a few examples to illustrate the versioning scheme:
1. `1.0`
2. `2.14.0.1478`
3. `3.2.1 build-354`
## Version Modifiers
Apart from the version numbers, there are also version modifiers used to indicate specific stages or statuses of a release. Some commonly used version modifiers include:
- **alpha**: An internal testing version with numerous known bugs. It is primarily used for communication among developers.
- **beta**: A testing version released to enthusiastic users for feedback and bug detection.
- **rc (release candidate)**: The final testing version before the official release.
- **ga (general availability)**: The initial stable release for public distribution.
- **r/release** (or no modifier at all): The final released version intended for general users.
- **lts (long-term support)**: Designates a version that will receive extended maintenance and bug fixes for a specified number of years.
## Versioning Strategy
To effectively manage version numbers, the following strategies are commonly employed:
- The initial version of a project can be either `0.1` or `1.0`.
- When fixing bugs, the patch version is incremented by 1.
- When adding new features, the minor version is incremented by 1, and the patch version is reset to 0.
- In the case of significant modifications, the major version is incremented by 1.
- The build version is usually automatically generated by the compilation process and follows a defined format. It does not require manual control.
By adhering to these strategies and guidelines, developers can maintain consistency and clarity in versioning their software projects. This enables users and collaborators to understand the nature of changes between different releases and ensure compatibility with their systems.
(Note: Markdown formatting has been used to structure this article. Markdown is a lightweight markup language used to format text on platforms like GitHub.)
------
**Note**: The above article is based on the given content and aims to provide a Markdown-formatted English article explaining the naming conventions for software project versions, specifically focusing on the Semantic Versioning 2.0.0.
+16 -23
View File
@@ -1,38 +1,31 @@
# Build Stage
FROM golang as build FROM golang as build
# go mod Installation source, container environment variable addition will override the default variable value # Set go mod installation source and proxy
ENV GO111MODULE=on ARG GO111MODULE=on
ENV GOPROXY=https://goproxy.cn,direct ARG GOPROXY=https://goproxy.cn,direct
ENV GO111MODULE=$GO111MODULE
ENV GOPROXY=$GOPROXY
# Set up the working directory # Set up the working directory
WORKDIR /Open-IM-Server WORKDIR /Open-IM-Server
# add all files to the container
COPY . .
WORKDIR /Open-IM-Server/scripts # Copy all files to the container
RUN chmod +x *.sh ADD . .
RUN /bin/sh -c ./build_all_service.sh RUN /bin/sh -c "make build"
#Blank image Multi-Stage Build # Production Stage
FROM ubuntu FROM alpine
RUN rm -rf /var/lib/apt/lists/* RUN apk --no-cache add tzdata
RUN apt-get update && apt-get install apt-transport-https && apt-get install procps\
&&apt-get install net-tools
#Non-interactive operation
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get install -y vim curl tzdata gawk
#Time zone adjusted to East eighth District
RUN ln -fs /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && dpkg-reconfigure -f noninteractive tzdata
# Set directory to map logs, config files, scripts, and SDK
VOLUME ["/Open-IM-Server/logs", "/Open-IM-Server/config", "/Open-IM-Server/scripts", "/Open-IM-Server/db/sdk"]
#set directory to map logs,config file,scripts file. # Copy scripts and binary files to the production image
VOLUME ["/Open-IM-Server/logs","/Open-IM-Server/config","/Open-IM-Server/scripts","/Open-IM-Server/db/sdk"]
#Copy scripts files and binary files to the blank image
COPY --from=build /Open-IM-Server/scripts /Open-IM-Server/scripts COPY --from=build /Open-IM-Server/scripts /Open-IM-Server/scripts
COPY --from=build /Open-IM-Server/_output/bin/platforms/linux/amd64 /Open-IM-Server/_output/bin/platforms/linux/amd64 COPY --from=build /Open-IM-Server/_output/bin/platforms/linux/arm64 /Open-IM-Server/_output/bin/platforms/linux/arm64
WORKDIR /Open-IM-Server/scripts WORKDIR /Open-IM-Server/scripts
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main package main
import ( import (
+1 -1
View File
@@ -100,7 +100,7 @@ services:
openim_server: openim_server:
image: ghcr.io/openimsdk/openim-server:v3.0.0 image: ghcr.io/openimsdk/openim-server:v3.0.0-alpha.1
container_name: openim-server container_name: openim-server
volumes: volumes:
- ./logs:/Open-IM-Server/logs - ./logs:/Open-IM-Server/logs
+4
View File
@@ -9,6 +9,10 @@ source .env
echo $MINIO_ENDPOINT echo $MINIO_ENDPOINT
# Replace local IP address with the public IP address in .env file # Replace local IP address with the public IP address in .env file
if [ $API_URL == "http://127.0.0.1:10002/object/" ]; then
sed -i "s/127.0.0.1/${internet_ip}/" .env
fi
if [ $MINIO_ENDPOINT == "http://127.0.0.1:10005" ]; then if [ $MINIO_ENDPOINT == "http://127.0.0.1:10005" ]; then
sed -i "s/127.0.0.1/${internet_ip}/" .env sed -i "s/127.0.0.1/${internet_ip}/" .env
fi fi
+3
View File
@@ -132,3 +132,6 @@ func (o *GroupApi) GetSuperGroupsInfo(c *gin.Context) {
func (o *GroupApi) GroupCreateCount(c *gin.Context) { func (o *GroupApi) GroupCreateCount(c *gin.Context) {
a2r.Call(group.GroupClient.GroupCreateCount, o.Client, c) a2r.Call(group.GroupClient.GroupCreateCount, o.Client, c)
} }
func (o *GroupApi) GetGroups(c *gin.Context) {
a2r.Call(group.GroupClient.GetGroups, o.Client, c)
}
+111 -2
View File
@@ -15,6 +15,7 @@
package api package api
import ( import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/user"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10" "github.com/go-playground/validator/v10"
"github.com/mitchellh/mapstructure" "github.com/mitchellh/mapstructure"
@@ -204,7 +205,7 @@ func (m *MessageApi) SendMessage(c *gin.Context) {
if err := mapstructure.WeakDecode(params.Content, &data); err != nil { if err := mapstructure.WeakDecode(params.Content, &data); err != nil {
apiresp.GinError(c, errs.ErrArgs.Wrap(err.Error())) apiresp.GinError(c, errs.ErrArgs.Wrap(err.Error()))
return return
} else if err := m.validate.Struct(data); err != nil { } else if err := m.validate.Struct(params); err != nil {
apiresp.GinError(c, errs.ErrArgs.Wrap(err.Error())) apiresp.GinError(c, errs.ErrArgs.Wrap(err.Error()))
return return
} }
@@ -227,7 +228,107 @@ func (m *MessageApi) SendMessage(c *gin.Context) {
} }
func (m *MessageApi) ManagementBatchSendMsg(c *gin.Context) { func (m *MessageApi) ManagementBatchSendMsg(c *gin.Context) {
a2r.Call(msg.MsgClient.SendMsg, m.Client, c) params := apistruct.ManagementBatchSendMsgReq{}
resp := apistruct.ManagementBatchSendMsgResp{}
var msgSendFailedFlag bool
if err := c.BindJSON(&params); err != nil {
apiresp.GinError(c, errs.ErrArgs.WithDetail(err.Error()).Wrap())
return
}
if !tokenverify.IsAppManagerUid(c) {
apiresp.GinError(c, errs.ErrNoPermission.Wrap("only app manager can send message"))
return
}
var data interface{}
switch params.ContentType {
case constant.Text:
data = apistruct.TextElem{}
case constant.Picture:
data = apistruct.PictureElem{}
case constant.Voice:
data = apistruct.SoundElem{}
case constant.Video:
data = apistruct.VideoElem{}
case constant.File:
data = apistruct.FileElem{}
case constant.Custom:
data = apistruct.CustomElem{}
case constant.Revoke:
data = apistruct.RevokeElem{}
case constant.OANotification:
data = apistruct.OANotificationElem{}
params.SessionType = constant.NotificationChatType
case constant.CustomNotTriggerConversation:
data = apistruct.CustomElem{}
case constant.CustomOnlineOnly:
data = apistruct.CustomElem{}
default:
apiresp.GinError(c, errs.ErrArgs.WithDetail("not support err contentType").Wrap())
return
}
if err := mapstructure.WeakDecode(params.Content, &data); err != nil {
apiresp.GinError(c, errs.ErrArgs.Wrap(err.Error()))
return
} else if err := m.validate.Struct(params); err != nil {
apiresp.GinError(c, errs.ErrArgs.Wrap(err.Error()))
return
}
t := &apistruct.ManagementSendMsgReq{
SendID: params.SendID,
GroupID: params.GroupID,
SenderNickname: params.SenderNickname,
SenderFaceURL: params.SenderFaceURL,
SenderPlatformID: params.SenderPlatformID,
Content: params.Content,
ContentType: params.ContentType,
SessionType: params.SessionType,
IsOnlineOnly: params.IsOnlineOnly,
NotOfflinePush: params.NotOfflinePush,
OfflinePushInfo: params.OfflinePushInfo,
}
pbReq := m.newUserSendMsgReq(c, t)
var recvList []string
if params.IsSendAll {
req2 := &user.GetAllUserIDReq{}
resp2, err := m.Message.GetAllUserID(c, req2)
if err != nil {
apiresp.GinError(c, errs.ErrArgs.Wrap(err.Error()))
return
}
recvList = resp2.UserIDs
} else {
recvList = params.RecvIDList
}
for _, recvID := range recvList {
pbReq.MsgData.RecvID = recvID
rpcResp, err := m.Client.SendMsg(c, pbReq)
if err != nil {
resp.Data.FailedIDList = append(resp.Data.FailedIDList, recvID)
msgSendFailedFlag = true
continue
}
resp.Data.ResultList = append(resp.Data.ResultList, &apistruct.SingleReturnResult{
ServerMsgID: rpcResp.ServerMsgID,
ClientMsgID: rpcResp.ClientMsgID,
SendTime: rpcResp.SendTime,
RecvID: recvID,
})
}
var status int32
if msgSendFailedFlag {
status = constant.MsgSendFailed
} else {
status = constant.MsgSendSuccessed
}
_, err := m.Client.SetSendMsgStatus(c, &msg.SetSendMsgStatusReq{Status: status})
if err != nil {
apiresp.GinError(c, errs.ErrArgs.Wrap(err.Error()))
return
}
apiresp.GinSuccess(c, resp)
} }
func (m *MessageApi) CheckMsgIsSendSuccess(c *gin.Context) { func (m *MessageApi) CheckMsgIsSendSuccess(c *gin.Context) {
@@ -245,3 +346,11 @@ func (m *MessageApi) GetActiveUser(c *gin.Context) {
func (m *MessageApi) GetActiveGroup(c *gin.Context) { func (m *MessageApi) GetActiveGroup(c *gin.Context) {
a2r.Call(msg.MsgClient.GetActiveGroup, m.Client, c) a2r.Call(msg.MsgClient.GetActiveGroup, m.Client, c)
} }
func (m *MessageApi) SearchMsg(c *gin.Context) {
a2r.Call(msg.MsgClient.SearchMessage, m.Client, c)
}
func (m *MessageApi) ManagementMsg(c *gin.Context) {
a2r.Call(msg.MsgClient.ManageMsg, m.Client, c)
}
+5
View File
@@ -103,6 +103,7 @@ func NewGinRouter(discov discoveryregistry.SvcDiscoveryRegistry, rdb redis.Unive
groupRouterGroup.POST("/cancel_mute_group", g.CancelMuteGroup) groupRouterGroup.POST("/cancel_mute_group", g.CancelMuteGroup)
groupRouterGroup.POST("/set_group_member_info", g.SetGroupMemberInfo) groupRouterGroup.POST("/set_group_member_info", g.SetGroupMemberInfo)
groupRouterGroup.POST("/get_group_abstract_info", g.GetGroupAbstractInfo) groupRouterGroup.POST("/get_group_abstract_info", g.GetGroupAbstractInfo)
groupRouterGroup.POST("/get_groups", g.GetGroups)
} }
superGroupRouterGroup := r.Group("/super_group", ParseToken) superGroupRouterGroup := r.Group("/super_group", ParseToken)
{ {
@@ -124,6 +125,8 @@ func NewGinRouter(discov discoveryregistry.SvcDiscoveryRegistry, rdb redis.Unive
thirdGroup.POST("/fcm_update_token", t.FcmUpdateToken) thirdGroup.POST("/fcm_update_token", t.FcmUpdateToken)
thirdGroup.POST("/set_app_badge", t.SetAppBadge) thirdGroup.POST("/set_app_badge", t.SetAppBadge)
thirdGroup.POST("/minio_upload", t.MinioUploadFile)
objectGroup := r.Group("/object", ParseToken) objectGroup := r.Group("/object", ParseToken)
objectGroup.POST("/part_limit", t.PartLimit) objectGroup.POST("/part_limit", t.PartLimit)
@@ -138,10 +141,12 @@ func NewGinRouter(discov discoveryregistry.SvcDiscoveryRegistry, rdb redis.Unive
msgGroup := r.Group("/msg", ParseToken) msgGroup := r.Group("/msg", ParseToken)
{ {
msgGroup.POST("/newest_seq", m.GetSeq) msgGroup.POST("/newest_seq", m.GetSeq)
msgGroup.POST("/search_msg", m.SearchMsg)
msgGroup.POST("/send_msg", m.SendMessage) msgGroup.POST("/send_msg", m.SendMessage)
msgGroup.POST("/pull_msg_by_seq", m.PullMsgBySeqs) msgGroup.POST("/pull_msg_by_seq", m.PullMsgBySeqs)
msgGroup.POST("/revoke_msg", m.RevokeMsg) msgGroup.POST("/revoke_msg", m.RevokeMsg)
msgGroup.POST("/mark_msgs_as_read", m.MarkMsgsAsRead) msgGroup.POST("/mark_msgs_as_read", m.MarkMsgsAsRead)
msgGroup.POST("/manage_msg", m.ManagementMsg)
msgGroup.POST("/mark_conversation_as_read", m.MarkConversationAsRead) msgGroup.POST("/mark_conversation_as_read", m.MarkConversationAsRead)
msgGroup.POST("/get_conversations_has_read_and_max_seq", m.GetConversationsHasReadAndMaxSeq) msgGroup.POST("/get_conversations_has_read_and_max_seq", m.GetConversationsHasReadAndMaxSeq)
msgGroup.POST("/set_conversation_has_read_seq", m.SetConversationHasReadSeq) msgGroup.POST("/set_conversation_has_read_seq", m.SetConversationHasReadSeq)
+79 -4
View File
@@ -1,16 +1,37 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package api package api
import ( import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/apistruct"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/minio/minio-go/v7"
"math/rand"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/OpenIMSDK/Open-IM-Server/pkg/a2r" "github.com/OpenIMSDK/Open-IM-Server/pkg/a2r"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext"
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/third" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/third"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"github.com/gin-gonic/gin"
"math/rand"
"net/http"
"strconv"
) )
type ThirdApi rpcclient.Third type ThirdApi rpcclient.Third
@@ -82,3 +103,57 @@ func (o *ThirdApi) ObjectRedirect(c *gin.Context) {
} }
c.Redirect(http.StatusTemporaryRedirect, resp.Url) c.Redirect(http.StatusTemporaryRedirect, resp.Url)
} }
func (o *ThirdApi) MinioUploadFile(c *gin.Context) {
var (
req apistruct.MinioUploadFileReq
resp apistruct.MinioUploadFile
)
if err := c.Bind(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
switch req.FileType {
// videoType upload snapShot
case constant.VideoType:
snapShotFile, err := c.FormFile("snapShot")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "missing snapshot arg: " + err.Error()})
return
}
snapShotFileObj, err := snapShotFile.Open()
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
snapShotNewName, snapShotNewType := utils.GetNewFileNameAndContentType(snapShotFile.Filename, constant.ImageType)
_, err = o.MinioClient.PutObject(c, config.Config.Object.Minio.Bucket, snapShotNewName, snapShotFileObj, snapShotFile.Size, minio.PutObjectOptions{ContentType: snapShotNewType})
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
resp.SnapshotURL = config.Config.Object.Minio.Endpoint + "/" + config.Config.Object.Minio.Bucket + "/" + snapShotNewName
resp.SnapshotNewName = snapShotNewName
}
file, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "missing file arg: " + err.Error()})
return
}
fileObj, err := file.Open()
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "invalid file path" + err.Error()})
return
}
newName, newType := utils.GetNewFileNameAndContentType(file.Filename, req.FileType)
_, err = o.MinioClient.PutObject(c, config.Config.Object.Minio.Bucket, newName, fileObj, file.Size, minio.PutObjectOptions{ContentType: newType})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "upload file error" + err.Error()})
return
}
resp.NewName = newName
resp.URL = config.Config.Object.Minio.Endpoint + "/" + config.Config.Object.Minio.Bucket + "/" + newName
c.JSON(http.StatusOK, gin.H{"errCode": 0, "errMsg": "", "data": resp})
return
}
+1 -1
View File
@@ -107,7 +107,7 @@ func (u *UserApi) GetUsersOnlineStatus(c *gin.Context) {
} }
if !flag { if !flag {
res.UserID = v1 res.UserID = v1
res.Status = constant.OnlineStatus res.Status = constant.OfflineStatus
} }
respResult = append(respResult, res) respResult = append(respResult, res)
} }
+19 -4
View File
@@ -21,13 +21,14 @@ import (
"runtime/debug" "runtime/debug"
"sync" "sync"
"google.golang.org/protobuf/proto"
"github.com/OpenIMSDK/Open-IM-Server/pkg/apiresp" "github.com/OpenIMSDK/Open-IM-Server/pkg/apiresp"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"google.golang.org/protobuf/proto"
) )
var ErrConnClosed = errors.New("conn has closed") var ErrConnClosed = errors.New("conn has closed")
@@ -80,7 +81,14 @@ func newClient(ctx *UserConnContext, conn LongConn, isCompress bool) *Client {
ctx: ctx, ctx: ctx,
} }
} }
func (c *Client) ResetClient(ctx *UserConnContext, conn LongConn, isBackground, isCompress bool, longConnServer LongConnServer, token string) {
func (c *Client) ResetClient(
ctx *UserConnContext,
conn LongConn,
isBackground, isCompress bool,
longConnServer LongConnServer,
token string,
) {
c.w = new(sync.Mutex) c.w = new(sync.Mutex)
c.conn = conn c.conn = conn
c.PlatformID = utils.StringToInt(ctx.GetPlatformID()) c.PlatformID = utils.StringToInt(ctx.GetPlatformID())
@@ -161,7 +169,9 @@ func (c *Client) handleMessage(message []byte) error {
if binaryReq.SendID != c.UserID { if binaryReq.SendID != c.UserID {
return utils.Wrap(errors.New("exception conn userID not same to req userID"), binaryReq.String()) return utils.Wrap(errors.New("exception conn userID not same to req userID"), binaryReq.String())
} }
ctx := mcontext.WithMustInfoCtx([]string{binaryReq.OperationID, binaryReq.SendID, constant.PlatformIDToName(c.PlatformID), c.ctx.GetConnID()}) ctx := mcontext.WithMustInfoCtx(
[]string{binaryReq.OperationID, binaryReq.SendID, constant.PlatformIDToName(c.PlatformID), c.ctx.GetConnID()},
)
log.ZDebug(ctx, "gateway req message", "req", binaryReq.String()) log.ZDebug(ctx, "gateway req message", "req", binaryReq.String())
var messageErr error var messageErr error
var resp []byte var resp []byte
@@ -179,7 +189,12 @@ func (c *Client) handleMessage(message []byte) error {
case WsSetBackgroundStatus: case WsSetBackgroundStatus:
resp, messageErr = c.setAppBackgroundStatus(ctx, binaryReq) resp, messageErr = c.setAppBackgroundStatus(ctx, binaryReq)
default: default:
return fmt.Errorf("ReqIdentifier failed,sendID:%s,msgIncr:%s,reqIdentifier:%d", binaryReq.SendID, binaryReq.MsgIncr, binaryReq.ReqIdentifier) return fmt.Errorf(
"ReqIdentifier failed,sendID:%s,msgIncr:%s,reqIdentifier:%d",
binaryReq.SendID,
binaryReq.MsgIncr,
binaryReq.ReqIdentifier,
)
} }
c.replyMessage(ctx, &binaryReq, messageErr, resp) c.replyMessage(ctx, &binaryReq, messageErr, resp)
return nil return nil
+17 -2
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package msgtransfer package msgtransfer
import ( import (
@@ -58,8 +72,9 @@ func StartTransfer(prometheusPort int) error {
client.AddOption(mw.GrpcClient(), grpc.WithTransportCredentials(insecure.NewCredentials())) client.AddOption(mw.GrpcClient(), grpc.WithTransportCredentials(insecure.NewCredentials()))
msgModel := cache.NewMsgCacheModel(rdb) msgModel := cache.NewMsgCacheModel(rdb)
msgDocModel := unrelation.NewMsgMongoDriver(mongo.GetDatabase()) msgDocModel := unrelation.NewMsgMongoDriver(mongo.GetDatabase())
chatLogDatabase := controller.NewChatLogDatabase(relation.NewChatLogGorm(db)) msgMysModel := relation.NewChatLogGorm(db)
msgDatabase := controller.NewCommonMsgDatabase(msgDocModel, msgModel) chatLogDatabase := controller.NewChatLogDatabase(msgMysModel)
msgDatabase := controller.NewCommonMsgDatabase(msgDocModel, msgModel, msgMysModel)
conversationRpcClient := rpcclient.NewConversationRpcClient(client) conversationRpcClient := rpcclient.NewConversationRpcClient(client)
groupRpcClient := rpcclient.NewGroupRpcClient(client) groupRpcClient := rpcclient.NewGroupRpcClient(client)
msgTransfer := NewMsgTransfer(chatLogDatabase, msgDatabase, &conversationRpcClient, &groupRpcClient) msgTransfer := NewMsgTransfer(chatLogDatabase, msgDatabase, &conversationRpcClient, &groupRpcClient)
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package push package push
import ( import (
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package conversation package conversation
import ( import (
+1 -1
View File
@@ -246,7 +246,6 @@ func (s *friendServer) GetPaginationFriendsApplyTo(
req *pbfriend.GetPaginationFriendsApplyToReq, req *pbfriend.GetPaginationFriendsApplyToReq,
) (resp *pbfriend.GetPaginationFriendsApplyToResp, err error) { ) (resp *pbfriend.GetPaginationFriendsApplyToResp, err error) {
defer log.ZInfo(ctx, utils.GetFuncName()+" Return") defer log.ZInfo(ctx, utils.GetFuncName()+" Return")
resp = &pbfriend.GetPaginationFriendsApplyToResp{}
if err := s.userRpcClient.Access(ctx, req.UserID); err != nil { if err := s.userRpcClient.Access(ctx, req.UserID); err != nil {
return nil, err return nil, err
} }
@@ -255,6 +254,7 @@ func (s *friendServer) GetPaginationFriendsApplyTo(
if err != nil { if err != nil {
return nil, err return nil, err
} }
resp = &pbfriend.GetPaginationFriendsApplyToResp{}
resp.FriendRequests, err = convert.FriendRequestDB2Pb(ctx, friendRequests, s.userRpcClient.GetUsersInfoMap) resp.FriendRequests, err = convert.FriendRequestDB2Pb(ctx, friendRequests, s.userRpcClient.GetUsersInfoMap)
if err != nil { if err != nil {
return nil, err return nil, err
+2 -1
View File
@@ -16,9 +16,10 @@ package group
import ( import (
"context" "context"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext"
"time" "time"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext"
pbGroup "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/group" pbGroup "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/group"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
) )
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package group package group
import ( import (
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package group package group
import ( import (
+21
View File
@@ -124,3 +124,24 @@ func (m *msgServer) RevokeMsg(ctx context.Context, req *msg.RevokeMsgReq) (*msg.
} }
return &msg.RevokeMsgResp{}, nil return &msg.RevokeMsgResp{}, nil
} }
func (m *msgServer) ManageMsg(ctx context.Context, req *msg.ManageMsgReq) (*msg.ManageMsgResp, error) {
resp := &msg.ManageMsgResp{}
msgData := &sdkws.MsgData{
SendID: req.SendID,
RecvID: req.RecvID,
SessionType: req.SessionType,
GroupID: req.GroupID,
}
conversationID := utils.GetChatConversationIDByMsg(msgData)
revokeReq := &msg.RevokeMsgReq{
ConversationID: conversationID,
Seq: req.Seq,
UserID: req.SendID,
}
_, err := m.RevokeMsg(ctx, revokeReq)
if err != nil {
return nil, err
}
return resp, nil
}
+25 -3
View File
@@ -1,7 +1,24 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package msg package msg
import ( import (
"context" "context"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/relation"
"google.golang.org/grpc"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
@@ -13,7 +30,6 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/conversation" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/conversation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"google.golang.org/grpc"
) )
type MessageInterceptorChain []MessageInterceptorFunc type MessageInterceptorChain []MessageInterceptorFunc
@@ -60,11 +76,16 @@ func Start(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) e
} }
cacheModel := cache.NewMsgCacheModel(rdb) cacheModel := cache.NewMsgCacheModel(rdb)
msgDocModel := unrelation.NewMsgMongoDriver(mongo.GetDatabase()) msgDocModel := unrelation.NewMsgMongoDriver(mongo.GetDatabase())
msgDatabase := controller.NewCommonMsgDatabase(msgDocModel, cacheModel)
conversationClient := rpcclient.NewConversationRpcClient(client) conversationClient := rpcclient.NewConversationRpcClient(client)
userRpcClient := rpcclient.NewUserRpcClient(client) userRpcClient := rpcclient.NewUserRpcClient(client)
groupRpcClient := rpcclient.NewGroupRpcClient(client) groupRpcClient := rpcclient.NewGroupRpcClient(client)
friendRpcClient := rpcclient.NewFriendRpcClient(client) friendRpcClient := rpcclient.NewFriendRpcClient(client)
mysql, err := relation.NewGormDB()
if err != nil {
return err
}
msgMysModel := relation.NewChatLogGorm(mysql)
msgDatabase := controller.NewCommonMsgDatabase(msgDocModel, cacheModel, msgMysModel)
s := &msgServer{ s := &msgServer{
Conversation: &conversationClient, Conversation: &conversationClient,
User: &userRpcClient, User: &userRpcClient,
@@ -100,7 +121,8 @@ func (m *msgServer) initPrometheus() {
} }
func (m *msgServer) conversationAndGetRecvID(conversation *conversation.Conversation, userID string) (recvID string) { func (m *msgServer) conversationAndGetRecvID(conversation *conversation.Conversation, userID string) (recvID string) {
if conversation.ConversationType == constant.SingleChatType || conversation.ConversationType == constant.NotificationChatType { if conversation.ConversationType == constant.SingleChatType ||
conversation.ConversationType == constant.NotificationChatType {
if userID == conversation.OwnerUserID { if userID == conversation.OwnerUserID {
recvID = conversation.UserID recvID = conversation.UserID
} else { } else {
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package msg package msg
import ( import (
+49
View File
@@ -16,6 +16,8 @@ package msg
import ( import (
"context" "context"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/tokenverify" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/tokenverify"
@@ -102,3 +104,50 @@ func (m *msgServer) GetMaxSeq(ctx context.Context, req *sdkws.GetMaxSeqReq) (*sd
resp.MaxSeqs = maxSeqs resp.MaxSeqs = maxSeqs
return resp, nil return resp, nil
} }
func (m *msgServer) SearchMessage(ctx context.Context, req *msg.SearchMessageReq) (resp *msg.SearchMessageResp, err error) {
var chatLogs []*sdkws.MsgData
resp = &msg.SearchMessageResp{}
if chatLogs, err = m.MsgDatabase.SearchMessage(ctx, req); err != nil {
return nil, err
}
var num int
for _, chatLog := range chatLogs {
pbChatLog := &msg.ChatLog{}
utils.CopyStructFields(pbChatLog, chatLog)
pbChatLog.SendTime = chatLog.SendTime
pbChatLog.CreateTime = chatLog.CreateTime
if chatLog.SenderNickname == "" {
sendUser, err := m.User.GetUserInfo(ctx, chatLog.SendID)
if err != nil {
return nil, err
}
pbChatLog.SenderNickname = sendUser.Nickname
}
switch chatLog.SessionType {
case constant.SingleChatType:
recvUser, err := m.User.GetUserInfo(ctx, chatLog.RecvID)
if err != nil {
return nil, err
}
pbChatLog.SenderNickname = recvUser.Nickname
case constant.GroupChatType, constant.SuperGroupChatType:
group, err := m.Group.GetGroupInfo(ctx, chatLog.GroupID)
if err != nil {
return nil, err
}
pbChatLog.SenderFaceURL = group.FaceURL
pbChatLog.GroupMemberCount = group.MemberCount
pbChatLog.RecvID = group.GroupID
pbChatLog.GroupName = group.GroupName
pbChatLog.GroupOwner = group.OwnerUserID
pbChatLog.GroupType = group.GroupType
}
resp.ChatLogs = append(resp.ChatLogs, pbChatLog)
num++
}
resp.ChatLogsNum = int32(num)
return resp, nil
}
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package third package third
import ( import (
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package third package third
import ( import (
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package third package third
import ( import (
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package user package user
import ( import (
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tools package tools
import ( import (
+20 -2
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tools package tools
import ( import (
@@ -65,8 +79,12 @@ func InitMsgTool() (*MsgTool, error) {
} }
discov.AddOption(mw.GrpcClient(), grpc.WithTransportCredentials(insecure.NewCredentials())) discov.AddOption(mw.GrpcClient(), grpc.WithTransportCredentials(insecure.NewCredentials()))
userDB := relation.NewUserGorm(db) userDB := relation.NewUserGorm(db)
msgDatabase := controller.InitCommonMsgDatabase(rdb, mongo.GetDatabase()) msgDatabase := controller.InitCommonMsgDatabase(rdb, mongo.GetDatabase(), db)
userDatabase := controller.NewUserDatabase(userDB, cache.NewUserCacheRedis(rdb, relation.NewUserGorm(db), cache.GetDefaultOpt()), tx.NewGorm(db)) userDatabase := controller.NewUserDatabase(
userDB,
cache.NewUserCacheRedis(rdb, relation.NewUserGorm(db), cache.GetDefaultOpt()),
tx.NewGorm(db),
)
groupDatabase := controller.InitGroupDatabase(db, rdb, mongo.GetDatabase()) groupDatabase := controller.InitGroupDatabase(db, rdb, mongo.GetDatabase())
conversationDatabase := controller.NewConversationDatabase(relation.NewConversationGorm(db), cache.NewConversationRedis(rdb, cache.GetDefaultOpt(), relation.NewConversationGorm(db)), tx.NewGorm(db)) conversationDatabase := controller.NewConversationDatabase(relation.NewConversationGorm(db), cache.NewConversationRedis(rdb, cache.GetDefaultOpt(), relation.NewConversationGorm(db)), tx.NewGorm(db))
msgRpcClient := rpcclient.NewMessageRpcClient(discov) msgRpcClient := rpcclient.NewMessageRpcClient(discov)
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package apiresp package apiresp
type ApiFormat interface { type ApiFormat interface {
+1 -2
View File
@@ -47,8 +47,7 @@ type ForceLogoutReq struct {
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
} }
type ForceLogoutResp struct { type ForceLogoutResp struct{}
}
type ParseTokenReq struct { type ParseTokenReq struct {
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
+3 -6
View File
@@ -68,16 +68,14 @@ type SetConversationReq struct {
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
} }
type SetConversationResp struct { type SetConversationResp struct{}
}
type ModifyConversationFieldReq struct { type ModifyConversationFieldReq struct {
Conversation Conversation
FieldType int32 `json:"fieldType" binding:"required"` FieldType int32 `json:"fieldType" binding:"required"`
UserIDList []string `json:"userIDList" binding:"required"` UserIDList []string `json:"userIDList" binding:"required"`
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
} }
type ModifyConversationFieldResp struct { type ModifyConversationFieldResp struct{}
}
type BatchSetConversationsReq struct { type BatchSetConversationsReq struct {
Conversations []Conversation `json:"conversations" binding:"required"` Conversations []Conversation `json:"conversations" binding:"required"`
@@ -130,5 +128,4 @@ type SetRecvMsgOptReq struct {
NotificationType int32 `json:"notificationType"` NotificationType int32 `json:"notificationType"`
} }
type SetRecvMsgOptResp struct { type SetRecvMsgOptResp struct{}
}
+6 -11
View File
@@ -185,8 +185,7 @@ type AddBlacklistReq struct {
ToUserID string `json:"toUserID" binding:"required"` ToUserID string `json:"toUserID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"` FromUserID string `json:"fromUserID" binding:"required"`
} }
type AddBlacklistResp struct { type AddBlacklistResp struct{}
}
type ImportFriendReq struct { type ImportFriendReq struct {
FriendUserIDList []string `json:"friendUserIDList" binding:"required"` FriendUserIDList []string `json:"friendUserIDList" binding:"required"`
@@ -212,15 +211,13 @@ type AddFriendResponseReq struct {
HandleResult int32 `json:"flag" binding:"required,oneof=-1 0 1"` HandleResult int32 `json:"flag" binding:"required,oneof=-1 0 1"`
HandleMsg string `json:"handleMsg"` HandleMsg string `json:"handleMsg"`
} }
type AddFriendResponseResp struct { type AddFriendResponseResp struct{}
}
type DeleteFriendReq struct { type DeleteFriendReq struct {
ToUserID string `json:"toUserID" binding:"required"` ToUserID string `json:"toUserID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"` FromUserID string `json:"fromUserID" binding:"required"`
} }
type DeleteFriendResp struct { type DeleteFriendResp struct{}
}
type GetBlackListReq struct { type GetBlackListReq struct {
FromUserID string `json:"fromUserID" binding:"required"` FromUserID string `json:"fromUserID" binding:"required"`
@@ -234,15 +231,13 @@ type SetFriendRemarkReq struct {
FromUserID string `json:"fromUserID" binding:"required"` FromUserID string `json:"fromUserID" binding:"required"`
Remark string `json:"remark"` Remark string `json:"remark"`
} }
type SetFriendRemarkResp struct { type SetFriendRemarkResp struct{}
}
type RemoveBlacklistReq struct { type RemoveBlacklistReq struct {
ToUserID string `json:"toUserID" binding:"required"` ToUserID string `json:"toUserID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"` FromUserID string `json:"fromUserID" binding:"required"`
} }
type RemoveBlacklistResp struct { type RemoveBlacklistResp struct{}
}
type IsFriendReq struct { type IsFriendReq struct {
ToUserID string `json:"toUserID" binding:"required"` ToUserID string `json:"toUserID" binding:"required"`
@@ -266,7 +261,7 @@ type GetFriendListResp struct {
AddSource int32 `json:"addSource"` AddSource int32 `json:"addSource"`
OperatorUserID string `json:"operatorUserID"` OperatorUserID string `json:"operatorUserID"`
Ex string `json:"ex"` Ex string `json:"ex"`
//FriendUser *UserInfo // TODO // FriendUser *UserInfo // TODO
} }
type GetFriendApplyListReq struct { type GetFriendApplyListReq struct {
+17 -30
View File
@@ -25,8 +25,7 @@ type KickGroupMemberReq struct {
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
} }
type KickGroupMemberResp struct { type KickGroupMemberResp struct {
// UserIDResultList []*UserIDResult `json:"data"`
//UserIDResultList []*UserIDResult `json:"data"`
} }
type GetGroupMembersInfoReq struct { type GetGroupMembersInfoReq struct {
@@ -46,8 +45,7 @@ type InviteUserToGroupReq struct {
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
} }
type InviteUserToGroupResp struct { type InviteUserToGroupResp struct {
// UserIDResultList []*UserIDResult `json:"data"`
//UserIDResultList []*UserIDResult `json:"data"`
} }
type GetJoinedGroupListReq struct { type GetJoinedGroupListReq struct {
@@ -114,8 +112,9 @@ type CreateGroupResp struct {
type GetGroupApplicationListReq struct { type GetGroupApplicationListReq struct {
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"` //作为管理员或群主收到的 进群申请 FromUserID string `json:"fromUserID" binding:"required"` // 作为管理员或群主收到的 进群申请
} }
type GetGroupApplicationListResp struct { type GetGroupApplicationListResp struct {
GroupRequestList []*sdkws.GroupRequest `json:"-"` GroupRequestList []*sdkws.GroupRequest `json:"-"`
Data []map[string]interface{} `json:"data" swaggerignore:"true"` Data []map[string]interface{} `json:"data" swaggerignore:"true"`
@@ -163,12 +162,11 @@ type GetGroupInfoResp struct {
type ApplicationGroupResponseReq struct { type ApplicationGroupResponseReq struct {
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID" binding:"required"` GroupID string `json:"groupID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"` //application from FromUserID FromUserID string `json:"fromUserID" binding:"required"` // application from FromUserID
HandledMsg string `json:"handledMsg"` HandledMsg string `json:"handledMsg"`
HandleResult int32 `json:"handleResult" binding:"required,oneof=-1 1"` HandleResult int32 `json:"handleResult" binding:"required,oneof=-1 1"`
} }
type ApplicationGroupResponseResp struct { type ApplicationGroupResponseResp struct{}
}
type JoinGroupReq struct { type JoinGroupReq struct {
GroupID string `json:"groupID" binding:"required"` GroupID string `json:"groupID" binding:"required"`
@@ -178,15 +176,13 @@ type JoinGroupReq struct {
InviterUserID string `json:"inviterUserID"` InviterUserID string `json:"inviterUserID"`
} }
type JoinGroupResp struct { type JoinGroupResp struct{}
}
type QuitGroupReq struct { type QuitGroupReq struct {
GroupID string `json:"groupID" binding:"required"` GroupID string `json:"groupID" binding:"required"`
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
} }
type QuitGroupResp struct { type QuitGroupResp struct{}
}
type SetGroupInfoReq struct { type SetGroupInfoReq struct {
GroupID string `json:"groupID" binding:"required"` GroupID string `json:"groupID" binding:"required"`
@@ -201,8 +197,7 @@ type SetGroupInfoReq struct {
ApplyMemberFriend *int32 `json:"applyMemberFriend"` ApplyMemberFriend *int32 `json:"applyMemberFriend"`
} }
type SetGroupInfoResp struct { type SetGroupInfoResp struct{}
}
type TransferGroupOwnerReq struct { type TransferGroupOwnerReq struct {
GroupID string `json:"groupID" binding:"required"` GroupID string `json:"groupID" binding:"required"`
@@ -210,15 +205,13 @@ type TransferGroupOwnerReq struct {
NewOwnerUserID string `json:"newOwnerUserID" binding:"required"` NewOwnerUserID string `json:"newOwnerUserID" binding:"required"`
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
} }
type TransferGroupOwnerResp struct { type TransferGroupOwnerResp struct{}
}
type DismissGroupReq struct { type DismissGroupReq struct {
GroupID string `json:"groupID" binding:"required"` GroupID string `json:"groupID" binding:"required"`
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
} }
type DismissGroupResp struct { type DismissGroupResp struct{}
}
type MuteGroupMemberReq struct { type MuteGroupMemberReq struct {
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
@@ -226,30 +219,26 @@ type MuteGroupMemberReq struct {
UserID string `json:"userID" binding:"required"` UserID string `json:"userID" binding:"required"`
MutedSeconds uint32 `json:"mutedSeconds" binding:"required"` MutedSeconds uint32 `json:"mutedSeconds" binding:"required"`
} }
type MuteGroupMemberResp struct { type MuteGroupMemberResp struct{}
}
type CancelMuteGroupMemberReq struct { type CancelMuteGroupMemberReq struct {
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID" binding:"required"` GroupID string `json:"groupID" binding:"required"`
UserID string `json:"userID" binding:"required"` UserID string `json:"userID" binding:"required"`
} }
type CancelMuteGroupMemberResp struct { type CancelMuteGroupMemberResp struct{}
}
type MuteGroupReq struct { type MuteGroupReq struct {
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID" binding:"required"` GroupID string `json:"groupID" binding:"required"`
} }
type MuteGroupResp struct { type MuteGroupResp struct{}
}
type CancelMuteGroupReq struct { type CancelMuteGroupReq struct {
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID" binding:"required"` GroupID string `json:"groupID" binding:"required"`
} }
type CancelMuteGroupResp struct { type CancelMuteGroupResp struct{}
}
type SetGroupMemberNicknameReq struct { type SetGroupMemberNicknameReq struct {
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
@@ -258,8 +247,7 @@ type SetGroupMemberNicknameReq struct {
Nickname string `json:"nickname"` Nickname string `json:"nickname"`
} }
type SetGroupMemberNicknameResp struct { type SetGroupMemberNicknameResp struct{}
}
type SetGroupMemberInfoReq struct { type SetGroupMemberInfoReq struct {
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
@@ -271,8 +259,7 @@ type SetGroupMemberInfoReq struct {
Ex *string `json:"ex"` Ex *string `json:"ex"`
} }
type SetGroupMemberInfoResp struct { type SetGroupMemberInfoResp struct{}
}
type GetGroupAbstractInfoReq struct { type GetGroupAbstractInfoReq struct {
OperationID string `json:"operationID"` OperationID string `json:"operationID"`
+3 -4
View File
@@ -36,15 +36,14 @@ type GetUsersOnlineStatusReq struct {
UserIDList []string `json:"userIDList" binding:"required,lte=200"` UserIDList []string `json:"userIDList" binding:"required,lte=200"`
} }
type GetUsersOnlineStatusResp struct { type GetUsersOnlineStatusResp struct {
// SuccessResult []*msggateway.GetUsersOnlineStatusResp_SuccessResult `json:"data"`
//SuccessResult []*msggateway.GetUsersOnlineStatusResp_SuccessResult `json:"data"`
} }
type AccountCheckReq struct { type AccountCheckReq struct {
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
CheckUserIDList []string `json:"checkUserIDList" binding:"required,lte=100"` CheckUserIDList []string `json:"checkUserIDList" binding:"required,lte=100"`
} }
type AccountCheckResp struct { type AccountCheckResp struct{}
}
type ManagementSendMsg struct { type ManagementSendMsg struct {
SendID string `json:"sendID" binding:"required"` SendID string `json:"sendID" binding:"required"`
+49 -39
View File
@@ -1,32 +1,43 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package apistruct package apistruct
type DelMsgReq struct { type DelMsgReq struct {
UserID string `json:"userID,omitempty" binding:"required"` UserID string `json:"userID,omitempty" binding:"required"`
SeqList []uint32 `json:"seqList,omitempty" binding:"required"` SeqList []uint32 `json:"seqList,omitempty" binding:"required"`
OperationID string `json:"operationID,omitempty" binding:"required"` OperationID string `json:"operationID,omitempty" binding:"required"`
} }
type DelMsgResp struct { type DelMsgResp struct{}
}
type CleanUpMsgReq struct { type CleanUpMsgReq struct {
UserID string `json:"userID" binding:"required"` UserID string `json:"userID" binding:"required"`
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
} }
type CleanUpMsgResp struct { type CleanUpMsgResp struct{}
}
type DelSuperGroupMsgReq struct { type DelSuperGroupMsgReq struct {
UserID string `json:"userID" binding:"required"` UserID string `json:"userID" binding:"required"`
GroupID string `json:"groupID" binding:"required"` GroupID string `json:"groupID" binding:"required"`
SeqList []uint32 `json:"seqList,omitempty"` SeqList []uint32 `json:"seqList,omitempty"`
IsAllDelete bool `json:"isAllDelete"` IsAllDelete bool `json:"isAllDelete"`
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
} }
type DelSuperGroupMsgResp struct { type DelSuperGroupMsgResp struct{}
}
type MsgDeleteNotificationElem struct { type MsgDeleteNotificationElem struct {
GroupID string `json:"groupID"` GroupID string `json:"groupID"`
@@ -35,28 +46,27 @@ type MsgDeleteNotificationElem struct {
} }
type SetMsgMinSeqReq struct { type SetMsgMinSeqReq struct {
UserID string `json:"userID" binding:"required"` UserID string `json:"userID" binding:"required"`
GroupID string `json:"groupID"` GroupID string `json:"groupID"`
MinSeq uint32 `json:"minSeq" binding:"required"` MinSeq uint32 `json:"minSeq" binding:"required"`
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
} }
type SetMsgMinSeqResp struct { type SetMsgMinSeqResp struct{}
}
type PictureBaseInfo struct { type PictureBaseInfo struct {
UUID string `mapstructure:"uuid"` UUID string `mapstructure:"uuid"`
Type string `mapstructure:"type" ` Type string `mapstructure:"type"`
Size int64 `mapstructure:"size" ` Size int64 `mapstructure:"size"`
Width int32 `mapstructure:"width" ` Width int32 `mapstructure:"width"`
Height int32 `mapstructure:"height"` Height int32 `mapstructure:"height"`
Url string `mapstructure:"url" ` Url string `mapstructure:"url"`
} }
type PictureElem struct { type PictureElem struct {
SourcePath string `mapstructure:"sourcePath"` SourcePath string `mapstructure:"sourcePath"`
SourcePicture PictureBaseInfo `mapstructure:"sourcePicture"` SourcePicture PictureBaseInfo `mapstructure:"sourcePicture"`
BigPicture PictureBaseInfo `mapstructure:"bigPicture" ` BigPicture PictureBaseInfo `mapstructure:"bigPicture"`
SnapshotPicture PictureBaseInfo `mapstructure:"snapshotPicture"` SnapshotPicture PictureBaseInfo `mapstructure:"snapshotPicture"`
} }
type SoundElem struct { type SoundElem struct {
@@ -98,7 +108,7 @@ type LocationElem struct {
Latitude float64 `mapstructure:"latitude"` Latitude float64 `mapstructure:"latitude"`
} }
type CustomElem struct { type CustomElem struct {
Data string `mapstructure:"data" validate:"required"` Data string `mapstructure:"data" validate:"required"`
Description string `mapstructure:"description"` Description string `mapstructure:"description"`
Extension string `mapstructure:"extension"` Extension string `mapstructure:"extension"`
} }
@@ -110,23 +120,23 @@ type RevokeElem struct {
RevokeMsgClientID string `mapstructure:"revokeMsgClientID" validate:"required"` RevokeMsgClientID string `mapstructure:"revokeMsgClientID" validate:"required"`
} }
type OANotificationElem struct { type OANotificationElem struct {
NotificationName string `mapstructure:"notificationName" json:"notificationName" validate:"required"` NotificationName string `mapstructure:"notificationName" json:"notificationName" validate:"required"`
NotificationFaceURL string `mapstructure:"notificationFaceURL" json:"notificationFaceURL"` NotificationFaceURL string `mapstructure:"notificationFaceURL" json:"notificationFaceURL"`
NotificationType int32 `mapstructure:"notificationType" json:"notificationType" validate:"required"` NotificationType int32 `mapstructure:"notificationType" json:"notificationType" validate:"required"`
Text string `mapstructure:"text" json:"text" validate:"required"` Text string `mapstructure:"text" json:"text" validate:"required"`
Url string `mapstructure:"url" json:"url"` Url string `mapstructure:"url" json:"url"`
MixType int32 `mapstructure:"mixType" json:"mixType"` MixType int32 `mapstructure:"mixType" json:"mixType"`
PictureElem PictureElem `mapstructure:"pictureElem" json:"pictureElem"` PictureElem PictureElem `mapstructure:"pictureElem" json:"pictureElem"`
SoundElem SoundElem `mapstructure:"soundElem" json:"soundElem"` SoundElem SoundElem `mapstructure:"soundElem" json:"soundElem"`
VideoElem VideoElem `mapstructure:"videoElem" json:"videoElem"` VideoElem VideoElem `mapstructure:"videoElem" json:"videoElem"`
FileElem FileElem `mapstructure:"fileElem" json:"fileElem"` FileElem FileElem `mapstructure:"fileElem" json:"fileElem"`
Ex string `mapstructure:"ex" json:"ex"` Ex string `mapstructure:"ex" json:"ex"`
} }
type MessageRevoked struct { type MessageRevoked struct {
RevokerID string `mapstructure:"revokerID" json:"revokerID" validate:"required"` RevokerID string `mapstructure:"revokerID" json:"revokerID" validate:"required"`
RevokerRole int32 `mapstructure:"revokerRole" json:"revokerRole" validate:"required"` RevokerRole int32 `mapstructure:"revokerRole" json:"revokerRole" validate:"required"`
ClientMsgID string `mapstructure:"clientMsgID" json:"clientMsgID" validate:"required"` ClientMsgID string `mapstructure:"clientMsgID" json:"clientMsgID" validate:"required"`
RevokerNickname string `mapstructure:"revokerNickname" json:"revokerNickname"` RevokerNickname string `mapstructure:"revokerNickname" json:"revokerNickname"`
SessionType int32 `mapstructure:"sessionType" json:"sessionType" validate:"required"` SessionType int32 `mapstructure:"sessionType" json:"sessionType" validate:"required"`
Seq uint32 `mapstructure:"seq" json:"seq" validate:"required"` Seq uint32 `mapstructure:"seq" json:"seq" validate:"required"`
} }
+5 -8
View File
@@ -58,8 +58,7 @@ type UploadUpdateAppReq struct {
UpdateLog string `form:"updateLog" binding:"required"` UpdateLog string `form:"updateLog" binding:"required"`
} }
type UploadUpdateAppResp struct { type UploadUpdateAppResp struct{}
}
type GetDownloadURLReq struct { type GetDownloadURLReq struct {
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
@@ -111,21 +110,19 @@ type GetRTCInvitationInfoStartAppResp struct {
} }
/** /**
* FCM第三方上报Token * FCM第三方上报Token.
*/ */
type FcmUpdateTokenReq struct { type FcmUpdateTokenReq struct {
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
Platform int `json:"platform" binding:"required,min=1,max=2"` //only for ios + android Platform int `json:"platform" binding:"required,min=1,max=2"` // only for ios + android
FcmToken string `json:"fcmToken" binding:"required"` FcmToken string `json:"fcmToken" binding:"required"`
} }
type FcmUpdateTokenResp struct { type FcmUpdateTokenResp struct{}
}
type SetAppBadgeReq struct { type SetAppBadgeReq struct {
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"` FromUserID string `json:"fromUserID" binding:"required"`
AppUnreadCount int32 `json:"appUnreadCount"` AppUnreadCount int32 `json:"appUnreadCount"`
} }
type SetAppBadgeResp struct { type SetAppBadgeResp struct{}
}
+1 -1
View File
@@ -16,7 +16,7 @@ package callbackstruct
type CallbackUserOnlineReq struct { type CallbackUserOnlineReq struct {
UserStatusCallbackReq UserStatusCallbackReq
//Token string `json:"token"` // Token string `json:"token"`
Seq int64 `json:"seq"` Seq int64 `json:"seq"`
IsAppBackground bool `json:"isAppBackground"` IsAppBackground bool `json:"isAppBackground"`
ConnID string `json:"connID"` ConnID string `json:"connID"`
+21 -3
View File
@@ -1,12 +1,27 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd package cmd
import ( import (
"errors" "errors"
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
"github.com/OpenIMSDK/Open-IM-Server/pkg/startrpc"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"google.golang.org/grpc" "google.golang.org/grpc"
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
"github.com/OpenIMSDK/Open-IM-Server/pkg/startrpc"
) )
type RpcCmd struct { type RpcCmd struct {
@@ -26,7 +41,10 @@ func (a *RpcCmd) Exec() error {
return a.Execute() return a.Execute()
} }
func (a *RpcCmd) StartSvr(name string, rpcFn func(discov discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) error) error { func (a *RpcCmd) StartSvr(
name string,
rpcFn func(discov discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) error,
) error {
if a.GetPortFlag() == 0 { if a.GetPortFlag() == 0 {
return errors.New("port is required") return errors.New("port is required")
} }
+65 -61
View File
@@ -17,20 +17,21 @@ package constant
const ( const (
///ContentType ///ContentType
//UserRelated //UserRelated.
Text = 101 ContentTypeBegin = 100
Picture = 102 Text = 101
Voice = 103 Picture = 102
Video = 104 Voice = 103
File = 105 Video = 104
AtText = 106 File = 105
Merger = 107 AtText = 106
Card = 108 Merger = 107
Location = 109 Card = 108
Custom = 110 Location = 109
Revoke = 111 Custom = 110
Typing = 113 Revoke = 111
Quote = 114 Typing = 113
Quote = 114
AdvancedText = 117 AdvancedText = 117
@@ -44,23 +45,23 @@ const (
SignalMsg = 202 SignalMsg = 202
CustomNotification = 203 CustomNotification = 203
//SysRelated //SysRelated.
NotificationBegin = 1000 NotificationBegin = 1000
FriendApplicationApprovedNotification = 1201 //add_friend_response FriendApplicationApprovedNotification = 1201 // add_friend_response
FriendApplicationRejectedNotification = 1202 //add_friend_response FriendApplicationRejectedNotification = 1202 // add_friend_response
FriendApplicationNotification = 1203 //add_friend FriendApplicationNotification = 1203 // add_friend
FriendAddedNotification = 1204 FriendAddedNotification = 1204
FriendDeletedNotification = 1205 //delete_friend FriendDeletedNotification = 1205 // delete_friend
FriendRemarkSetNotification = 1206 //set_friend_remark? FriendRemarkSetNotification = 1206 // set_friend_remark?
BlackAddedNotification = 1207 //add_black BlackAddedNotification = 1207 // add_black
BlackDeletedNotification = 1208 //remove_black BlackDeletedNotification = 1208 // remove_black
FriendInfoUpdatedNotification = 1209 FriendInfoUpdatedNotification = 1209
ConversationChangeNotification = 1300 // change conversation opt ConversationChangeNotification = 1300 // change conversation opt
UserNotificationBegin = 1301 UserNotificationBegin = 1301
UserInfoUpdatedNotification = 1303 //SetSelfInfoTip = 204 UserInfoUpdatedNotification = 1303 // SetSelfInfoTip = 204
UserNotificationEnd = 1399 UserNotificationEnd = 1399
OANotification = 1400 OANotification = 1400
@@ -112,37 +113,37 @@ const (
NotificationEnd = 5000 NotificationEnd = 5000
//status //status.
MsgNormal = 1 MsgNormal = 1
MsgDeleted = 4 MsgDeleted = 4
//MsgFrom //MsgFrom.
UserMsgType = 100 UserMsgType = 100
SysMsgType = 200 SysMsgType = 200
//SessionType //SessionType.
SingleChatType = 1 SingleChatType = 1
GroupChatType = 2 GroupChatType = 2
SuperGroupChatType = 3 SuperGroupChatType = 3
NotificationChatType = 4 NotificationChatType = 4
//token //token.
NormalToken = 0 NormalToken = 0
InValidToken = 1 InValidToken = 1
KickedToken = 2 KickedToken = 2
ExpiredToken = 3 ExpiredToken = 3
//MultiTerminalLogin //MultiTerminalLogin.
DefalutNotKick = 0 DefalutNotKick = 0
//Full-end login, but the same end is mutually exclusive //Full-end login, but the same end is mutually exclusive.
AllLoginButSameTermKick = 1 AllLoginButSameTermKick = 1
//Only one of the endpoints can log in //Only one of the endpoints can log in.
SingleTerminalLogin = 2 SingleTerminalLogin = 2
//The web side can be online at the same time, and the other side can only log in at one end //The web side can be online at the same time, and the other side can only log in at one end.
WebAndOther = 3 WebAndOther = 3
// The PC side is mutually exclusive, and the mobile side is mutually exclusive, but the web side can be online at // The PC side is mutually exclusive, and the mobile side is mutually exclusive, but the web side can be online at
// the same time // the same time.
PcMobileAndWeb = 4 PcMobileAndWeb = 4
//The PC terminal can be online at the same time,but other terminal only one of the endpoints can login //The PC terminal can be online at the same time,but other terminal only one of the endpoints can login.
PCAndOther = 5 PCAndOther = 5
OnlineStatus = "online" OnlineStatus = "online"
@@ -150,12 +151,12 @@ const (
Registered = "registered" Registered = "registered"
UnRegistered = "unregistered" UnRegistered = "unregistered"
//MsgReceiveOpt //MsgReceiveOpt.
ReceiveMessage = 0 ReceiveMessage = 0
NotReceiveMessage = 1 NotReceiveMessage = 1
ReceiveNotNotifyMessage = 2 ReceiveNotNotifyMessage = 2
//OptionsKey //OptionsKey.
IsHistory = "history" IsHistory = "history"
IsPersistent = "persistent" IsPersistent = "persistent"
IsOfflinePush = "offlinePush" IsOfflinePush = "offlinePush"
@@ -169,13 +170,13 @@ const (
IsNotNotification = "isNotNotification" IsNotNotification = "isNotNotification"
IsSendMsg = "isSendMsg" IsSendMsg = "isSendMsg"
//GroupStatus //GroupStatus.
GroupOk = 0 GroupOk = 0
GroupBanChat = 1 GroupBanChat = 1
GroupStatusDismissed = 2 GroupStatusDismissed = 2
GroupStatusMuted = 3 GroupStatusMuted = 3
//GroupType //GroupType.
NormalGroup = 0 NormalGroup = 0
SuperGroup = 1 SuperGroup = 1
WorkingGroup = 2 WorkingGroup = 2
@@ -183,19 +184,19 @@ const (
GroupBaned = 3 GroupBaned = 3
GroupBanPrivateChat = 4 GroupBanPrivateChat = 4
//UserJoinGroupSource //UserJoinGroupSource.
JoinByAdmin = 1 JoinByAdmin = 1
JoinByInvitation = 2 JoinByInvitation = 2
JoinBySearch = 3 JoinBySearch = 3
JoinByQRCode = 4 JoinByQRCode = 4
//Minio //Minio.
MinioDurationTimes = 3600 MinioDurationTimes = 3600
//Aws //Aws.
AwsDurationTimes = 3600 AwsDurationTimes = 3600
//callbackCommand //callbackCommand.
CallbackBeforeSendSingleMsgCommand = "callbackBeforeSendSingleMsgCommand" CallbackBeforeSendSingleMsgCommand = "callbackBeforeSendSingleMsgCommand"
CallbackAfterSendSingleMsgCommand = "callbackAfterSendSingleMsgCommand" CallbackAfterSendSingleMsgCommand = "callbackAfterSendSingleMsgCommand"
CallbackBeforeSendGroupMsgCommand = "callbackBeforeSendGroupMsgCommand" CallbackBeforeSendGroupMsgCommand = "callbackBeforeSendGroupMsgCommand"
@@ -216,19 +217,19 @@ const (
CallbackGetMessageListReactionExtensionsCommand = "callbackGetMessageListReactionExtensionsCommand" CallbackGetMessageListReactionExtensionsCommand = "callbackGetMessageListReactionExtensionsCommand"
CallbackAddMessageListReactionExtensionsCommand = "callbackAddMessageListReactionExtensionsCommand" CallbackAddMessageListReactionExtensionsCommand = "callbackAddMessageListReactionExtensionsCommand"
//callback actionCode //callback actionCode.
ActionAllow = 0 ActionAllow = 0
ActionForbidden = 1 ActionForbidden = 1
//callback callbackHandleCode //callback callbackHandleCode.
CallbackHandleSuccess = 0 CallbackHandleSuccess = 0
CallbackHandleFailed = 1 CallbackHandleFailed = 1
// minioUpload // minioUpload.
OtherType = 1 OtherType = 1
VideoType = 2 VideoType = 2
ImageType = 3 ImageType = 3
// sendMsgStaus // sendMsgStaus.
MsgStatusNotExist = 0 MsgStatusNotExist = 0
MsgIsSending = 1 MsgIsSending = 1
MsgSendSuccessed = 2 MsgSendSuccessed = 2
@@ -290,32 +291,35 @@ const (
GroupResponseAgree = 1 GroupResponseAgree = 1
GroupResponseRefuse = -1 GroupResponseRefuse = -1
FriendResponseAgree = 1 FriendResponseNotHandle = 0
FriendResponseRefuse = -1 FriendResponseAgree = 1
FriendResponseRefuse = -1
Male = 1 Male = 1
Female = 2 Female = 2
) )
const OperationID = "operationID" const (
const OpUserID = "opUserID" OperationID = "operationID"
const ConnID = "connID" OpUserID = "opUserID"
const OpUserPlatform = "platform" ConnID = "connID"
const Token = "token" OpUserPlatform = "platform"
const RpcCustomHeader = "customHeader" // rpc中间件自定义ctx参数 Token = "token"
const CheckKey = "CheckKey" RpcCustomHeader = "customHeader" // rpc中间件自定义ctx参数
const TriggerID = "triggerID" CheckKey = "CheckKey"
const RemoteAddr = "remoteAddr" TriggerID = "triggerID"
RemoteAddr = "remoteAddr"
)
const ( const (
BecomeFriendByImport = 1 //管理员导入 BecomeFriendByImport = 1 // 管理员导入
BecomeFriendByApply = 2 //申请添加 BecomeFriendByApply = 2 // 申请添加
) )
const ( const (
ApplyNeedVerificationInviteDirectly = 0 // 申请需要同意 邀请直接进 ApplyNeedVerificationInviteDirectly = 0 // 申请需要同意 邀请直接进
AllNeedVerification = 1 //所有人进群需要验证,除了群主管理员邀请进群 AllNeedVerification = 1 // 所有人进群需要验证,除了群主管理员邀请进群
Directly = 2 //直接进群 Directly = 2 // 直接进群
) )
const ( const (
@@ -343,7 +347,7 @@ const LogFileName = "OpenIM.log"
const LocalHost = "0.0.0.0" const LocalHost = "0.0.0.0"
// flag parse // flag parse.
const ( const (
FlagPort = "port" FlagPort = "port"
FlagWsPort = "ws_port" FlagWsPort = "ws_port"
+10 -5
View File
@@ -15,10 +15,9 @@
package constant package constant
// fixme 1<--->IOS 2<--->Android 3<--->Windows // fixme 1<--->IOS 2<--->Android 3<--->Windows
//fixme 4<--->OSX 5<--->Web 6<--->MiniWeb 7<--->Linux // fixme 4<--->OSX 5<--->Web 6<--->MiniWeb 7<--->Linux
const ( const (
//Platform ID //Platform ID.
IOSPlatformID = 1 IOSPlatformID = 1
AndroidPlatformID = 2 AndroidPlatformID = 2
WindowsPlatformID = 3 WindowsPlatformID = 3
@@ -30,7 +29,7 @@ const (
IPadPlatformID = 9 IPadPlatformID = 9
AdminPlatformID = 10 AdminPlatformID = 10
//Platform string match to Platform ID //Platform string match to Platform ID.
IOSPlatformStr = "IOS" IOSPlatformStr = "IOS"
AndroidPlatformStr = "Android" AndroidPlatformStr = "Android"
WindowsPlatformStr = "Windows" WindowsPlatformStr = "Windows"
@@ -42,7 +41,7 @@ const (
IPadPlatformStr = "IPad" IPadPlatformStr = "IPad"
AdminPlatformStr = "Admin" AdminPlatformStr = "Admin"
//terminal types //terminal types.
TerminalPC = "PC" TerminalPC = "PC"
TerminalMobile = "Mobile" TerminalMobile = "Mobile"
) )
@@ -59,6 +58,7 @@ var PlatformID2Name = map[int]string{
IPadPlatformID: IPadPlatformStr, IPadPlatformID: IPadPlatformStr,
AdminPlatformID: AdminPlatformStr, AdminPlatformID: AdminPlatformStr,
} }
var PlatformName2ID = map[string]int{ var PlatformName2ID = map[string]int{
IOSPlatformStr: IOSPlatformID, IOSPlatformStr: IOSPlatformID,
AndroidPlatformStr: AndroidPlatformID, AndroidPlatformStr: AndroidPlatformID,
@@ -71,6 +71,7 @@ var PlatformName2ID = map[string]int{
IPadPlatformStr: IPadPlatformID, IPadPlatformStr: IPadPlatformID,
AdminPlatformStr: AdminPlatformID, AdminPlatformStr: AdminPlatformID,
} }
var PlatformName2class = map[string]string{ var PlatformName2class = map[string]string{
IOSPlatformStr: TerminalMobile, IOSPlatformStr: TerminalMobile,
AndroidPlatformStr: TerminalMobile, AndroidPlatformStr: TerminalMobile,
@@ -80,6 +81,7 @@ var PlatformName2class = map[string]string{
OSXPlatformStr: TerminalPC, OSXPlatformStr: TerminalPC,
LinuxPlatformStr: TerminalPC, LinuxPlatformStr: TerminalPC,
} }
var PlatformID2class = map[int]string{ var PlatformID2class = map[int]string{
IOSPlatformID: TerminalMobile, IOSPlatformID: TerminalMobile,
AndroidPlatformID: TerminalMobile, AndroidPlatformID: TerminalMobile,
@@ -93,12 +95,15 @@ var PlatformID2class = map[int]string{
func PlatformIDToName(num int) string { func PlatformIDToName(num int) string {
return PlatformID2Name[num] return PlatformID2Name[num]
} }
func PlatformNameToID(name string) int { func PlatformNameToID(name string) int {
return PlatformName2ID[name] return PlatformName2ID[name]
} }
func PlatformNameToClass(name string) string { func PlatformNameToClass(name string) string {
return PlatformName2class[name] return PlatformName2class[name]
} }
func PlatformIDToClass(num int) string { func PlatformIDToClass(num int) string {
return PlatformID2class[num] return PlatformID2class[num]
} }
+3
View File
@@ -27,6 +27,9 @@ func BlackDB2Pb(
blackDBs []*relation.BlackModel, blackDBs []*relation.BlackModel,
f func(ctx context.Context, userIDs []string) (map[string]*sdkws.UserInfo, error), f func(ctx context.Context, userIDs []string) (map[string]*sdkws.UserInfo, error),
) (blackPbs []*sdk.BlackInfo, err error) { ) (blackPbs []*sdk.BlackInfo, err error) {
if len(blackDBs) == 0 {
return nil, nil
}
var userIDs []string var userIDs []string
for _, blackDB := range blackDBs { for _, blackDB := range blackDBs {
userIDs = append(userIDs, blackDB.BlockUserID) userIDs = append(userIDs, blackDB.BlockUserID)
+6
View File
@@ -54,6 +54,9 @@ func FriendsDB2Pb(
friendsDB []*relation.FriendModel, friendsDB []*relation.FriendModel,
getUsers func(ctx context.Context, userIDs []string) (map[string]*sdkws.UserInfo, error), getUsers func(ctx context.Context, userIDs []string) (map[string]*sdkws.UserInfo, error),
) (friendsPb []*sdkws.FriendInfo, err error) { ) (friendsPb []*sdkws.FriendInfo, err error) {
if len(friendsDB) == 0 {
return nil, nil
}
var userID []string var userID []string
for _, friendDB := range friendsDB { for _, friendDB := range friendsDB {
userID = append(userID, friendDB.FriendUserID) userID = append(userID, friendDB.FriendUserID)
@@ -80,6 +83,9 @@ func FriendRequestDB2Pb(
friendRequests []*relation.FriendRequestModel, friendRequests []*relation.FriendRequestModel,
getUsers func(ctx context.Context, userIDs []string) (map[string]*sdkws.UserInfo, error), getUsers func(ctx context.Context, userIDs []string) (map[string]*sdkws.UserInfo, error),
) ([]*sdkws.FriendRequest, error) { ) ([]*sdkws.FriendRequest, error) {
if len(friendRequests) == 0 {
return nil, nil
}
userIDMap := make(map[string]struct{}) userIDMap := make(map[string]struct{})
for _, friendRequest := range friendRequests { for _, friendRequest := range friendRequests {
userIDMap[friendRequest.ToUserID] = struct{}{} userIDMap[friendRequest.ToUserID] = struct{}{}
+20 -11
View File
@@ -27,6 +27,11 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
) )
const (
maxRetry = 10 //number of retries
)
// NewRedis Initialize redis connection
func NewRedis() (redis.UniversalClient, error) { func NewRedis() (redis.UniversalClient, error) {
if len(config.Config.Redis.Address) == 0 { if len(config.Config.Redis.Address) == 0 {
return nil, errors.New("redis address is empty") return nil, errors.New("redis address is empty")
@@ -35,25 +40,29 @@ func NewRedis() (redis.UniversalClient, error) {
var rdb redis.UniversalClient var rdb redis.UniversalClient
if len(config.Config.Redis.Address) > 1 { if len(config.Config.Redis.Address) > 1 {
rdb = redis.NewClusterClient(&redis.ClusterOptions{ rdb = redis.NewClusterClient(&redis.ClusterOptions{
Addrs: config.Config.Redis.Address, Addrs: config.Config.Redis.Address,
Username: config.Config.Redis.Username, Username: config.Config.Redis.Username,
Password: config.Config.Redis.Password, // no password set Password: config.Config.Redis.Password, // no password set
PoolSize: 50, PoolSize: 50,
MaxRetries: maxRetry,
}) })
} else { } else {
rdb = redis.NewClient(&redis.Options{ rdb = redis.NewClient(&redis.Options{
Addr: config.Config.Redis.Address[0], Addr: config.Config.Redis.Address[0],
Username: config.Config.Redis.Username, Username: config.Config.Redis.Username,
Password: config.Config.Redis.Password, // no password set Password: config.Config.Redis.Password, // no password set
DB: 0, // use default DB DB: 0, // use default DB
PoolSize: 100, // 连接池大小 PoolSize: 100, // connection pool size
MaxRetries: maxRetry,
}) })
} }
var err error = nil
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel() defer cancel()
err := rdb.Ping(ctx).Err() err = rdb.Ping(ctx).Err()
if err != nil { if err != nil {
return nil, fmt.Errorf("redis ping %w", err) return nil, fmt.Errorf("redis ping %w", err)
} }
return rdb, nil return rdb, err
} }
+36
View File
@@ -0,0 +1,36 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cache
import (
"fmt"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"testing"
)
//TestNewRedis Test redis connection
func TestNewRedis(t *testing.T) {
err := config.InitConfig("config_folder_path")
if err != nil {
fmt.Println("config load error")
return
}
redis, err := NewRedis()
if err != nil {
fmt.Println(err)
return
}
fmt.Println(redis)
}
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controller package controller
import ( import (
+16 -1
View File
@@ -221,6 +221,7 @@ func (f *friendDatabase) AgreeFriendRequest(
friendRequest *relation.FriendRequestModel, friendRequest *relation.FriendRequestModel,
) (err error) { ) (err error) {
return f.tx.Transaction(func(tx any) error { return f.tx.Transaction(func(tx any) error {
now := time.Now()
fr, err := f.friendRequest.NewTx(tx).Take(ctx, friendRequest.FromUserID, friendRequest.ToUserID) fr, err := f.friendRequest.NewTx(tx).Take(ctx, friendRequest.FromUserID, friendRequest.ToUserID)
if err != nil { if err != nil {
return err return err
@@ -230,11 +231,25 @@ func (f *friendDatabase) AgreeFriendRequest(
} }
friendRequest.HandlerUserID = mcontext.GetOpUserID(ctx) friendRequest.HandlerUserID = mcontext.GetOpUserID(ctx)
friendRequest.HandleResult = constant.FriendResponseAgree friendRequest.HandleResult = constant.FriendResponseAgree
friendRequest.HandleTime = time.Now() friendRequest.HandleTime = now
err = f.friendRequest.NewTx(tx).Update(ctx, friendRequest) err = f.friendRequest.NewTx(tx).Update(ctx, friendRequest)
if err != nil { if err != nil {
return err return err
} }
fr2, err := f.friendRequest.NewTx(tx).Take(ctx, friendRequest.ToUserID, friendRequest.FromUserID)
if err == nil && fr2.HandleResult == constant.FriendResponseNotHandle {
fr2.HandlerUserID = mcontext.GetOpUserID(ctx)
fr2.HandleResult = constant.FriendResponseAgree
fr2.HandleTime = now
err = f.friendRequest.NewTx(tx).Update(ctx, fr2)
if err != nil {
return err
}
} else if errs.Unwrap(err) != gorm.ErrRecordNotFound {
return err
}
exists, err := f.friend.NewTx(tx).FindUserState(ctx, friendRequest.FromUserID, friendRequest.ToUserID) exists, err := f.friend.NewTx(tx).FindUserState(ctx, friendRequest.FromUserID, friendRequest.ToUserID)
if err != nil { if err != nil {
return err return err
+36 -3
View File
@@ -1,6 +1,23 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controller package controller
import ( import (
relation2 "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"gorm.io/gorm"
"time" "time"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
@@ -78,6 +95,7 @@ type CommonMsgDatabase interface {
GetConversationMinMaxSeqInMongoAndCache(ctx context.Context, conversationID string) (minSeqMongo, maxSeqMongo, minSeqCache, maxSeqCache int64, err error) GetConversationMinMaxSeqInMongoAndCache(ctx context.Context, conversationID string) (minSeqMongo, maxSeqMongo, minSeqCache, maxSeqCache int64, err error)
SetSendMsgStatus(ctx context.Context, id string, status int32) error SetSendMsgStatus(ctx context.Context, id string, status int32) error
GetSendMsgStatus(ctx context.Context, id string) (int32, error) GetSendMsgStatus(ctx context.Context, id string) (int32, error)
SearchMessage(ctx context.Context, req *pbMsg.SearchMessageReq) (msgData []*sdkws.MsgData, err error)
// to mq // to mq
MsgToMQ(ctx context.Context, key string, msg2mq *sdkws.MsgData) error MsgToMQ(ctx context.Context, key string, msg2mq *sdkws.MsgData) error
@@ -89,8 +107,9 @@ type CommonMsgDatabase interface {
RangeGroupSendCount(ctx context.Context, start time.Time, end time.Time, ase bool, pageNumber int32, showNumber int32) (msgCount int64, userCount int64, groups []*unRelationTb.GroupCount, dateCount map[string]int64, err error) RangeGroupSendCount(ctx context.Context, start time.Time, end time.Time, ase bool, pageNumber int32, showNumber int32) (msgCount int64, userCount int64, groups []*unRelationTb.GroupCount, dateCount map[string]int64, err error)
} }
func NewCommonMsgDatabase(msgDocModel unRelationTb.MsgDocModelInterface, cacheModel cache.MsgModel) CommonMsgDatabase { func NewCommonMsgDatabase(msgDocModel unRelationTb.MsgDocModelInterface, cacheModel cache.MsgModel, msgMyqModel relation.ChatLogModelInterface) CommonMsgDatabase {
return &commonMsgDatabase{ return &commonMsgDatabase{
msgMyq: msgMyqModel,
msgDocDatabase: msgDocModel, msgDocDatabase: msgDocModel,
cache: cacheModel, cache: cacheModel,
producer: kafka.NewKafkaProducer(config.Config.Kafka.Addr, config.Config.Kafka.LatestMsgToRedis.Topic), producer: kafka.NewKafkaProducer(config.Config.Kafka.Addr, config.Config.Kafka.LatestMsgToRedis.Topic),
@@ -99,16 +118,18 @@ func NewCommonMsgDatabase(msgDocModel unRelationTb.MsgDocModelInterface, cacheMo
} }
} }
func InitCommonMsgDatabase(rdb redis.UniversalClient, database *mongo.Database) CommonMsgDatabase { func InitCommonMsgDatabase(rdb redis.UniversalClient, database *mongo.Database, dbGrom *gorm.DB) CommonMsgDatabase {
cacheModel := cache.NewMsgCacheModel(rdb) cacheModel := cache.NewMsgCacheModel(rdb)
msgDocModel := unrelation.NewMsgMongoDriver(database) msgDocModel := unrelation.NewMsgMongoDriver(database)
CommonMsgDatabase := NewCommonMsgDatabase(msgDocModel, cacheModel) msgMyqModel := relation2.NewChatLogGorm(dbGrom)
CommonMsgDatabase := NewCommonMsgDatabase(msgDocModel, cacheModel, msgMyqModel)
return CommonMsgDatabase return CommonMsgDatabase
} }
type commonMsgDatabase struct { type commonMsgDatabase struct {
msgDocDatabase unRelationTb.MsgDocModelInterface msgDocDatabase unRelationTb.MsgDocModelInterface
msg unRelationTb.MsgDocModel msg unRelationTb.MsgDocModel
msgMyq relation.ChatLogModelInterface
cache cache.MsgModel cache cache.MsgModel
producer *kafka.Producer producer *kafka.Producer
producerToMongo *kafka.Producer producerToMongo *kafka.Producer
@@ -870,3 +891,15 @@ func (db *commonMsgDatabase) RangeUserSendCount(ctx context.Context, start time.
func (db *commonMsgDatabase) RangeGroupSendCount(ctx context.Context, start time.Time, end time.Time, ase bool, pageNumber int32, showNumber int32) (msgCount int64, userCount int64, groups []*unRelationTb.GroupCount, dateCount map[string]int64, err error) { func (db *commonMsgDatabase) RangeGroupSendCount(ctx context.Context, start time.Time, end time.Time, ase bool, pageNumber int32, showNumber int32) (msgCount int64, userCount int64, groups []*unRelationTb.GroupCount, dateCount map[string]int64, err error) {
return db.msgDocDatabase.RangeGroupSendCount(ctx, start, end, ase, pageNumber, showNumber) return db.msgDocDatabase.RangeGroupSendCount(ctx, start, end, ase, pageNumber, showNumber)
} }
func (db *commonMsgDatabase) SearchMessage(ctx context.Context, req *pbMsg.SearchMessageReq) (msgData []*sdkws.MsgData, err error) {
var totalMsgs []*sdkws.MsgData
msgs, err := db.msgDocDatabase.SearchMessage(ctx, req)
if err != nil {
return nil, err
}
for _, msg := range msgs {
totalMsgs = append(totalMsgs, convert.MsgDB2Pb(msg.Msg))
}
return totalMsgs, nil
}
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controller package controller
import ( import (
+147 -26
View File
@@ -1,12 +1,27 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package relation package relation
import ( import (
"context" "context"
"gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"gorm.io/gorm"
) )
type ConversationGorm struct { type ConversationGorm struct {
@@ -29,66 +44,172 @@ func (c *ConversationGorm) Delete(ctx context.Context, groupIDs []string) (err e
return utils.Wrap(c.db(ctx).Where("group_id in (?)", groupIDs).Delete(&relation.ConversationModel{}).Error, "") return utils.Wrap(c.db(ctx).Where("group_id in (?)", groupIDs).Delete(&relation.ConversationModel{}).Error, "")
} }
func (c *ConversationGorm) UpdateByMap(ctx context.Context, userIDList []string, conversationID string, args map[string]interface{}) (rows int64, err error) { func (c *ConversationGorm) UpdateByMap(
ctx context.Context,
userIDList []string,
conversationID string,
args map[string]interface{},
) (rows int64, err error) {
result := c.db(ctx).Where("owner_user_id IN (?) and conversation_id=?", userIDList, conversationID).Updates(args) result := c.db(ctx).Where("owner_user_id IN (?) and conversation_id=?", userIDList, conversationID).Updates(args)
return result.RowsAffected, utils.Wrap(result.Error, "") return result.RowsAffected, utils.Wrap(result.Error, "")
} }
func (c *ConversationGorm) Update(ctx context.Context, conversation *relation.ConversationModel) (err error) { func (c *ConversationGorm) Update(ctx context.Context, conversation *relation.ConversationModel) (err error) {
return utils.Wrap(c.db(ctx).Where("owner_user_id = ? and conversation_id = ?", conversation.OwnerUserID, conversation.ConversationID).Updates(conversation).Error, "") return utils.Wrap(
c.db(ctx).
Where("owner_user_id = ? and conversation_id = ?", conversation.OwnerUserID, conversation.ConversationID).
Updates(conversation).
Error,
"",
)
} }
func (c *ConversationGorm) Find(ctx context.Context, ownerUserID string, conversationIDs []string) (conversations []*relation.ConversationModel, err error) { func (c *ConversationGorm) Find(
err = utils.Wrap(c.db(ctx).Where("owner_user_id=? and conversation_id IN (?)", ownerUserID, conversationIDs).Find(&conversations).Error, "") ctx context.Context,
ownerUserID string,
conversationIDs []string,
) (conversations []*relation.ConversationModel, err error) {
err = utils.Wrap(
c.db(ctx).
Where("owner_user_id=? and conversation_id IN (?)", ownerUserID, conversationIDs).
Find(&conversations).
Error,
"",
)
return conversations, err return conversations, err
} }
func (c *ConversationGorm) Take(ctx context.Context, userID, conversationID string) (conversation *relation.ConversationModel, err error) { func (c *ConversationGorm) Take(
ctx context.Context,
userID, conversationID string,
) (conversation *relation.ConversationModel, err error) {
cc := &relation.ConversationModel{} cc := &relation.ConversationModel{}
return cc, utils.Wrap(c.db(ctx).Where("conversation_id = ? And owner_user_id = ?", conversationID, userID).Take(cc).Error, "") return cc, utils.Wrap(
c.db(ctx).Where("conversation_id = ? And owner_user_id = ?", conversationID, userID).Take(cc).Error,
"",
)
} }
func (c *ConversationGorm) FindUserID(ctx context.Context, userIDs []string, conversationIDs []string) (existUserID []string, err error) { func (c *ConversationGorm) FindUserID(
return existUserID, utils.Wrap(c.db(ctx).Where(" owner_user_id IN (?) and conversation_id in (?)", userIDs, conversationIDs).Pluck("owner_user_id", &existUserID).Error, "") ctx context.Context,
userIDs []string,
conversationIDs []string,
) (existUserID []string, err error) {
return existUserID, utils.Wrap(
c.db(ctx).
Where(" owner_user_id IN (?) and conversation_id in (?)", userIDs, conversationIDs).
Pluck("owner_user_id", &existUserID).
Error,
"",
)
} }
func (c *ConversationGorm) FindConversationID(ctx context.Context, userID string, conversationIDList []string) (existConversationID []string, err error) { func (c *ConversationGorm) FindConversationID(
return existConversationID, utils.Wrap(c.db(ctx).Where(" conversation_id IN (?) and owner_user_id=?", conversationIDList, userID).Pluck("conversation_id", &existConversationID).Error, "") ctx context.Context,
userID string,
conversationIDList []string,
) (existConversationID []string, err error) {
return existConversationID, utils.Wrap(
c.db(ctx).
Where(" conversation_id IN (?) and owner_user_id=?", conversationIDList, userID).
Pluck("conversation_id", &existConversationID).
Error,
"",
)
} }
func (c *ConversationGorm) FindUserIDAllConversationID(ctx context.Context, userID string) (conversationIDList []string, err error) { func (c *ConversationGorm) FindUserIDAllConversationID(
return conversationIDList, utils.Wrap(c.db(ctx).Where("owner_user_id=?", userID).Pluck("conversation_id", &conversationIDList).Error, "") ctx context.Context,
userID string,
) (conversationIDList []string, err error) {
return conversationIDList, utils.Wrap(
c.db(ctx).Where("owner_user_id=?", userID).Pluck("conversation_id", &conversationIDList).Error,
"",
)
} }
func (c *ConversationGorm) FindUserIDAllConversations(ctx context.Context, userID string) (conversations []*relation.ConversationModel, err error) { func (c *ConversationGorm) FindUserIDAllConversations(
ctx context.Context,
userID string,
) (conversations []*relation.ConversationModel, err error) {
return conversations, utils.Wrap(c.db(ctx).Where("owner_user_id=?", userID).Find(&conversations).Error, "") return conversations, utils.Wrap(c.db(ctx).Where("owner_user_id=?", userID).Find(&conversations).Error, "")
} }
func (c *ConversationGorm) FindRecvMsgNotNotifyUserIDs(ctx context.Context, groupID string) (userIDs []string, err error) { func (c *ConversationGorm) FindRecvMsgNotNotifyUserIDs(
return userIDs, utils.Wrap(c.db(ctx).Where("group_id = ? and recv_msg_opt = ?", groupID, constant.ReceiveNotNotifyMessage).Pluck("user_id", &userIDs).Error, "") ctx context.Context,
groupID string,
) (userIDs []string, err error) {
return userIDs, utils.Wrap(
c.db(ctx).
Where("group_id = ? and recv_msg_opt = ?", groupID, constant.ReceiveNotNotifyMessage).
Pluck("user_id", &userIDs).
Error,
"",
)
} }
func (c *ConversationGorm) FindSuperGroupRecvMsgNotNotifyUserIDs(ctx context.Context, groupID string) (userIDs []string, err error) { func (c *ConversationGorm) FindSuperGroupRecvMsgNotNotifyUserIDs(
return userIDs, utils.Wrap(c.db(ctx).Where("group_id = ? and recv_msg_opt = ? and conversation_type = ?", groupID, constant.ReceiveNotNotifyMessage, constant.SuperGroupChatType).Pluck("user_id", &userIDs).Error, "") ctx context.Context,
groupID string,
) (userIDs []string, err error) {
return userIDs, utils.Wrap(
c.db(ctx).
Where("group_id = ? and recv_msg_opt = ? and conversation_type = ?", groupID, constant.ReceiveNotNotifyMessage, constant.SuperGroupChatType).
Pluck("user_id", &userIDs).
Error,
"",
)
} }
func (c *ConversationGorm) GetUserRecvMsgOpt(ctx context.Context, ownerUserID, conversationID string) (opt int, err error) { func (c *ConversationGorm) GetUserRecvMsgOpt(
ctx context.Context,
ownerUserID, conversationID string,
) (opt int, err error) {
var conversation relation.ConversationModel var conversation relation.ConversationModel
return int(conversation.RecvMsgOpt), utils.Wrap(c.db(ctx).Where("conversation_id = ? And owner_user_id = ?", conversationID, ownerUserID).Select("recv_msg_opt").Find(&conversation).Error, "") return int(
conversation.RecvMsgOpt,
), utils.Wrap(
c.db(ctx).
Where("conversation_id = ? And owner_user_id = ?", conversationID, ownerUserID).
Select("recv_msg_opt").
Find(&conversation).
Error,
"",
)
} }
func (c *ConversationGorm) GetAllConversationIDs(ctx context.Context) (conversationIDs []string, err error) { func (c *ConversationGorm) GetAllConversationIDs(ctx context.Context) (conversationIDs []string, err error) {
return conversationIDs, utils.Wrap(c.db(ctx).Distinct("conversation_id").Pluck("conversation_id", &conversationIDs).Error, "") return conversationIDs, utils.Wrap(
c.db(ctx).Distinct("conversation_id").Pluck("conversation_id", &conversationIDs).Error,
"",
)
} }
func (c *ConversationGorm) GetUserAllHasReadSeqs(ctx context.Context, ownerUserID string) (hasReadSeqs map[string]int64, err error) { func (c *ConversationGorm) GetUserAllHasReadSeqs(
ctx context.Context,
ownerUserID string,
) (hasReadSeqs map[string]int64, err error) {
return nil, nil return nil, nil
} }
func (c *ConversationGorm) GetConversationsByConversationID(ctx context.Context, conversationIDs []string) (conversations []*relation.ConversationModel, err error) { func (c *ConversationGorm) GetConversationsByConversationID(
return conversations, utils.Wrap(c.db(ctx).Where("conversation_id IN (?)", conversationIDs).Find(&conversations).Error, "") ctx context.Context,
conversationIDs []string,
) (conversations []*relation.ConversationModel, err error) {
return conversations, utils.Wrap(
c.db(ctx).Where("conversation_id IN (?)", conversationIDs).Find(&conversations).Error,
"",
)
} }
func (c *ConversationGorm) GetConversationIDsNeedDestruct(ctx context.Context) (conversations []*relation.ConversationModel, err error) { func (c *ConversationGorm) GetConversationIDsNeedDestruct(
return conversations, utils.Wrap(c.db(ctx).Where("is_msg_destruct = 1 && UNIX_TIMESTAMP(NOW()) > (msg_destruct_time + UNIX_TIMESTAMP(latest_msg_destruct_time)) && msg_destruct_time != 0").Find(&conversations).Error, "") ctx context.Context,
) (conversations []*relation.ConversationModel, err error) {
return conversations, utils.Wrap(
c.db(ctx).
Where("is_msg_destruct = 1 && UNIX_TIMESTAMP(NOW()) > (msg_destruct_time + UNIX_TIMESTAMP(latest_msg_destruct_time)) && msg_destruct_time != 0").
Find(&conversations).
Error,
"",
)
} }
+22 -4
View File
@@ -1,13 +1,30 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package relation package relation
import ( import (
"context" "context"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"time"
"gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/ormutil" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/ormutil"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"gorm.io/gorm"
"time"
) )
var _ relation.GroupModelInterface = (*GroupGorm)(nil) var _ relation.GroupModelInterface = (*GroupGorm)(nil)
@@ -46,9 +63,10 @@ func (g *GroupGorm) Take(ctx context.Context, groupID string) (group *relation.G
} }
func (g *GroupGorm) Search(ctx context.Context, keyword string, pageNumber, showNumber int32) (total uint32, groups []*relation.GroupModel, err error) { func (g *GroupGorm) Search(ctx context.Context, keyword string, pageNumber, showNumber int32) (total uint32, groups []*relation.GroupModel, err error) {
return ormutil.GormSearch[relation.GroupModel](g.DB, []string{"name"}, keyword, pageNumber, showNumber) db := g.DB
db = db.WithContext(ctx).Where("status!=?", constant.GroupStatusDismissed)
return ormutil.GormSearch[relation.GroupModel](db, []string{"name"}, keyword, pageNumber, showNumber)
} }
func (g *GroupGorm) GetGroupIDsByGroupType(ctx context.Context, groupType int) (groupIDs []string, err error) { func (g *GroupGorm) GetGroupIDsByGroupType(ctx context.Context, groupType int) (groupIDs []string, err error) {
return groupIDs, utils.Wrap(g.DB.Model(&relation.GroupModel{}).Where("group_type = ? ", groupType).Pluck("group_id", &groupIDs).Error, "") return groupIDs, utils.Wrap(g.DB.Model(&relation.GroupModel{}).Where("group_type = ? ", groupType).Pluck("group_id", &groupIDs).Error, "")
} }
+17 -1
View File
@@ -1,10 +1,26 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package relation package relation
import ( import (
"context" "context"
"gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"gorm.io/gorm"
) )
type ObjectInfoGorm struct { type ObjectInfoGorm struct {
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cont package cont
const ( const (
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cont package cont
import ( import (
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cont package cont
import ( import (
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cont package cont
import ( import (
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cont package cont
import "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/s3" import "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/s3"
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cos package cos
import ( import (
+23
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package minio package minio
import ( import (
@@ -40,6 +54,15 @@ func NewMinio() (s3.Interface, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
exists, err := client.BucketExists(context.Background(), conf.Bucket)
if err != nil {
return nil, err
}
if !exists {
if err := client.MakeBucket(context.Background(), conf.Bucket, minio.MakeBucketOptions{}); err != nil {
return nil, err
}
}
return &Minio{ return &Minio{
bucket: conf.Bucket, bucket: conf.Bucket,
bucketURL: conf.Endpoint + "/" + conf.Bucket + "/", bucketURL: conf.Endpoint + "/" + conf.Bucket + "/",
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oss package oss
import ( import (
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oss package oss
import ( import (
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oss package oss
import ( import (
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package s3 package s3
import ( import (
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package relation package relation
import ( import (
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package relation package relation
import ( import (
+19 -2
View File
@@ -16,6 +16,7 @@ package unrelation
import ( import (
"context" "context"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg"
"strconv" "strconv"
"time" "time"
@@ -108,8 +109,24 @@ type MsgDocModelInterface interface {
GetMsgDocModelByIndex(ctx context.Context, conversationID string, index, sort int64) (*MsgDocModel, error) GetMsgDocModelByIndex(ctx context.Context, conversationID string, index, sort int64) (*MsgDocModel, error)
DeleteMsgsInOneDocByIndex(ctx context.Context, docID string, indexes []int) error DeleteMsgsInOneDocByIndex(ctx context.Context, docID string, indexes []int) error
MarkSingleChatMsgsAsRead(ctx context.Context, userID string, docID string, indexes []int64) error MarkSingleChatMsgsAsRead(ctx context.Context, userID string, docID string, indexes []int64) error
RangeUserSendCount(ctx context.Context, start time.Time, end time.Time, group bool, ase bool, pageNumber int32, showNumber int32) (msgCount int64, userCount int64, users []*UserCount, dateCount map[string]int64, err error) SearchMessage(ctx context.Context, req *msg.SearchMessageReq) ([]*MsgInfoModel, error)
RangeGroupSendCount(ctx context.Context, start time.Time, end time.Time, ase bool, pageNumber int32, showNumber int32) (msgCount int64, userCount int64, groups []*GroupCount, dateCount map[string]int64, err error) RangeUserSendCount(
ctx context.Context,
start time.Time,
end time.Time,
group bool,
ase bool,
pageNumber int32,
showNumber int32,
) (msgCount int64, userCount int64, users []*UserCount, dateCount map[string]int64, err error)
RangeGroupSendCount(
ctx context.Context,
start time.Time,
end time.Time,
ase bool,
pageNumber int32,
showNumber int32,
) (msgCount int64, userCount int64, groups []*GroupCount, dateCount map[string]int64, err error)
} }
func (MsgDocModel) TableName() string { func (MsgDocModel) TableName() string {
+22 -9
View File
@@ -31,19 +31,21 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
) )
const (
maxRetry = 10 //number of retries
)
type Mongo struct { type Mongo struct {
db *mongo.Client db *mongo.Client
} }
// NewMongo Initialize MongoDB connection
func NewMongo() (*Mongo, error) { func NewMongo() (*Mongo, error) {
specialerror.AddReplace(mongo.ErrNoDocuments, errs.ErrRecordNotFound) specialerror.AddReplace(mongo.ErrNoDocuments, errs.ErrRecordNotFound)
uri := "mongodb://sample.host:27017/?maxPoolSize=20&w=majority" uri := "mongodb://sample.host:27017/?maxPoolSize=20&w=majority"
if config.Config.Mongo.Uri != "" { if config.Config.Mongo.Uri != "" {
// example:
// mongodb://$user:$password@mongo1.mongo:27017,mongo2.mongo:27017,mongo3.mongo:27017/$DBDatabase/?replicaSet=rs0&readPreference=secondary&authSource=admin&maxPoolSize=$DBMaxPoolSize
uri = config.Config.Mongo.Uri uri = config.Config.Mongo.Uri
} else { } else {
//mongodb://mongodb1.example.com:27317,mongodb2.example.com:27017/?replicaSet=mySet&authSource=authDB
mongodbHosts := "" mongodbHosts := ""
for i, v := range config.Config.Mongo.Address { for i, v := range config.Config.Mongo.Address {
if i == len(config.Config.Mongo.Address)-1 { if i == len(config.Config.Mongo.Address)-1 {
@@ -63,13 +65,24 @@ func NewMongo() (*Mongo, error) {
} }
} }
fmt.Println("mongo:", uri) fmt.Println("mongo:", uri)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*60) var mongoClient *mongo.Client
defer cancel() var err error = nil
mongoClient, err := mongo.Connect(ctx, options.Client().ApplyURI(uri)) for i := 0; i <= maxRetry; i++ {
if err != nil { ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
return nil, err defer cancel()
mongoClient, err = mongo.Connect(ctx, options.Client().ApplyURI(uri))
if err == nil {
return &Mongo{db: mongoClient}, nil
}
if cmdErr, ok := err.(mongo.CommandError); ok {
if cmdErr.Code == 13 || cmdErr.Code == 18 {
return nil, err
} else {
fmt.Printf("Failed to connect to MongoDB: %s\n", err)
}
}
} }
return &Mongo{db: mongoClient}, nil return nil, err
} }
func (m *Mongo) GetClient() *mongo.Client { func (m *Mongo) GetClient() *mongo.Client {
+151 -2
View File
@@ -19,6 +19,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg"
"time" "time"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
@@ -555,7 +556,15 @@ func (m *MsgMongoDriver) MarkSingleChatMsgsAsRead(
// } // }
// //
// ]) // ])
func (m *MsgMongoDriver) RangeUserSendCount(ctx context.Context, start time.Time, end time.Time, group bool, ase bool, pageNumber int32, showNumber int32) (msgCount int64, userCount int64, users []*table.UserCount, dateCount map[string]int64, err error) { func (m *MsgMongoDriver) RangeUserSendCount(
ctx context.Context,
start time.Time,
end time.Time,
group bool,
ase bool,
pageNumber int32,
showNumber int32,
) (msgCount int64, userCount int64, users []*table.UserCount, dateCount map[string]int64, err error) {
var sort int var sort int
if ase { if ase {
sort = 1 sort = 1
@@ -808,7 +817,14 @@ func (m *MsgMongoDriver) RangeUserSendCount(ctx context.Context, start time.Time
return result[0].MsgCount, result[0].UserCount, users, dateCount, nil return result[0].MsgCount, result[0].UserCount, users, dateCount, nil
} }
func (m *MsgMongoDriver) RangeGroupSendCount(ctx context.Context, start time.Time, end time.Time, ase bool, pageNumber int32, showNumber int32) (msgCount int64, userCount int64, groups []*table.GroupCount, dateCount map[string]int64, err error) { func (m *MsgMongoDriver) RangeGroupSendCount(
ctx context.Context,
start time.Time,
end time.Time,
ase bool,
pageNumber int32,
showNumber int32,
) (msgCount int64, userCount int64, groups []*table.GroupCount, dateCount map[string]int64, err error) {
var sort int var sort int
if ase { if ase {
sort = 1 sort = 1
@@ -1049,3 +1065,136 @@ func (m *MsgMongoDriver) RangeGroupSendCount(ctx context.Context, start time.Tim
} }
return result[0].MsgCount, result[0].UserCount, groups, dateCount, nil return result[0].MsgCount, result[0].UserCount, groups, dateCount, nil
} }
func (m *MsgMongoDriver) SearchMessage(ctx context.Context, req *msg.SearchMessageReq) ([]*table.MsgInfoModel, error) {
msgs, err := m.searchMessage(ctx, req)
if err != nil {
return nil, err
}
for _, msg1 := range msgs {
if msg1.IsRead {
msg1.Msg.IsRead = true
}
}
return msgs, nil
}
func (m *MsgMongoDriver) searchMessage(ctx context.Context, req *msg.SearchMessageReq) ([]*table.MsgInfoModel, error) {
var pipe mongo.Pipeline
conditon := bson.A{}
if req.SendTime != "" {
conditon = append(conditon, bson.M{"$eq": bson.A{bson.M{"$dateToString": bson.M{"format": "%Y-%m-%d", "date": bson.M{"$toDate": "$$item.msg.send_time"}}}, req.SendTime}})
}
if req.MsgType != 0 {
conditon = append(conditon, bson.M{"$eq": bson.A{"$$item.msg.content_type", req.MsgType}})
}
if req.SessionType != 0 {
conditon = append(conditon, bson.M{"$eq": bson.A{"$$item.msg.session_type", req.SessionType}})
}
if req.RecvID != "" {
conditon = append(conditon, bson.M{"$regexFind": bson.M{"input": "$$item.msg.recv_id", "regex": req.RecvID}})
}
if req.SendID != "" {
conditon = append(conditon, bson.M{"$regexFind": bson.M{"input": "$$item.msg.send_id", "regex": req.SendID}})
}
or := bson.A{
bson.M{
"doc_id": bson.M{
"$regex": "^si_",
"$options": "i",
},
},
}
or = append(or,
bson.M{
"doc_id": bson.M{
"$regex": "^g_",
"$options": "i",
},
},
bson.M{
"doc_id": bson.M{
"$regex": "^sg_",
"$options": "i",
},
},
)
pipe = mongo.Pipeline{
{
{"$match", bson.D{
{
"$or", or,
},
}},
},
{
{"$project", bson.D{
{"msgs", bson.D{
{"$filter", bson.D{
{"input", "$msgs"},
{"as", "item"},
{"cond", bson.D{
{"$and", conditon},
},
}},
}},
},
{"doc_id", 1},
}},
},
}
cursor, err := m.MsgCollection.Aggregate(ctx, pipe)
if err != nil {
return nil, err
}
var msgsDocs []table.MsgDocModel
err = cursor.All(ctx, &msgsDocs)
if err != nil {
return nil, err
}
if len(msgsDocs) == 0 {
return nil, errs.Wrap(mongo.ErrNoDocuments)
}
msgs := make([]*table.MsgInfoModel, 0)
for index, _ := range msgsDocs {
for i := range msgsDocs[index].Msg {
msg := msgsDocs[index].Msg[i]
if msg == nil || msg.Msg == nil {
continue
}
if msg.Revoke != nil {
revokeContent := sdkws.MessageRevokedContent{
RevokerID: msg.Revoke.UserID,
RevokerRole: msg.Revoke.Role,
ClientMsgID: msg.Msg.ClientMsgID,
RevokerNickname: msg.Revoke.Nickname,
RevokeTime: msg.Revoke.Time,
SourceMessageSendTime: msg.Msg.SendTime,
SourceMessageSendID: msg.Msg.SendID,
SourceMessageSenderNickname: msg.Msg.SenderNickname,
SessionType: msg.Msg.SessionType,
Seq: msg.Msg.Seq,
Ex: msg.Msg.Ex,
}
data, err := json.Marshal(&revokeContent)
if err != nil {
return nil, err
}
elem := sdkws.NotificationElem{
Detail: string(data),
}
content, err := json.Marshal(&elem)
if err != nil {
return nil, err
}
msg.Msg.ContentType = constant.MsgRevokeNotification
msg.Msg.Content = string(content)
}
msgs = append(msgs, msg)
}
}
return msgs, nil
}
+15 -6
View File
@@ -1,9 +1,18 @@
/* // Copyright © 2023 OpenIM. All rights reserved.
** description(""). //
** copyright('open-im,www.open-im.io'). // Licensed under the Apache License, Version 2.0 (the "License");
** author("fg,Gordon@tuoyun.net"). // you may not use this file except in compliance with the License.
** time(2021/5/27 10:31). // You may obtain a copy of the License at
*/package http //
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package http
import ( import (
"bytes" "bytes"
+24 -2
View File
@@ -17,12 +17,12 @@ package kafka
import ( import (
"context" "context"
"errors" "errors"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
log "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" log "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"time"
"github.com/Shopify/sarama" "github.com/Shopify/sarama"
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"
@@ -30,6 +30,10 @@ import (
prome "github.com/OpenIMSDK/Open-IM-Server/pkg/common/prome" prome "github.com/OpenIMSDK/Open-IM-Server/pkg/common/prome"
) )
const (
maxRetry = 10 //number of retries
)
var errEmptyMsg = errors.New("binary msg is empty") var errEmptyMsg = errors.New("binary msg is empty")
type Producer struct { type Producer struct {
@@ -39,6 +43,7 @@ type Producer struct {
producer sarama.SyncProducer producer sarama.SyncProducer
} }
// NewKafkaProducer Initialize kafka producer
func NewKafkaProducer(addr []string, topic string) *Producer { func NewKafkaProducer(addr []string, topic string) *Producer {
p := Producer{} p := Producer{}
p.config = sarama.NewConfig() //Instantiate a sarama Config p.config = sarama.NewConfig() //Instantiate a sarama Config
@@ -53,7 +58,24 @@ func NewKafkaProducer(addr []string, topic string) *Producer {
} }
p.addr = addr p.addr = addr
p.topic = topic p.topic = topic
producer, err := sarama.NewSyncProducer(p.addr, p.config) //Initialize the client var producer sarama.SyncProducer
var err error
for i := 0; i <= maxRetry; i++ {
producer, err = sarama.NewSyncProducer(p.addr, p.config) //Initialize the client
if err == nil {
p.producer = producer
return &p
}
//TODO If the password is wrong, exit directly
//if packetErr, ok := err.(*sarama.PacketEncodingError); ok {
//if _, ok := packetErr.Err.(sarama.AuthenticationError); ok {
// fmt.Println("Kafka password is wrong.")
//}
//} else {
// fmt.Printf("Failed to create Kafka producer: %v\n", err)
//}
time.Sleep(time.Duration(1) * time.Second)
}
if err != nil { if err != nil {
panic(err.Error()) panic(err.Error())
} }
+14
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package log package log
import ( import (
+7 -2
View File
@@ -26,12 +26,15 @@ var mapper = []string{constant.OperationID, constant.OpUserID, constant.OpUserPl
func WithOpUserIDContext(ctx context.Context, opUserID string) context.Context { func WithOpUserIDContext(ctx context.Context, opUserID string) context.Context {
return context.WithValue(ctx, constant.OpUserID, opUserID) return context.WithValue(ctx, constant.OpUserID, opUserID)
} }
func WithOpUserPlatformContext(ctx context.Context, platform string) context.Context { func WithOpUserPlatformContext(ctx context.Context, platform string) context.Context {
return context.WithValue(ctx, constant.OpUserPlatform, platform) return context.WithValue(ctx, constant.OpUserPlatform, platform)
} }
func WithTriggerIDContext(ctx context.Context, triggerID string) context.Context { func WithTriggerIDContext(ctx context.Context, triggerID string) context.Context {
return context.WithValue(ctx, constant.TriggerID, triggerID) return context.WithValue(ctx, constant.TriggerID, triggerID)
} }
func NewCtx(operationID string) context.Context { func NewCtx(operationID string) context.Context {
c := context.Background() c := context.Background()
ctx := context.WithValue(c, constant.OperationID, operationID) ctx := context.WithValue(c, constant.OperationID, operationID)
@@ -59,6 +62,7 @@ func GetOperationID(ctx context.Context) string {
} }
return "" return ""
} }
func GetOpUserID(ctx context.Context) string { func GetOpUserID(ctx context.Context) string {
if ctx.Value(constant.OpUserID) != "" { if ctx.Value(constant.OpUserID) != "" {
s, ok := ctx.Value(constant.OpUserID).(string) s, ok := ctx.Value(constant.OpUserID).(string)
@@ -68,6 +72,7 @@ func GetOpUserID(ctx context.Context) string {
} }
return "" return ""
} }
func GetConnID(ctx context.Context) string { func GetConnID(ctx context.Context) string {
if ctx.Value(constant.ConnID) != "" { if ctx.Value(constant.ConnID) != "" {
s, ok := ctx.Value(constant.ConnID).(string) s, ok := ctx.Value(constant.ConnID).(string)
@@ -87,6 +92,7 @@ func GetTriggerID(ctx context.Context) string {
} }
return "" return ""
} }
func GetOpUserPlatform(ctx context.Context) string { func GetOpUserPlatform(ctx context.Context) string {
if ctx.Value(constant.OpUserPlatform) != "" { if ctx.Value(constant.OpUserPlatform) != "" {
s, ok := ctx.Value(constant.OpUserPlatform).(string) s, ok := ctx.Value(constant.OpUserPlatform).(string)
@@ -96,6 +102,7 @@ func GetOpUserPlatform(ctx context.Context) string {
} }
return "" return ""
} }
func GetRemoteAddr(ctx context.Context) string { func GetRemoteAddr(ctx context.Context) string {
if ctx.Value(constant.RemoteAddr) != "" { if ctx.Value(constant.RemoteAddr) != "" {
s, ok := ctx.Value(constant.RemoteAddr).(string) s, ok := ctx.Value(constant.RemoteAddr).(string)
@@ -142,8 +149,6 @@ func WithMustInfoCtx(values []string) context.Context {
ctx := context.Background() ctx := context.Background()
for i, v := range values { for i, v := range values {
ctx = context.WithValue(ctx, mapper[i], v) ctx = context.WithValue(ctx, mapper[i], v)
} }
return ctx return ctx
} }
+5 -4
View File
@@ -31,6 +31,7 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
) )
// CorsHandler gin cross-domain configuration.
func CorsHandler() gin.HandlerFunc { func CorsHandler() gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*") c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
@@ -39,19 +40,19 @@ func CorsHandler() gin.HandlerFunc {
c.Header( c.Header(
"Access-Control-Expose-Headers", "Access-Control-Expose-Headers",
"Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar",
) // 跨域关键设置 让浏览器可以解析 ) // Cross-domain key settings allow browsers to resolve.
c.Header( c.Header(
"Access-Control-Max-Age", "Access-Control-Max-Age",
"172800", "172800",
) // 缓存请求信息 单位为秒 ) // Cache request information in seconds.
c.Header( c.Header(
"Access-Control-Allow-Credentials", "Access-Control-Allow-Credentials",
"false", "false",
) // 跨域请求是否需要带cookie信息 默认设置为true ) // Whether cross-domain requests need to carry cookie information, the default setting is true.
c.Header( c.Header(
"content-type", "content-type",
"application/json", "application/json",
) // 设置返回格式是json ) // Set the return format to json.
//Release all option pre-requests //Release all option pre-requests
if c.Request.Method == http.MethodOptions { if c.Request.Method == http.MethodOptions {
c.JSON(http.StatusOK, "Options Request!") c.JSON(http.StatusOK, "Options Request!")
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package zookeeper package zookeeper
import ( import (
+28 -28
View File
@@ -14,7 +14,7 @@
package errs package errs
// UnknownCode 没有解析到code或解析的code=0 // UnknownCode 没有解析到code或解析的code=0.
const UnknownCode = 1000 const UnknownCode = 1000
const ( const (
@@ -34,47 +34,47 @@ const (
InvitationError = 10014 InvitationError = 10014
) )
// 通用错误码 // 通用错误码.
const ( const (
NoError = 0 //无错误 NoError = 0 // 无错误
DatabaseError = 90002 //redis/mysql等db错误 DatabaseError = 90002 // redis/mysql等db错误
NetworkError = 90004 //网络错误 NetworkError = 90004 // 网络错误
DataError = 90007 //数据错误 DataError = 90007 // 数据错误
CallbackError = 80000 CallbackError = 80000
//通用错误码 //通用错误码.
ServerInternalError = 500 //服务器内部错误 ServerInternalError = 500 //服务器内部错误
ArgsError = 1001 //输入参数错误 ArgsError = 1001 //输入参数错误
NoPermissionError = 1002 //权限不足 NoPermissionError = 1002 //权限不足
DuplicateKeyError = 1003 DuplicateKeyError = 1003
RecordNotFoundError = 1004 //记录不存在 RecordNotFoundError = 1004 // 记录不存在
// 账号错误码 // 账号错误码.
UserIDNotFoundError = 1101 //UserID不存在 或未注册 UserIDNotFoundError = 1101 // UserID不存在 或未注册
RegisteredAlreadyError = 1102 //用户已经注册过了 RegisteredAlreadyError = 1102 // 用户已经注册过了
// 群组错误码 // 群组错误码.
GroupIDNotFoundError = 1201 //GroupID不存在 GroupIDNotFoundError = 1201 // GroupID不存在
GroupIDExisted = 1202 //GroupID已存在 GroupIDExisted = 1202 // GroupID已存在
NotInGroupYetError = 1203 //不在群组中 NotInGroupYetError = 1203 // 不在群组中
DismissedAlreadyError = 1204 //群组已经解散 DismissedAlreadyError = 1204 // 群组已经解散
GroupTypeNotSupport = 1205 GroupTypeNotSupport = 1205
GroupRequestHandled = 1206 GroupRequestHandled = 1206
// 关系链错误码 // 关系链错误码.
CanNotAddYourselfError = 1301 //不能添加自己为好友 CanNotAddYourselfError = 1301 // 不能添加自己为好友
BlockedByPeer = 1302 //被对方拉黑 BlockedByPeer = 1302 // 被对方拉黑
NotPeersFriend = 1303 //不是对方的好友 NotPeersFriend = 1303 // 不是对方的好友
RelationshipAlreadyError = 1304 //已经是好友关系 RelationshipAlreadyError = 1304 // 已经是好友关系
// 消息错误码 // 消息错误码.
MessageHasReadDisable = 1401 MessageHasReadDisable = 1401
MutedInGroup = 1402 //群成员被禁言 MutedInGroup = 1402 // 群成员被禁言
MutedGroup = 1403 //群被禁言 MutedGroup = 1403 // 群被禁言
MsgAlreadyRevoke = 1404 //消息已撤回 MsgAlreadyRevoke = 1404 // 消息已撤回
// token错误码 // token错误码.
TokenExpiredError = 1501 TokenExpiredError = 1501
TokenInvalidError = 1502 TokenInvalidError = 1502
TokenMalformedError = 1503 TokenMalformedError = 1503
@@ -83,10 +83,10 @@ const (
TokenKickedError = 1506 TokenKickedError = 1506
TokenNotExistError = 1507 TokenNotExistError = 1507
// 长连接网关错误码 // 长连接网关错误码.
ConnOverMaxNumLimit = 1601 ConnOverMaxNumLimit = 1601
ConnArgsErr = 1602 ConnArgsErr = 1602
// S3错误码 // S3错误码.
FileUploadedExpiredError = 1701 // 上传过期 FileUploadedExpiredError = 1701 // 上传过期
) )
+4 -4
View File
@@ -38,11 +38,11 @@ var (
ErrData = NewCodeError(DataError, "DataError") ErrData = NewCodeError(DataError, "DataError")
ErrTokenExpired = NewCodeError(TokenExpiredError, "TokenExpiredError") ErrTokenExpired = NewCodeError(TokenExpiredError, "TokenExpiredError")
ErrTokenInvalid = NewCodeError(TokenInvalidError, "TokenInvalidError") // ErrTokenInvalid = NewCodeError(TokenInvalidError, "TokenInvalidError") //
ErrTokenMalformed = NewCodeError(TokenMalformedError, "TokenMalformedError") //格式错误 ErrTokenMalformed = NewCodeError(TokenMalformedError, "TokenMalformedError") // 格式错误
ErrTokenNotValidYet = NewCodeError(TokenNotValidYetError, "TokenNotValidYetError") //还未生效 ErrTokenNotValidYet = NewCodeError(TokenNotValidYetError, "TokenNotValidYetError") // 还未生效
ErrTokenUnknown = NewCodeError(TokenUnknownError, "TokenUnknownError") //未知错误 ErrTokenUnknown = NewCodeError(TokenUnknownError, "TokenUnknownError") // 未知错误
ErrTokenKicked = NewCodeError(TokenKickedError, "TokenKickedError") ErrTokenKicked = NewCodeError(TokenKickedError, "TokenKickedError")
ErrTokenNotExist = NewCodeError(TokenNotExistError, "TokenNotExistError") //在redis中不存在 ErrTokenNotExist = NewCodeError(TokenNotExistError, "TokenNotExistError") // 在redis中不存在
ErrDuplicateKey = NewCodeError(DuplicateKeyError, "DuplicateKeyError") ErrDuplicateKey = NewCodeError(DuplicateKeyError, "DuplicateKeyError")
ErrMessageHasReadDisable = NewCodeError(MessageHasReadDisable, "MessageHasReadDisable") ErrMessageHasReadDisable = NewCodeError(MessageHasReadDisable, "MessageHasReadDisable")
+16 -3
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by protoc-gen-go. DO NOT EDIT. // Code generated by protoc-gen-go. DO NOT EDIT.
// versions: // versions:
// protoc-gen-go v1.29.1 // protoc-gen-go v1.29.1
@@ -8,14 +22,13 @@ package auth
import ( import (
context "context" context "context"
reflect "reflect"
sync "sync"
grpc "google.golang.org/grpc" grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes" codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status" status "google.golang.org/grpc/status"
protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl" protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
) )
const ( const (
+17 -5
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by protoc-gen-go. DO NOT EDIT. // Code generated by protoc-gen-go. DO NOT EDIT.
// versions: // versions:
// protoc-gen-go v1.29.1 // protoc-gen-go v1.29.1
@@ -8,16 +22,14 @@ package conversation
import ( import (
context "context" context "context"
reflect "reflect" wrapperspb "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/wrapperspb"
sync "sync"
grpc "google.golang.org/grpc" grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes" codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status" status "google.golang.org/grpc/status"
protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl" protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
wrapperspb "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/wrapperspb" sync "sync"
) )
const ( const (
+16 -3
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by protoc-gen-go. DO NOT EDIT. // Code generated by protoc-gen-go. DO NOT EDIT.
// versions: // versions:
// protoc-gen-go v1.29.1 // protoc-gen-go v1.29.1
@@ -7,11 +21,10 @@
package errinfo package errinfo
import ( import (
reflect "reflect"
sync "sync"
protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl" protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
) )
const ( const (
+17 -5
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by protoc-gen-go. DO NOT EDIT. // Code generated by protoc-gen-go. DO NOT EDIT.
// versions: // versions:
// protoc-gen-go v1.29.1 // protoc-gen-go v1.29.1
@@ -8,16 +22,14 @@ package friend
import ( import (
context "context" context "context"
reflect "reflect" sdkws "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
sync "sync"
grpc "google.golang.org/grpc" grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes" codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status" status "google.golang.org/grpc/status"
protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl" protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sdkws "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws" sync "sync"
) )
const ( const (
-3
View File
@@ -23,9 +23,6 @@ func (x *CreateGroupReq) Check() error {
if x.GroupInfo == nil { if x.GroupInfo == nil {
return errs.ErrArgs.Wrap("groupInfo is empty") return errs.ErrArgs.Wrap("groupInfo is empty")
} }
if x.GroupInfo.OwnerUserID == "" {
return errs.ErrArgs.Wrap("GroupInfo.ownerUserID")
}
if x.GroupInfo.GroupType > 2 || x.GroupInfo.GroupType < 0 { if x.GroupInfo.GroupType > 2 || x.GroupInfo.GroupType < 0 {
return errs.ErrArgs.Wrap("GroupType is invalid") return errs.ErrArgs.Wrap("GroupType is invalid")
} }
+18 -6
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by protoc-gen-go. DO NOT EDIT. // Code generated by protoc-gen-go. DO NOT EDIT.
// versions: // versions:
// protoc-gen-go v1.29.1 // protoc-gen-go v1.29.1
@@ -8,17 +22,15 @@ package group
import ( import (
context "context" context "context"
reflect "reflect" sdkws "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
sync "sync" wrapperspb "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/wrapperspb"
grpc "google.golang.org/grpc" grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes" codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status" status "google.golang.org/grpc/status"
protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl" protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sdkws "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws" sync "sync"
wrapperspb "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/wrapperspb"
) )
const ( const (
-12
View File
@@ -133,9 +133,6 @@ func (x *MarkConversationAsReadReq) Check() error {
if x.ConversationID == "" { if x.ConversationID == "" {
return errs.ErrArgs.Wrap("conversationID is empty") return errs.ErrArgs.Wrap("conversationID is empty")
} }
if x.Seqs == nil {
return errs.ErrArgs.Wrap("seqs is empty")
}
if x.UserID == "" { if x.UserID == "" {
return errs.ErrArgs.Wrap("userID is empty") return errs.ErrArgs.Wrap("userID is empty")
} }
@@ -165,9 +162,6 @@ func (x *ClearConversationsMsgReq) Check() error {
if x.UserID == "" { if x.UserID == "" {
return errs.ErrArgs.Wrap("userID is empty") return errs.ErrArgs.Wrap("userID is empty")
} }
if x.DeleteSyncOpt == nil {
return errs.ErrArgs.Wrap("deleteSyncOpt is empty")
}
return nil return nil
} }
@@ -175,9 +169,6 @@ func (x *UserClearAllMsgReq) Check() error {
if x.UserID == "" { if x.UserID == "" {
return errs.ErrArgs.Wrap("userID is empty") return errs.ErrArgs.Wrap("userID is empty")
} }
if x.DeleteSyncOpt == nil {
return errs.ErrArgs.Wrap("deleteSyncOpt is empty")
}
return nil return nil
} }
@@ -191,9 +182,6 @@ func (x *DeleteMsgsReq) Check() error {
if x.Seqs == nil { if x.Seqs == nil {
return errs.ErrArgs.Wrap("seqs is empty") return errs.ErrArgs.Wrap("seqs is empty")
} }
if x.DeleteSyncOpt == nil {
return errs.ErrArgs.Wrap("deleteSyncOpt is empty")
}
return nil return nil
} }
+906 -180
View File
File diff suppressed because it is too large Load Diff
+54
View File
@@ -232,12 +232,66 @@ message GetActiveGroupResp {
repeated ActiveGroup groups = 4; repeated ActiveGroup groups = 4;
} }
message SearchMessageReq{
string sendID=1;//ID
string recvID=2;//ID
int32 msgType=3;
string sendTime=4;
int32 sessionType=5;
sdkws.RequestPagination pagination = 6;
}
message SearchMessageResp{
repeated ChatLog chatLogs=1;
int32 chatLogsNum = 2;
}
message manageMsgReq{
string recvID=1;
string sendID=2;
string groupID=3;
int64 seq=4;
int32 sessionType=5;
}
message manageMsgResp{
}
message ChatLog {
string serverMsgID = 1;
string clientMsgID = 2;
string sendID = 3;
string recvID = 4;
string groupID = 5;
string recvNickname = 6;
int32 senderPlatformID = 7;
string senderNickname = 8;
string senderFaceURL = 9;
string groupName = 10;
int32 sessionType = 11;
int32 msgFrom = 12;
int32 contentType = 13;
string content = 14;
int32 status = 15;
int64 sendTime = 16;
int64 createTime = 17;
string ex = 18;
string groupFaceURL=19;
uint32 groupMemberCount=20;
int64 seq=21;
string groupOwner=22;
int32 groupType=23;
}
service msg { service msg {
//seq //seq
rpc GetMaxSeq(sdkws.GetMaxSeqReq) returns(sdkws.GetMaxSeqResp); rpc GetMaxSeq(sdkws.GetMaxSeqReq) returns(sdkws.GetMaxSeqResp);
rpc GetConversationMaxSeq(GetConversationMaxSeqReq) returns(GetConversationMaxSeqResp); rpc GetConversationMaxSeq(GetConversationMaxSeqReq) returns(GetConversationMaxSeqResp);
// //
rpc PullMessageBySeqs(sdkws.PullMessageBySeqsReq) returns(sdkws.PullMessageBySeqsResp); rpc PullMessageBySeqs(sdkws.PullMessageBySeqsReq) returns(sdkws.PullMessageBySeqsResp);
rpc SearchMessage(SearchMessageReq) returns(SearchMessageResp);
rpc ManageMsg(manageMsgReq) returns (manageMsgResp);
// //
rpc SendMsg(SendMsgReq) returns(SendMsgResp); rpc SendMsg(SendMsgReq) returns(SendMsgResp);
+17 -5
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by protoc-gen-go. DO NOT EDIT. // Code generated by protoc-gen-go. DO NOT EDIT.
// versions: // versions:
// protoc-gen-go v1.29.1 // protoc-gen-go v1.29.1
@@ -8,16 +22,14 @@ package msggateway
import ( import (
context "context" context "context"
reflect "reflect" sdkws "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
sync "sync"
grpc "google.golang.org/grpc" grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes" codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status" status "google.golang.org/grpc/status"
protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl" protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sdkws "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws" sync "sync"
) )
const ( const (
+17 -5
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by protoc-gen-go. DO NOT EDIT. // Code generated by protoc-gen-go. DO NOT EDIT.
// versions: // versions:
// protoc-gen-go v1.29.1 // protoc-gen-go v1.29.1
@@ -8,16 +22,14 @@ package push
import ( import (
context "context" context "context"
reflect "reflect" sdkws "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
sync "sync"
grpc "google.golang.org/grpc" grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes" codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status" status "google.golang.org/grpc/status"
protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl" protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sdkws "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws" sync "sync"
) )
const ( const (
+3 -3
View File
@@ -26,10 +26,10 @@ func (x *MsgData) Check() error {
if x.Content == nil { if x.Content == nil {
return errs.ErrArgs.Wrap("content is empty") return errs.ErrArgs.Wrap("content is empty")
} }
if x.ContentType < 101 || x.ContentType > 203 { if x.ContentType <= constant.ContentTypeBegin || x.ContentType >= constant.NotificationEnd {
return errs.ErrArgs.Wrap("content is empty") return errs.ErrArgs.Wrap("content type is invalid")
} }
if x.SessionType < 1 || x.SessionType > 4 { if x.SessionType < constant.SingleChatType || x.SessionType > constant.NotificationChatType {
return errs.ErrArgs.Wrap("sessionType is invalid") return errs.ErrArgs.Wrap("sessionType is invalid")
} }
if x.SessionType == constant.SingleChatType || x.SessionType == constant.NotificationChatType { if x.SessionType == constant.SingleChatType || x.SessionType == constant.NotificationChatType {
+17 -5
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by protoc-gen-go. DO NOT EDIT. // Code generated by protoc-gen-go. DO NOT EDIT.
// versions: // versions:
// protoc-gen-go v1.29.1 // protoc-gen-go v1.29.1
@@ -7,13 +21,11 @@
package sdkws package sdkws
import ( import (
reflect "reflect" wrapperspb "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/wrapperspb"
sync "sync"
protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl" protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
wrapperspb "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/wrapperspb" sync "sync"
) )
const ( const (
+15 -2
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by protoc-gen-go. DO NOT EDIT. // Code generated by protoc-gen-go. DO NOT EDIT.
// versions: // versions:
// protoc-gen-go v1.29.1 // protoc-gen-go v1.29.1
@@ -7,10 +21,9 @@
package statistics package statistics
import ( import (
reflect "reflect"
protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl" protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
) )
const ( const (
+16 -3
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by protoc-gen-go. DO NOT EDIT. // Code generated by protoc-gen-go. DO NOT EDIT.
// versions: // versions:
// protoc-gen-go v1.29.1 // protoc-gen-go v1.29.1
@@ -8,14 +22,13 @@ package third
import ( import (
context "context" context "context"
reflect "reflect"
sync "sync"
grpc "google.golang.org/grpc" grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes" codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status" status "google.golang.org/grpc/status"
protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl" protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
) )
const ( const (
+18 -6
View File
@@ -1,3 +1,17 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by protoc-gen-go. DO NOT EDIT. // Code generated by protoc-gen-go. DO NOT EDIT.
// versions: // versions:
// protoc-gen-go v1.29.1 // protoc-gen-go v1.29.1
@@ -8,17 +22,15 @@ package user
import ( import (
context "context" context "context"
reflect "reflect" conversation "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/conversation"
sync "sync" sdkws "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
grpc "google.golang.org/grpc" grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes" codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status" status "google.golang.org/grpc/status"
protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl" protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
conversation "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/conversation" sync "sync"
sdkws "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
) )
const ( const (

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