Compare commits

..

464 Commits

Author SHA1 Message Date
Gordon
381e72f1ef send message 2022-05-13 21:05:39 +08:00
Gordon
91fe549c25 add log 2022-05-13 16:30:36 +08:00
Gordon
a472da9ea6 msg bug fix 2022-05-13 16:19:11 +08:00
Gordon
20c7fe81dc Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-05-13 16:00:03 +08:00
Gordon
3ef445eb2e msg bug fix 2022-05-13 15:59:38 +08:00
wangchuxiao
4afc38523d organization 2022-05-13 15:41:11 +08:00
wangchuxiao
15616e8d07 Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-05-13 15:38:19 +08:00
wangchuxiao
2534921af9 organization 2022-05-13 15:38:05 +08:00
Gordon
0206198f55 Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-05-13 10:07:43 +08:00
Gordon
3c8c402f10 compose restore 2022-05-13 10:06:56 +08:00
wangchuxiao
098dae9640 organization 2022-05-12 19:11:55 +08:00
wangchuxiao
42c38de3e2 organization 2022-05-12 19:09:25 +08:00
wangchuxiao
be10e6a9de organization 2022-05-12 19:07:26 +08:00
wangchuxiao
6b5fb81e01 Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-05-12 19:06:25 +08:00
wangchuxiao
bb5991b111 organization 2022-05-12 19:00:48 +08:00
wenxu12345
8f261970e9 Update group members' faceURL immediately 2022-05-12 18:00:23 +08:00
Gordon
093a8f18ef test 2022-05-11 21:01:36 +08:00
Gordon
9c19b5b785 test 2022-05-11 20:54:04 +08:00
Gordon
35958ca3a2 test 2022-05-11 20:49:47 +08:00
Gordon
3bc2e97e8b test 2022-05-11 20:02:33 +08:00
Gordon
eb7ff77461 test 2022-05-11 19:45:44 +08:00
Gordon
d36f4cf6f8 test 2022-05-11 19:44:08 +08:00
Gordon
f373669f02 test 2022-05-11 19:31:32 +08:00
Gordon
37596589a7 Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-05-11 19:28:00 +08:00
Gordon
3e90426d8e test 2022-05-11 19:27:49 +08:00
wenxu12345
35a184827a Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-05-11 19:25:33 +08:00
wenxu12345
2edd3c5614 When you create a group chat, the group member can be empty 2022-05-11 19:25:06 +08:00
Gordon
cec5a6ceeb test 2022-05-11 19:21:28 +08:00
Gordon
dc6b0b4dde test 2022-05-11 19:16:57 +08:00
Gordon
3ecc1816be test 2022-05-11 18:58:11 +08:00
Gordon
9a90c2e568 test 2022-05-11 18:54:22 +08:00
Gordon
ab747d0338 test 2022-05-11 18:49:21 +08:00
Gordon
8753f91a4a send group message split topic 2022-05-11 18:38:58 +08:00
Gordon
f8af109821 send group message split topic 2022-05-11 18:33:48 +08:00
Gordon
804eb6c076 video message send 2022-05-11 14:34:21 +08:00
Gordon
f4f3ff0eda Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-05-11 13:26:50 +08:00
Gordon
03c0b1ea91 add kafka manager 2022-05-11 13:26:39 +08:00
wenxu12345
38535bde84 add RpcRegisterIP 2022-05-11 12:20:28 +08:00
wenxu12345
17e1fa54cf Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-05-11 12:13:43 +08:00
wenxu12345
a4f5dd9d89 add log 2022-05-11 12:13:17 +08:00
wangchuxiao
6269902140 update app 2022-05-11 11:07:04 +08:00
wangchuxiao
b964e424b2 update app 2022-05-11 10:47:32 +08:00
wangchuxiao
73665f62b3 update app 2022-05-11 10:46:54 +08:00
wangchuxiao
3fca780132 update app 2022-05-11 10:27:00 +08:00
wangchuxiao
b5e01dcb5e update app 2022-05-11 10:24:11 +08:00
wangchuxiao
f180b89a9c Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-05-11 10:20:13 +08:00
wangchuxiao
98a903e60c update app 2022-05-11 10:19:58 +08:00
Gordon
c20cc8fb18 Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-05-11 09:55:13 +08:00
Gordon
99f5c4e12f update sarama version 2022-05-11 09:54:47 +08:00
wangchuxiao
17759f9a98 update app 2022-05-10 19:28:36 +08:00
wangchuxiao
6c0e96213f update app 2022-05-10 19:04:08 +08:00
wangchuxiao
2c89d80a27 update app 2022-05-10 18:28:57 +08:00
wangchuxiao
e314fd4a0a update app 2022-05-10 18:22:18 +08:00
wangchuxiao
affbe9f5a9 update app 2022-05-10 17:50:57 +08:00
wangchuxiao
7a423eb6e1 update app 2022-05-10 17:50:22 +08:00
wangchuxiao
7137924baa update app 2022-05-10 17:39:27 +08:00
wangchuxiao
c998bce34f update app 2022-05-10 17:23:28 +08:00
wangchuxiao
f5d4397f0b update app 2022-05-10 17:17:20 +08:00
wangchuxiao
608b166b32 update app 2022-05-10 17:00:52 +08:00
wangchuxiao
472cda8315 update app 2022-05-10 16:59:45 +08:00
wangchuxiao
7a78e5d869 update app 2022-05-10 16:53:58 +08:00
wangchuxiao
8effca3a7c update app 2022-05-10 16:39:08 +08:00
wangchuxiao
fab52b6a56 update app 2022-05-10 16:23:56 +08:00
wangchuxiao
e98ef5f5f2 update app 2022-05-10 16:22:16 +08:00
wangchuxiao
7aa84607c8 update app 2022-05-10 16:21:26 +08:00
wangchuxiao
928fc374c7 update app 2022-05-10 16:07:58 +08:00
wangchuxiao
4ea8cb5903 update app 2022-05-10 16:04:26 +08:00
wangchuxiao
db6acacf2e update app 2022-05-10 16:02:05 +08:00
wangchuxiao
59aa71b3b8 update app 2022-05-10 15:58:29 +08:00
wangchuxiao
ccfa487493 update app 2022-05-10 15:41:59 +08:00
wangchuxiao
9fcc41aeff update app 2022-05-10 15:34:00 +08:00
wangchuxiao
d9a4fa3f49 update app 2022-05-10 15:21:51 +08:00
wangchuxiao
6c821dc42a update app 2022-05-10 15:16:20 +08:00
wangchuxiao
d58e34ed3d update app 2022-05-10 15:07:07 +08:00
wangchuxiao
ff37d1cb02 update app 2022-05-10 14:57:54 +08:00
wangchuxiao
dcf119ae59 update app 2022-05-10 14:38:43 +08:00
wangchuxiao
1338cf875a update app 2022-05-10 14:20:15 +08:00
wangchuxiao
ed3e299e0b update app 2022-05-10 14:18:36 +08:00
wangchuxiao
f85645a78a update app 2022-05-10 14:17:31 +08:00
wangchuxiao
e412abd017 update app 2022-05-10 14:07:44 +08:00
wangchuxiao
1efa654e7d update app 2022-05-10 13:06:13 +08:00
wangchuxiao
00b58068dc Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-05-10 12:30:16 +08:00
wangchuxiao
7be5208daf update app 2022-05-10 12:30:00 +08:00
wenxu12345
7ad555a41b add ParseToken 2022-05-10 12:20:53 +08:00
wenxu12345
872f70a418 Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-05-10 12:07:33 +08:00
wenxu12345
c37d2e78d2 add ParseToken 2022-05-10 12:07:09 +08:00
wangchuxiao
b606d066fc Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-05-10 12:07:07 +08:00
wangchuxiao
d4608eec26 update app 2022-05-10 12:05:02 +08:00
wenxu12345
0bc8e231ad Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-05-10 12:01:26 +08:00
wenxu12345
2dab5e4a78 add ParseToken 2022-05-10 11:57:25 +08:00
wangchuxiao
c6aa37851d Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-05-10 11:53:08 +08:00
wangchuxiao
31bd106ffd update app 2022-05-10 11:52:52 +08:00
wenxu12345
74cea2b41c Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-05-10 11:49:11 +08:00
wangchuxiao
46f9a00b75 update app 2022-05-10 11:48:33 +08:00
wenxu12345
450d8c21cf Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-05-10 11:48:28 +08:00
wenxu12345
2073bc77c8 add ParseToken 2022-05-10 11:48:10 +08:00
wangchuxiao
b6a5501f71 update app 2022-05-10 11:41:13 +08:00
wangchuxiao
e27b98cdc1 update app 2022-05-10 11:40:40 +08:00
wangchuxiao
8af500462f update app 2022-05-10 11:22:10 +08:00
wangchuxiao
30fc4c28b7 cache 2022-05-10 11:17:54 +08:00
Gordon
74b582369a log change 2022-05-10 11:00:15 +08:00
Gordon
c9ab2b507b Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-05-10 10:52:43 +08:00
Gordon
2b479319c1 log change 2022-05-10 10:52:32 +08:00
wangchuxiao
3a3ac012bb Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-05-10 10:45:21 +08:00
wangchuxiao
00265a7e8e cache 2022-05-10 10:44:43 +08:00
wenxu12345
0dafb50223 Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-05-10 10:13:23 +08:00
wenxu12345
ac9620c253 add ParseToken 2022-05-10 10:12:53 +08:00
Gordon
6e226b165c sdk version 2022-05-10 10:01:46 +08:00
wenxu12345
6226f65e20 add ParseToken 2022-05-10 09:47:00 +08:00
wenxu12345
7de29c29e9 add ParseToken 2022-05-10 09:45:55 +08:00
wenxu12345
deed6c7bbe Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-05-10 09:17:22 +08:00
wenxu12345
c234e2ca3d log 2022-05-10 09:16:56 +08:00
Gordon
19bffa288d Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-05-10 09:13:34 +08:00
Gordon
9303096430 log change 2022-05-10 09:09:37 +08:00
wenxu12345
98d5f5ee3e Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-05-10 09:09:20 +08:00
wenxu12345
ba16fceeb8 log 2022-05-10 09:06:49 +08:00
Gordon
c49b5f78bf test 2022-05-09 18:45:44 +08:00
Gordon
446688d5b2 test 2022-05-09 18:34:14 +08:00
Gordon
e2cacd9c4b test 2022-05-09 18:23:06 +08:00
Gordon
d5c9e08888 manager send message to mysql duplicate primary key fix 2022-05-09 14:15:29 +08:00
skiffer-git
ab0ead4e05 grpc 2022-05-09 11:39:55 +08:00
wenxu12345
9a267db583 Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-05-09 11:38:22 +08:00
wenxu12345
fb15cbef90 grpc 1.45.0 2022-05-09 11:38:08 +08:00
wangchuxiao
97e5d9f610 Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-05-09 10:00:12 +08:00
wangchuxiao
305ee394b1 cache 2022-05-09 10:00:03 +08:00
skiffer-git
a251d521a1 set api ip in config 2022-05-07 19:52:18 +08:00
skiffer-git
b5065cb52f Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-05-07 17:05:56 +08:00
skiffer-git
dca16e83d3 rpc register ip 2022-05-07 17:05:05 +08:00
wangchuxiao
c5256fe2cb Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-05-07 15:02:03 +08:00
wangchuxiao
1b93ba5355 cache 2022-05-07 15:01:48 +08:00
FG
fd7171f5a4 Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-05-07 14:25:54 +08:00
wangchuxiao
685fc1a37b cache 2022-05-07 14:13:47 +08:00
wangchuxiao
a738c93163 Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-05-07 13:21:22 +08:00
wangchuxiao
4ac863fa6a cache 2022-05-07 13:21:05 +08:00
skiffer-git
fed369ad5d add err log 2022-05-07 12:04:07 +08:00
skiffer-git
f2c91d015e add err log 2022-05-07 12:01:01 +08:00
skiffer-git
e122349f9e Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-05-07 11:55:32 +08:00
skiffer-git
bb07c3ab45 add err log 2022-05-07 11:55:19 +08:00
wangchuxiao
65a4b38ee5 cache 2022-05-07 11:42:47 +08:00
wangchuxiao
bbc3f5c19a cache 2022-05-07 11:39:27 +08:00
wangchuxiao
0b4ba548a5 Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-05-07 11:14:56 +08:00
wangchuxiao
747b963bd4 cache 2022-05-07 11:14:29 +08:00
FG
32b9820725 remove timer and database init 2022-05-07 10:37:52 +08:00
skiffer-git
b217fede87 upgrade etcd & grpc 2022-05-07 09:41:56 +08:00
skiffer-git
a9ce8a3b2e upgrade etcd & grpc 2022-05-07 09:34:49 +08:00
wangchuxiao
7914e7bc14 office 2022-05-06 17:35:33 +08:00
wangchuxiao
ed8716510b office 2022-05-06 17:32:52 +08:00
wangchuxiao
efd2ae59f5 office 2022-05-06 17:23:37 +08:00
wangchuxiao
1923d0b809 office 2022-05-06 17:05:59 +08:00
wangchuxiao
99f6752590 office 2022-05-06 16:51:59 +08:00
wangchuxiao
131746f94e office 2022-05-06 16:51:34 +08:00
wangchuxiao
f0ed6973c8 office 2022-05-06 16:50:19 +08:00
wangchuxiao
2cf070a26c office 2022-05-06 16:38:29 +08:00
wangchuxiao
3c68ecb7f1 office 2022-05-06 15:58:50 +08:00
wangchuxiao
243f5fcda4 fix bug 2022-05-06 11:19:16 +08:00
wangchuxiao
e22b7f36ce fix bug 2022-05-06 11:07:32 +08:00
wangchuxiao
308ea15763 Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-05-05 19:23:01 +08:00
wangchuxiao
e26f9c58fa office 2022-05-05 19:22:47 +08:00
Gordon
4ca758174e Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-05-05 16:14:16 +08:00
Gordon
bf8e35e168 log change 2022-05-05 16:13:45 +08:00
wangchuxiao
2a3265ed71 office 2022-05-05 14:14:30 +08:00
wangchuxiao
3a06617a7d office 2022-05-05 11:59:44 +08:00
wangchuxiao
d75eb456dc office 2022-05-05 11:58:48 +08:00
wangchuxiao
8ed0f8ec73 Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-05-05 10:11:00 +08:00
skiffer-git
185e0dce6e delete msg by index 2022-05-04 18:35:13 +08:00
skiffer-git
d9e74a78f0 delete msg by index 2022-05-04 18:02:24 +08:00
skiffer-git
700483dd48 group chat log 2022-05-02 20:03:13 +08:00
skiffer-git
1c80b820cb group chat log 2022-05-02 20:00:09 +08:00
skiffer-git
59e5cfb04d group chat log 2022-05-02 19:45:32 +08:00
skiffer-git
b06550e2cb group chat log 2022-05-02 19:43:22 +08:00
skiffer-git
ca4bf13569 group chat log 2022-05-02 19:23:26 +08:00
skiffer-git
eae3a50435 group chat log 2022-05-02 19:16:00 +08:00
skiffer-git
de2956ec3c group chat log 2022-05-02 08:47:21 +08:00
skiffer-git
a2e62c9fb5 fix bug: group chat share pb 2022-05-01 16:21:28 +08:00
wangchuxiao
e7fdc318f1 cache bug fix 2022-05-01 13:27:52 +08:00
wangchuxiao
62dd559b7c cache bug fix 2022-05-01 13:08:46 +08:00
skiffer-git
4a631753a0 add msgToMQSingle && msgToMQGroup 2022-05-01 12:04:31 +08:00
wangchuxiao
b696984655 cache 2022-04-29 19:36:36 +08:00
wangchuxiao
f1dbec122a cache 2022-04-29 18:59:08 +08:00
wangchuxiao
47cb54461f cache 2022-04-29 18:56:53 +08:00
wangchuxiao
91e03f7cfd cache 2022-04-29 18:53:33 +08:00
Gordon
c0314d95c9 send message parallel 2022-04-29 18:47:55 +08:00
wenxu12345
8e17b3ff51 Revert "update etcd to v3.5.2 (#206)"
This reverts commit 766b6e9f
2022-04-29 18:45:11 +08:00
wenxu12345
b932a659b6 etcd 2022-04-29 18:35:55 +08:00
wenxu12345
80b2ed19e0 etcd 2022-04-29 18:32:46 +08:00
wenxu12345
88000926f4 etcd 2022-04-29 18:30:02 +08:00
wenxu12345
12245fefed etcd 2022-04-29 18:24:18 +08:00
wenxu12345
8eebd5fb9a Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-04-29 18:20:09 +08:00
wenxu12345
c5b0e31d36 config 2022-04-29 18:19:59 +08:00
wangchuxiao
5c5e828cc6 Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-04-29 18:00:29 +08:00
Gordon
ecb11cf927 test 2022-04-29 17:59:53 +08:00
wangchuxiao
485241d080 cache & workMoments 2022-04-29 17:59:42 +08:00
Gordon
8701f8868c test 2022-04-29 17:58:57 +08:00
wenxu12345
e68086e149 config 2022-04-29 17:04:15 +08:00
wenxu12345
16a2d80801 config 2022-04-29 17:02:03 +08:00
wenxu12345
d5e5659a2c config 2022-04-29 16:42:42 +08:00
wenxu12345
3c2e8dcf87 config 2022-04-29 16:33:01 +08:00
wangchuxiao
03320e8644 Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-04-29 15:52:18 +08:00
wangchuxiao
40ae6ccf2f cache & workMoments 2022-04-29 14:26:04 +08:00
Gordon
bcbade3729 Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-04-28 21:21:27 +08:00
Gordon
58a6f9cae3 test 2022-04-28 21:17:50 +08:00
Gordon
bf154eb8c3 Merge branch 'main' into tuoyun
# Conflicts:
#	script/sdk_svr_start.sh
2022-04-28 21:12:14 +08:00
yiippee
766b6e9fef update etcd to v3.5.2 (#206)
Co-authored-by: lizhanbin <lizhanbin@52tt.com>
2022-04-28 21:09:43 +08:00
wangchuxiao
d89a41d4c7 Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-04-28 19:08:15 +08:00
wangchuxiao
d24a7d7b22 cache & workMoments 2022-04-28 19:05:04 +08:00
wenxu12345
57a746fc21 Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-04-28 19:01:20 +08:00
wenxu12345
2c1bd41fba ulimit -n 2022-04-28 19:00:37 +08:00
wangchuxiao
6260cf24cc cache 2022-04-28 18:25:10 +08:00
wangchuxiao
88d4a670d4 cache 2022-04-28 18:23:55 +08:00
wangchuxiao
ea0b6c5ee5 cache 2022-04-28 17:38:09 +08:00
wangchuxiao
20f61042fc cache 2022-04-28 17:35:19 +08:00
wangchuxiao
2751a967e8 Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-04-28 16:48:52 +08:00
wangchuxiao
93057870a7 cache 2022-04-28 16:48:39 +08:00
Gordon
6b98c3fed5 Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-04-28 16:47:56 +08:00
Gordon
eb63ed926d log modify 2022-04-28 16:47:46 +08:00
wangchuxiao
b72787f5bb cache 2022-04-28 16:38:33 +08:00
wangchuxiao
0793b2ab38 cache 2022-04-28 16:29:40 +08:00
wangchuxiao
604ed3e3e1 cache 2022-04-28 16:19:51 +08:00
wangchuxiao
0aefbc2c7d Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun
# Conflicts:
#	internal/rpc/friend/firend.go
2022-04-28 15:32:38 +08:00
wangchuxiao
eb1fa90788 cache 2022-04-28 15:17:19 +08:00
wangchuxiao
65f02e5139 cache 2022-04-28 15:13:39 +08:00
Gordon
bbfe65a905 send message add cache 2022-04-28 15:10:42 +08:00
wangchuxiao
59468eb162 fix work moments bug 2022-04-28 10:46:21 +08:00
wangchuxiao
1889a283ee fix work moments bug 2022-04-27 14:43:46 +08:00
wangchuxiao
0655b2021d Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-04-27 14:36:15 +08:00
wangchuxiao
a1b8c9b6fd fix work moments bug 2022-04-27 14:35:02 +08:00
wenxu12345
c4a60bc6f6 Merge remote-tracking branch 'origin/main' 2022-04-27 10:09:18 +08:00
wenxu12345
eb7037eea8 ulimit -n 2022-04-27 10:09:05 +08:00
wenxu12345
7546083cd5 ulimit -n 2022-04-27 10:08:09 +08:00
wangchuxiao
74ee36f43a Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-04-26 20:20:39 +08:00
wangchuxiao
f8c3e4d66f Merge branch 'tuoyun'
# Conflicts:
#	cmd/open_im_cms_api/main.go
#	config/config.yaml
2022-04-26 20:19:02 +08:00
wenxu12345
6db8d9a38a Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-04-26 18:26:48 +08:00
wenxu12345
61145a2d03 fix bug user_register port 2022-04-26 18:23:10 +08:00
wangchuxiao
4a9410742a Merge branch 'tuoyun'
# Conflicts:
#	cmd/open_im_cms_api/main.go
#	config/config.yaml
2022-04-26 16:50:43 +08:00
wangchuxiao
db78e4ef03 Merge branch 'main' of github.com:OpenIMSDK/Open-IM-Server 2022-04-26 16:46:17 +08:00
wangchuxiao
7b0eb4e79d work moments 2022-04-26 16:24:43 +08:00
wangchuxiao
17f6b8eb2a work moments 2022-04-26 16:01:48 +08:00
wangchuxiao
37c40d7dda work moments 2022-04-26 15:52:03 +08:00
wangchuxiao
1a2aa876e3 work moments 2022-04-26 15:06:43 +08:00
wangchuxiao
39822f323f work moments 2022-04-26 15:05:23 +08:00
wangchuxiao
338acfba75 cache rpc 2022-04-26 14:57:15 +08:00
wangchuxiao
490f4f36f1 cache rpc 2022-04-26 14:43:55 +08:00
wangchuxiao
69c46f684f cache rpc 2022-04-26 14:38:11 +08:00
wangchuxiao
1626406557 cache rpc 2022-04-26 14:13:36 +08:00
wangchuxiao
f662defcf9 cache rpc 2022-04-26 11:19:21 +08:00
wangchuxiao
8f07f8e9e1 cache rpc 2022-04-26 11:19:14 +08:00
wangchuxiao
7e44f7f110 cache rpc 2022-04-26 10:33:49 +08:00
skiffer-git
b211a66e99 Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-04-26 09:09:44 +08:00
skiffer-git
0bdb066820 add cache 2022-04-26 09:09:33 +08:00
wenxu12345
4ee84e10fd fix bug 2022-04-25 21:13:46 +08:00
wenxu12345
ab706f4076 fix bug 2022-04-25 21:13:32 +08:00
wangchuxiao
bd7266653f cache rpc 2022-04-25 20:29:33 +08:00
wangchuxiao
08f968dced cache rpc 2022-04-25 20:20:34 +08:00
wangchuxiao
9f9ebd838a cache rpc 2022-04-25 20:16:43 +08:00
wangchuxiao
a03f89fb68 cache rpc 2022-04-25 20:05:21 +08:00
wangchuxiao
51146a4ed5 Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-04-25 19:57:54 +08:00
wangchuxiao
80301f2cb2 alter router 2022-04-25 19:57:35 +08:00
Gordon
9a9f26c435 conversation update 2022-04-25 19:56:46 +08:00
Gordon
eebe9cbd5f conversation update 2022-04-25 19:41:17 +08:00
Gordon
503d43b552 Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-04-25 19:15:01 +08:00
Gordon
b3077fc15d conversation update 2022-04-25 19:14:51 +08:00
wenxu12345
fdc462d071 Adjust port 2022-04-25 17:30:13 +08:00
wenxu12345
f44a26da3c Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-04-25 17:28:56 +08:00
wenxu12345
d12d03fd5e Adjust port 2022-04-25 17:28:43 +08:00
Gordon
51ee2df755 flag parse update 2022-04-25 17:13:54 +08:00
wenxu12345
a89bb33015 Adjust port 2022-04-25 16:58:35 +08:00
wenxu12345
7659cca8ba Adjust port 2022-04-25 16:58:05 +08:00
wenxu12345
f754e951f7 Adjust port 2022-04-25 16:55:56 +08:00
wenxu12345
e2905d01ac Adjust port 2022-04-25 16:47:51 +08:00
wenxu12345
9d691f2452 Adjust port 2022-04-25 16:21:48 +08:00
wenxu12345
a426c8bb26 Adjust port 2022-04-25 15:45:39 +08:00
wenxu12345
bc8b1722b0 config 2022-04-25 15:29:56 +08:00
wangchuxiao
ac31c612b3 work_moments 2022-04-25 10:40:31 +08:00
wangchuxiao
03c3eea54e work_moments 2022-04-25 10:35:20 +08:00
wangchuxiao
bccaf16343 work_moments 2022-04-25 10:07:14 +08:00
wangchuxiao
30df45ef2e work_moments 2022-04-24 18:49:03 +08:00
wangchuxiao
6500ba48a7 work_moments 2022-04-24 18:23:44 +08:00
wangchuxiao
03b35721a2 work_moments 2022-04-24 18:01:27 +08:00
wangchuxiao
14327d4462 Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-04-24 18:00:18 +08:00
wangchuxiao
1b968903e2 work_moments 2022-04-24 18:00:04 +08:00
Gordon
b719e95e6e Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-04-24 17:54:25 +08:00
Gordon
318eb2f47d shell update 2022-04-24 17:54:02 +08:00
wangchuxiao
010f24e5c3 work_moments 2022-04-24 17:46:47 +08:00
wangchuxiao
db9762c5b2 Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-04-24 17:44:10 +08:00
wangchuxiao
d1ebcde725 work_moments 2022-04-24 17:42:41 +08:00
Gordon
545f9cad2d add modify conversation api 2022-04-24 17:30:53 +08:00
Gordon
3247d84b6b add modify conversation api 2022-04-24 17:27:26 +08:00
Gordon
e73f0a916a add modify conversation api 2022-04-24 16:55:47 +08:00
Gordon
150af5ff8b @ people update 2022-04-24 15:55:19 +08:00
wangchuxiao
1659ab146d fix docker-compose 2022-04-24 11:57:21 +08:00
wangchuxiao
86e17d38d4 Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-04-24 11:54:08 +08:00
Gordon
1809c59f25 config 2022-04-24 11:53:50 +08:00
wangchuxiao
4eb9661730 fix docker-compose 2022-04-24 11:50:36 +08:00
Gordon
4acbe4b31a config 2022-04-24 11:49:01 +08:00
Gordon
df17dd749f add rpc conversation 2022-04-24 11:23:54 +08:00
wangchuxiao
20e5a88e56 Merge branch 'tuoyun' 2022-04-24 10:51:20 +08:00
wangchuxiao
0a939a5b91 Merge branch 'tuoyun'
# Conflicts:
#	config/config.yaml
2022-04-24 10:38:22 +08:00
wangchuxiao
6ad7c30a18 Merge branch 'main' of github.com:OpenIMSDK/Open-IM-Server 2022-04-24 10:34:54 +08:00
wangchuxiao
e6bfc60139 Merge branch 'tuoyun'
# Conflicts:
#	config/config.yaml
2022-04-24 10:34:15 +08:00
Gordon
c866baa4eb Merge branch 'tuoyun' 2022-04-22 19:46:31 +08:00
Gordon
91303acdbe conversation update 2022-04-22 19:45:29 +08:00
Gordon
1273af4b1b Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-04-22 19:45:10 +08:00
Gordon
e682b408f3 conversation update 2022-04-22 19:44:58 +08:00
skiffer-git
0a0c206998 add cache 2022-04-22 18:56:39 +08:00
wangchuxiao
44ffd98d0c Merge branch 'tuoyun'
# Conflicts:
#	config/config.yaml
2022-04-22 18:37:59 +08:00
wangchuxiao
53ec93c8f8 minio config 2022-04-22 18:36:02 +08:00
wangchuxiao
f779ed7628 workMoments 2022-04-22 17:19:35 +08:00
wangchuxiao
f2fdb74f23 Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-04-22 16:41:50 +08:00
wangchuxiao
4ba87e3349 workMoments 2022-04-22 16:41:41 +08:00
Gordon
7abee90992 Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-04-22 15:12:21 +08:00
Gordon
159a9e00c8 conversation update 2022-04-22 15:12:10 +08:00
wangchuxiao
9c62f38345 Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-04-21 18:39:01 +08:00
wangchuxiao
1443f5f997 workMoments 2022-04-21 18:38:48 +08:00
Gordon
17d8a124cd kick group invite group update 2022-04-21 18:09:20 +08:00
Gordon
5cd565306e kick group invite group update 2022-04-21 17:23:40 +08:00
Gordon
67010e20d7 Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-04-21 16:47:10 +08:00
Gordon
704604f6fe kick group invite group update 2022-04-21 16:46:48 +08:00
wangchuxiao
e687f56c7f Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-04-21 16:14:41 +08:00
wangchuxiao
ff85575e98 workMoments 2022-04-21 16:14:26 +08:00
Gordon
26be25c218 quit group and dismiss group update 2022-04-21 14:58:57 +08:00
Gordon
d3d5e0cbfb Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-04-21 12:53:39 +08:00
Gordon
4796bf632c quit group and dismiss group update 2022-04-21 12:53:28 +08:00
wangchuxiao
5eef365baf workMoments 2022-04-21 11:52:31 +08:00
wangchuxiao
937ff63af9 workMoments 2022-04-21 11:34:15 +08:00
wangchuxiao
33211bfb27 workMoments 2022-04-21 11:18:11 +08:00
wangchuxiao
a243da8b1e Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-04-21 10:43:46 +08:00
wangchuxiao
62e605a443 workMoments 2022-04-21 10:43:31 +08:00
skiffer-git
2bdaaa5a33 log 2022-04-20 20:58:51 +08:00
Gordon
bcad3c1ced add save message to mysql switch 2022-04-20 18:53:23 +08:00
Gordon
b865f5d6e7 Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-04-20 18:47:31 +08:00
Gordon
00664822ec conversation add fields 2022-04-20 18:47:21 +08:00
skiffer-git
4594c15de7 Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-04-20 18:39:23 +08:00
skiffer-git
2b6ec1672c Organization 2022-04-20 18:39:12 +08:00
Gordon
d44d5711cb Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-04-20 18:06:53 +08:00
Gordon
54cb13ba62 pb file 2022-04-20 18:06:43 +08:00
Gordon
c32f5dd951 pb file 2022-04-20 18:06:24 +08:00
wangchuxiao
2e6c42c8ac workMoments 2022-04-20 16:33:19 +08:00
wangchuxiao
5757b86d39 workMoments 2022-04-20 16:32:22 +08:00
wangchuxiao
9df4a79827 Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-04-20 16:25:48 +08:00
wangchuxiao
071dd46a4c workMoments 2022-04-20 16:25:33 +08:00
skiffer-git
030d619910 Organization 2022-04-20 11:53:32 +08:00
skiffer-git
c56fd399c1 Organization 2022-04-20 09:07:35 +08:00
skiffer-git
31c954db0e Organization 2022-04-19 21:28:12 +08:00
skiffer-git
cb6a040c4d Organization 2022-04-19 21:27:06 +08:00
skiffer-git
51c3a753a9 Organization 2022-04-19 20:57:59 +08:00
skiffer-git
c28c592c80 OrganizationChangedNotification 2022-04-19 18:52:28 +08:00
skiffer-git
fc07f851f7 OrganizationChangedNotification 2022-04-19 18:46:33 +08:00
skiffer-git
ab4a5e6719 OrganizationChangedNotification 2022-04-19 18:46:02 +08:00
skiffer-git
88e9dd54b2 Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-04-19 16:41:43 +08:00
skiffer-git
f53f34559a organization 2022-04-19 16:40:57 +08:00
wangchuxiao
3e5d9a394f workMoments 2022-04-19 16:33:44 +08:00
wangchuxiao
3f287eb148 workMoments 2022-04-19 16:28:03 +08:00
wangchuxiao
dfe854a236 workMoments 2022-04-19 16:15:41 +08:00
wangchuxiao
3854c7bba2 workMoments 2022-04-19 15:52:44 +08:00
wangchuxiao
01c066419d workMoments 2022-04-19 15:38:16 +08:00
wangchuxiao
040b1d9bc8 workMoments 2022-04-19 15:37:20 +08:00
wangchuxiao
6c4acbad68 workMoments 2022-04-19 14:54:43 +08:00
wangchuxiao
b5c11ece57 workMoments 2022-04-19 14:33:48 +08:00
wangchuxiao
50696d2e88 workMoments 2022-04-19 14:12:30 +08:00
wangchuxiao
e7661fd4be Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-04-19 13:06:10 +08:00
wangchuxiao
957e11eff0 workMoments 2022-04-19 13:05:54 +08:00
skiffer-git
bd6e8d093a add operationID when ws connecting 2022-04-18 21:39:46 +08:00
skiffer-git
f7b5a86a09 add operationID when ws connecting 2022-04-18 21:34:58 +08:00
skiffer-git
97fd107f47 add operationID when ws connecting 2022-04-18 21:29:48 +08:00
skiffer-git
fc688dca99 Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-04-18 21:16:56 +08:00
skiffer-git
fe3bd2a1f1 add operationID when ws connecting 2022-04-18 21:16:23 +08:00
wangchuxiao
3625befc0b Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun
# Conflicts:
#	pkg/common/constant/constant.go
2022-04-18 19:26:26 +08:00
wangchuxiao
6e6508aafd workMoments 2022-04-18 19:24:36 +08:00
skiffer-git
3a8a0a541e organization 2022-04-18 18:11:07 +08:00
skiffer-git
650495306f organization 2022-04-18 18:06:47 +08:00
skiffer-git
5664c34790 organization 2022-04-18 18:02:11 +08:00
skiffer-git
b1c66997ca organization 2022-04-18 17:25:54 +08:00
skiffer-git
114ffd4667 organization 2022-04-18 16:58:41 +08:00
skiffer-git
ad1770ec95 organization 2022-04-18 16:46:03 +08:00
skiffer-git
5f22402761 organization 2022-04-18 16:42:50 +08:00
skiffer-git
c11094a11e organization 2022-04-18 16:27:04 +08:00
skiffer-git
6873bf384e organization 2022-04-18 16:24:12 +08:00
skiffer-git
42242daf9b organization 2022-04-18 16:18:10 +08:00
skiffer-git
1f96b960ab organization 2022-04-18 15:51:17 +08:00
skiffer-git
f6b30ed0c6 organization 2022-04-18 15:45:44 +08:00
skiffer-git
c59dc129a8 /user/get_users_online_status 2022-04-18 14:27:12 +08:00
skiffer-git
472c1a9e3e set group member nickname 2022-04-18 13:01:16 +08:00
skiffer-git
24fe8ab4a4 set group member nickname 2022-04-18 11:53:03 +08:00
skiffer-git
453c6f05bd set group member nickname 2022-04-18 11:52:49 +08:00
skiffer-git
248de7f1f2 set groupmember nickname 2022-04-18 11:52:17 +08:00
skiffer-git
3bbf84861e organization 2022-04-18 10:53:23 +08:00
skiffer-git
0dac9044a5 organization 2022-04-17 15:18:21 +08:00
skiffer-git
a981d1082a organization 2022-04-17 15:11:27 +08:00
skiffer-git
803d0c2ae2 organization 2022-04-17 15:09:18 +08:00
skiffer-git
06e44cc649 organization 2022-04-17 15:03:50 +08:00
skiffer-git
fd01e5c263 organization 2022-04-17 15:01:26 +08:00
skiffer-git
ecc47dcfbb organization 2022-04-17 14:54:51 +08:00
skiffer-git
b6e06dfdc2 organization 2022-04-17 14:47:52 +08:00
skiffer-git
eb630b23ae organization 2022-04-17 14:45:45 +08:00
skiffer-git
eae7a48991 organization 2022-04-17 14:44:44 +08:00
skiffer-git
9436c836e6 organization 2022-04-17 14:42:07 +08:00
skiffer-git
7c64239b36 organization 2022-04-17 14:39:48 +08:00
skiffer-git
80ba371296 organization 2022-04-17 12:41:42 +08:00
skiffer-git
6787563efe organization 2022-04-17 12:37:00 +08:00
skiffer-git
9def85f9ba organization 2022-04-17 12:32:28 +08:00
skiffer-git
6d55f35404 organization 2022-04-17 11:59:31 +08:00
skiffer-git
1902c37924 organization 2022-04-17 11:51:36 +08:00
skiffer-git
02b5ff38a4 organization 2022-04-16 21:41:38 +08:00
skiffer-git
f076a927c9 organization 2022-04-16 21:34:29 +08:00
skiffer-git
6184eaa30e organization 2022-04-16 21:32:53 +08:00
skiffer-git
a42b72e9ce organization 2022-04-16 21:31:28 +08:00
skiffer-git
f4dcae722c organization 2022-04-16 21:28:37 +08:00
skiffer-git
bbcb3e9403 organization 2022-04-16 21:26:16 +08:00
skiffer-git
3d690b7c72 organization 2022-04-16 21:23:38 +08:00
skiffer-git
b4ab2c69ae organization 2022-04-16 21:20:17 +08:00
skiffer-git
4a7f406edb organization 2022-04-16 21:17:32 +08:00
skiffer-git
9e18bcaeb8 organization 2022-04-16 21:14:28 +08:00
skiffer-git
9abfe233bc organization 2022-04-16 21:10:46 +08:00
skiffer-git
3267958541 organization 2022-04-16 20:59:38 +08:00
skiffer-git
af5ee45206 organization 2022-04-16 20:56:28 +08:00
skiffer-git
300b72b9b8 organization 2022-04-16 20:47:00 +08:00
skiffer-git
42af55a740 organization 2022-04-16 20:45:41 +08:00
skiffer-git
3c1e6d0e5c organization 2022-04-16 20:42:50 +08:00
skiffer-git
edf7df368e organization 2022-04-16 20:30:02 +08:00
skiffer-git
cde38e012f organization 2022-04-16 20:27:18 +08:00
skiffer-git
bef4f0c4e2 organization 2022-04-16 20:25:01 +08:00
skiffer-git
bf081dce32 organization 2022-04-16 20:22:01 +08:00
skiffer-git
0bb3cb4aab organization 2022-04-16 20:19:24 +08:00
skiffer-git
0d5132f710 organization 2022-04-16 20:17:21 +08:00
skiffer-git
cad147faf8 organization 2022-04-16 20:14:47 +08:00
skiffer-git
cc405b83e2 organization 2022-04-16 20:10:10 +08:00
skiffer-git
c65f5b7279 Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-04-15 20:37:26 +08:00
skiffer-git
c216340120 organization 2022-04-15 19:48:17 +08:00
wangchuxiao
ff5cbc490e getui 2022-04-15 18:22:27 +08:00
wangchuxiao
27cba5ba31 getui 2022-04-15 18:16:28 +08:00
wangchuxiao
9976b8132f getui 2022-04-15 17:45:33 +08:00
wangchuxiao
dbc5bd96f3 getui 2022-04-15 17:43:04 +08:00
wangchuxiao
9489ab862b getui 2022-04-15 12:10:33 +08:00
wangchuxiao
1bb634bc6f merge code 2022-04-15 12:03:23 +08:00
wangchuxiao
07b5c7fef4 Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-04-15 11:58:32 +08:00
wangchuxiao
4a7cfab543 getui 2022-04-15 11:56:36 +08:00
Gordon
426ef5cb88 push update 2022-04-13 18:34:36 +08:00
Gordon
5b86412407 Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-04-13 18:33:35 +08:00
Gordon
4f8fcd2d3d push update 2022-04-13 18:33:22 +08:00
wangchuxiao
16c40aa51c getui 2022-04-13 16:25:33 +08:00
Gordon
6449c4a53d push update 2022-04-13 16:20:30 +08:00
wangchuxiao
d670356388 getui 2022-04-13 15:29:35 +08:00
wangchuxiao
fb4c8549dc Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-04-13 15:22:03 +08:00
wangchuxiao
42dc5c1f0f getui 2022-04-13 15:21:53 +08:00
skiffer-git
659c3bc1cf add department db 2022-04-13 08:58:52 +08:00
skiffer-git
f5684f2c45 add department db 2022-04-13 08:58:16 +08:00
skiffer-git
1d2d2b1c9c Merge remote-tracking branch 'origin/tuoyun' into tuoyun 2022-04-12 22:07:03 +08:00
skiffer-git
bc06ba54b9 organization && department 2022-04-12 22:02:43 +08:00
wangchuxiao
1b6e223456 Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-04-12 11:13:17 +08:00
wangchuxiao
9e4a2168c0 getui 2022-04-12 11:12:36 +08:00
Gordon
46aa26a444 version code 2022-04-12 09:51:25 +08:00
wangchuxiao
4d01aa3006 getui 2022-04-11 18:12:00 +08:00
wangchuxiao
2c308af615 getui 2022-04-11 17:58:23 +08:00
wangchuxiao
caf4ab60cd minio add inner ip 2022-04-11 17:08:54 +08:00
wangchuxiao
4a8d37bde1 getui 2022-04-11 16:18:36 +08:00
wangchuxiao
3289dd8419 Merge branch 'tuoyun' 2022-04-11 15:09:24 +08:00
wangchuxiao
13473eeb4d getui 2022-04-11 14:44:58 +08:00
wangchuxiao
4264cd8830 Merge branch 'tuoyun' of github.com:OpenIMSDK/Open-IM-Server into tuoyun 2022-04-11 14:43:15 +08:00
wangchuxiao
edcc215774 getui 2022-04-11 14:41:09 +08:00
skiffer-git
3085fffb49 add department db 2022-04-11 14:08:23 +08:00
wangchuxiao
81a6e4b46c getui 2022-04-11 11:31:20 +08:00
wangchuxiao
e0d612c92f getui 2022-04-11 10:35:33 +08:00
wangchuxiao
fadbb91287 getui 2022-04-08 19:31:13 +08:00
wangchuxiao
72146c08ae getui 2022-04-08 19:18:00 +08:00
139 changed files with 15306 additions and 2832 deletions

View File

@@ -8,6 +8,7 @@ import (
"Open_IM/internal/api/group"
"Open_IM/internal/api/manage"
"Open_IM/internal/api/office"
"Open_IM/internal/api/organization"
apiThird "Open_IM/internal/api/third"
"Open_IM/internal/api/user"
"Open_IM/pkg/common/config"
@@ -29,17 +30,21 @@ func main() {
gin.SetMode(gin.ReleaseMode)
f, _ := os.Create("../logs/api.log")
gin.DefaultWriter = io.MultiWriter(f)
gin.SetMode(gin.DebugMode)
r := gin.Default()
r.Use(utils.CorsHandler())
log.Info("load config: ", config.Config)
log.Info("load config: ", config.Config)
// user routing group, which handles user registration and login services
userRouterGroup := r.Group("/user")
{
userRouterGroup.POST("/update_user_info", user.UpdateUserInfo) //1
userRouterGroup.POST("/get_users_info", user.GetUsersInfo) //1
userRouterGroup.POST("/get_self_user_info", user.GetSelfUserInfo) //1
userRouterGroup.POST("/update_user_info", user.UpdateUserInfo) //1
userRouterGroup.POST("/get_users_info", user.GetUsersInfo) //1
userRouterGroup.POST("/get_self_user_info", user.GetSelfUserInfo) //1
userRouterGroup.POST("/get_users_online_status", user.GetUsersOnlineStatus) //1
userRouterGroup.POST("/get_users_info_from_cache", user.GetUsersInfoFromCache)
userRouterGroup.POST("/get_user_friend_from_cache", user.GetFriendIDListFromCache)
userRouterGroup.POST("/get_black_list_from_cache", user.GetBlackIDListFromCache)
}
//friend routing group
friendRouterGroup := r.Group("/friend")
@@ -83,12 +88,16 @@ func main() {
groupRouterGroup.POST("/cancel_mute_group_member", group.CancelMuteGroupMember) //MuteGroup
groupRouterGroup.POST("/mute_group", group.MuteGroup)
groupRouterGroup.POST("/cancel_mute_group", group.CancelMuteGroup)
groupRouterGroup.POST("/set_group_member_nickname", group.SetGroupMemberNickname)
}
//certificate
authRouterGroup := r.Group("/auth")
{
authRouterGroup.POST("/user_register", apiAuth.UserRegister) //1
authRouterGroup.POST("/user_token", apiAuth.UserToken) //1
authRouterGroup.POST("/parse_token", apiAuth.ParseToken) //1
}
//Third service
thirdGroup := r.Group("/third")
@@ -97,6 +106,8 @@ func main() {
thirdGroup.POST("/ali_oss_credential", apiThird.AliOSSCredential)
thirdGroup.POST("/minio_storage_credential", apiThird.MinioStorageCredential)
thirdGroup.POST("/minio_upload", apiThird.MinioUploadFile)
thirdGroup.POST("/upload_update_app", apiThird.UploadUpdateApp)
thirdGroup.POST("/get_download_url", apiThird.GetDownloadURL)
}
//Message
chatGroup := r.Group("/msg")
@@ -114,6 +125,7 @@ func main() {
managementGroup.POST("/get_all_users_uid", manage.GetAllUsersUid) //1
managementGroup.POST("/account_check", manage.AccountCheck) //1
managementGroup.POST("/get_users_online_status", manage.GetUsersOnlineStatus) //1
}
//Conversation
conversationGroup := r.Group("/conversation")
@@ -124,6 +136,7 @@ func main() {
conversationGroup.POST("/set_conversation", conversation.SetConversation)
conversationGroup.POST("/batch_set_conversation", conversation.BatchSetConversations)
conversationGroup.POST("/set_recv_msg_opt", conversation.SetRecvMsgOpt)
conversationGroup.POST("/modify_conversation_field", conversation.ModifyConversationField)
}
// office
officeGroup := r.Group("/office")
@@ -135,12 +148,49 @@ func main() {
officeGroup.POST("/set_tag", office.SetTag)
officeGroup.POST("/send_msg_to_tag", office.SendMsg2Tag)
officeGroup.POST("/get_send_tag_log", office.GetTagSendLogs)
officeGroup.POST("/create_one_work_moment", office.CreateOneWorkMoment)
officeGroup.POST("/delete_one_work_moment", office.DeleteOneWorkMoment)
officeGroup.POST("/like_one_work_moment", office.LikeOneWorkMoment)
officeGroup.POST("/comment_one_work_moment", office.CommentOneWorkMoment)
officeGroup.POST("/get_work_moment_by_id", office.GetWorkMomentByID)
officeGroup.POST("/get_user_work_moments", office.GetUserWorkMoments)
officeGroup.POST("/get_user_friend_work_moments", office.GetUserFriendWorkMoments)
officeGroup.POST("/set_user_work_moments_level", office.SetUserWorkMomentsLevel)
officeGroup.POST("/delete_comment", office.DeleteComment)
}
organizationGroup := r.Group("/organization")
{
organizationGroup.POST("/create_department", organization.CreateDepartment)
organizationGroup.POST("/update_department", organization.UpdateDepartment)
organizationGroup.POST("/get_sub_department", organization.GetSubDepartment)
organizationGroup.POST("/delete_department", organization.DeleteDepartment)
organizationGroup.POST("/get_all_department", organization.GetAllDepartment)
organizationGroup.POST("/create_organization_user", organization.CreateOrganizationUser)
organizationGroup.POST("/update_organization_user", organization.UpdateOrganizationUser)
organizationGroup.POST("/delete_organization_user", organization.DeleteOrganizationUser)
organizationGroup.POST("/create_department_member", organization.CreateDepartmentMember)
organizationGroup.POST("/get_user_in_department", organization.GetUserInDepartment)
organizationGroup.POST("/update_user_in_department", organization.UpdateUserInDepartment)
organizationGroup.POST("/get_department_member", organization.GetDepartmentMember)
organizationGroup.POST("/delete_user_in_department", organization.DeleteUserInDepartment)
}
go apiThird.MinioInit()
ginPort := flag.Int("port", 10000, "get ginServerPort from cmd,default 10000 as port")
ginPort := flag.Int("port", 10002, "get ginServerPort from cmd,default 10002 as port")
flag.Parse()
fmt.Println("start api server, port: ", *ginPort)
err := r.Run(":" + strconv.Itoa(*ginPort))
address := "0.0.0.0:" + strconv.Itoa(*ginPort)
if config.Config.Api.ListenIP != "" {
address = config.Config.Api.ListenIP + ":" + strconv.Itoa(*ginPort)
}
address = config.Config.Api.ListenIP + ":" + strconv.Itoa(*ginPort)
fmt.Println("start api server, address: ", address)
err := r.Run(address)
if err != nil {
log.Error("", "run failed ", *ginPort, err.Error())
}

View File

@@ -3,8 +3,11 @@ package main
import (
"Open_IM/internal/cms_api"
"Open_IM/pkg/utils"
"flag"
"fmt"
"strconv"
"Open_IM/pkg/common/config"
"github.com/gin-gonic/gin"
)
@@ -12,6 +15,13 @@ func main() {
gin.SetMode(gin.ReleaseMode)
router := cms_api.NewGinRouter()
router.Use(utils.CorsHandler())
fmt.Println("start cms api server, port: ", 8000)
router.Run(":" + "8000")
ginPort := flag.Int("port", 10006, "get ginServerPort from cmd,default 10006 as port")
flag.Parse()
address := "0.0.0.0:" + strconv.Itoa(*ginPort)
if config.Config.Api.ListenIP != "" {
address = config.Config.Api.ListenIP + ":" + strconv.Itoa(*ginPort)
}
address = config.Config.CmsApi.ListenIP + ":" + strconv.Itoa(*ginPort)
fmt.Println("start cms api server, address: ", address)
router.Run(address)
}

View File

@@ -9,6 +9,7 @@ import (
"os"
"strconv"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/log"
"github.com/gin-gonic/gin"
@@ -23,7 +24,7 @@ func main() {
r := gin.Default()
r.Use(utils.CorsHandler())
authRouterGroup := r.Group("/auth")
authRouterGroup := r.Group("/demo")
{
authRouterGroup.POST("/code", register.SendVerificationCode)
authRouterGroup.POST("/verify", register.Verify)
@@ -35,7 +36,13 @@ func main() {
ginPort := flag.Int("port", 42233, "get ginServerPort from cmd,default 42233 as port")
flag.Parse()
fmt.Println("start demo api server, port: ", *ginPort)
err := r.Run(":" + strconv.Itoa(*ginPort))
address := "0.0.0.0:" + strconv.Itoa(*ginPort)
if config.Config.Api.ListenIP != "" {
address = config.Config.Api.ListenIP + ":" + strconv.Itoa(*ginPort)
}
address = config.Config.CmsApi.ListenIP + ":" + strconv.Itoa(*ginPort)
fmt.Println("start demo api server address: ", address)
err := r.Run(address)
if err != nil {
log.Error("", "run failed ", *ginPort, err.Error())
}

View File

@@ -1,63 +0,0 @@
package main
import (
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/log"
)
func main() {
log.NewPrivateLog(constant.LogFileName)
//for {
// fmt.Println("start delete mongodb expired record")
// timeUnixBegin := time.Now().Unix()
// count, _ := db.DB.MgoUserCount()
// fmt.Println("mongodb record count: ", count)
// for i := 0; i < count; i++ {
// time.Sleep(1 * time.Millisecond)
// uid, _ := db.DB.MgoSkipUID(i)
// fmt.Println("operate uid: ", uid)
// err := db.DB.DelUserChat(uid)
// if err != nil {
// fmt.Println("operate uid failed: ", uid, err.Error())
// }
// }
//
// timeUnixEnd := time.Now().Unix()
// costTime := timeUnixEnd - timeUnixBegin
// if costTime > int64(config.Config.Mongo.DBRetainChatRecords*24*3600) {
// continue
// } else {
// sleepTime := 0
// if int64(config.Config.Mongo.DBRetainChatRecords*24*3600)-costTime > 24*3600 {
// sleepTime = 24 * 3600
// } else {
// sleepTime = config.Config.Mongo.DBRetainChatRecords*24*3600 - int(costTime)
// }
// fmt.Println("sleep: ", sleepTime)
// time.Sleep(time.Duration(sleepTime) * time.Second)
// }
//}
//for {
// uidList, err := im_mysql_model.SelectAllUserID()
// if err != nil {
// //log.NewError("999999", err.Error())
// } else {
// for _, v := range uidList {
// minSeq, err := commonDB.DB.GetMinSeqFromMongo(v)
// if err != nil {
// //log.NewError("999999", "get user minSeq err", err.Error(), v)
// continue
// } else {
// err := commonDB.DB.SetUserMinSeq(v, minSeq)
// if err != nil {
// //log.NewError("999999", "set user minSeq err", err.Error(), v)
// }
// }
// time.Sleep(time.Duration(100) * time.Millisecond)
// }
//
// }
//
//}
}

View File

@@ -1,7 +1,7 @@
.PHONY: all build run gotool install clean help
BINARY_NAME=open_im_timer_task
BIN_DIR=../../bin/
BINARY_NAME=open_im_cache
BIN_DIR=../../../bin/
all: gotool build
@@ -22,4 +22,3 @@ install:
clean:
@if [ -f ${BINARY_NAME} ] ; then rm ${BINARY_NAME} ; fi

View File

@@ -0,0 +1,16 @@
package main
import (
rpcCache "Open_IM/internal/rpc/cache"
"flag"
"fmt"
)
func main() {
rpcPort := flag.Int("port", 10600, "RpcToken default listen port 10800")
flag.Parse()
fmt.Println("start auth rpc server, port: ", *rpcPort)
rpcServer := rpcCache.NewCacheServer(*rpcPort)
rpcServer.Run()
}

View File

@@ -0,0 +1,24 @@
.PHONY: all build run gotool install clean help
BINARY_NAME=open_im_conversation
BIN_DIR=../../../bin/
all: gotool build
build:
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-w -s"
run:
@go run ./
gotool:
go fmt ./
go vet ./
install:
make build
mv ${BINARY_NAME} ${BIN_DIR}
clean:
@if [ -f ${BINARY_NAME} ] ; then rm ${BINARY_NAME} ; fi

View File

@@ -0,0 +1,16 @@
package main
import (
rpcConversation "Open_IM/internal/rpc/conversation"
"flag"
"fmt"
)
func main() {
rpcPort := flag.Int("port", 11400, "RpcConversation default listen port 11300")
flag.Parse()
fmt.Println("start conversation rpc server, port: ", *rpcPort)
rpcServer := rpcConversation.NewRpcConversationServer(*rpcPort)
rpcServer.Run()
}

View File

@@ -0,0 +1,25 @@
.PHONY: all build run gotool install clean help
BINARY_NAME=open_im_organization
BIN_DIR=../../../bin/
all: gotool build
build:
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-w -s"
run:
@go run ./
gotool:
go fmt ./
go vet ./
install:
make build
mv ${BINARY_NAME} ${BIN_DIR}
clean:
@if [ -f ${BINARY_NAME} ] ; then rm ${BINARY_NAME} ; fi

View File

@@ -0,0 +1,15 @@
package main
import (
"Open_IM/internal/rpc/organization"
"flag"
"fmt"
)
func main() {
rpcPort := flag.Int("port", 11200, "get RpcOrganizationPort from cmd,default 11200 as port")
flag.Parse()
fmt.Println("start organization rpc server, port: ", *rpcPort)
rpcServer := organization.NewServer(*rpcPort)
rpcServer.Run()
}

View File

@@ -4,7 +4,7 @@
serverversion: 2.0.0
#---------------Infrastructure configuration---------------------#
etcd:
etcdSchema: openIM #默认即可
etcdSchema: openim #默认即可
etcdAddr: [ 127.0.0.1:2379 ] #单机部署时,默认即可
mysql:
@@ -41,11 +41,15 @@ kafka:
ws2mschat:
addr: [ 127.0.0.1:9092 ] #kafka配置默认即可
topic: "ws2ms_chat"
ws2mschatoffline:
addr: [ 127.0.0.1:9092 ] #kafka配置默认即可
topic: "ws2ms_chat_offline"
ms2pschat:
addr: [ 127.0.0.1:9092 ] #kafka配置默认即可
topic: "ms2ps_chat"
consumergroupid:
msgToMongo: mongo
msgToMongoOffline: mongo_offline
msgToMySql: mysql
msgToPush: push
@@ -59,6 +63,11 @@ kafka:
#如果是单机模式用0.0.0.0或者不填,默认即可
serverip: 0.0.0.0
rpcRegisterIP: 127.0.0.1
listenIP: 0.0.0.0
# endpoints 内部组件间访问的端点host名称访问时可以内部直接访问 host:port 来访问
endpoints:
api: openim_api
@@ -76,23 +85,29 @@ endpoints:
rpc_office: openim_rpc_office
api:
openImApiPort: [ 10000 ] #api服务端口默认即可需要开放此端口或做nginx转发
openImApiPort: [ 10002 ] #api服务端口默认即可需要开放此端口或做nginx转发
listenIP: 0.0.0.0
cmsapi:
openImCmsApiPort: [ 8000 ] #管理后台api服务端口默认即可需要开放此端口或做nginx转发
openImCmsApiPort: [ 10006 ] #管理后台api服务端口默认即可需要开放此端口或做nginx转发
listenIP: 0.0.0.0
sdk:
openImSdkWsPort: [ 30000 ] #jssdk服务端口默认即可项目中使用jssdk才需开放此端口或做nginx转发
openImSdkWsPort: [ 10003 ] #jssdk服务端口默认即可项目中使用jssdk才需开放此端口或做nginx转发
dataDir: [ ../db/sdk/ ]
#对象存储服务以下配置二选一目前支持两种腾讯云和minio二者配置好其中一种即可如果使用minio参考https://doc.rentsoft.cn/#/qa/minio搭建minio服务器
credential: #腾讯cos发送图片、视频、文件时需要请自行申请后替换必须修改
tencent:
appID: 1302656840
region: ap-chengdu
bucket: echat-1302656840
secretID: AKIDGNYVChzIQinu7QEgtNp0hnNgqcV8vZTC
secretKey: kz15vW83qM6dBUWIq681eBZA0c0vlIbe
secretID: AKIDGNYVChzIQinu7QEgtNp0hnNgqcV8vZTC1
secretKey: kz15vW83qM6dBUWIq681eBZA0c0vlIbe1
minio: #MinIO 发送图片、视频、文件时需要,请自行申请后替换,必须修改。 客户端初始化InitSDK中 object_storage参数为minio
bucket: openim
bucket: openim # 存储内容桶
appBucket: app # 存储app的桶
location: us-east-1
endpoint: http://121.37.25.71:9000
endpoint: http://127.0.0.1:10005 #minio外网ip 这个ip是给客户端访问的
endpointInner: http://127.0.0.1:10005 #minio内网地址 如果im server 可以通过内网访问到 minio就可以填写
endpointInnerEnable: true #是否启用minio内网地址 启用可以让桶初始化IM server连接minio走内网地址访问
accessKeyID: user12345
secretAccessKey: key12345
ali: # ali oss
@@ -109,17 +124,20 @@ credential: #腾讯cos发送图片、视频、文件时需要请自行申
rpcport: #rpc服务端口 默认即可
openImUserPort: [ 10100 ]
openImFriendPort: [ 10200 ]
openImOfflineMessagePort: [ 10300 ]
openImOnlineRelayPort: [ 10400 ]
openImGroupPort: [ 10500 ]
openImAuthPort: [ 10600 ]
openImPushPort: [ 10700 ]
openImStatisticsPort: [ 10800 ]
openImMessageCmsPort: [ 10900 ]
openImAdminCmsPort: [ 11000 ]
openImOfficePort: [ 11100 ]
openImUserPort: [ 10110 ]
openImFriendPort: [ 10120 ]
openImMessagePort: [ 10130 ]
openImMessageGatewayPort: [ 10140 ]
openImGroupPort: [ 10150 ]
openImAuthPort: [ 10160 ]
openImPushPort: [ 10170 ]
openImStatisticsPort: [ 10180 ]
openImMessageCmsPort: [ 10190 ]
openImAdminCmsPort: [ 10200 ]
openImOfficePort: [ 10210 ]
openImOrganizationPort: [ 10220 ]
openImConversationPort: [ 10230 ]
openImCachePort: [10240]
c2c:
callbackBeforeSendMsg:
switch: false
@@ -138,11 +156,14 @@ rpcregistername: #rpc注册服务名默认即可
openImOnlineMessageRelayName: OnlineMessageRelay
openImGroupName: Group
openImAuthName: Auth
OpenImStatisticsName: Statistics
OpenImMessageCMSName: MessageCMS
openImStatisticsName: Statistics
openImMessageCMSName: MessageCMS
openImAdminCMSName: AdminCMS
openImOfficeName: Office
openImOrganizationName: Organization
openImConversationName: Conversation
openImCacheName: Cache
openImRealTimeCommName: RealTimeComm
log:
storageLocation: ../logs/
rotationTime: 24
@@ -160,12 +181,12 @@ modulename: #日志文件按模块命名,默认即可
pushName: push
longconnsvr:
openImWsPort: [ 17778 ] # ws服务端口默认即可要开放此端口或做nginx转发
openImWsPort: [ 10001 ] # ws服务端口默认即可要开放此端口或做nginx转发
websocketMaxConnNum: 10000
websocketMaxMsgLen: 4096
websocketTimeOut: 10
## 推送只能开启一个
## 推送只能开启一个 enable代表开启
push:
tpns: #腾讯推送,暂未测试 暂不要使用
ios:
@@ -200,6 +221,9 @@ secret: tuoyun
# 1多平台登录Android、iOS、Windows、Mac 每种平台只能一个在线web端可以多个同时在线
multiloginpolicy: 1
#chat log insert to db
chatPersistenceMysql: true
#token config
tokenpolicy:
accessSecret: "open_im_server" #token生成相关默认即可
@@ -428,6 +452,34 @@ notification:
ext: "groupMemberCancelMuted ext"
defaultTips:
tips: "group Member Cancel Muted"
groupMemberInfoSet:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: false
title: "groupMemberInfoSet title"
desc: "groupMemberInfoSet desc"
ext: "groupMemberInfoSet ext"
defaultTips:
tips: "group member info set"
organizationChanged:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: false
title: "organizationChanged title"
desc: "organizationChanged desc"
ext: "organizationChanged ext"
defaultTips:
tips: "organization changed"
#############################friend#################################
friendApplicationAdded:
@@ -565,7 +617,7 @@ notification:
conversationSetPrivate:
conversation:
reliabilityLevel: 2
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: true
@@ -576,6 +628,32 @@ notification:
openTips: "burn after reading was opened"
closeTips: "burn after reading was closed"
###################workMoments################
workMomentsNotification:
conversation:
reliabilityLevel: 2
unreadCount: true
offlinePush:
switch: true
title: "burn after reading"
desc: "burn after reading"
ext: "burn after reading"
defaultTips:
openTips: "burn after reading was opened"
closeTips: "burn after reading was closed"
###################organization################
joinDepartmentNotification:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "welcome user join department"
desc: "welcome user join department"
ext: "welcome user join department"
defaultTips:
tips: "welcome user join department"
#---------------demo configuration---------------------#
@@ -583,8 +661,9 @@ notification:
#是否启动demo如果自身没有账号体系设置为true
demoswitch: true
demo:
listenIP: 0.0.0.0
#demo对外服务端口默认即可需要开放此端口或做nginx转发
openImDemoPort: [ 42233 ]
openImDemoPort: [ 10004 ]
alismsverify: #阿里云短信配置,在阿里云申请成功后修改以下四项,必须修改
accessKeyId: LTAI5tJPkn4HuuePdiLdGqe7
accessKeySecret: 4n9OJ7ZCVN1U6KeHDAtOyNeVZcjOuV
@@ -599,7 +678,8 @@ demo:
senderAuthorizationCode: "gxyausfoevlzbfag"
smtpAddr: "smtp.qq.com"
smtpPort: 25 #需开放此端口 出口方向
testDepartMentID: 001
rtc:
port: 11300
address: 127.0.0.1
address: 127.0.0.1

View File

@@ -94,7 +94,7 @@ services:
command: /usr/local/bin/etcd --name etcd0 --data-dir /etcd-data --listen-client-urls http://0.0.0.0:2379 --advertise-client-urls http://0.0.0.0:2379 --listen-peer-urls http://0.0.0.0:2380 --initial-advertise-peer-urls http://0.0.0.0:2380 --initial-cluster etcd0=http://0.0.0.0:2380 --initial-cluster-token tkn --initial-cluster-state new
open_im_server:
image: openim/open_im_server:v2.0.7
image: openim/open_im_server:v2.0.9
container_name: open_im_server
volumes:
- ./logs:/Open-IM-Server/logs

20
go.mod
View File

@@ -3,7 +3,7 @@ module Open_IM
go 1.15
require (
github.com/Shopify/sarama v1.19.0
github.com/Shopify/sarama v1.32.0
github.com/Shopify/toxiproxy v2.1.4+incompatible // indirect
github.com/alibabacloud-go/darabonba-openapi v0.1.11
github.com/alibabacloud-go/dysmsapi-20170525/v2 v2.0.8
@@ -11,13 +11,10 @@ require (
github.com/alibabacloud-go/tea v1.1.17
github.com/antonfisher/nested-logrus-formatter v1.3.0
github.com/bwmarrin/snowflake v0.3.0
github.com/coreos/etcd v3.3.27+incompatible // indirect
github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f // indirect
github.com/eapache/go-resiliency v1.2.0 // indirect
github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21 // indirect
github.com/eapache/queue v1.1.0 // indirect
github.com/fatih/structs v1.1.0
github.com/frankban/quicktest v1.14.0 // indirect
github.com/garyburd/redigo v1.6.2
github.com/gin-gonic/gin v1.7.0
github.com/go-playground/validator/v10 v10.4.1
@@ -34,8 +31,6 @@ require (
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible
github.com/lestrrat-go/strftime v1.0.4 // indirect
github.com/lib/pq v1.2.0 // indirect
//github.com/livekit/protocol v0.11.14-0.20220223195254-d8c251e13231 // indirect
//github.com/livekit/server-sdk-go v0.9.1
github.com/mattn/go-sqlite3 v1.14.6 // indirect
github.com/minio/minio-go/v7 v7.0.22
github.com/mitchellh/mapstructure v1.4.2
@@ -46,24 +41,19 @@ require (
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5
github.com/sirupsen/logrus v1.8.1
github.com/spf13/viper v1.9.0
github.com/stretchr/testify v1.7.0
github.com/tencentyun/qcloud-cos-sts-sdk v0.0.0-20210325043845-84a0811633ca
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5 // indirect
//go.etcd.io/etcd v3.3.27+incompatible
go.etcd.io/etcd v0.0.0-20200402134248-51bdeb39e698
go.etcd.io/etcd/api/v3 v3.5.4
go.etcd.io/etcd/client/v3 v3.5.4
go.mongodb.org/mongo-driver v1.8.3
golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd
google.golang.org/grpc v1.42.0
google.golang.org/grpc/examples v0.0.0-20220311002955-722367c4a737 // indirect
google.golang.org/genproto v0.0.0-20210828152312-66f60bf46e71 // indirect
google.golang.org/grpc v1.45.0
google.golang.org/protobuf v1.27.1
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
gopkg.in/ini.v1 v1.66.2 // indirect
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b
sigs.k8s.io/yaml v1.2.0 // indirect
)
replace google.golang.org/grpc => google.golang.org/grpc v1.29.0

715
go.sum

File diff suppressed because it is too large Load Diff

View File

@@ -4,11 +4,13 @@ import (
api "Open_IM/pkg/base_info"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
rpc "Open_IM/pkg/proto/auth"
open_im_sdk "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils"
"context"
"github.com/fatih/structs"
"github.com/gin-gonic/gin"
"net/http"
"strings"
@@ -17,14 +19,16 @@ import (
func UserRegister(c *gin.Context) {
params := api.UserRegisterReq{}
if err := c.BindJSON(&params); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
errMsg := " BindJSON failed " + err.Error()
log.NewError("0", errMsg)
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": errMsg})
return
}
if params.Secret != config.Config.Secret {
log.NewError(params.OperationID, "params.Secret != config.Config.Secret", params.Secret, config.Config.Secret)
c.JSON(http.StatusBadRequest, gin.H{"errCode": 401, "errMsg": "not authorized"})
errMsg := " params.Secret != config.Config.Secret "
log.NewError(params.OperationID, errMsg, params.Secret, config.Config.Secret)
c.JSON(http.StatusBadRequest, gin.H{"errCode": 401, "errMsg": errMsg})
return
}
req := &rpc.UserRegisterReq{UserInfo: &open_im_sdk.UserInfo{}}
@@ -36,22 +40,24 @@ func UserRegister(c *gin.Context) {
client := rpc.NewAuthClient(etcdConn)
reply, err := client.UserRegister(context.Background(), req)
if err != nil {
log.NewError(req.OperationID, "call rpc err ", err)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "internal service err"})
errMsg := req.OperationID + " " + "UserRegister failed " + err.Error() + req.String()
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
if reply.CommonResp.ErrCode != 0 {
log.NewError(req.OperationID, "UserRegister failed ", err)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": reply.CommonResp.ErrMsg})
errMsg := req.OperationID + " " + " UserRegister failed " + reply.CommonResp.ErrMsg + req.String()
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
pbDataToken := &rpc.UserTokenReq{Platform: params.Platform, FromUserID: params.UserID, OperationID: params.OperationID}
replyToken, err := client.UserToken(context.Background(), pbDataToken)
if err != nil {
log.NewError(req.OperationID, "UserToken failed ", err.Error(), pbDataToken)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": err.Error()})
errMsg := req.OperationID + " " + " client.UserToken failed " + err.Error() + pbDataToken.String()
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
resp := api.UserRegisterResp{CommResp: api.CommResp{ErrCode: replyToken.CommonResp.ErrCode, ErrMsg: replyToken.CommonResp.ErrMsg},
@@ -64,14 +70,16 @@ func UserRegister(c *gin.Context) {
func UserToken(c *gin.Context) {
params := api.UserTokenReq{}
if err := c.BindJSON(&params); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
errMsg := " BindJSON failed " + err.Error()
log.NewError("0", errMsg)
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": errMsg})
return
}
if params.Secret != config.Config.Secret {
errMsg := params.OperationID + " params.Secret != config.Config.Secret "
log.NewError(params.OperationID, "params.Secret != config.Config.Secret", params.Secret, config.Config.Secret)
c.JSON(http.StatusBadRequest, gin.H{"errCode": 401, "errMsg": "not authorized"})
c.JSON(http.StatusBadRequest, gin.H{"errCode": 401, "errMsg": errMsg})
return
}
req := &rpc.UserTokenReq{Platform: params.Platform, FromUserID: params.UserID, OperationID: params.OperationID}
@@ -80,12 +88,39 @@ func UserToken(c *gin.Context) {
client := rpc.NewAuthClient(etcdConn)
reply, err := client.UserToken(context.Background(), req)
if err != nil {
log.NewError(req.OperationID, "UserToken failed ", err.Error(), req.String())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": err.Error()})
errMsg := req.OperationID + " UserToken failed " + err.Error() + req.String()
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
resp := api.UserTokenResp{CommResp: api.CommResp{ErrCode: reply.CommonResp.ErrCode, ErrMsg: reply.CommonResp.ErrMsg},
UserToken: api.UserTokenInfo{UserID: req.FromUserID, Token: reply.Token, ExpiredTime: reply.ExpiredTime}}
log.NewInfo(req.OperationID, "UserRegister return ", resp)
log.NewInfo(req.OperationID, "UserToken return ", resp)
c.JSON(http.StatusOK, resp)
}
func ParseToken(c *gin.Context) {
params := api.ParseTokenReq{}
if err := c.BindJSON(&params); err != nil {
errMsg := " BindJSON failed " + err.Error()
log.NewError("0", errMsg)
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": errMsg})
return
}
var ok bool
var errInfo string
var expireTime int64
ok, _, errInfo, expireTime = token_verify.GetUserIDFromTokenExpireTime(c.Request.Header.Get("token"), params.OperationID)
if !ok {
errMsg := params.OperationID + " " + "GetUserIDFromTokenExpireTime failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(params.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
resp := api.ParseTokenResp{CommResp: api.CommResp{ErrCode: 0, ErrMsg: ""}, ExpireTime: api.ExpireTime{ExpireTimeSeconds: uint32(expireTime)}}
resp.Data = structs.Map(&resp.ExpireTime)
log.NewInfo(params.OperationID, "ParseToken return ", resp)
c.JSON(http.StatusOK, resp)
}

View File

@@ -25,10 +25,10 @@ func DelMsg(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req:", req)
if err := utils.CopyStructFields(&reqPb, &req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields", err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req:", req)
grpcConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfflineMessageName)
msgClient := pbChat.NewChatClient(grpcConn)
respPb, err := msgClient.DelMsgList(context.Background(), &reqPb)
@@ -39,5 +39,6 @@ func DelMsg(c *gin.Context) {
}
resp.ErrCode = respPb.ErrCode
resp.ErrMsg = respPb.ErrMsg
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), resp)
c.JSON(http.StatusOK, resp)
}

View File

@@ -35,10 +35,6 @@ func GetSeq(c *gin.Context) {
pbData.UserID = params.SendID
pbData.OperationID = params.OperationID
grpcConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfflineMessageName)
if grpcConn == nil {
log.ErrorByKv("get grpcConn err", pbData.OperationID, "args", params)
}
msgClient := pbMsg.NewChatClient(grpcConn)
reply, err := msgClient.GetMaxAndMinSeq(context.Background(), &pbData)
if err != nil {

View File

@@ -55,10 +55,10 @@ func PullMsgBySeqList(c *gin.Context) {
msgClient := pbChat.NewChatClient(grpcConn)
reply, err := msgClient.PullMessageBySeqList(context.Background(), &pbData)
if err != nil {
log.ErrorByKv("PullMessageBySeqList error", pbData.OperationID, "err", err.Error())
log.Error(pbData.OperationID, "PullMessageBySeqList error", err.Error())
return
}
log.InfoByKv("rpc call success to PullMessageBySeqList", pbData.OperationID, "ReplyArgs", reply.String(), len(reply.List))
log.NewInfo(pbData.OperationID, "rpc call success to PullMessageBySeqList", reply.String(), len(reply.List))
c.JSON(http.StatusOK, gin.H{
"errCode": reply.ErrCode,
"errMsg": reply.ErrMsg,

View File

@@ -62,14 +62,12 @@ func SendMsg(c *gin.Context) {
params := paramsUserSendMsg{}
if err := c.BindJSON(&params); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
log.ErrorByKv("json unmarshal err", "", "err", err.Error(), "data", c.PostForm("data"))
log.Error("0", "BindJSON failed ", err.Error())
return
}
token := c.Request.Header.Get("token")
log.InfoByKv("api call success to sendMsgReq", params.OperationID, "Parameters", params)
log.NewInfo(params.OperationID, "api call success to sendMsgReq", params)
pbData := newUserSendMsgReq(token, &params)
log.Info("", "", "api SendMsg call start..., [data: %s]", pbData.String())

View File

@@ -5,6 +5,7 @@ import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/log"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
pbConversation "Open_IM/pkg/proto/conversation"
pbUser "Open_IM/pkg/proto/user"
"Open_IM/pkg/utils"
"context"
@@ -24,13 +25,13 @@ func SetConversation(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
reqPb.Conversation = &pbUser.Conversation{}
err := utils.CopyStructFields(&reqPb, req)
err = utils.CopyStructFields(reqPb.Conversation, req.Conversation)
if err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", reqPb.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pbUser.NewUserClient(etcdConn)
respPb, err := client.SetConversation(context.Background(), &reqPb)
@@ -44,6 +45,37 @@ func SetConversation(c *gin.Context) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, resp)
}
func ModifyConversationField(c *gin.Context) {
var (
req api.ModifyConversationFieldReq
resp api.ModifyConversationFieldResp
reqPb pbConversation.ModifyConversationFieldReq
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
reqPb.Conversation = &pbConversation.Conversation{}
err := utils.CopyStructFields(&reqPb, req)
err = utils.CopyStructFields(reqPb.Conversation, req.Conversation)
if err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImConversationName)
client := pbConversation.NewConversationClient(etcdConn)
respPb, err := client.ModifyConversationField(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "SetConversation rpc failed, ", reqPb.String(), err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 500, "errMsg": "GetAllConversationMsgOpt rpc failed, " + err.Error()})
return
}
resp.ErrMsg = respPb.CommonResp.ErrMsg
resp.ErrCode = respPb.CommonResp.ErrCode
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, resp)
}
func BatchSetConversations(c *gin.Context) {
var (
@@ -56,10 +88,10 @@ func BatchSetConversations(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", reqPb.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pbUser.NewUserClient(etcdConn)
respPb, err := client.BatchSetConversations(context.Background(), &reqPb)
@@ -88,10 +120,10 @@ func GetAllConversations(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", reqPb.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pbUser.NewUserClient(etcdConn)
respPb, err := client.GetAllConversations(context.Background(), &reqPb)
@@ -120,10 +152,10 @@ func GetConversation(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", reqPb.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pbUser.NewUserClient(etcdConn)
respPb, err := client.GetConversation(context.Background(), &reqPb)
@@ -152,10 +184,10 @@ func GetConversations(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", reqPb.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pbUser.NewUserClient(etcdConn)
respPb, err := client.GetConversations(context.Background(), &reqPb)
@@ -184,10 +216,10 @@ func SetRecvMsgOpt(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", reqPb.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pbUser.NewUserClient(etcdConn)
respPb, err := client.SetRecvMsgOpt(context.Background(), &reqPb)

View File

@@ -26,10 +26,12 @@ func AddBlack(c *gin.Context) {
req := &rpc.AddBlacklistReq{CommID: &rpc.CommID{}}
utils.CopyStructFields(req.CommID, &params)
var ok bool
ok, req.CommID.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.CommID.OperationID)
var errInfo string
ok, req.CommID.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.CommID.OperationID)
if !ok {
log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.CommID.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.CommID.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(params.OperationID, "AddBlacklist args ", req.String())
@@ -57,12 +59,15 @@ func ImportFriend(c *gin.Context) {
req := &rpc.ImportFriendReq{}
utils.CopyStructFields(req, &params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, "ImportFriend args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImFriendName)
@@ -96,13 +101,17 @@ func AddFriend(c *gin.Context) {
req := &rpc.AddFriendReq{CommID: &rpc.CommID{}}
utils.CopyStructFields(req.CommID, &params.ParamsCommFriend)
req.ReqMsg = params.ReqMsg
var ok bool
ok, req.CommID.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.CommID.OperationID)
var errInfo string
ok, req.CommID.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.CommID.OperationID)
if !ok {
log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.CommID.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.CommID.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.CommID.OperationID, "AddFriend args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImFriendName)
@@ -130,13 +139,17 @@ func AddFriendResponse(c *gin.Context) {
utils.CopyStructFields(req.CommID, &params.ParamsCommFriend)
req.HandleMsg = params.HandleMsg
req.HandleResult = params.Flag
var ok bool
ok, req.CommID.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.CommID.OperationID)
var errInfo string
ok, req.CommID.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.CommID.OperationID)
if !ok {
log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.CommID.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.CommID.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
utils.CopyStructFields(req, &params)
log.NewInfo(req.CommID.OperationID, "AddFriendResponse args ", req.String())
@@ -163,13 +176,17 @@ func DeleteFriend(c *gin.Context) {
}
req := &rpc.DeleteFriendReq{CommID: &rpc.CommID{}}
utils.CopyStructFields(req.CommID, &params.ParamsCommFriend)
var ok bool
ok, req.CommID.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.CommID.OperationID)
var errInfo string
ok, req.CommID.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.CommID.OperationID)
if !ok {
log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.CommID.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.CommID.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.CommID.OperationID, "DeleteFriend args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImFriendName)
@@ -195,13 +212,17 @@ func GetBlacklist(c *gin.Context) {
}
req := &rpc.GetBlacklistReq{CommID: &rpc.CommID{}}
utils.CopyStructFields(req.CommID, &params)
var ok bool
ok, req.CommID.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.CommID.OperationID)
var errInfo string
ok, req.CommID.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.CommID.OperationID)
if !ok {
log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.CommID.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.CommID.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.CommID.OperationID, "GetBlacklist args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImFriendName)
@@ -234,13 +255,17 @@ func SetFriendRemark(c *gin.Context) {
req := &rpc.SetFriendRemarkReq{CommID: &rpc.CommID{}}
utils.CopyStructFields(req.CommID, &params.ParamsCommFriend)
req.Remark = params.Remark
var ok bool
ok, req.CommID.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.CommID.OperationID)
var errInfo string
ok, req.CommID.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.CommID.OperationID)
if !ok {
log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.CommID.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.CommID.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.CommID.OperationID, "SetFriendComment args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImFriendName)
@@ -266,11 +291,14 @@ func RemoveBlack(c *gin.Context) {
}
req := &rpc.RemoveBlacklistReq{CommID: &rpc.CommID{}}
utils.CopyStructFields(req.CommID, &params.ParamsCommFriend)
var ok bool
ok, req.CommID.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.CommID.OperationID)
var errInfo string
ok, req.CommID.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.CommID.OperationID)
if !ok {
log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.CommID.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.CommID.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
@@ -297,13 +325,17 @@ func IsFriend(c *gin.Context) {
}
req := &rpc.IsFriendReq{CommID: &rpc.CommID{}}
utils.CopyStructFields(req.CommID, &params.ParamsCommFriend)
var ok bool
ok, req.CommID.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.CommID.OperationID)
var errInfo string
ok, req.CommID.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.CommID.OperationID)
if !ok {
log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.CommID.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.CommID.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.CommID.OperationID, "IsFriend args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImFriendName)
@@ -321,40 +353,6 @@ func IsFriend(c *gin.Context) {
c.JSON(http.StatusOK, resp)
}
//
//func GetFriendsInfo(c *gin.Context) {
// params := api.GetFriendsInfoReq{}
// if err := c.BindJSON(&params); err != nil {
// log.NewError("0", "BindJSON failed ", err.Error())
// c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
// return
// }
// req := &rpc.GetFriendsInfoReq{}
// utils.CopyStructFields(req.CommID, params)
// var ok bool
// ok, req.CommID.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"))
// if !ok {
// log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
// c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
// return
// }
// log.NewInfo(req.CommID.OperationID, "GetFriendsInfo args ", req.String())
//
// etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImFriendName)
// client := rpc.NewFriendClient(etcdConn)
// RpcResp, err := client.GetFriendsInfo(context.Background(), req)
// if err != nil {
// log.NewError(req.CommID.OperationID, "GetFriendsInfo failed ", err.Error(), req.String())
// c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "call search friend rpc server failed"})
// return
// }
//
// resp := api.GetFriendsInfoResp{CommResp:api.CommResp{ErrCode: RpcResp.ErrCode, ErrMsg: RpcResp.ErrMsg}}
// utils.CopyStructFields(&resp, RpcResp)
// c.JSON(http.StatusOK, resp)
// log.NewInfo(req.CommID.OperationID, "GetFriendsInfo api return ", resp)
//}
func GetFriendList(c *gin.Context) {
params := api.GetFriendListReq{}
if err := c.BindJSON(&params); err != nil {
@@ -364,13 +362,17 @@ func GetFriendList(c *gin.Context) {
}
req := &rpc.GetFriendListReq{CommID: &rpc.CommID{}}
utils.CopyStructFields(req.CommID, &params)
var ok bool
ok, req.CommID.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.CommID.OperationID)
var errInfo string
ok, req.CommID.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.CommID.OperationID)
if !ok {
log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.CommID.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.CommID.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.CommID.OperationID, "GetFriendList args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImFriendName)
@@ -398,13 +400,17 @@ func GetFriendApplyList(c *gin.Context) {
}
req := &rpc.GetFriendApplyListReq{CommID: &rpc.CommID{}}
utils.CopyStructFields(req.CommID, &params)
var ok bool
ok, req.CommID.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.CommID.OperationID)
var errInfo string
ok, req.CommID.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.CommID.OperationID)
if !ok {
log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.CommID.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.CommID.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.CommID.OperationID, "GetFriendApplyList args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImFriendName)
@@ -432,13 +438,17 @@ func GetSelfFriendApplyList(c *gin.Context) {
}
req := &rpc.GetSelfApplyListReq{CommID: &rpc.CommID{}}
utils.CopyStructFields(req.CommID, &params)
var ok bool
ok, req.CommID.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.CommID.OperationID)
var errInfo string
ok, req.CommID.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.CommID.OperationID)
if !ok {
log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.CommID.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.CommID.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.CommID.OperationID, "GetSelfApplyList args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImFriendName)

View File

@@ -29,11 +29,14 @@ func KickGroupMember(c *gin.Context) {
req := &rpc.KickGroupMemberReq{}
utils.CopyStructFields(req, &params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
@@ -71,14 +74,17 @@ func GetGroupMembersInfo(c *gin.Context) {
}
req := &rpc.GetGroupMembersInfoReq{}
utils.CopyStructFields(req, params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
//c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
api.SetErrCodeMsg(c, http.StatusInternalServerError)
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, "GetGroupMembersInfo args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -106,13 +112,17 @@ func GetGroupMemberList(c *gin.Context) {
}
req := &rpc.GetGroupMemberListReq{}
utils.CopyStructFields(req, params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, "GetGroupMemberList args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -141,13 +151,17 @@ func GetGroupAllMemberList(c *gin.Context) {
}
req := &rpc.GetGroupAllMemberReq{}
utils.CopyStructFields(req, &params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, "GetGroupAllMember args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -174,13 +188,17 @@ func GetJoinedGroupList(c *gin.Context) {
}
req := &rpc.GetJoinedGroupListReq{}
utils.CopyStructFields(req, params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, "GetJoinedGroupList args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -207,13 +225,17 @@ func InviteUserToGroup(c *gin.Context) {
}
req := &rpc.InviteUserToGroupReq{}
utils.CopyStructFields(req, &params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, "InviteUserToGroup args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -252,15 +274,20 @@ func CreateGroup(c *gin.Context) {
for _, v := range params.MemberList {
req.InitMemberList = append(req.InitMemberList, &rpc.GroupAddMemberInfo{UserID: v.UserID, RoleLevel: v.RoleLevel})
}
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
req.OwnerUserID = params.OwnerUserID
req.OperationID = params.OperationID
log.NewInfo(req.OperationID, "CreateGroup args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -355,13 +382,17 @@ func GetGroupsInfo(c *gin.Context) {
}
req := &rpc.GetGroupsInfoReq{}
utils.CopyStructFields(req, &params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, "GetGroupsInfo args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := rpc.NewGroupClient(etcdConn)
@@ -388,13 +419,17 @@ func ApplicationGroupResponse(c *gin.Context) {
}
req := &rpc.GroupApplicationResponseReq{}
utils.CopyStructFields(req, &params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, "ApplicationGroupResponse args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -420,13 +455,17 @@ func JoinGroup(c *gin.Context) {
}
req := &rpc.JoinGroupReq{}
utils.CopyStructFields(req, params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, "JoinGroup args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := rpc.NewGroupClient(etcdConn)
@@ -451,13 +490,17 @@ func QuitGroup(c *gin.Context) {
}
req := &rpc.QuitGroupReq{}
utils.CopyStructFields(req, &params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, "QuitGroup args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -483,13 +526,17 @@ func SetGroupInfo(c *gin.Context) {
req := &rpc.SetGroupInfoReq{GroupInfo: &open_im_sdk.GroupInfo{}}
utils.CopyStructFields(req.GroupInfo, &params)
req.OperationID = params.OperationID
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, "SetGroupInfo args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -514,13 +561,17 @@ func TransferGroupOwner(c *gin.Context) {
}
req := &rpc.TransferGroupOwnerReq{}
utils.CopyStructFields(req, &params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, "TransferGroupOwner args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -546,13 +597,17 @@ func DismissGroup(c *gin.Context) {
}
req := &rpc.DismissGroupReq{}
utils.CopyStructFields(req, &params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -578,13 +633,17 @@ func MuteGroupMember(c *gin.Context) {
}
req := &rpc.MuteGroupMemberReq{}
utils.CopyStructFields(req, &params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " api args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -610,13 +669,17 @@ func CancelMuteGroupMember(c *gin.Context) {
}
req := &rpc.CancelMuteGroupMemberReq{}
utils.CopyStructFields(req, &params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " api args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -642,13 +705,17 @@ func MuteGroup(c *gin.Context) {
}
req := &rpc.MuteGroupReq{}
utils.CopyStructFields(req, &params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " api args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -674,13 +741,17 @@ func CancelMuteGroup(c *gin.Context) {
}
req := &rpc.CancelMuteGroupReq{}
utils.CopyStructFields(req, &params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " api args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -696,3 +767,45 @@ func CancelMuteGroup(c *gin.Context) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " api return ", resp)
c.JSON(http.StatusOK, resp)
}
//SetGroupMemberNickname
func SetGroupMemberNickname(c *gin.Context) {
params := api.SetGroupMemberNicknameReq{}
if err := c.BindJSON(&params); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
req := &rpc.SetGroupMemberNicknameReq{}
utils.CopyStructFields(req, &params)
var ok bool
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " api args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := rpc.NewGroupClient(etcdConn)
reply, err := client.SetGroupMemberNickname(context.Background(), req)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), " failed ", req.String())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": err.Error()})
return
}
resp := api.SetGroupMemberNicknameResp{CommResp: api.CommResp{ErrCode: reply.CommonResp.ErrCode, ErrMsg: reply.CommonResp.ErrMsg}}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " api return ", resp)
c.JSON(http.StatusOK, resp)
}
func GetGroupMemberIDListFromCache(c *gin.Context) {
}

View File

@@ -40,11 +40,12 @@ func newUserSendMsgReq(params *ManagementSendMsgReq) *pbChat.SendMsgReq {
fallthrough
case constant.Voice:
fallthrough
case constant.Video:
fallthrough
case constant.File:
newContent = utils.StructToJsonString(params.Content)
case constant.Revoke:
newContent = params.Content["revokeMsgClientID"].(string)
default:
}
var options map[string]bool
@@ -94,7 +95,7 @@ func ManagementSendMsg(c *gin.Context) {
params := ManagementSendMsgReq{}
if err := c.BindJSON(&params); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
log.ErrorByKv("json unmarshal err", c.PostForm("operationID"), "err", err.Error(), "content", c.PostForm("content"))
log.Error(c.PostForm("operationID"), "json unmarshal err", err.Error(), c.PostForm("content"))
return
}
switch params.ContentType {
@@ -126,16 +127,16 @@ func ManagementSendMsg(c *gin.Context) {
//case constant.Quote:
default:
c.JSON(http.StatusBadRequest, gin.H{"errCode": 404, "errMsg": "contentType err"})
log.ErrorByKv("contentType err", c.PostForm("operationID"), "content", c.PostForm("content"))
log.Error(c.PostForm("operationID"), "contentType err", c.PostForm("content"))
return
}
if err := mapstructure.WeakDecode(params.Content, &data); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 401, "errMsg": err.Error()})
log.ErrorByKv("content to Data struct err", "", "err", err.Error())
log.Error(c.PostForm("operationID"), "content to Data struct err", err.Error())
return
} else if err := validate.Struct(data); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 403, "errMsg": err.Error()})
log.ErrorByKv("data args validate err", "", "err", err.Error())
log.Error(c.PostForm("operationID"), "data args validate err", err.Error())
return
}
log.NewInfo("", data, params)
@@ -166,7 +167,7 @@ func ManagementSendMsg(c *gin.Context) {
}
}
log.InfoByKv("Ws call success to ManagementSendMsgReq", params.OperationID, "Parameters", params)
log.NewInfo(params.OperationID, "Ws call success to ManagementSendMsgReq", params)
pbData := newUserSendMsgReq(&params)
log.Info("", "", "api ManagementSendMsg call start..., [data: %s]", pbData.String())

View File

@@ -30,13 +30,17 @@ func DeleteUser(c *gin.Context) {
}
req := &rpc.DeleteUsersReq{}
utils.CopyStructFields(req, &params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(params.OperationID, "DeleteUser args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := rpc.NewUserClient(etcdConn)
@@ -62,13 +66,17 @@ func GetAllUsersUid(c *gin.Context) {
}
req := &rpc.GetAllUserIDReq{}
utils.CopyStructFields(req, &params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(params.OperationID, "GetAllUsersUid args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := rpc.NewUserClient(etcdConn)
@@ -94,13 +102,17 @@ func AccountCheck(c *gin.Context) {
}
req := &rpc.AccountCheckReq{}
utils.CopyStructFields(req, &params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(params.OperationID, "AccountCheck args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := rpc.NewUserClient(etcdConn)
@@ -118,6 +130,7 @@ func AccountCheck(c *gin.Context) {
log.NewInfo(req.OperationID, "AccountCheck api return", resp)
c.JSON(http.StatusOK, resp)
}
func GetUsersOnlineStatus(c *gin.Context) {
params := api.GetUsersOnlineStatusReq{}
if err := c.BindJSON(&params); err != nil {
@@ -126,13 +139,17 @@ func GetUsersOnlineStatus(c *gin.Context) {
}
req := &pbRelay.GetUsersOnlineStatusReq{}
utils.CopyStructFields(req, &params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(params.OperationID, "GetUsersOnlineStatus args ", req.String())
var wsResult []*pbRelay.GetUsersOnlineStatusResp_SuccessResult
var respResult []*pbRelay.GetUsersOnlineStatusResp_SuccessResult
@@ -176,5 +193,4 @@ func GetUsersOnlineStatus(c *gin.Context) {
}
log.NewInfo(req.OperationID, "GetUsersOnlineStatus api return", resp)
c.JSON(http.StatusOK, resp)
}

View File

@@ -27,12 +27,18 @@ func GetUserTags(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
ok, userID := token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
reqPb.UserID = userID
reqPb.OperationID = req.OperationID
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName)
@@ -69,12 +75,18 @@ func CreateTag(c *gin.Context) {
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
ok, userID := token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
reqPb.UserID = userID
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName)
client := pbOffice.NewOfficeServiceClient(etcdConn)
@@ -105,12 +117,18 @@ func DeleteTag(c *gin.Context) {
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
ok, userID := token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
reqPb.UserID = userID
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName)
client := pbOffice.NewOfficeServiceClient(etcdConn)
@@ -141,12 +159,18 @@ func SetTag(c *gin.Context) {
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
ok, userID := token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
reqPb.UserID = userID
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName)
client := pbOffice.NewOfficeServiceClient(etcdConn)
@@ -177,12 +201,18 @@ func SendMsg2Tag(c *gin.Context) {
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
ok, userID := token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
reqPb.SendID = userID
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName)
client := pbOffice.NewOfficeServiceClient(etcdConn)
@@ -210,12 +240,18 @@ func GetTagSendLogs(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
ok, userID := token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
reqPb.UserID = userID
reqPb.OperationID = req.OperationID
reqPb.Pagination = &pbCommon.RequestPagination{
@@ -255,12 +291,18 @@ func GetUserTagByID(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
ok, userID := token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
reqPb.UserID = userID
reqPb.OperationID = req.OperationID
reqPb.TagID = req.TagID

View File

@@ -0,0 +1,522 @@
package office
import (
apiStruct "Open_IM/pkg/base_info"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
pbOffice "Open_IM/pkg/proto/office"
pbCommon "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils"
"context"
"github.com/gin-gonic/gin"
"net/http"
"strings"
)
func CreateOneWorkMoment(c *gin.Context) {
var (
req apiStruct.CreateOneWorkMomentReq
resp apiStruct.CreateOneWorkMomentResp
reqPb pbOffice.CreateOneWorkMomentReq
respPb *pbOffice.CreateOneWorkMomentResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
reqPb.WorkMoment.UserID = userID
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName)
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.CreateOneWorkMoment(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "CreateOneWorkMoment rpc failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "CreateOneWorkMoment rpc server failed" + err.Error()})
return
}
resp.CommResp = apiStruct.CommResp{
ErrCode: respPb.CommonResp.ErrCode,
ErrMsg: respPb.CommonResp.ErrMsg,
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, resp)
}
func DeleteOneWorkMoment(c *gin.Context) {
var (
req apiStruct.DeleteOneWorkMomentReq
resp apiStruct.DeleteOneWorkMomentResp
reqPb pbOffice.DeleteOneWorkMomentReq
respPb *pbOffice.DeleteOneWorkMomentResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
reqPb.UserID = userID
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName)
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.DeleteOneWorkMoment(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "DeleteOneWorkMoment rpc failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "DeleteOneWorkMoment rpc server failed" + err.Error()})
return
}
if err := utils.CopyStructFields(&resp, respPb.CommonResp); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, resp)
}
func LikeOneWorkMoment(c *gin.Context) {
var (
req apiStruct.LikeOneWorkMomentReq
resp apiStruct.LikeOneWorkMomentResp
reqPb pbOffice.LikeOneWorkMomentReq
respPb *pbOffice.LikeOneWorkMomentResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
reqPb.UserID = userID
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName)
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.LikeOneWorkMoment(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "LikeOneWorkMoment rpc failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "LikeOneWorkMoment rpc server failed" + err.Error()})
return
}
if err := utils.CopyStructFields(&resp, respPb.CommonResp); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, resp)
}
func CommentOneWorkMoment(c *gin.Context) {
var (
req apiStruct.CommentOneWorkMomentReq
resp apiStruct.CommentOneWorkMomentResp
reqPb pbOffice.CommentOneWorkMomentReq
respPb *pbOffice.CommentOneWorkMomentResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
reqPb.UserID = userID
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName)
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.CommentOneWorkMoment(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "CommentOneWorkMoment rpc failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "CommentOneWorkMoment rpc server failed" + err.Error()})
return
}
if err := utils.CopyStructFields(&resp, respPb.CommonResp); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, resp)
}
func DeleteComment(c *gin.Context) {
var (
req apiStruct.DeleteCommentReq
resp apiStruct.DeleteCommentResp
reqPb pbOffice.DeleteCommentReq
respPb *pbOffice.DeleteCommentResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), err.Error())
}
var ok bool
var errInfo string
ok, reqPb.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName)
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.DeleteComment(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "DeleteComment rpc failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "DeleteComment rpc server failed" + err.Error()})
return
}
if err := utils.CopyStructFields(&resp, respPb.CommonResp); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, resp)
}
func GetWorkMomentByID(c *gin.Context) {
var (
req apiStruct.GetWorkMomentByIDReq
resp apiStruct.GetWorkMomentByIDResp
reqPb pbOffice.GetWorkMomentByIDReq
respPb *pbOffice.GetWorkMomentByIDResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
reqPb.OperationID = req.OperationID
reqPb.OpUserID = userID
reqPb.WorkMomentID = req.WorkMomentID
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName)
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.GetWorkMomentByID(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserWorkMoments rpc failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserWorkMoments rpc server failed" + err.Error()})
return
}
if err := utils.CopyStructFields(&resp, respPb.CommonResp); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
resp.Data.WorkMoment = &apiStruct.WorkMoment{LikeUserList: []*apiStruct.WorkMomentUser{}, Comments: []*apiStruct.Comment{},
AtUserList: []*apiStruct.WorkMomentUser{}, PermissionUserList: []*apiStruct.WorkMomentUser{}}
if err := utils.CopyStructFields(&resp.Data.WorkMoment, respPb.WorkMoment); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, resp)
}
func GetUserWorkMoments(c *gin.Context) {
var (
req apiStruct.GetUserWorkMomentsReq
resp apiStruct.GetUserWorkMomentsResp
reqPb pbOffice.GetUserWorkMomentsReq
respPb *pbOffice.GetUserWorkMomentsResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
var ok bool
var errInfo string
var opUserID string
ok, opUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
reqPb.OperationID = req.OperationID
reqPb.Pagination = &pbCommon.RequestPagination{
PageNumber: req.PageNumber,
ShowNumber: req.ShowNumber,
}
reqPb.OpUserID = opUserID
reqPb.UserID = req.UserID
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName)
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.GetUserWorkMoments(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserWorkMoments rpc failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserWorkMoments rpc server failed" + err.Error()})
return
}
resp.Data.WorkMoments = []*apiStruct.WorkMoment{}
if err := utils.CopyStructFields(&resp, respPb.CommonResp); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
//if err := utils.CopyStructFields(&resp.Data.WorkMoments, respPb.WorkMoments); err != nil {
// log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
//}
for _, v := range respPb.WorkMoments {
workMoment := apiStruct.WorkMoment{
WorkMomentID: v.WorkMomentID,
UserID: v.UserID,
Content: v.Content,
FaceURL: v.FaceURL,
UserName: v.UserName,
CreateTime: v.CreateTime,
Comments: make([]*apiStruct.Comment, len(v.Comments)),
LikeUserList: make([]*apiStruct.WorkMomentUser, len(v.LikeUserList)),
AtUserList: make([]*apiStruct.WorkMomentUser, len(v.AtUserList)),
PermissionUserList: make([]*apiStruct.WorkMomentUser, len(v.PermissionUserList)),
Permission: v.Permission,
}
for i, comment := range v.Comments {
workMoment.Comments[i] = &apiStruct.Comment{
UserID: comment.UserID,
UserName: comment.UserName,
ReplyUserID: comment.ReplyUserID,
ReplyUserName: comment.ReplyUserName,
ContentID: comment.ContentID,
Content: comment.Content,
CreateTime: comment.CreateTime,
}
}
for i, likeUser := range v.LikeUserList {
workMoment.LikeUserList[i] = &apiStruct.WorkMomentUser{
UserID: likeUser.UserID,
UserName: likeUser.UserName,
}
}
for i, atUser := range v.AtUserList {
workMoment.AtUserList[i] = &apiStruct.WorkMomentUser{
UserID: atUser.UserID,
UserName: atUser.UserName,
}
}
for i, permissionUser := range v.PermissionUserList {
workMoment.PermissionUserList[i] = &apiStruct.WorkMomentUser{
UserID: permissionUser.UserID,
UserName: permissionUser.UserName,
}
}
resp.Data.WorkMoments = append(resp.Data.WorkMoments, &workMoment)
}
resp.Data.ShowNumber = respPb.Pagination.ShowNumber
resp.Data.CurrentPage = respPb.Pagination.CurrentPage
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, resp)
}
func GetUserFriendWorkMoments(c *gin.Context) {
var (
req apiStruct.GetUserFriendWorkMomentsReq
resp apiStruct.GetUserFriendWorkMomentsResp
reqPb pbOffice.GetUserFriendWorkMomentsReq
respPb *pbOffice.GetUserFriendWorkMomentsResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
reqPb.OperationID = req.OperationID
reqPb.Pagination = &pbCommon.RequestPagination{
PageNumber: req.PageNumber,
ShowNumber: req.ShowNumber,
}
reqPb.UserID = userID
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName)
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.GetUserFriendWorkMoments(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserFriendWorkMoments rpc failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserFriendWorkMoments rpc server failed" + err.Error()})
return
}
if err := utils.CopyStructFields(&resp, respPb.CommonResp); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
//if err := utils.CopyStructFields(&resp.Data.WorkMoments, respPb.WorkMoments); err != nil {
// log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
//}
resp.Data.WorkMoments = []*apiStruct.WorkMoment{}
for _, v := range respPb.WorkMoments {
workMoment := apiStruct.WorkMoment{
WorkMomentID: v.WorkMomentID,
UserID: v.UserID,
Content: v.Content,
FaceURL: v.FaceURL,
UserName: v.UserName,
CreateTime: v.CreateTime,
Comments: make([]*apiStruct.Comment, len(v.Comments)),
LikeUserList: make([]*apiStruct.WorkMomentUser, len(v.LikeUserList)),
AtUserList: make([]*apiStruct.WorkMomentUser, len(v.AtUserList)),
PermissionUserList: make([]*apiStruct.WorkMomentUser, len(v.PermissionUserList)),
Permission: v.Permission,
}
for i, comment := range v.Comments {
workMoment.Comments[i] = &apiStruct.Comment{
UserID: comment.UserID,
UserName: comment.UserName,
ReplyUserID: comment.ReplyUserID,
ReplyUserName: comment.ReplyUserName,
ContentID: comment.ContentID,
Content: comment.Content,
CreateTime: comment.CreateTime,
}
}
for i, likeUser := range v.LikeUserList {
workMoment.LikeUserList[i] = &apiStruct.WorkMomentUser{
UserID: likeUser.UserID,
UserName: likeUser.UserName,
}
}
for i, atUser := range v.AtUserList {
workMoment.AtUserList[i] = &apiStruct.WorkMomentUser{
UserID: atUser.UserID,
UserName: atUser.UserName,
}
}
for i, permissionUser := range v.PermissionUserList {
workMoment.PermissionUserList[i] = &apiStruct.WorkMomentUser{
UserID: permissionUser.UserID,
UserName: permissionUser.UserName,
}
}
resp.Data.WorkMoments = append(resp.Data.WorkMoments, &workMoment)
}
resp.Data.ShowNumber = respPb.Pagination.ShowNumber
resp.Data.CurrentPage = respPb.Pagination.CurrentPage
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, resp)
}
func SetUserWorkMomentsLevel(c *gin.Context) {
var (
req apiStruct.SetUserWorkMomentsLevelReq
resp apiStruct.SetUserWorkMomentsLevelResp
reqPb pbOffice.SetUserWorkMomentsLevelReq
respPb *pbOffice.SetUserWorkMomentsLevelResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
reqPb.UserID = userID
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName)
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.SetUserWorkMomentsLevel(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "SetUserWorkMomentsLevel rpc failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "SetUserWorkMomentsLevel rpc server failed" + err.Error()})
return
}
if err := utils.CopyStructFields(&resp, respPb.CommonResp); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, resp)
}

View File

@@ -0,0 +1,443 @@
package organization
import (
jsonData "Open_IM/internal/utils"
api "Open_IM/pkg/base_info"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
rpc "Open_IM/pkg/proto/organization"
open_im_sdk "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils"
"context"
"github.com/gin-gonic/gin"
"net/http"
"strings"
)
func CreateDepartment(c *gin.Context) {
params := api.CreateDepartmentReq{}
if err := c.BindJSON(&params); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
req := &rpc.CreateDepartmentReq{DepartmentInfo: &open_im_sdk.Department{}}
utils.CopyStructFields(req, &params)
utils.CopyStructFields(req.DepartmentInfo, &params)
err, opUserID := token_verify.ParseTokenGetUserID(c.Request.Header.Get("token"), req.OperationID)
req.OpUserID = opUserID
if err != nil {
errMsg := "ParseTokenGetUserID failed " + err.Error() + " " + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api args ", req.String(), "params", params)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOrganizationName)
client := rpc.NewOrganizationClient(etcdConn)
RpcResp, err := client.CreateDepartment(context.Background(), req)
if err != nil {
errMsg := "rpc CreateDepartment failed " + err.Error() + req.String()
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
apiResp := api.CreateDepartmentResp{CommResp: api.CommResp{ErrCode: RpcResp.ErrCode, ErrMsg: RpcResp.ErrMsg}, Department: RpcResp.DepartmentInfo}
apiResp.Data = jsonData.JsonDataOne(RpcResp.DepartmentInfo)
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api return ", apiResp)
c.JSON(http.StatusOK, apiResp)
}
func UpdateDepartment(c *gin.Context) {
params := api.UpdateDepartmentReq{}
if err := c.BindJSON(&params); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
req := &rpc.UpdateDepartmentReq{DepartmentInfo: &open_im_sdk.Department{}}
utils.CopyStructFields(req, &params)
utils.CopyStructFields(req.DepartmentInfo, &params)
err, opUserID := token_verify.ParseTokenGetUserID(c.Request.Header.Get("token"), req.OperationID)
req.OpUserID = opUserID
if err != nil {
errMsg := "ParseTokenGetUserID failed " + err.Error() + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api args ", req.String(), "params", params)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOrganizationName)
client := rpc.NewOrganizationClient(etcdConn)
RpcResp, err := client.UpdateDepartment(context.Background(), req)
if err != nil {
errMsg := "rpc UpdateDepartment failed " + err.Error() + req.String()
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
apiResp := api.UpdateDepartmentResp{CommResp: api.CommResp{ErrCode: RpcResp.ErrCode, ErrMsg: RpcResp.ErrMsg}}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api return ", apiResp)
c.JSON(http.StatusOK, apiResp)
}
func GetSubDepartment(c *gin.Context) {
params := api.GetSubDepartmentReq{}
if err := c.BindJSON(&params); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
req := &rpc.GetSubDepartmentReq{}
utils.CopyStructFields(req, &params)
err, opUserID := token_verify.ParseTokenGetUserID(c.Request.Header.Get("token"), req.OperationID)
req.OpUserID = opUserID
if err != nil {
errMsg := "ParseTokenGetUserID failed " + err.Error() + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api args ", req.String(), "params", params)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOrganizationName)
client := rpc.NewOrganizationClient(etcdConn)
RpcResp, err := client.GetSubDepartment(context.Background(), req)
if err != nil {
errMsg := "rpc GetDepartment failed " + err.Error() + req.String()
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
apiResp := api.GetSubDepartmentResp{CommResp: api.CommResp{ErrCode: RpcResp.ErrCode, ErrMsg: RpcResp.ErrMsg}, DepartmentList: RpcResp.DepartmentList}
apiResp.Data = jsonData.JsonDataList(RpcResp.DepartmentList)
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api return ", apiResp)
c.JSON(http.StatusOK, apiResp)
}
func GetAllDepartment(c *gin.Context) {
}
func DeleteDepartment(c *gin.Context) {
params := api.DeleteDepartmentReq{}
if err := c.BindJSON(&params); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
req := &rpc.DeleteDepartmentReq{}
utils.CopyStructFields(req, &params)
err, opUserID := token_verify.ParseTokenGetUserID(c.Request.Header.Get("token"), req.OperationID)
req.OpUserID = opUserID
if err != nil {
errMsg := "ParseTokenGetUserID failed " + err.Error() + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api args ", req.String(), "params", params)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOrganizationName)
client := rpc.NewOrganizationClient(etcdConn)
RpcResp, err := client.DeleteDepartment(context.Background(), req)
if err != nil {
errMsg := "rpc DeleteDepartment failed " + err.Error() + req.String()
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
apiResp := api.DeleteDepartmentResp{CommResp: api.CommResp{ErrCode: RpcResp.ErrCode, ErrMsg: RpcResp.ErrMsg}}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api return ", apiResp)
c.JSON(http.StatusOK, apiResp)
}
func CreateOrganizationUser(c *gin.Context) {
params := api.CreateOrganizationUserReq{}
if err := c.BindJSON(&params); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
req := &rpc.CreateOrganizationUserReq{OrganizationUser: &open_im_sdk.OrganizationUser{}}
utils.CopyStructFields(req, &params)
utils.CopyStructFields(req.OrganizationUser, &params)
err, opUserID := token_verify.ParseTokenGetUserID(c.Request.Header.Get("token"), req.OperationID)
req.OpUserID = opUserID
if err != nil {
errMsg := "ParseTokenGetUserID failed " + err.Error() + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api args ", req.String(), "params", params)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOrganizationName)
client := rpc.NewOrganizationClient(etcdConn)
RpcResp, err := client.CreateOrganizationUser(context.Background(), req)
if err != nil {
errMsg := "rpc CreateOrganizationUser failed " + err.Error() + req.String()
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
apiResp := api.CreateOrganizationUserResp{CommResp: api.CommResp{ErrCode: RpcResp.ErrCode, ErrMsg: RpcResp.ErrMsg}}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api return ", apiResp)
c.JSON(http.StatusOK, apiResp)
}
func UpdateOrganizationUser(c *gin.Context) {
params := api.UpdateOrganizationUserReq{}
if err := c.BindJSON(&params); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
req := &rpc.UpdateOrganizationUserReq{OrganizationUser: &open_im_sdk.OrganizationUser{}}
utils.CopyStructFields(req, &params)
utils.CopyStructFields(req.OrganizationUser, &params)
err, opUserID := token_verify.ParseTokenGetUserID(c.Request.Header.Get("token"), req.OperationID)
req.OpUserID = opUserID
if err != nil {
errMsg := "ParseTokenGetUserID failed " + err.Error() + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api args ", req.String(), "params", params)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOrganizationName)
client := rpc.NewOrganizationClient(etcdConn)
RpcResp, err := client.UpdateOrganizationUser(context.Background(), req)
if err != nil {
errMsg := "rpc UpdateOrganizationUser failed " + err.Error() + req.String()
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
apiResp := api.UpdateOrganizationUserResp{CommResp: api.CommResp{ErrCode: RpcResp.ErrCode, ErrMsg: RpcResp.ErrMsg}}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api return ", apiResp)
c.JSON(http.StatusOK, apiResp)
}
func CreateDepartmentMember(c *gin.Context) {
params := api.CreateDepartmentMemberReq{}
if err := c.BindJSON(&params); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
req := &rpc.CreateDepartmentMemberReq{DepartmentMember: &open_im_sdk.DepartmentMember{}}
utils.CopyStructFields(req, &params)
utils.CopyStructFields(req.DepartmentMember, &params)
err, opUserID := token_verify.ParseTokenGetUserID(c.Request.Header.Get("token"), req.OperationID)
req.OpUserID = opUserID
if err != nil {
errMsg := "ParseTokenGetUserID failed " + err.Error() + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api args ", req.String(), "params", params)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOrganizationName)
client := rpc.NewOrganizationClient(etcdConn)
RpcResp, err := client.CreateDepartmentMember(context.Background(), req)
if err != nil {
errMsg := "rpc CreateDepartmentMember failed " + err.Error() + req.String()
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
apiResp := api.CreateDepartmentMemberResp{CommResp: api.CommResp{ErrCode: RpcResp.ErrCode, ErrMsg: RpcResp.ErrMsg}}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api return ", apiResp)
c.JSON(http.StatusOK, apiResp)
}
func GetUserInDepartment(c *gin.Context) {
params := api.GetUserInDepartmentReq{}
if err := c.BindJSON(&params); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
req := &rpc.GetUserInDepartmentReq{}
utils.CopyStructFields(req, &params)
err, opUserID := token_verify.ParseTokenGetUserID(c.Request.Header.Get("token"), req.OperationID)
req.OpUserID = opUserID
if err != nil {
errMsg := "ParseTokenGetUserID failed " + err.Error() + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api args ", req.String(), "params", params)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOrganizationName)
client := rpc.NewOrganizationClient(etcdConn)
RpcResp, err := client.GetUserInDepartment(context.Background(), req)
if err != nil {
errMsg := "rpc GetUserInDepartment failed " + err.Error() + req.String()
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
apiResp := api.GetUserInDepartmentResp{CommResp: api.CommResp{ErrCode: RpcResp.ErrCode, ErrMsg: RpcResp.ErrMsg}, UserInDepartment: RpcResp.UserInDepartment}
apiResp.Data = jsonData.JsonDataOne(RpcResp.UserInDepartment)
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api return ", apiResp)
c.JSON(http.StatusOK, apiResp)
}
func UpdateUserInDepartment(c *gin.Context) {
params := api.UpdateUserInDepartmentReq{}
if err := c.BindJSON(&params); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
req := &rpc.UpdateUserInDepartmentReq{DepartmentMember: &open_im_sdk.DepartmentMember{}}
utils.CopyStructFields(req.DepartmentMember, &params)
utils.CopyStructFields(req, &params)
err, opUserID := token_verify.ParseTokenGetUserID(c.Request.Header.Get("token"), req.OperationID)
req.OpUserID = opUserID
if err != nil {
errMsg := "ParseTokenGetUserID failed " + err.Error() + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api args ", req.String(), "params", params)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOrganizationName)
client := rpc.NewOrganizationClient(etcdConn)
RpcResp, err := client.UpdateUserInDepartment(context.Background(), req)
if err != nil {
errMsg := "rpc UpdateUserInDepartment failed " + err.Error() + req.String()
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
apiResp := api.UpdateUserInDepartmentResp{CommResp: api.CommResp{ErrCode: RpcResp.ErrCode, ErrMsg: RpcResp.ErrMsg}}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api return ", apiResp)
c.JSON(http.StatusOK, apiResp)
}
func DeleteOrganizationUser(c *gin.Context) {
params := api.DeleteOrganizationUserReq{}
if err := c.BindJSON(&params); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
req := &rpc.DeleteOrganizationUserReq{}
utils.CopyStructFields(req, &params)
err, opUserID := token_verify.ParseTokenGetUserID(c.Request.Header.Get("token"), req.OperationID)
req.OpUserID = opUserID
if err != nil {
errMsg := "ParseTokenGetUserID failed " + err.Error() + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api args ", req.String(), "params", params)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOrganizationName)
client := rpc.NewOrganizationClient(etcdConn)
RpcResp, err := client.DeleteOrganizationUser(context.Background(), req)
if err != nil {
errMsg := "rpc DeleteOrganizationUser failed " + err.Error() + req.String()
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
apiResp := api.DeleteOrganizationUserResp{CommResp: api.CommResp{ErrCode: RpcResp.ErrCode, ErrMsg: RpcResp.ErrMsg}}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api return ", apiResp)
c.JSON(http.StatusOK, apiResp)
}
func GetDepartmentMember(c *gin.Context) {
params := api.GetDepartmentMemberReq{}
if err := c.BindJSON(&params); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
req := &rpc.GetDepartmentMemberReq{}
utils.CopyStructFields(req, &params)
err, opUserID := token_verify.ParseTokenGetUserID(c.Request.Header.Get("token"), req.OperationID)
req.OpUserID = opUserID
if err != nil {
errMsg := "ParseTokenGetUserID failed " + err.Error() + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api args ", req.String(), "params", params)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOrganizationName)
client := rpc.NewOrganizationClient(etcdConn)
RpcResp, err := client.GetDepartmentMember(context.Background(), req)
if err != nil {
errMsg := "rpc GetDepartmentMember failed " + err.Error() + req.String()
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
apiResp := api.GetDepartmentMemberResp{CommResp: api.CommResp{ErrCode: RpcResp.ErrCode, ErrMsg: RpcResp.ErrMsg}, UserInDepartmentList: RpcResp.UserDepartmentMemberList}
apiResp.Data = jsonData.JsonDataList(RpcResp.UserDepartmentMemberList)
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api return ", apiResp)
c.JSON(http.StatusOK, apiResp)
}
func DeleteUserInDepartment(c *gin.Context) {
params := api.DeleteUserInDepartmentReq{}
if err := c.BindJSON(&params); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
req := &rpc.DeleteUserInDepartmentReq{}
utils.CopyStructFields(req, &params)
err, opUserID := token_verify.ParseTokenGetUserID(c.Request.Header.Get("token"), req.OperationID)
req.OpUserID = opUserID
if err != nil {
errMsg := "ParseTokenGetUserID failed " + err.Error() + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api args ", req.String(), "params", params)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOrganizationName)
client := rpc.NewOrganizationClient(etcdConn)
RpcResp, err := client.DeleteUserInDepartment(context.Background(), req)
if err != nil {
errMsg := "rpc DeleteUserInDepartment failed " + err.Error() + req.String()
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
apiResp := api.DeleteUserInDepartmentResp{CommResp: api.CommResp{ErrCode: RpcResp.ErrCode, ErrMsg: RpcResp.ErrMsg}}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "api return ", apiResp)
c.JSON(http.StatusOK, apiResp)
}

View File

@@ -54,12 +54,18 @@ func AliOSSCredential(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
ok, userID := token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var ok bool
var userID string
var errInfo string
ok, userID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, "AliOSSCredential args ", userID)
stsResp, err := getStsClient().AssumeRole(&sts20150401.AssumeRoleRequest{

View File

@@ -11,22 +11,34 @@ import (
)
var (
minioClient *minio.Client
MinioClient *minio.Client
)
func MinioInit() {
operationID := utils.OperationIDGenerator()
log.NewInfo(operationID, utils.GetSelfFuncName(), "minio config: ", config.Config.Credential.Minio)
minioUrl, err := url2.Parse(config.Config.Credential.Minio.Endpoint)
var initUrl string
if config.Config.Credential.Minio.EndpointInnerEnable {
initUrl = config.Config.Credential.Minio.EndpointInner
} else {
initUrl = config.Config.Credential.Minio.Endpoint
}
log.NewInfo(operationID, utils.GetSelfFuncName(), "use initUrl: ", initUrl)
minioUrl, err := url2.Parse(initUrl)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "parse failed, please check config/config.yaml", err.Error())
return
}
opts := &minio.Options{
Creds: credentials.NewStaticV4(config.Config.Credential.Minio.AccessKeyID, config.Config.Credential.Minio.SecretAccessKey, ""),
}
if minioUrl.Scheme == "http" {
opts.Secure = false
} else if minioUrl.Scheme == "https" {
opts.Secure = true
}
log.NewInfo(operationID, utils.GetSelfFuncName(), "Parse ok ", config.Config.Credential.Minio)
minioClient, err = minio.New(minioUrl.Host, &minio.Options{
Creds: credentials.NewStaticV4(config.Config.Credential.Minio.AccessKeyID, config.Config.Credential.Minio.SecretAccessKey, ""),
Secure: false,
})
MinioClient, err = minio.New(minioUrl.Host, opts)
log.NewInfo(operationID, utils.GetSelfFuncName(), "new ok ", config.Config.Credential.Minio)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "init minio client failed", err.Error())
@@ -36,10 +48,25 @@ func MinioInit() {
Region: config.Config.Credential.Minio.Location,
ObjectLocking: false,
}
err = minioClient.MakeBucket(context.Background(), config.Config.Credential.Minio.Bucket, opt)
err = MinioClient.MakeBucket(context.Background(), config.Config.Credential.Minio.Bucket, opt)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "MakeBucket failed ", err.Error())
exists, err := minioClient.BucketExists(context.Background(), config.Config.Credential.Minio.Bucket)
exists, err := MinioClient.BucketExists(context.Background(), config.Config.Credential.Minio.Bucket)
if err == nil && exists {
log.NewWarn(operationID, utils.GetSelfFuncName(), "We already own ", config.Config.Credential.Minio.Bucket)
} else {
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), err.Error())
}
log.NewError(operationID, utils.GetSelfFuncName(), "create bucket failed and bucket not exists")
return
}
}
// make app bucket
err = MinioClient.MakeBucket(context.Background(), config.Config.Credential.Minio.AppBucket, opt)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "MakeBucket failed ", err.Error())
exists, err := MinioClient.BucketExists(context.Background(), config.Config.Credential.Minio.Bucket)
if err == nil && exists {
log.NewWarn(operationID, utils.GetSelfFuncName(), "We already own ", config.Config.Credential.Minio.Bucket)
} else {
@@ -51,9 +78,10 @@ func MinioInit() {
}
}
// 自动化桶public的代码
//err = minioClient.SetBucketPolicy(context.Background(), config.Config.Credential.Minio.Bucket, policy.BucketPolicyReadWrite)
//err = MinioClient.SetBucketPolicy(context.Background(), config.Config.Credential.Minio.Bucket, policy.BucketPolicyReadWrite)
//err = MinioClient.SetBucketPolicy(context.Background(), config.Config.Credential.Minio.AppBucket, policy.BucketPolicyReadWrite)
//if err != nil {
// log.NewError("", utils.GetSelfFuncName(), "SetBucketPolicy failed please set in web", err.Error())
// log.NewDebug("", utils.GetSelfFuncName(), "SetBucketPolicy failed please set in web", err.Error())
// return
//}
log.NewInfo(operationID, utils.GetSelfFuncName(), "minio create and set policy success")

View File

@@ -4,6 +4,7 @@ import (
apiStruct "Open_IM/pkg/base_info"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
imdb "Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
_ "Open_IM/pkg/common/token_verify"
@@ -33,12 +34,17 @@ func MinioUploadFile(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
ok, _ := token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), req)
var ok bool
var errInfo string
ok, _, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError("", utils.GetSelfFuncName(), "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), req)
switch req.FileType {
// videoType upload snapShot
@@ -56,7 +62,7 @@ func MinioUploadFile(c *gin.Context) {
}
snapShotNewName, snapShotNewType := utils.GetNewFileNameAndContentType(snapShotFile.Filename, constant.ImageType)
log.Debug(req.OperationID, utils.GetSelfFuncName(), snapShotNewName, snapShotNewType)
_, err = minioClient.PutObject(context.Background(), config.Config.Credential.Minio.Bucket, snapShotNewName, snapShotFileObj, snapShotFile.Size, minio.PutObjectOptions{ContentType: snapShotNewType})
_, err = MinioClient.PutObject(context.Background(), config.Config.Credential.Minio.Bucket, snapShotNewName, snapShotFileObj, snapShotFile.Size, minio.PutObjectOptions{ContentType: snapShotNewType})
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "PutObject snapShotFile error", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
@@ -67,6 +73,7 @@ func MinioUploadFile(c *gin.Context) {
}
file, err := c.FormFile("file")
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "FormFile failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "missing file arg: " + err.Error()})
return
}
@@ -77,11 +84,11 @@ func MinioUploadFile(c *gin.Context) {
return
}
newName, newType := utils.GetNewFileNameAndContentType(file.Filename, req.FileType)
log.Debug(req.OperationID, utils.GetSelfFuncName(), newName, newType)
_, err = minioClient.PutObject(context.Background(), config.Config.Credential.Minio.Bucket, newName, fileObj, file.Size, minio.PutObjectOptions{ContentType: newType})
log.Debug(req.OperationID, utils.GetSelfFuncName(), config.Config.Credential.Minio.Bucket, newName, fileObj, file.Size, newType, MinioClient.EndpointURL())
_, err = MinioClient.PutObject(context.Background(), config.Config.Credential.Minio.Bucket, newName, fileObj, file.Size, minio.PutObjectOptions{ContentType: newType})
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "open file error")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "invalid file path" + err.Error()})
log.NewError(req.OperationID, utils.GetSelfFuncName(), "upload file error")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "upload file error" + err.Error()})
return
}
resp.NewName = newName
@@ -101,17 +108,28 @@ func MinioStorageCredential(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
ok, _ := token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
var ok bool
var errInfo string
ok, _, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError("", utils.GetSelfFuncName(), "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
var stsOpts cr.STSAssumeRoleOptions
stsOpts.AccessKey = config.Config.Credential.Minio.AccessKeyID
stsOpts.SecretKey = config.Config.Credential.Minio.SecretAccessKey
stsOpts.DurationSeconds = constant.MinioDurationTimes
li, err := cr.NewSTSAssumeRole(config.Config.Credential.Minio.Endpoint, stsOpts)
var endpoint string
if config.Config.Credential.Minio.EndpointInnerEnable {
endpoint = config.Config.Credential.Minio.EndpointInner
} else {
endpoint = config.Config.Credential.Minio.Endpoint
}
li, err := cr.NewSTSAssumeRole(endpoint, stsOpts)
if err != nil {
log.NewError("", utils.GetSelfFuncName(), "NewSTSAssumeRole failed", err.Error(), stsOpts, config.Config.Credential.Minio.Endpoint)
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
@@ -130,3 +148,98 @@ func MinioStorageCredential(c *gin.Context) {
resp.StsEndpointURL = config.Config.Credential.Minio.Endpoint
c.JSON(http.StatusOK, gin.H{"errCode": 0, "errMsg": "", "data": resp})
}
func UploadUpdateApp(c *gin.Context) {
var (
req apiStruct.UploadUpdateAppReq
resp apiStruct.UploadUpdateAppResp
)
if err := c.Bind(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
var yamlName string
if req.Yaml == nil {
yamlName = ""
} else {
yamlName = req.Yaml.Filename
}
fileObj, err := req.File.Open()
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "Open file error", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "Open file error" + err.Error()})
return
}
_, err = MinioClient.PutObject(context.Background(), config.Config.Credential.Minio.AppBucket, req.File.Filename, fileObj, req.File.Size, minio.PutObjectOptions{})
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "PutObject file error")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "PutObject file error" + err.Error()})
return
}
if yamlName != "" {
yamlObj, err := req.Yaml.Open()
if err == nil {
_, err = MinioClient.PutObject(context.Background(), config.Config.Credential.Minio.AppBucket, yamlName, yamlObj, req.Yaml.Size, minio.PutObjectOptions{})
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "PutObject yaml error")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "PutObject yaml error" + err.Error()})
return
}
} else {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error())
}
}
if err := imdb.UpdateAppVersion(req.Type, req.Version, req.ForceUpdate, req.File.Filename, yamlName, req.UpdateLog); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "UpdateAppVersion error", err.Error())
resp.ErrCode = http.StatusInternalServerError
resp.ErrMsg = err.Error()
c.JSON(http.StatusInternalServerError, resp)
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName())
c.JSON(http.StatusOK, resp)
}
func GetDownloadURL(c *gin.Context) {
var (
req apiStruct.GetDownloadURLReq
resp apiStruct.GetDownloadURLResp
)
defer func() {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
}()
if err := c.Bind(&req); err != nil {
log.NewError("0", utils.GetSelfFuncName(), "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
app, err := imdb.GetNewestVersion(req.Type)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "getNewestVersion failed", err.Error())
}
log.Debug(req.OperationID, utils.GetSelfFuncName(), "app: ", app)
if app != nil {
if app.Version != req.Version && app.Version != "" {
resp.Data.HasNewVersion = true
if app.ForceUpdate == true {
resp.Data.ForceUpdate = true
}
if app.YamlName != "" {
resp.Data.YamlURL = config.Config.Credential.Minio.Endpoint + "/" + config.Config.Credential.Minio.AppBucket + "/" + app.YamlName
}
resp.Data.FileURL = config.Config.Credential.Minio.Endpoint + "/" + config.Config.Credential.Minio.AppBucket + "/" + app.FileName
resp.Data.Version = app.Version
resp.Data.UpdateLog = app.UpdateLog
c.JSON(http.StatusOK, resp)
return
} else {
resp.Data.HasNewVersion = false
c.JSON(http.StatusOK, resp)
return
}
}
c.JSON(http.StatusBadRequest, gin.H{"errCode": 0, "errMsg": "not found app version"})
}

View File

@@ -22,12 +22,18 @@ func TencentCloudStorageCredential(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
ok, userID := token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var ok bool
var userID string
var errInfo string
ok, userID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(req.OperationID, "TencentCloudStorageCredential args ", userID)
cli := sts.NewClient(

View File

@@ -4,9 +4,12 @@ import (
jsonData "Open_IM/internal/utils"
api "Open_IM/pkg/base_info"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
cacheRpc "Open_IM/pkg/proto/cache"
pbRelay "Open_IM/pkg/proto/relay"
open_im_sdk "Open_IM/pkg/proto/sdk_ws"
rpc "Open_IM/pkg/proto/user"
"Open_IM/pkg/utils"
@@ -16,6 +19,116 @@ import (
"strings"
)
func GetUsersInfoFromCache(c *gin.Context) {
params := api.GetUsersInfoReq{}
if err := c.BindJSON(&params); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": http.StatusBadRequest, "errMsg": err.Error()})
return
}
log.NewInfo(params.OperationID, "GetUsersInfoFromCache req: ", params)
req := &rpc.GetUserInfoReq{}
utils.CopyStructFields(req, &params)
var ok bool
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := rpc.NewUserClient(etcdConn)
RpcResp, err := client.GetUserInfo(context.Background(), req)
if err != nil {
log.NewError(req.OperationID, "GetUserInfo failed ", err.Error(), req.String())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "call rpc server failed"})
return
}
var publicUserInfoList []*open_im_sdk.PublicUserInfo
for _, v := range RpcResp.UserInfoList {
publicUserInfoList = append(publicUserInfoList,
&open_im_sdk.PublicUserInfo{UserID: v.UserID, Nickname: v.Nickname, FaceURL: v.FaceURL, Gender: v.Gender, Ex: v.Ex})
}
resp := api.GetUsersInfoResp{CommResp: api.CommResp{ErrCode: RpcResp.CommonResp.ErrCode, ErrMsg: RpcResp.CommonResp.ErrMsg}, UserInfoList: publicUserInfoList}
resp.Data = jsonData.JsonDataList(resp.UserInfoList)
log.NewInfo(req.OperationID, "GetUserInfo api return ", resp)
c.JSON(http.StatusOK, resp)
}
func GetFriendIDListFromCache(c *gin.Context) {
var (
req api.GetFriendIDListFromCacheReq
resp api.GetFriendIDListFromCacheResp
reqPb cacheRpc.GetFriendIDListFromCacheReq
respPb *cacheRpc.GetFriendIDListFromCacheResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": http.StatusBadRequest, "errMsg": err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), req)
reqPb.OperationID = req.OperationID
var ok bool
var errInfo string
ok, reqPb.UserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImCacheName)
client := cacheRpc.NewCacheClient(etcdConn)
respPb, err := client.GetFriendIDListFromCache(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetFriendIDListFromCache", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "call rpc server failed:" + err.Error()})
return
}
resp.UserIDList = respPb.UserIDList
resp.CommResp = api.CommResp{ErrMsg: respPb.CommonResp.ErrMsg, ErrCode: respPb.CommonResp.ErrCode}
c.JSON(http.StatusOK, resp)
}
func GetBlackIDListFromCache(c *gin.Context) {
var (
req api.GetBlackIDListFromCacheReq
resp api.GetBlackIDListFromCacheResp
reqPb cacheRpc.GetBlackIDListFromCacheReq
respPb *cacheRpc.GetBlackIDListFromCacheResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": http.StatusBadRequest, "errMsg": err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
reqPb.OperationID = req.OperationID
var ok bool
var errInfo string
ok, reqPb.UserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImCacheName)
client := cacheRpc.NewCacheClient(etcdConn)
respPb, err := client.GetBlackIDListFromCache(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetFriendIDListFromCache", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "call rpc server failed:" + err.Error()})
return
}
resp.UserIDList = respPb.UserIDList
resp.CommResp = api.CommResp{ErrMsg: respPb.CommonResp.ErrMsg, ErrCode: respPb.CommonResp.ErrCode}
c.JSON(http.StatusOK, resp)
}
func GetUsersInfo(c *gin.Context) {
params := api.GetUsersInfoReq{}
if err := c.BindJSON(&params); err != nil {
@@ -25,13 +138,17 @@ func GetUsersInfo(c *gin.Context) {
}
req := &rpc.GetUserInfoReq{}
utils.CopyStructFields(req, &params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(params.OperationID, "GetUserInfo args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
@@ -63,13 +180,14 @@ func UpdateUserInfo(c *gin.Context) {
}
req := &rpc.UpdateUserInfoReq{UserInfo: &open_im_sdk.UserInfo{}}
utils.CopyStructFields(req.UserInfo, &params)
req.OperationID = params.OperationID
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
log.NewInfo(params.OperationID, "UpdateUserInfo args ", req.String())
@@ -97,13 +215,17 @@ func GetSelfUserInfo(c *gin.Context) {
req := &rpc.GetUserInfoReq{}
utils.CopyStructFields(req, &params)
var ok bool
ok, req.OpUserID = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"})
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
req.UserIDList = append(req.UserIDList, req.OpUserID)
log.NewInfo(params.OperationID, "GetUserInfo args ", req.String())
@@ -127,3 +249,74 @@ func GetSelfUserInfo(c *gin.Context) {
}
}
func GetUsersOnlineStatus(c *gin.Context) {
params := api.GetUsersOnlineStatusReq{}
if err := c.BindJSON(&params); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
req := &pbRelay.GetUsersOnlineStatusReq{}
utils.CopyStructFields(req, &params)
var ok bool
var errInfo string
ok, req.OpUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
if len(config.Config.Manager.AppManagerUid) == 0 {
log.NewError(req.OperationID, "Manager == 0")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "Manager == 0"})
return
}
req.OpUserID = config.Config.Manager.AppManagerUid[0]
log.NewInfo(params.OperationID, "GetUsersOnlineStatus args ", req.String())
var wsResult []*pbRelay.GetUsersOnlineStatusResp_SuccessResult
var respResult []*pbRelay.GetUsersOnlineStatusResp_SuccessResult
flag := false
grpcCons := getcdv3.GetConn4Unique(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOnlineMessageRelayName)
for _, v := range grpcCons {
client := pbRelay.NewOnlineMessageRelayServiceClient(v)
reply, err := client.GetUsersOnlineStatus(context.Background(), req)
if err != nil {
log.NewError(params.OperationID, "GetUsersOnlineStatus rpc err", req.String(), err.Error())
continue
} else {
if reply.ErrCode == 0 {
wsResult = append(wsResult, reply.SuccessResult...)
}
}
}
log.NewInfo(params.OperationID, "call GetUsersOnlineStatus rpc server is success", wsResult)
//Online data merge of each node
for _, v1 := range params.UserIDList {
flag = false
temp := new(pbRelay.GetUsersOnlineStatusResp_SuccessResult)
for _, v2 := range wsResult {
if v2.UserID == v1 {
flag = true
temp.UserID = v1
temp.Status = constant.OnlineStatus
temp.DetailPlatformStatus = append(temp.DetailPlatformStatus, v2.DetailPlatformStatus...)
}
}
if !flag {
temp.UserID = v1
temp.Status = constant.OfflineStatus
}
respResult = append(respResult, temp)
}
resp := api.GetUsersOnlineStatusResp{CommResp: api.CommResp{ErrCode: 0, ErrMsg: ""}, SuccessResult: respResult}
if len(respResult) == 0 {
resp.SuccessResult = []*pbRelay.GetUsersOnlineStatusResp_SuccessResult{}
}
log.NewInfo(req.OperationID, "GetUsersOnlineStatus api return", resp)
c.JSON(http.StatusOK, resp)
}

View File

@@ -1,7 +1,7 @@
package admin
import (
"Open_IM/pkg/cms_api_struct"
apiStruct "Open_IM/pkg/cms_api_struct"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
openIMHttp "Open_IM/pkg/common/http"
@@ -10,16 +10,55 @@ import (
pbAdmin "Open_IM/pkg/proto/admin_cms"
"Open_IM/pkg/utils"
"context"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"strings"
"github.com/gin-gonic/gin"
url2 "net/url"
)
var (
minioClient *minio.Client
)
func init() {
operationID := utils.OperationIDGenerator()
log.NewInfo(operationID, utils.GetSelfFuncName(), "minio config: ", config.Config.Credential.Minio)
var initUrl string
if config.Config.Credential.Minio.EndpointInnerEnable {
initUrl = config.Config.Credential.Minio.EndpointInner
} else {
initUrl = config.Config.Credential.Minio.Endpoint
}
log.NewInfo(operationID, utils.GetSelfFuncName(), "use initUrl: ", initUrl)
minioUrl, err := url2.Parse(initUrl)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "parse failed, please check config/config.yaml", err.Error())
return
}
opts := &minio.Options{
Creds: credentials.NewStaticV4(config.Config.Credential.Minio.AccessKeyID, config.Config.Credential.Minio.SecretAccessKey, ""),
}
if minioUrl.Scheme == "http" {
opts.Secure = false
} else if minioUrl.Scheme == "https" {
opts.Secure = true
}
log.NewInfo(operationID, utils.GetSelfFuncName(), "Parse ok ", config.Config.Credential.Minio)
minioClient, err = minio.New(minioUrl.Host, opts)
log.NewInfo(operationID, utils.GetSelfFuncName(), "new ok ", config.Config.Credential.Minio)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "init minio client failed", err.Error())
return
}
}
// register
func AdminLogin(c *gin.Context) {
var (
req cms_api_struct.AdminLoginRequest
resp cms_api_struct.AdminLoginResponse
req apiStruct.AdminLoginRequest
resp apiStruct.AdminLoginResponse
reqPb pbAdmin.AdminLoginReq
)
if err := c.BindJSON(&req); err != nil {

View File

@@ -28,6 +28,7 @@ func GetGroupById(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
reqPb.GroupId = req.GroupId
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := pbGroup.NewGroupClient(etcdConn)
@@ -44,6 +45,7 @@ func GetGroupById(c *gin.Context) {
resp.GroupMasterName = respPb.CMSGroup.GroupMasterName
resp.GroupMasterId = respPb.CMSGroup.GroupMasterId
resp.IsBanChat = constant.GroupIsBanChat(respPb.CMSGroup.GroupInfo.Status)
log.NewInfo("", utils.GetSelfFuncName(), "req: ", resp)
openIMHttp.RespHttp200(c, constant.OK, resp)
}
@@ -58,6 +60,7 @@ func GetGroups(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
reqPb.Pagination = &commonPb.RequestPagination{}
utils.CopyStructFields(&reqPb.Pagination, req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -83,6 +86,7 @@ func GetGroups(c *gin.Context) {
resp.GroupNums = int(respPb.GroupNum)
resp.CurrentPage = int(respPb.Pagination.PageNumber)
resp.ShowNumber = int(respPb.Pagination.ShowNumber)
log.NewInfo("", utils.GetSelfFuncName(), "resp: ", resp)
openIMHttp.RespHttp200(c, constant.OK, resp)
}
@@ -97,6 +101,7 @@ func GetGroupByName(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
reqPb.GroupName = req.GroupName
reqPb.Pagination = &commonPb.RequestPagination{}
utils.CopyStructFields(&reqPb.Pagination, req)
@@ -123,6 +128,7 @@ func GetGroupByName(c *gin.Context) {
resp.CurrentPage = int(respPb.Pagination.PageNumber)
resp.ShowNumber = int(respPb.Pagination.ShowNumber)
resp.GroupNums = int(respPb.GroupNums)
log.NewInfo("", utils.GetSelfFuncName(), "resp: ", resp)
openIMHttp.RespHttp200(c, constant.OK, resp)
}
@@ -137,6 +143,7 @@ func CreateGroup(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
reqPb.GroupInfo = &commonPb.GroupInfo{}
reqPb.GroupInfo.GroupName = req.GroupName
reqPb.GroupInfo.CreatorUserID = req.GroupMasterId
@@ -169,6 +176,7 @@ func BanGroupChat(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
reqPb.GroupId = req.GroupId
reqPb.Status = constant.GroupBanChat
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -193,6 +201,7 @@ func BanPrivateChat(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
reqPb.GroupId = req.GroupId
reqPb.Status = constant.GroupBanPrivateChat
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -216,6 +225,7 @@ func OpenGroupChat(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
reqPb.GroupId = req.GroupId
reqPb.Status = constant.GroupOk
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -239,6 +249,7 @@ func OpenPrivateChat(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
reqPb.GroupId = req.GroupId
reqPb.Status = constant.GroupOk
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -263,6 +274,7 @@ func GetGroupMembers(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
reqPb.Pagination = &commonPb.RequestPagination{
PageNumber: int32(req.PageNumber),
ShowNumber: int32(req.ShowNumber),
@@ -290,6 +302,7 @@ func GetGroupMembers(c *gin.Context) {
JoinTime: utils.UnixSecondToTime(int64(groupMembers.JoinTime)).String(),
})
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", resp)
openIMHttp.RespHttp200(c, constant.OK, resp)
}
@@ -304,6 +317,7 @@ func AddGroupMembers(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
reqPb.UserIds = req.Members
reqPb.GroupId = req.GroupId
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -316,6 +330,7 @@ func AddGroupMembers(c *gin.Context) {
}
resp.Success = respPb.Success
resp.Failed = respPb.Failed
log.NewInfo("", utils.GetSelfFuncName(), "resp: ", resp)
openIMHttp.RespHttp200(c, constant.OK, resp)
}
@@ -330,6 +345,7 @@ func RemoveGroupMembers(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
reqPb.UserIds = req.Members
reqPb.GroupId = req.GroupId
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -342,6 +358,7 @@ func RemoveGroupMembers(c *gin.Context) {
}
resp.Success = respPb.Success
resp.Failed = respPb.Failed
log.NewInfo("", utils.GetSelfFuncName(), "req: ", resp)
openIMHttp.RespHttp200(c, constant.OK, resp)
}
@@ -356,6 +373,7 @@ func DeleteGroup(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
reqPb.GroupId = req.GroupId
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := pbGroup.NewGroupClient(etcdConn)
@@ -379,6 +397,7 @@ func SetGroupMaster(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
reqPb.GroupId = req.GroupId
reqPb.UserId = req.UserId
reqPb.RoleLevel = constant.GroupOwner
@@ -404,6 +423,7 @@ func SetGroupOrdinaryUsers(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
reqPb.GroupId = req.GroupId
reqPb.UserId = req.UserId
reqPb.RoleLevel = constant.GroupOrdinaryUsers
@@ -424,6 +444,7 @@ func AlterGroupInfo(c *gin.Context) {
_ cms_api_struct.SetGroupMasterResponse
reqPb pbGroup.SetGroupInfoReq
)
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
if err := c.BindJSON(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "BindJSON failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)

View File

@@ -78,6 +78,7 @@ func GetChatLogs(c *gin.Context) {
ShowNumber: int32(req.ShowNumber),
}
utils.CopyStructFields(&reqPb, &req)
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImMessageCMSName)
client := pbMessage.NewMessageCMSClient(etcdConn)
respPb, err := client.GetChatLogs(context.Background(), &reqPb)
@@ -105,5 +106,6 @@ func GetChatLogs(c *gin.Context) {
resp.ShowNumber = int(respPb.Pagination.ShowNumber)
resp.CurrentPage = int(respPb.Pagination.CurrentPage)
resp.ChatLogsNum = int(respPb.ChatLogsNum)
log.NewInfo("", utils.GetSelfFuncName(), "resp", resp)
openIMHttp.RespHttp200(c, constant.OK, resp)
}

View File

@@ -11,14 +11,16 @@ import (
func JWTAuth() gin.HandlerFunc {
return func(c *gin.Context) {
ok, userID := token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), "")
ok, userID, errInfo := token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), "")
log.NewInfo("0", utils.GetSelfFuncName(), "userID: ", userID)
c.Set("userID", userID)
if !ok {
log.NewError("","GetUserIDFromToken false ", c.Request.Header.Get("token"))
log.NewError("", "GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.Abort()
http.RespHttp200(c, constant.ErrParseToken, nil)
return
} else {
log.NewInfo("0", utils.GetSelfFuncName(), "failed: ", errInfo)
}
}
}

View File

@@ -15,7 +15,7 @@ import (
func NewGinRouter() *gin.Engine {
gin.SetMode(gin.ReleaseMode)
baseRouter := gin.Default()
router := baseRouter.Group("/api")
router := baseRouter.Group("/cms")
router.Use(middleware.CorsHandler())
adminRouterGroup := router.Group("/admin")
{

View File

@@ -27,6 +27,7 @@ func GetMessagesStatistics(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
utils.CopyStructFields(&reqPb.StatisticsReq, &req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImStatisticsName)
client := pb.NewUserClient(etcdConn)
@@ -57,6 +58,7 @@ func GetMessagesStatistics(c *gin.Context) {
MessageNum: int(v.Num),
})
}
log.NewInfo("", utils.GetSelfFuncName(), "resp: ", resp)
openIMHttp.RespHttp200(c, constant.OK, resp)
}
@@ -72,6 +74,7 @@ func GetUserStatistics(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
utils.CopyStructFields(&reqPb.StatisticsReq, &req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImStatisticsName)
client := pb.NewUserClient(etcdConn)
@@ -112,6 +115,7 @@ func GetUserStatistics(c *gin.Context) {
TotalUserNum: int(v.Num),
})
}
log.NewInfo("", utils.GetSelfFuncName(), "resp: ", resp)
openIMHttp.RespHttp200(c, constant.OK, resp)
}
@@ -127,6 +131,7 @@ func GetGroupStatistics(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
utils.CopyStructFields(&reqPb.StatisticsReq, &req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImStatisticsName)
client := pb.NewUserClient(etcdConn)
@@ -160,6 +165,7 @@ func GetGroupStatistics(c *gin.Context) {
})
}
log.NewInfo("", utils.GetSelfFuncName(), "resp: ", resp)
openIMHttp.RespHttp200(c, constant.OK, resp)
}
@@ -175,6 +181,7 @@ func GetActiveUser(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
utils.CopyStructFields(&reqPb.StatisticsReq, req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImStatisticsName)
client := pb.NewUserClient(etcdConn)
@@ -185,6 +192,7 @@ func GetActiveUser(c *gin.Context) {
return
}
utils.CopyStructFields(&resp.ActiveUserList, respPb.Users)
log.NewInfo("", utils.GetSelfFuncName(), "resp: ", resp)
openIMHttp.RespHttp200(c, constant.OK, resp)
}
@@ -200,6 +208,7 @@ func GetActiveGroup(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
utils.CopyStructFields(&reqPb.StatisticsReq, req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImStatisticsName)
client := pb.NewUserClient(etcdConn)
@@ -220,5 +229,6 @@ func GetActiveGroup(c *gin.Context) {
MessageNum: int(group.MessageNum),
})
}
log.NewInfo("", utils.GetSelfFuncName(), "resp: ", resp)
openIMHttp.RespHttp200(c, constant.OK, resp)
}

View File

@@ -29,6 +29,7 @@ func GetUserById(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
utils.CopyStructFields(&reqPb, &req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pb.NewUserClient(etcdConn)
@@ -43,15 +44,17 @@ func GetUserById(c *gin.Context) {
return
}
utils.CopyStructFields(&resp, respPb.User)
log.NewInfo("", utils.GetSelfFuncName(), "resp: ", resp)
openIMHttp.RespHttp200(c, constant.OK, resp)
}
func GetUsersByName(c *gin.Context) {
var (
req cms_api_struct.GetUsersByNameRequest
resp cms_api_struct.GetUsersByNameResponse
req cms_api_struct.GetUsersByNameRequest
resp cms_api_struct.GetUsersByNameResponse
reqPb pb.GetUsersByNameReq
)
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
if err := c.ShouldBindQuery(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "ShouldBindQuery failed", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
@@ -74,6 +77,7 @@ func GetUsersByName(c *gin.Context) {
resp.ShowNumber = int(respPb.Pagination.ShowNumber)
resp.CurrentPage = int(respPb.Pagination.CurrentPage)
resp.UserNums = respPb.UserNums
log.NewInfo("", utils.GetSelfFuncName(), "resp: ", resp)
openIMHttp.RespHttp200(c, constant.OK, resp)
}
@@ -89,6 +93,7 @@ func GetUsers(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
utils.CopyStructFields(&reqPb.Pagination, &req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pb.NewUserClient(etcdConn)
@@ -101,6 +106,7 @@ func GetUsers(c *gin.Context) {
resp.ShowNumber = int(respPb.Pagination.ShowNumber)
resp.CurrentPage = int(respPb.Pagination.CurrentPage)
resp.UserNums = respPb.UserNums
log.NewInfo("", utils.GetSelfFuncName(), "resp: ", resp)
openIMHttp.RespHttp200(c, constant.OK, resp)
}
@@ -116,14 +122,15 @@ func ResignUser(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": http.StatusBadRequest, "errMsg": err.Error()})
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
utils.CopyStructFields(&reqPb, &req)
fmt.Println(reqPb.UserId)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pb.NewUserClient(etcdConn)
_, err := client.ResignUser(context.Background(), &reqPb)
if err != nil {
openIMHttp.RespHttp200(c, err, resp)
}
log.NewInfo("", utils.GetSelfFuncName(), "resp: ", resp)
openIMHttp.RespHttp200(c, constant.OK, resp)
}
@@ -138,6 +145,7 @@ func AlterUser(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, resp)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
utils.CopyStructFields(&reqPb, &req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pb.NewUserClient(etcdConn)
@@ -159,6 +167,7 @@ func AddUser(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
utils.CopyStructFields(&reqPb, &req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pb.NewUserClient(etcdConn)
@@ -182,6 +191,7 @@ func BlockUser(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, resp)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
utils.CopyStructFields(&reqPb, &req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pb.NewUserClient(etcdConn)
@@ -205,6 +215,7 @@ func UnblockUser(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, resp)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
utils.CopyStructFields(&reqPb, &req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pb.NewUserClient(etcdConn)
@@ -213,6 +224,7 @@ func UnblockUser(c *gin.Context) {
openIMHttp.RespHttp200(c, err, resp)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "resp: ", resp)
openIMHttp.RespHttp200(c, constant.OK, resp)
}
@@ -229,6 +241,7 @@ func GetBlockUsers(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, resp)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
utils.CopyStructFields(&reqPb.Pagination, &req)
log.NewInfo(reqPb.OperationID, utils.GetSelfFuncName(), "blockUsers", reqPb.Pagination, req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
@@ -255,6 +268,7 @@ func GetBlockUsers(c *gin.Context) {
resp.ShowNumber = int(respPb.Pagination.ShowNumber)
resp.CurrentPage = int(respPb.Pagination.CurrentPage)
resp.UserNums = respPb.UserNums
log.NewInfo("", utils.GetSelfFuncName(), "req: ", resp)
openIMHttp.RespHttp200(c, constant.OK, resp)
}
@@ -269,6 +283,7 @@ func GetBlockUserById(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
reqPb.UserId = req.UserId
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pb.NewUserClient(etcdConn)
@@ -281,6 +296,7 @@ func GetBlockUserById(c *gin.Context) {
resp.EndDisableTime = respPb.BlockUser.EndDisableTime
resp.BeginDisableTime = respPb.BlockUser.BeginDisableTime
utils.CopyStructFields(&resp, respPb.BlockUser.User)
log.NewInfo("", utils.GetSelfFuncName(), "resp: ", resp)
openIMHttp.RespHttp200(c, constant.OK, resp)
}
@@ -294,6 +310,7 @@ func DeleteUser(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", req)
reqPb.UserId = req.UserId
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pb.NewUserClient(etcdConn)

View File

@@ -42,11 +42,11 @@ func Login(c *gin.Context) {
return
}
if r.Password != params.Password {
log.NewError(params.OperationID, "password err", params.Password, account, r.Password, r.Account)
log.NewError(params.OperationID, "password err", params.Password, account, r.Password, r.Account)
c.JSON(http.StatusOK, gin.H{"errCode": constant.PasswordErr, "errMsg": "password err"})
return
}
url := fmt.Sprintf("http://%s:10000/auth/user_token", utils.ServerIP)
url := fmt.Sprintf("http://%s:%d/auth/user_token", utils.ServerIP, config.Config.Api.GinPort[0])
openIMGetUserToken := api.UserTokenReq{}
openIMGetUserToken.OperationID = params.OperationID
openIMGetUserToken.Platform = params.Platform

View File

@@ -0,0 +1,197 @@
package register
import (
"Open_IM/internal/rpc/msg"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/log"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
groupRpc "Open_IM/pkg/proto/group"
organizationRpc "Open_IM/pkg/proto/organization"
commonPb "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils"
"context"
"errors"
"fmt"
"github.com/golang/protobuf/proto"
"math/rand"
"strings"
"time"
)
func onboardingProcess(operationID, userID, userName string) {
if err := createOrganizationUser(operationID, userID, userName); err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "createOrganizationUser failed", err.Error())
}
departmentID := config.Config.Demo.TestDepartMentID
if err := joinTestDepartment(operationID, userID, departmentID); err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "joinTestDepartment failed", err.Error())
}
groupIDList, err := GetDepartmentGroupIDList(operationID, departmentID)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), err.Error())
}
joinGroups(operationID, userID, userName, groupIDList)
log.NewInfo(operationID, utils.GetSelfFuncName(), "fineshed")
}
func createOrganizationUser(operationID, userID, userName string) error {
defer func() {
log.NewInfo(operationID, utils.GetSelfFuncName(), userID)
}()
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOrganizationName)
client := organizationRpc.NewOrganizationClient(etcdConn)
req := &organizationRpc.CreateOrganizationUserReq{
OrganizationUser: &commonPb.OrganizationUser{
UserID: userID,
Nickname: userName,
EnglishName: randomEnglishName(),
Gender: constant.Male,
CreateTime: uint32(time.Now().Unix()),
},
OperationID: operationID,
OpUserID: userID,
}
if strings.Contains("@", userID) {
req.OrganizationUser.Email = userID
} else {
req.OrganizationUser.Telephone = userID
}
resp, err := client.CreateOrganizationUser(context.Background(), req)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), err.Error())
return err
}
if resp.ErrCode != 0 {
log.NewError(req.OperationID, utils.GetSelfFuncName(), resp)
return errors.New(resp.ErrMsg)
}
return nil
}
func joinTestDepartment(operationID, userID, departmentID string) error {
defer func() {
log.NewInfo(operationID, utils.GetSelfFuncName(), userID)
}()
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOrganizationName)
client := organizationRpc.NewOrganizationClient(etcdConn)
req := &organizationRpc.CreateDepartmentMemberReq{
DepartmentMember: &commonPb.DepartmentMember{
UserID: userID,
DepartmentID: departmentID,
Position: randomPosition(),
},
OperationID: operationID,
OpUserID: config.Config.Manager.AppManagerUid[0],
}
resp, err := client.CreateDepartmentMember(context.Background(), req)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), err.Error())
return err
}
if resp.ErrCode != 0 {
log.NewError(req.OperationID, utils.GetSelfFuncName(), resp)
return errors.New(resp.ErrMsg)
}
return nil
}
func GetDepartmentGroupIDList(operationID, departmentID string) ([]string, error) {
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOrganizationName)
client := organizationRpc.NewOrganizationClient(etcdConn)
req := organizationRpc.GetDepartmentParentIDListReq{
DepartmentID: departmentID,
OperationID: operationID,
}
resp, err := client.GetDepartmentParentIDList(context.Background(), &req)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), err.Error(), req.String())
return nil, err
}
if resp.ErrCode != 0 {
log.NewError(req.OperationID, utils.GetSelfFuncName(), resp)
return nil, errors.New(resp.ErrMsg)
}
resp.ParentIDList = append(resp.ParentIDList, departmentID)
getDepartmentRelatedGroupIDListReq := organizationRpc.GetDepartmentRelatedGroupIDListReq{OperationID: operationID, DepartmentIDList: resp.ParentIDList}
getDepartmentParentIDListResp, err := client.GetDepartmentRelatedGroupIDList(context.Background(), &getDepartmentRelatedGroupIDListReq)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), err.Error(), getDepartmentRelatedGroupIDListReq.String())
return nil, err
}
if getDepartmentParentIDListResp.ErrCode != 0 {
log.NewError(req.OperationID, utils.GetSelfFuncName(), getDepartmentParentIDListResp)
return nil, errors.New(getDepartmentParentIDListResp.ErrMsg)
}
return getDepartmentParentIDListResp.GroupIDList, nil
}
func joinGroups(operationID, userID, userName string, groupIDList []string) {
defer func() {
log.NewInfo(operationID, utils.GetSelfFuncName(), userID, groupIDList)
}()
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := groupRpc.NewGroupClient(etcdConn)
for _, groupID := range groupIDList {
req := &groupRpc.InviteUserToGroupReq{
OperationID: operationID,
GroupID: groupID,
Reason: "register auto join",
InvitedUserIDList: []string{userID},
OpUserID: userID,
}
resp, err := client.InviteUserToGroup(context.Background(), req)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), err.Error(), req.String())
continue
}
if resp.ErrCode != 0 {
log.NewError(req.OperationID, utils.GetSelfFuncName(), resp)
continue
}
onboardingProcessNotification(operationID, userID, groupID)
}
}
// welcome user join department notification
func onboardingProcessNotification(operationID, userID, groupID string) {
defer func() {
log.NewInfo(operationID, utils.GetSelfFuncName(), userID, groupID)
}()
var tips commonPb.TipsComm
tips.DefaultTips = config.Config.Notification.JoinDepartmentNotification.DefaultTips.Tips
content, err := proto.Marshal(&tips)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), err.Error(), "proto marshal failed")
return
}
notification := &msg.NotificationMsg{
SendID: userID,
RecvID: groupID,
Content: content,
MsgFrom: constant.UserMsgType,
ContentType: constant.Text,
SessionType: constant.SingleChatType,
OperationID: operationID,
}
// notification user join group
msg.Notification(notification)
}
func randomEnglishName() string {
l := []string{"abandon", "entail", "nebula", "shrink", "accumulate", "etch", "nostalgia", "slide",
"feudal", "adverse", "exploit", "occupy", "solve", "amazing", "fantasy", "orchid", "spiky", "approve", "flap"}
rand.Seed(time.Now().UnixNano())
index := rand.Intn(len(l) - 1)
fmt.Println(index)
return l[index]
}
func randomPosition() string {
l := []string{"Golang工程师", "前端工程师", "后端工程师", "产品经理", "测试开发工程师", "运维开发工程师"}
rand.Seed(time.Now().UnixNano())
index := rand.Intn(len(l) - 1)
fmt.Println(index)
return l[index]
}

View File

@@ -21,7 +21,7 @@ type paramsVerificationCode struct {
Email string `json:"email"`
PhoneNumber string `json:"phoneNumber"`
OperationID string `json:"operationID" binding:"required"`
UsedFor int `json:"usedFor"`
UsedFor int `json:"usedFor"`
}
func SendVerificationCode(c *gin.Context) {
@@ -62,7 +62,7 @@ func SendVerificationCode(c *gin.Context) {
}
rand.Seed(time.Now().UnixNano())
code := 100000 + rand.Intn(900000)
log.NewInfo(params.OperationID, params.UsedFor,"begin store redis", accountKey, code)
log.NewInfo(params.OperationID, params.UsedFor, "begin store redis", accountKey, code)
err := db.DB.SetAccountCode(accountKey, code, config.Config.Demo.CodeTTL)
if err != nil {
log.NewError(params.OperationID, "set redis error", accountKey, "err", err.Error())
@@ -77,7 +77,7 @@ func SendVerificationCode(c *gin.Context) {
m.SetHeader(`Subject`, config.Config.Demo.Mail.Title)
m.SetBody(`text/html`, fmt.Sprintf("%d", code))
if err := gomail.NewDialer(config.Config.Demo.Mail.SmtpAddr, config.Config.Demo.Mail.SmtpPort, config.Config.Demo.Mail.SenderMail, config.Config.Demo.Mail.SenderAuthorizationCode).DialAndSend(m); err != nil {
log.ErrorByKv("send mail error", account, "err", err.Error())
log.Error(params.OperationID, "send mail error", account, err.Error())
c.JSON(http.StatusOK, gin.H{"errCode": constant.MailSendCodeErr, "errMsg": ""})
return
}

View File

@@ -53,7 +53,7 @@ func SetPassword(c *gin.Context) {
return
}
}
url := fmt.Sprintf("http://%s:10000/auth/user_register", utils.ServerIP)
url := fmt.Sprintf("http://%s:%d/auth/user_register", utils.ServerIP, config.Config.Api.GinPort[0])
openIMRegisterReq := api.UserRegisterReq{}
openIMRegisterReq.OperationID = params.OperationID
openIMRegisterReq.Platform = params.Platform
@@ -84,6 +84,8 @@ func SetPassword(c *gin.Context) {
return
}
log.Info(params.OperationID, "end setPassword", account, params.Password)
// demo onboarding
onboardingProcess(params.OperationID, account, params.Name)
c.JSON(http.StatusOK, gin.H{"errCode": constant.NoError, "errMsg": "", "data": openIMRegisterResp.UserToken})
return
}

View File

@@ -35,14 +35,14 @@ func Verify(c *gin.Context) {
}
if params.VerificationCode == config.Config.Demo.SuperCode {
log.InfoByKv("Super Code Verified successfully", account)
log.NewInfo(params.OperationID, "Super Code Verified successfully", account)
data := make(map[string]interface{})
data["account"] = account
data["verificationCode"] = params.VerificationCode
c.JSON(http.StatusOK, gin.H{"errCode": constant.NoError, "errMsg": "Verified successfully!", "data": data})
return
}
log.NewInfo("0", " params.VerificationCode != config.Config.Demo.SuperCode", params.VerificationCode, config.Config.Demo)
log.NewInfo(params.OperationID, " params.VerificationCode != config.Config.Demo.SuperCode", params.VerificationCode, config.Config.Demo)
log.NewInfo(params.OperationID, "begin get form redis", account)
if params.UsedFor == 0 {
params.UsedFor = constant.VerificationCodeForRegister

View File

@@ -2,6 +2,7 @@ package gate
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/statistics"
"fmt"
@@ -10,12 +11,14 @@ import (
)
var (
rwLock *sync.RWMutex
validate *validator.Validate
ws WServer
rpcSvr RPCServer
sendMsgCount uint64
userCount uint64
rwLock *sync.RWMutex
validate *validator.Validate
ws WServer
rpcSvr RPCServer
sendMsgAllCount uint64
sendMsgFailedCount uint64
sendMsgSuccessCount uint64
userCount uint64
)
func Init(rpcPort, wsPort int) {
@@ -23,8 +26,8 @@ func Init(rpcPort, wsPort int) {
rwLock = new(sync.RWMutex)
validate = validator.New()
statistics.NewStatistics(&sendMsgCount, config.Config.ModuleName.LongConnSvrName, fmt.Sprintf("%d second recv to msg_gateway sendMsgCount", sendMsgCount), 300)
statistics.NewStatistics(&userCount, config.Config.ModuleName.LongConnSvrName, fmt.Sprintf("%d second add user conn", userCount), 300)
statistics.NewStatistics(&sendMsgAllCount, config.Config.ModuleName.LongConnSvrName, fmt.Sprintf("%d second recv to msg_gateway sendMsgCount", constant.StatisticsTimeInterval), constant.StatisticsTimeInterval)
statistics.NewStatistics(&userCount, config.Config.ModuleName.LongConnSvrName, fmt.Sprintf("%d second add user conn", constant.StatisticsTimeInterval), constant.StatisticsTimeInterval)
ws.onInit(wsPort)
rpcSvr.onInit(rpcPort)
}

View File

@@ -14,9 +14,7 @@ import (
"encoding/gob"
"github.com/golang/protobuf/proto"
"github.com/gorilla/websocket"
"google.golang.org/grpc"
"runtime"
"strconv"
"strings"
)
@@ -62,7 +60,7 @@ func (ws *WServer) msgParse(conn *UserConn, binaryMsg []byte) {
ws.pullMsgBySeqListReq(conn, &m)
default:
}
log.NewInfo("", "goroutine num is ", runtime.NumGoroutine())
log.NewInfo(m.OperationID, "goroutine num is ", runtime.NumGoroutine())
}
func (ws *WServer) getSeqReq(conn *UserConn, m *Req) {
log.NewInfo(m.OperationID, "Ws call success to getNewSeq", m.MsgIncr, m.SendID, m.ReqIdentifier, m.Data)
@@ -71,9 +69,6 @@ func (ws *WServer) getSeqReq(conn *UserConn, m *Req) {
rpcReq.UserID = m.SendID
rpcReq.OperationID = m.OperationID
grpcConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfflineMessageName)
if grpcConn == nil {
log.ErrorByKv("get grpcConn err", rpcReq.OperationID, "args", m)
}
msgClient := pbChat.NewChatClient(grpcConn)
rpcReply, err := msgClient.GetMaxAndMinSeq(context.Background(), &rpcReq)
if err != nil {
@@ -82,7 +77,7 @@ func (ws *WServer) getSeqReq(conn *UserConn, m *Req) {
nReply.ErrMsg = err.Error()
ws.getSeqResp(conn, m, nReply)
} else {
log.InfoByKv("rpc call success to getSeqReq", rpcReq.OperationID, "replyData", rpcReply.String())
log.NewInfo(rpcReq.OperationID, "rpc call success to getSeqReq", rpcReply.String())
ws.getSeqResp(conn, m, rpcReply)
}
}
@@ -148,7 +143,7 @@ func (ws *WServer) pullMsgBySeqListResp(conn *UserConn, m *Req, pb *sdk_ws.PullM
}
func (ws *WServer) sendMsgReq(conn *UserConn, m *Req) {
sendMsgCount++
sendMsgAllCount++
log.NewInfo(m.OperationID, "Ws call success to sendMsgReq start", m.MsgIncr, m.ReqIdentifier, m.SendID, m.Data)
nReply := new(pbChat.SendMsgResp)
isPass, errCode, errMsg, pData := ws.argsValidate(m, constant.WSSendMsg)
@@ -205,21 +200,15 @@ func (ws *WServer) sendSignalMsgReq(conn *UserConn, m *Req) {
isPass, errCode, errMsg, pData := ws.argsValidate(m, constant.WSSendSignalMsg)
if isPass {
signalResp := pbRtc.SignalResp{}
//isPass2, errCode2, errMsg2, signalResp, msgData := ws.signalMessageAssemble(pData.(*sdk_ws.SignalReq), m.OperationID)
connGrpc, err := grpc.Dial(config.Config.Rtc.Address+":"+strconv.Itoa(config.Config.Rtc.Port), grpc.WithInsecure())
if err != nil {
log.NewError(m.OperationID, utils.GetSelfFuncName(), "grpc.Dial failed", err.Error())
ws.sendSignalMsgResp(conn, 204, "create grpc failed"+err.Error(), m, nil)
return
}
rtcClient := pbRtc.NewRtcServiceClient(connGrpc)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImRealTimeCommName)
rtcClient := pbRtc.NewRtcServiceClient(etcdConn)
req := &pbRtc.SignalMessageAssembleReq{
SignalReq: pData.(*pbRtc.SignalReq),
OperationID: m.OperationID,
}
respPb, err := rtcClient.SignalMessageAssemble(context.Background(), req)
if err != nil {
log.NewError(m.OperationID, utils.GetSelfFuncName(), "SignalMessageAssemble", err.Error(), config.Config.Rtc.Address+":"+strconv.Itoa(config.Config.Rtc.Port))
log.NewError(m.OperationID, utils.GetSelfFuncName(), "SignalMessageAssemble", err.Error(), config.Config.RpcRegisterName.OpenImRealTimeCommName)
ws.sendSignalMsgResp(conn, 204, "grpc SignalMessageAssemble failed: "+err.Error(), m, &signalResp)
return
}

View File

@@ -11,9 +11,9 @@ import (
"bytes"
"context"
"encoding/gob"
"fmt"
"github.com/golang/protobuf/proto"
"net"
"strconv"
"strings"
"github.com/gorilla/websocket"
@@ -34,29 +34,41 @@ func (r *RPCServer) onInit(rpcPort int) {
r.etcdAddr = config.Config.Etcd.EtcdAddr
}
func (r *RPCServer) run() {
ip := utils.ServerIP
registerAddress := ip + ":" + utils.IntToString(r.rpcPort)
listener, err := net.Listen("tcp", registerAddress)
listenIP := ""
if config.Config.ListenIP == "" {
listenIP = "0.0.0.0"
} else {
listenIP = config.Config.ListenIP
}
address := listenIP + ":" + strconv.Itoa(r.rpcPort)
listener, err := net.Listen("tcp", address)
if err != nil {
log.ErrorByArgs(fmt.Sprintf("fail to listening consumer, err:%v\n", err))
return
panic("listening err:" + err.Error() + r.rpcRegisterName)
}
defer listener.Close()
srv := grpc.NewServer()
defer srv.GracefulStop()
pbRelay.RegisterOnlineMessageRelayServiceServer(srv, r)
err = getcdv3.RegisterEtcd4Unique(r.etcdSchema, strings.Join(r.etcdAddr, ","), ip, r.rpcPort, r.rpcRegisterName, 10)
rpcRegisterIP := ""
if config.Config.RpcRegisterIP == "" {
rpcRegisterIP, err = utils.GetLocalIP()
if err != nil {
log.Error("", "GetLocalIP failed ", err.Error())
}
}
err = getcdv3.RegisterEtcd4Unique(r.etcdSchema, strings.Join(r.etcdAddr, ","), rpcRegisterIP, r.rpcPort, r.rpcRegisterName, 10)
if err != nil {
log.ErrorByKv("register push message rpc to etcd err", "", "err", err.Error())
log.Error("", "register push message rpc to etcd err", "", "err", err.Error(), r.etcdSchema, strings.Join(r.etcdAddr, ","), rpcRegisterIP, r.rpcPort, r.rpcRegisterName)
}
err = srv.Serve(listener)
if err != nil {
log.ErrorByKv("push message rpc listening err", "", "err", err.Error())
log.Error("", "push message rpc listening err", "", "err", err.Error())
return
}
}
func (r *RPCServer) OnlinePushMsg(_ context.Context, in *pbRelay.OnlinePushMsgReq) (*pbRelay.OnlinePushMsgResp, error) {
log.InfoByKv("PushMsgToUser is arriving", in.OperationID, "args", in.String())
log.NewInfo(in.OperationID, "PushMsgToUser is arriving", in.String())
var resp []*pbRelay.SingleMsgToUser
msgBytes, _ := proto.Marshal(in.MsgData)
mReply := Resp{
@@ -93,7 +105,7 @@ func (r *RPCServer) OnlinePushMsg(_ context.Context, in *pbRelay.OnlinePushMsgRe
}
}
if !tag {
log.NewError(in.OperationID, "push err ,no matched ws conn not in map", in.String())
log.NewDebug(in.OperationID, "push err ,no matched ws conn not in map", in.String())
}
return &pbRelay.OnlinePushMsgResp{
Resp: resp,
@@ -101,7 +113,7 @@ func (r *RPCServer) OnlinePushMsg(_ context.Context, in *pbRelay.OnlinePushMsgRe
}
func (r *RPCServer) GetUsersOnlineStatus(_ context.Context, req *pbRelay.GetUsersOnlineStatusReq) (*pbRelay.GetUsersOnlineStatusResp, error) {
log.NewInfo(req.OperationID, "rpc GetUsersOnlineStatus arrived server", req.String())
if !token_verify.IsMangerUserID(req.OpUserID) {
if !token_verify.IsManagerUserID(req.OpUserID) {
log.NewError(req.OperationID, "no permission GetUsersOnlineStatus ", req.OpUserID)
return &pbRelay.GetUsersOnlineStatusResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: constant.ErrAccess.ErrMsg}, nil
}
@@ -130,12 +142,12 @@ func (r *RPCServer) GetUsersOnlineStatus(_ context.Context, req *pbRelay.GetUser
func sendMsgToUser(conn *UserConn, bMsg []byte, in *pbRelay.OnlinePushMsgReq, RecvPlatForm, RecvID string) (ResultCode int64) {
err := ws.writeMsg(conn, websocket.BinaryMessage, bMsg)
if err != nil {
log.ErrorByKv("PushMsgToUser is failed By Ws", "", "Addr", conn.RemoteAddr().String(),
log.NewError(in.OperationID, "PushMsgToUser is failed By Ws", "Addr", conn.RemoteAddr().String(),
"error", err, "senderPlatform", constant.PlatformIDToName(in.MsgData.SenderPlatformID), "recvPlatform", RecvPlatForm, "args", in.String(), "recvID", RecvID)
ResultCode = -2
return ResultCode
} else {
log.InfoByKv("PushMsgToUser is success By Ws", in.OperationID, "args", in.String(), "recvPlatForm", RecvPlatForm, "recvID", RecvID)
log.NewDebug(in.OperationID, "PushMsgToUser is success By Ws", "args", in.String(), "recvPlatForm", RecvPlatForm, "recvID", RecvID)
ResultCode = 0
return ResultCode
}

View File

@@ -62,11 +62,11 @@ func (ws *WServer) argsValidate(m *Req, r int32) (isPass bool, errCode int32, er
case constant.WSSendMsg:
data := open_im_sdk.MsgData{}
if err := proto.Unmarshal(m.Data, &data); err != nil {
log.ErrorByKv("Decode Data struct err", "", "err", err.Error(), "reqIdentifier", r)
log.Error("", "Decode Data struct err", err.Error(), r)
return false, 203, err.Error(), nil
}
if err := validate.Struct(data); err != nil {
log.ErrorByKv("data args validate err", "", "err", err.Error(), "reqIdentifier", r)
log.Error("", "data args validate err", err.Error(), r)
return false, 204, err.Error(), nil
}
@@ -74,11 +74,11 @@ func (ws *WServer) argsValidate(m *Req, r int32) (isPass bool, errCode int32, er
case constant.WSSendSignalMsg:
data := pbRtc.SignalReq{}
if err := proto.Unmarshal(m.Data, &data); err != nil {
log.ErrorByKv("Decode Data struct err", "", "err", err.Error(), "reqIdentifier", r)
log.Error("", "Decode Data struct err", err.Error(), r)
return false, 203, err.Error(), nil
}
if err := validate.Struct(data); err != nil {
log.ErrorByKv("data args validate err", "", "err", err.Error(), "reqIdentifier", r)
log.Error("", "data args validate err", err.Error(), r)
return false, 204, err.Error(), nil
}
@@ -86,11 +86,11 @@ func (ws *WServer) argsValidate(m *Req, r int32) (isPass bool, errCode int32, er
case constant.WSPullMsgBySeqList:
data := open_im_sdk.PullMessageBySeqListReq{}
if err := proto.Unmarshal(m.Data, &data); err != nil {
log.ErrorByKv("Decode Data struct err", "", "err", err.Error(), "reqIdentifier", r)
log.Error("", "Decode Data struct err", err.Error(), r)
return false, 203, err.Error(), nil
}
if err := validate.Struct(data); err != nil {
log.ErrorByKv("data args validate err", "", "err", err.Error(), "reqIdentifier", r)
log.Error("", "data args validate err", err.Error(), r)
return false, 204, err.Error(), nil
}
@@ -114,140 +114,3 @@ func (ws *WServer) argsValidate(m *Req, r int32) (isPass bool, errCode int32, er
//} else
}
//func (ws *WServer) signalMessageAssemble(s *open_im_sdk.SignalReq, operationID string) (isPass bool, errCode int32, errMsg string, r *open_im_sdk.SignalResp, msgData *open_im_sdk.MsgData) {
// var msg open_im_sdk.MsgData
// var resp open_im_sdk.SignalResp
// media := open_im_media.NewMedia()
// msg.MsgFrom = constant.UserMsgType
// msg.ContentType = constant.SignalingNotification
// reqData, e := proto.Marshal(s)
// if e != nil {
// return false, 201, e.Error(), nil, nil
// }
// msg.Content = reqData
// msg.CreateTime = utils.GetCurrentTimestampByMill()
// options := make(map[string]bool, 6)
// utils.SetSwitchFromOptions(options, constant.IsHistory, false)
// utils.SetSwitchFromOptions(options, constant.IsPersistent, false)
// utils.SetSwitchFromOptions(options, constant.IsSenderSync, true)
// utils.SetSwitchFromOptions(options, constant.IsConversationUpdate, false)
// utils.SetSwitchFromOptions(options, constant.IsSenderConversationUpdate, false)
// utils.SetSwitchFromOptions(options, constant.IsUnreadCount, false)
// utils.SetSwitchFromOptions(options, constant.IsOfflinePush, true)
// msg.Options = options
// switch payload := s.Payload.(type) {
// case *open_im_sdk.SignalReq_Invite:
// token, liveURL, err2 := media.GetJoinToken(payload.Invite.Invitation.RoomID, payload.Invite.Invitation.InviterUserID, operationID, payload.Invite.Participant)
// if err2 != nil {
// return false, 202, err2.Error(), nil, nil
// }
// invite := open_im_sdk.SignalResp_Invite{&open_im_sdk.SignalInviteReply{
// Token: token,
// RoomID: payload.Invite.Invitation.RoomID,
// LiveURL: liveURL,
// }}
// resp.Payload = &invite
// msg.SenderPlatformID = payload.Invite.Invitation.PlatformID
// msg.SessionType = payload.Invite.Invitation.SessionType
// msg.OfflinePushInfo = payload.Invite.OfflinePushInfo
// msg.SendID = payload.Invite.Invitation.InviterUserID
// if len(payload.Invite.Invitation.InviteeUserIDList) > 0 {
// msg.RecvID = payload.Invite.Invitation.InviteeUserIDList[0]
// } else {
// return false, 203, errors.New("InviteeUserIDList is null").Error(), nil, nil
// }
// msg.ClientMsgID = utils.GetMsgID(payload.Invite.Invitation.InviterUserID)
// return true, 0, "", &resp, &msg
// case *open_im_sdk.SignalReq_InviteInGroup:
// token, liveURL, err2 := media.GetJoinToken(payload.InviteInGroup.Invitation.RoomID, payload.InviteInGroup.Invitation.InviterUserID, operationID, payload.InviteInGroup.Participant)
// if err2 != nil {
// return false, 204, err2.Error(), nil, nil
// }
// inviteGroup := open_im_sdk.SignalResp_InviteInGroup{&open_im_sdk.SignalInviteInGroupReply{
// RoomID: payload.InviteInGroup.Invitation.RoomID,
// Token: token,
// LiveURL: liveURL,
// }}
// resp.Payload = &inviteGroup
// msg.SenderPlatformID = payload.InviteInGroup.Invitation.PlatformID
// msg.SessionType = payload.InviteInGroup.Invitation.SessionType
// msg.OfflinePushInfo = payload.InviteInGroup.OfflinePushInfo
// msg.SendID = payload.InviteInGroup.Invitation.InviterUserID
// if len(payload.InviteInGroup.Invitation.InviteeUserIDList) > 0 {
// msg.GroupID = payload.InviteInGroup.Invitation.GroupID
// } else {
// return false, 205, errors.New("InviteeUserIDList is null").Error(), nil, nil
// }
// msg.ClientMsgID = utils.GetMsgID(payload.InviteInGroup.Invitation.InviterUserID)
//
// return true, 0, "", &resp, &msg
// case *open_im_sdk.SignalReq_Cancel:
// cancel := open_im_sdk.SignalResp_Cancel{&open_im_sdk.SignalCancelReply{}}
// resp.Payload = &cancel
// msg.OfflinePushInfo = payload.Cancel.OfflinePushInfo
// msg.SendID = payload.Cancel.Invitation.InviterUserID
// msg.SenderPlatformID = payload.Cancel.Invitation.PlatformID
// msg.SessionType = payload.Cancel.Invitation.SessionType
// if len(payload.Cancel.Invitation.InviteeUserIDList) > 0 {
// switch payload.Cancel.Invitation.SessionType {
// case constant.SingleChatType:
// msg.RecvID = payload.Cancel.Invitation.InviteeUserIDList[0]
// case constant.GroupChatType:
// msg.GroupID = payload.Cancel.Invitation.GroupID
// }
// } else {
// return false, 206, errors.New("InviteeUserIDList is null").Error(), nil, nil
// }
// msg.ClientMsgID = utils.GetMsgID(payload.Cancel.OpUserID)
// return true, 0, "", &resp, &msg
// case *open_im_sdk.SignalReq_Accept:
// token, liveURL, err2 := media.GetJoinToken(payload.Accept.Invitation.RoomID, payload.Accept.OpUserID, operationID, payload.Accept.Participant)
// if err2 != nil {
// return false, 207, err2.Error(), nil, nil
// }
// accept := open_im_sdk.SignalResp_Accept{&open_im_sdk.SignalAcceptReply{
// Token: token,
// LiveURL: liveURL,
// RoomID: payload.Accept.Invitation.RoomID,
// }}
// resp.Payload = &accept
// msg.OfflinePushInfo = payload.Accept.OfflinePushInfo
// msg.SendID = payload.Accept.OpUserID
// msg.SenderPlatformID = payload.Accept.Invitation.PlatformID
// msg.SessionType = payload.Accept.Invitation.SessionType
// if len(payload.Accept.Invitation.InviteeUserIDList) > 0 {
// switch payload.Accept.Invitation.SessionType {
// case constant.SingleChatType:
// msg.RecvID = payload.Accept.Invitation.InviterUserID
// case constant.GroupChatType:
// msg.GroupID = payload.Accept.Invitation.GroupID
// }
// } else {
// return false, 208, errors.New("InviteeUserIDList is null").Error(), nil, nil
// }
// msg.ClientMsgID = utils.GetMsgID(payload.Accept.OpUserID)
// return true, 0, "", &resp, &msg
// case *open_im_sdk.SignalReq_HungUp:
// case *open_im_sdk.SignalReq_Reject:
// reject := open_im_sdk.SignalResp_Reject{&open_im_sdk.SignalRejectReply{}}
// resp.Payload = &reject
// msg.OfflinePushInfo = payload.Reject.OfflinePushInfo
// msg.SendID = payload.Reject.OpUserID
// msg.SenderPlatformID = payload.Reject.Invitation.PlatformID
// msg.SessionType = payload.Reject.Invitation.SessionType
// if len(payload.Reject.Invitation.InviteeUserIDList) > 0 {
// switch payload.Reject.Invitation.SessionType {
// case constant.SingleChatType:
// msg.RecvID = payload.Reject.Invitation.InviterUserID
// case constant.GroupChatType:
// msg.GroupID = payload.Reject.Invitation.GroupID
// }
// } else {
// return false, 209, errors.New("InviteeUserIDList is null").Error(), nil, nil
// }
// msg.ClientMsgID = utils.GetMsgID(payload.Reject.OpUserID)
// return true, 0, "", &resp, &msg
// }
// return false, 210, errors.New("InviteeUserIDList is null").Error(), nil, nil
//}

View File

@@ -45,7 +45,7 @@ func (ws *WServer) run() {
http.HandleFunc("/", ws.wsHandler) //Get request from client to handle by wsHandler
err := http.ListenAndServe(ws.wsAddr, nil) //Start listening
if err != nil {
log.ErrorByKv("Ws listening err", "", "err", err.Error())
panic("Ws listening err:" + err.Error())
}
}
@@ -54,7 +54,7 @@ func (ws *WServer) wsHandler(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
conn, err := ws.wsUpGrader.Upgrade(w, r, nil) //Conn is obtained through the upgraded escalator
if err != nil {
log.ErrorByKv("upgrade http conn err", "", "err", err)
log.Error("", "upgrade http conn err", err, query)
return
} else {
//Connection mapping relationship,
@@ -62,6 +62,7 @@ func (ws *WServer) wsHandler(w http.ResponseWriter, r *http.Request) {
//Initialize a lock for each user
newConn := &UserConn{conn, new(sync.Mutex)}
userCount++
ws.addUserConn(query["sendID"][0], int32(utils.StringToInt64(query["platformID"][0])), newConn, query["token"][0])
go ws.readMsg(newConn)
}
@@ -76,7 +77,8 @@ func (ws *WServer) readMsg(conn *UserConn) {
}
if err != nil {
uid, platform := ws.getUserUid(conn)
log.ErrorByKv("WS ReadMsg error", "", "userIP", conn.RemoteAddr().String(), "userUid", uid, "platform", platform, "error", err.Error())
log.Error("", "WS ReadMsg error", "userIP", conn.RemoteAddr().String(), "userUid", uid, "platform", platform, "error", err.Error())
userCount--
ws.delUserConn(conn)
return
} else {
@@ -189,13 +191,13 @@ func (ws *WServer) addUserConn(uid string, platformID int32, conn *UserConn, tok
count = count + len(v)
}
log.Debug(operationID, "WS Add operation", "", "wsUser added", ws.wsUserToConn, "connection_uid", uid, "connection_platform", constant.PlatformIDToName(platformID), "online_user_num", len(ws.wsUserToConn), "online_conn_num", count)
userCount = uint64(len(ws.wsUserToConn))
}
func (ws *WServer) delUserConn(conn *UserConn) {
rwLock.Lock()
defer rwLock.Unlock()
operationID := utils.OperationIDGenerator()
var platform, uid string
if oldStringMap, ok := ws.wsConnToUser[conn]; ok {
for k, v := range oldStringMap {
@@ -212,18 +214,16 @@ func (ws *WServer) delUserConn(conn *UserConn) {
for _, v := range ws.wsUserToConn {
count = count + len(v)
}
log.WarnByKv("WS delete operation", "", "wsUser deleted", ws.wsUserToConn, "disconnection_uid", uid, "disconnection_platform", platform, "online_user_num", len(ws.wsUserToConn), "online_conn_num", count)
log.Debug(operationID, "WS delete operation", "", "wsUser deleted", ws.wsUserToConn, "disconnection_uid", uid, "disconnection_platform", platform, "online_user_num", len(ws.wsUserToConn), "online_conn_num", count)
} else {
log.WarnByKv("WS delete operation", "", "wsUser deleted", ws.wsUserToConn, "disconnection_uid", uid, "disconnection_platform", platform, "online_user_num", len(ws.wsUserToConn))
log.Debug(operationID, "WS delete operation", "", "wsUser deleted", ws.wsUserToConn, "disconnection_uid", uid, "disconnection_platform", platform, "online_user_num", len(ws.wsUserToConn))
}
userCount = uint64(len(ws.wsUserToConn))
delete(ws.wsConnToUser, conn)
}
err := conn.Close()
if err != nil {
log.ErrorByKv("close err", "", "uid", uid, "platform", platform)
log.Error(operationID, " close err", "", "uid", uid, "platform", platform)
}
}
@@ -262,20 +262,26 @@ func (ws *WServer) getUserUid(conn *UserConn) (uid, platform string) {
func (ws *WServer) headerCheck(w http.ResponseWriter, r *http.Request) bool {
status := http.StatusUnauthorized
query := r.URL.Query()
operationID := ""
if len(query["operationID"]) != 0 {
operationID = query["operationID"][0]
}
if len(query["token"]) != 0 && len(query["sendID"]) != 0 && len(query["platformID"]) != 0 {
if ok, err, msg := token_verify.WsVerifyToken(query["token"][0], query["sendID"][0], query["platformID"][0]); !ok {
e := err.(*constant.ErrInfo)
log.ErrorByKv("Token verify failed", "", "query", query, msg)
if ok, err, msg := token_verify.WsVerifyToken(query["token"][0], query["sendID"][0], query["platformID"][0], operationID); !ok {
// e := err.(*constant.ErrInfo)
log.Error(operationID, "Token verify failed ", "query ", query, msg, err.Error())
w.Header().Set("Sec-Websocket-Version", "13")
http.Error(w, e.ErrMsg, int(e.ErrCode))
w.Header().Set("ws_err_msg", err.Error())
http.Error(w, err.Error(), status)
return false
} else {
log.InfoByKv("Connection Authentication Success", "", "token", query["token"][0], "userID", query["sendID"][0])
log.Info(operationID, "Connection Authentication Success", "", "token", query["token"][0], "userID", query["sendID"][0])
return true
}
} else {
log.ErrorByKv("Args err", "", "query", query)
log.Error(operationID, "Args err", "query", query)
w.Header().Set("Sec-Websocket-Version", "13")
w.Header().Set("ws_err_msg", "args err, need token, sendID, platformID")
http.Error(w, http.StatusText(status), status)
return false
}

View File

@@ -2,24 +2,59 @@ package logic
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/kafka"
"Open_IM/pkg/common/log"
"Open_IM/pkg/statistics"
"fmt"
"sync"
)
const OnlineTopicBusy = 1
const OnlineTopicVacancy = 0
var (
persistentCH PersistentConsumerHandler
historyCH HistoryConsumerHandler
producer *kafka.Producer
persistentCH PersistentConsumerHandler
historyCH OnlineHistoryConsumerHandler
offlineHistoryCH OfflineHistoryConsumerHandler
producer *kafka.Producer
cmdCh chan Cmd2Value
onlineTopicStatus int
w *sync.Mutex
singleMsgSuccessCount uint64
groupMsgCount uint64
singleMsgFailedCount uint64
)
func Init() {
cmdCh = make(chan Cmd2Value, 10000)
w = new(sync.Mutex)
persistentCH.Init()
historyCH.Init()
historyCH.Init(cmdCh)
onlineTopicStatus = OnlineTopicVacancy
log.Debug("come msg transfer ts", config.Config.Kafka.ConsumerGroupID.MsgToMongoOffline, config.Config.Kafka.Ws2mschatOffline.Topic)
offlineHistoryCH.Init(cmdCh)
statistics.NewStatistics(&singleMsgSuccessCount, config.Config.ModuleName.MsgTransferName, fmt.Sprintf("%d second singleMsgCount insert to mongo", constant.StatisticsTimeInterval), constant.StatisticsTimeInterval)
statistics.NewStatistics(&groupMsgCount, config.Config.ModuleName.MsgTransferName, fmt.Sprintf("%d second groupMsgCount insert to mongo", constant.StatisticsTimeInterval), constant.StatisticsTimeInterval)
producer = kafka.NewKafkaProducer(config.Config.Kafka.Ms2pschat.Addr, config.Config.Kafka.Ms2pschat.Topic)
}
func Run() {
//register mysqlConsumerHandler to
go persistentCH.persistentConsumerGroup.RegisterHandleAndConsumer(&persistentCH)
if config.Config.ChatPersistenceMysql {
go persistentCH.persistentConsumerGroup.RegisterHandleAndConsumer(&persistentCH)
} else {
fmt.Println("not start mysql consumer")
}
go historyCH.historyConsumerGroup.RegisterHandleAndConsumer(&historyCH)
go offlineHistoryCH.historyConsumerGroup.RegisterHandleAndConsumer(&offlineHistoryCH)
}
func SetOnlineTopicStatus(status int) {
w.Lock()
defer w.Unlock()
onlineTopicStatus = status
}
func GetOnlineTopicStatus() int {
w.Lock()
defer w.Unlock()
return onlineTopicStatus
}

View File

@@ -0,0 +1,126 @@
package logic
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
kfk "Open_IM/pkg/common/kafka"
"Open_IM/pkg/common/log"
pbMsg "Open_IM/pkg/proto/chat"
"Open_IM/pkg/utils"
"github.com/Shopify/sarama"
"github.com/golang/protobuf/proto"
"time"
)
type OfflineHistoryConsumerHandler struct {
msgHandle map[string]fcb
cmdCh chan Cmd2Value
historyConsumerGroup *kfk.MConsumerGroup
}
func (mc *OfflineHistoryConsumerHandler) Init(cmdCh chan Cmd2Value) {
mc.msgHandle = make(map[string]fcb)
mc.cmdCh = cmdCh
mc.msgHandle[config.Config.Kafka.Ws2mschatOffline.Topic] = mc.handleChatWs2Mongo
mc.historyConsumerGroup = kfk.NewMConsumerGroup(&kfk.MConsumerGroupConfig{KafkaVersion: sarama.V0_10_2_0,
OffsetsInitial: sarama.OffsetNewest, IsReturnErr: false}, []string{config.Config.Kafka.Ws2mschatOffline.Topic},
config.Config.Kafka.Ws2mschatOffline.Addr, config.Config.Kafka.ConsumerGroupID.MsgToMongoOffline)
}
func (mc *OfflineHistoryConsumerHandler) handleChatWs2Mongo(msg []byte, msgKey string) {
now := time.Now()
msgFromMQ := pbMsg.MsgDataToMQ{}
err := proto.Unmarshal(msg, &msgFromMQ)
if err != nil {
log.Error("msg_transfer Unmarshal msg err", "", "msg", string(msg), "err", err.Error())
return
}
operationID := msgFromMQ.OperationID
log.NewInfo(operationID, "msg come mongo!!!", "", "msg", string(msg))
//Control whether to store offline messages (mongo)
isHistory := utils.GetSwitchFromOptions(msgFromMQ.MsgData.Options, constant.IsHistory)
//Control whether to store history messages (mysql)
isPersist := utils.GetSwitchFromOptions(msgFromMQ.MsgData.Options, constant.IsPersistent)
isSenderSync := utils.GetSwitchFromOptions(msgFromMQ.MsgData.Options, constant.IsSenderSync)
switch msgFromMQ.MsgData.SessionType {
case constant.SingleChatType:
log.NewDebug(msgFromMQ.OperationID, "msg_transfer msg type = SingleChatType", isHistory, isPersist)
if isHistory {
err := saveUserChat(msgKey, &msgFromMQ)
if err != nil {
singleMsgFailedCount++
log.NewError(operationID, "single data insert to mongo err", err.Error(), msgFromMQ.String())
return
}
singleMsgSuccessCount++
log.NewDebug(msgFromMQ.OperationID, "sendMessageToPush cost time ", time.Since(now))
}
if !isSenderSync && msgKey == msgFromMQ.MsgData.SendID {
} else {
go sendMessageToPush(&msgFromMQ, msgKey)
}
log.NewDebug(operationID, "saveSingleMsg cost time ", time.Since(now))
case constant.GroupChatType:
log.NewDebug(msgFromMQ.OperationID, "msg_transfer msg type = GroupChatType", isHistory, isPersist)
if isHistory {
err := saveUserChat(msgFromMQ.MsgData.RecvID, &msgFromMQ)
if err != nil {
log.NewError(operationID, "group data insert to mongo err", msgFromMQ.String(), msgFromMQ.MsgData.RecvID, err.Error())
return
}
groupMsgCount++
}
go sendMessageToPush(&msgFromMQ, msgFromMQ.MsgData.RecvID)
log.NewDebug(operationID, "saveGroupMsg cost time ", time.Since(now))
case constant.NotificationChatType:
log.NewDebug(msgFromMQ.OperationID, "msg_transfer msg type = NotificationChatType", isHistory, isPersist)
if isHistory {
err := saveUserChat(msgKey, &msgFromMQ)
if err != nil {
log.NewError(operationID, "single data insert to mongo err", err.Error(), msgFromMQ.String())
return
}
log.NewDebug(msgFromMQ.OperationID, "sendMessageToPush cost time ", time.Since(now))
}
if !isSenderSync && msgKey == msgFromMQ.MsgData.SendID {
} else {
go sendMessageToPush(&msgFromMQ, msgKey)
}
log.NewDebug(operationID, "saveUserChat cost time ", time.Since(now))
default:
log.NewError(msgFromMQ.OperationID, "SessionType error", msgFromMQ.String())
return
}
log.NewDebug(msgFromMQ.OperationID, "msg_transfer handle topic data to database success...", msgFromMQ.String())
}
func (OfflineHistoryConsumerHandler) Setup(_ sarama.ConsumerGroupSession) error { return nil }
func (OfflineHistoryConsumerHandler) Cleanup(_ sarama.ConsumerGroupSession) error { return nil }
func (mc *OfflineHistoryConsumerHandler) ConsumeClaim(sess sarama.ConsumerGroupSession,
claim sarama.ConsumerGroupClaim) error { // a instance in the consumer group
//log.NewDebug("", "offline new session msg come", claim.HighWaterMarkOffset(), claim.Topic(), claim.Partition())
//for msg := range claim.Messages() {
// log.NewDebug("", "kafka get info to delay mongo", "msgTopic", msg.Topic, "msgPartition", msg.Partition, "offline")
// //mc.msgHandle[msg.Topic](msg.Value, string(msg.Key))
//}
for msg := range claim.Messages() {
if GetOnlineTopicStatus() == OnlineTopicVacancy {
log.NewDebug("", "vacancy offline kafka get info to mongo", "msgTopic", msg.Topic, "msgPartition", msg.Partition, "msg", string(msg.Value))
mc.msgHandle[msg.Topic](msg.Value, string(msg.Key))
sess.MarkMessage(msg, "")
} else {
select {
case <-mc.cmdCh:
log.NewDebug("", "cmd offline kafka get info to mongo", "msgTopic", msg.Topic, "msgPartition", msg.Partition, "msg", string(msg.Value))
case <-time.After(time.Millisecond * time.Duration(100)):
log.NewDebug("", "timeout offline kafka get info to mongo", "msgTopic", msg.Topic, "msgPartition", msg.Partition, "msg", string(msg.Value))
}
mc.msgHandle[msg.Topic](msg.Value, string(msg.Key))
sess.MarkMessage(msg, "")
}
}
return nil
}

View File

@@ -8,37 +8,61 @@ import (
"Open_IM/pkg/grpc-etcdv3/getcdv3"
pbMsg "Open_IM/pkg/proto/chat"
pbPush "Open_IM/pkg/proto/push"
"Open_IM/pkg/statistics"
"Open_IM/pkg/utils"
"context"
"errors"
"github.com/Shopify/sarama"
"github.com/golang/protobuf/proto"
"strings"
"time"
)
type fcb func(msg []byte, msgKey string)
type HistoryConsumerHandler struct {
type Cmd2Value struct {
Cmd int
Value interface{}
}
type OnlineHistoryConsumerHandler struct {
msgHandle map[string]fcb
historyConsumerGroup *kfk.MConsumerGroup
singleMsgCount uint64
groupMsgCount uint64
cmdCh chan Cmd2Value
}
func (mc *HistoryConsumerHandler) Init() {
statistics.NewStatistics(&mc.singleMsgCount, config.Config.ModuleName.MsgTransferName, "singleMsgCount insert to mongo ", 300)
statistics.NewStatistics(&mc.groupMsgCount, config.Config.ModuleName.MsgTransferName, "groupMsgCount insert to mongo ", 300)
mc.msgHandle = make(map[string]fcb)
mc.msgHandle[config.Config.Kafka.Ws2mschat.Topic] = mc.handleChatWs2Mongo
mc.historyConsumerGroup = kfk.NewMConsumerGroup(&kfk.MConsumerGroupConfig{KafkaVersion: sarama.V0_10_2_0,
func (och *OnlineHistoryConsumerHandler) Init(cmdCh chan Cmd2Value) {
och.msgHandle = make(map[string]fcb)
och.cmdCh = cmdCh
och.msgHandle[config.Config.Kafka.Ws2mschat.Topic] = och.handleChatWs2Mongo
och.historyConsumerGroup = kfk.NewMConsumerGroup(&kfk.MConsumerGroupConfig{KafkaVersion: sarama.V0_10_2_0,
OffsetsInitial: sarama.OffsetNewest, IsReturnErr: false}, []string{config.Config.Kafka.Ws2mschat.Topic},
config.Config.Kafka.Ws2mschat.Addr, config.Config.Kafka.ConsumerGroupID.MsgToMongo)
}
func (och *OnlineHistoryConsumerHandler) TriggerCmd(status int) {
operationID := utils.OperationIDGenerator()
err := sendCmd(och.cmdCh, Cmd2Value{Cmd: status, Value: ""}, 1)
if err != nil {
log.Error(operationID, "TriggerCmd failed ", err.Error(), status)
return
}
log.Debug(operationID, "TriggerCmd success", status)
func (mc *HistoryConsumerHandler) handleChatWs2Mongo(msg []byte, msgKey string) {
time := utils.GetCurrentTimestampByNano()
}
func sendCmd(ch chan Cmd2Value, value Cmd2Value, timeout int64) error {
var flag = 0
select {
case ch <- value:
flag = 1
case <-time.After(time.Second * time.Duration(timeout)):
flag = 2
}
if flag == 1 {
return nil
} else {
return errors.New("send cmd timeout")
}
}
func (och *OnlineHistoryConsumerHandler) handleChatWs2Mongo(msg []byte, msgKey string) {
now := time.Now()
msgFromMQ := pbMsg.MsgDataToMQ{}
err := proto.Unmarshal(msg, &msgFromMQ)
if err != nil {
@@ -58,17 +82,18 @@ func (mc *HistoryConsumerHandler) handleChatWs2Mongo(msg []byte, msgKey string)
if isHistory {
err := saveUserChat(msgKey, &msgFromMQ)
if err != nil {
singleMsgFailedCount++
log.NewError(operationID, "single data insert to mongo err", err.Error(), msgFromMQ.String())
return
}
mc.singleMsgCount++
log.NewDebug(msgFromMQ.OperationID, "sendMessageToPush cost time ", utils.GetCurrentTimestampByNano()-time)
singleMsgSuccessCount++
log.NewDebug(msgFromMQ.OperationID, "sendMessageToPush cost time ", time.Since(now))
}
if !isSenderSync && msgKey == msgFromMQ.MsgData.SendID {
} else {
go sendMessageToPush(&msgFromMQ, msgKey)
}
log.NewDebug(operationID, "saveUserChat cost time ", utils.GetCurrentTimestampByNano()-time)
log.NewDebug(operationID, "saveUserChat cost time ", time.Since(now))
case constant.GroupChatType:
log.NewDebug(msgFromMQ.OperationID, "msg_transfer msg type = GroupChatType", isHistory, isPersist)
if isHistory {
@@ -77,7 +102,7 @@ func (mc *HistoryConsumerHandler) handleChatWs2Mongo(msg []byte, msgKey string)
log.NewError(operationID, "group data insert to mongo err", msgFromMQ.String(), msgFromMQ.MsgData.RecvID, err.Error())
return
}
mc.groupMsgCount++
groupMsgCount++
}
go sendMessageToPush(&msgFromMQ, msgFromMQ.MsgData.RecvID)
case constant.NotificationChatType:
@@ -88,14 +113,13 @@ func (mc *HistoryConsumerHandler) handleChatWs2Mongo(msg []byte, msgKey string)
log.NewError(operationID, "single data insert to mongo err", err.Error(), msgFromMQ.String())
return
}
mc.singleMsgCount++
log.NewDebug(msgFromMQ.OperationID, "sendMessageToPush cost time ", utils.GetCurrentTimestampByNano()-time)
log.NewDebug(msgFromMQ.OperationID, "sendMessageToPush cost time ", time.Since(now))
}
if !isSenderSync && msgKey == msgFromMQ.MsgData.SendID {
} else {
go sendMessageToPush(&msgFromMQ, msgKey)
}
log.NewDebug(operationID, "saveUserChat cost time ", utils.GetCurrentTimestampByNano()-time)
log.NewDebug(operationID, "saveUserChat cost time ", time.Since(now))
default:
log.NewError(msgFromMQ.OperationID, "SessionType error", msgFromMQ.String())
return
@@ -103,14 +127,22 @@ func (mc *HistoryConsumerHandler) handleChatWs2Mongo(msg []byte, msgKey string)
log.NewDebug(msgFromMQ.OperationID, "msg_transfer handle topic data to database success...", msgFromMQ.String())
}
func (HistoryConsumerHandler) Setup(_ sarama.ConsumerGroupSession) error { return nil }
func (HistoryConsumerHandler) Cleanup(_ sarama.ConsumerGroupSession) error { return nil }
func (mc *HistoryConsumerHandler) ConsumeClaim(sess sarama.ConsumerGroupSession,
claim sarama.ConsumerGroupClaim) error {
func (OnlineHistoryConsumerHandler) Setup(_ sarama.ConsumerGroupSession) error { return nil }
func (OnlineHistoryConsumerHandler) Cleanup(_ sarama.ConsumerGroupSession) error { return nil }
func (och *OnlineHistoryConsumerHandler) ConsumeClaim(sess sarama.ConsumerGroupSession,
claim sarama.ConsumerGroupClaim) error { // a instance in the consumer group
log.NewDebug("", "online new session msg come", claim.HighWaterMarkOffset(), claim.Topic(), claim.Partition())
for msg := range claim.Messages() {
log.InfoByKv("kafka get info to mongo", "", "msgTopic", msg.Topic, "msgPartition", msg.Partition, "msg", string(msg.Value))
mc.msgHandle[msg.Topic](msg.Value, string(msg.Key))
SetOnlineTopicStatus(OnlineTopicBusy)
//och.TriggerCmd(OnlineTopicBusy)
log.NewDebug("", "online kafka get info to mongo", "msgTopic", msg.Topic, "msgPartition", msg.Partition, "online", msg.Offset, claim.HighWaterMarkOffset())
och.msgHandle[msg.Topic](msg.Value, string(msg.Key))
sess.MarkMessage(msg, "")
if claim.HighWaterMarkOffset()-msg.Offset <= 1 {
log.Debug("", "online msg consume end", claim.HighWaterMarkOffset(), msg.Offset)
SetOnlineTopicStatus(OnlineTopicVacancy)
och.TriggerCmd(OnlineTopicVacancy)
}
}
return nil
}
@@ -133,10 +165,10 @@ func sendMessageToPush(message *pbMsg.MsgDataToMQ, pushToUserID string) {
log.Error(rpcPushMsg.OperationID, "rpc send failed", rpcPushMsg.OperationID, "push data", rpcPushMsg.String(), "err", err.Error())
pid, offset, err := producer.SendMessage(&mqPushMsg)
if err != nil {
log.Error("kafka send failed", mqPushMsg.OperationID, "send data", mqPushMsg.String(), "pid", pid, "offset", offset, "err", err.Error())
log.Error(message.OperationID, "kafka send failed", mqPushMsg.OperationID, "send data", mqPushMsg.String(), "pid", pid, "offset", offset, "err", err.Error())
}
} else {
log.Info("rpc send success", rpcPushMsg.OperationID, "push data", rpcPushMsg.String())
log.Info(message.OperationID, "rpc send success", rpcPushMsg.OperationID, "push data", rpcPushMsg.String())
}
}

View File

@@ -51,7 +51,7 @@ func (pc *PersistentConsumerHandler) handleChatWs2Mysql(msg []byte, msgKey strin
tag = true
}
case constant.GroupChatType:
if msgKey == msgFromMQ.MsgData.SendID || utils.IsContain(msgFromMQ.MsgData.SendID, config.Config.Manager.AppManagerUid) {
if msgKey == msgFromMQ.MsgData.SendID {
tag = true
}
}
@@ -70,7 +70,7 @@ func (PersistentConsumerHandler) Cleanup(_ sarama.ConsumerGroupSession) error {
func (pc *PersistentConsumerHandler) ConsumeClaim(sess sarama.ConsumerGroupSession,
claim sarama.ConsumerGroupClaim) error {
for msg := range claim.Messages() {
log.InfoByKv("kafka get info to mysql", "", "msgTopic", msg.Topic, "msgPartition", msg.Partition, "msg", string(msg.Value))
log.NewDebug("", "kafka get info to mysql", "msgTopic", msg.Topic, "msgPartition", msg.Partition, "msg", string(msg.Value))
pc.msgHandle[msg.Topic](msg.Value, string(msg.Key))
sess.MarkMessage(msg, "")
}

View File

@@ -7,6 +7,8 @@ import (
"Open_IM/pkg/utils"
"bytes"
"crypto/sha256"
"errors"
//"crypto/sha512"
"encoding/hex"
"encoding/json"
@@ -18,10 +20,12 @@ import (
var (
GetuiClient *Getui
TokenExpireError = errors.New("token expire")
)
const (
PushURL = "/push/single/cid"
PushURL = "/push/single/alias"
AuthURL = "/auth"
)
@@ -51,19 +55,40 @@ type AuthResp struct {
type PushReq struct {
RequestID string `json:"request_id"`
Audience struct {
Cid []string `json:"cid"`
Alias []string `json:"alias"`
} `json:"audience"`
PushMssage struct {
Notification Notification `json:"notification"`
PushMessage struct {
Notification Notification `json:"notification,omitempty"`
Transmission string `json:"transmission,omitempty"`
} `json:"push_message"`
PushChannel struct {
Ios Ios `json:"ios"`
Android Android `json:"android"`
} `json:"push_channel"`
}
type Ios struct {
Aps struct {
Sound string `json:"sound"`
Alert Alert `json:"alert"`
} `json:"aps"`
}
type Alert struct {
Title string `json:"title"`
Body string `json:"body"`
}
type Android struct {
Ups struct {
Notification Notification `json:"notification"`
} `json:"ups"`
}
type Notification struct {
Title string `json:"title"`
Body string `json:"body"`
ClickType string `json:"click_type"`
Intent string `json:"intent"`
Url string `json:"url"`
}
type PushResp struct {
@@ -73,44 +98,56 @@ func newGetuiClient() *Getui {
return &Getui{}
}
func (g *Getui) Push(userIDList []string, alert, detailContent, platform, operationID string) (resp string, err error) {
func (g *Getui) Push(userIDList []string, alert, detailContent, operationID string) (resp string, err error) {
token, err := db.DB.GetGetuiToken()
log.NewDebug(operationID, utils.GetSelfFuncName(), "token", token)
if err != nil {
log.NewError(operationID, utils.OperationIDGenerator(), "GetGetuiToken failed", err.Error())
}
if token == "" || err != nil {
token, expireTime, err := g.Auth(operationID, time.Now().UnixNano()/1e6)
token, err = g.getTokenAndSave2Redis(operationID)
if err != nil {
return "", utils.Wrap(err, "Auth failed")
}
log.NewInfo(operationID, "getui", utils.GetSelfFuncName(), token, expireTime, err)
err = db.DB.SetGetuiToken(token, 60*60*23)
if err != nil {
return "", utils.Wrap(err, "Auth failed")
log.NewError(operationID, utils.GetSelfFuncName(), "getTokenAndSave2Redis failed", err.Error())
return "", utils.Wrap(err, "")
}
}
pushReq := PushReq{
RequestID: utils.OperationIDGenerator(),
Audience: struct {
Cid []string `json:"cid"`
}{Cid: []string{userIDList[0]}},
Alias []string `json:"alias"`
}{Alias: []string{userIDList[0]}},
}
pushReq.PushMssage.Notification = Notification{
pushReq.PushMessage.Notification = Notification{
Title: alert,
Body: alert,
ClickType: "none",
ClickType: "startapp",
}
if config.Config.Push.Getui.Intent != "" {
pushReq.PushMssage.Notification.Intent = config.Config.Push.Getui.Intent
pushReq.PushMssage.Notification.ClickType = "intent"
pushReq.PushChannel.Ios.Aps.Sound = "default"
pushReq.PushChannel.Ios.Aps.Alert = Alert{
Title: alert,
Body: alert,
}
pushReq.PushChannel.Android.Ups.Notification = Notification{
Title: alert,
Body: alert,
ClickType: "startapp",
}
pushResp := PushResp{}
err = g.request(PushURL, pushReq, token, &pushResp, operationID)
switch err {
case TokenExpireError:
token, err = g.getTokenAndSave2Redis(operationID)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "getTokenAndSave2Redis failed, ", err.Error())
} else {
log.NewInfo(operationID, utils.GetSelfFuncName(), "getTokenAndSave2Redis: ", token)
}
}
if err != nil {
return "", utils.Wrap(err, "push failed")
}
respBytes, err := json.Marshal(pushResp)
return string(respBytes), err
return string(respBytes), utils.Wrap(err, "")
}
func (g *Getui) Auth(operationID string, timeStamp int64) (token string, expireTime int64, err error) {
@@ -147,7 +184,7 @@ func (g *Getui) request(url string, content interface{}, token string, returnStr
return err
}
if token != "" {
req.Header.Set(token, token)
req.Header.Set("token", token)
}
req.Header.Set("content-type", "application/json")
resp, err := client.Do(req)
@@ -160,8 +197,26 @@ func (g *Getui) request(url string, content interface{}, token string, returnStr
return err
}
log.NewInfo(operationID, "getui", utils.GetSelfFuncName(), "resp, ", string(result))
if err := json.Unmarshal(result, returnStruct); err != nil {
commonResp := GetuiCommonResp{}
commonResp.Data = returnStruct
if err := json.Unmarshal(result, &commonResp); err != nil {
return err
}
if commonResp.Code == 10001 {
return TokenExpireError
}
return nil
}
func (g *Getui) getTokenAndSave2Redis(operationID string) (token string, err error) {
token, expireTime, err := g.Auth(operationID, time.Now().UnixNano()/1e6)
if err != nil {
return "", utils.Wrap(err, "Auth failed")
}
log.NewDebug(operationID, "getui", utils.GetSelfFuncName(), token, expireTime, err)
err = db.DB.SetGetuiToken(token, 60*60*23)
if err != nil {
return "", utils.Wrap(err, "Auth failed")
}
return token, nil
}

View File

@@ -32,13 +32,13 @@ func (j *JPush) SetAlias(cid, alias string) (resp string, err error) {
return resp, nil
}
func (j *JPush) Push(accounts []string, alert, detailContent, platform, operationID string) (string, error) {
func (j *JPush) Push(accounts []string, alert, detailContent, operationID string) (string, error) {
var pf requestBody.Platform
_ = pf.SetPlatform(platform)
pf.SetAll()
var au requestBody.Audience
au.SetAlias(accounts)
var no requestBody.Notification
no.SetAlert(alert, platform)
no.SetAlert(alert)
var me requestBody.Message
me.SetMsgContent(detailContent)
var o requestBody.Options

View File

@@ -2,7 +2,6 @@ package requestBody
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
)
type Notification struct {
@@ -23,18 +22,14 @@ type Ios struct {
Badge string `json:"badge,omitempty"`
}
func (n *Notification) SetAlert(alert, platform string) {
func (n *Notification) SetAlert(alert string) {
n.Alert = alert
switch platform {
case constant.AndroidPlatformStr:
n.Android.Alert = alert
n.SetAndroidIntent()
case constant.IOSPlatformStr:
n.IOS.Alert = alert
n.IOS.Sound = "default"
n.IOS.Badge = "+1"
default:
}
n.Android.Alert = alert
n.SetAndroidIntent()
n.IOS.Alert = alert
n.IOS.Sound = "default"
n.IOS.Badge = "+1"
}
func (n *Notification) SetAndroidIntent() {
n.Android.Intent.URL = config.Config.Push.Jpns.PushIntent

View File

@@ -19,7 +19,7 @@ var (
pushCh PushConsumerHandler
pushTerminal []int32
producer *kafka.Producer
count uint64
successCount uint64
)
func Init(rpcPort int) {
@@ -30,7 +30,7 @@ func Init(rpcPort int) {
}
func init() {
producer = kafka.NewKafkaProducer(config.Config.Kafka.Ws2mschat.Addr, config.Config.Kafka.Ws2mschat.Topic)
statistics.NewStatistics(&count, config.Config.ModuleName.PushName, fmt.Sprintf("%d second push to msg_gateway count", 300), 300)
statistics.NewStatistics(&successCount, config.Config.ModuleName.PushName, fmt.Sprintf("%d second push to msg_gateway count", constant.StatisticsTimeInterval), constant.StatisticsTimeInterval)
}
func Run() {

View File

@@ -31,10 +31,10 @@ func (ms *PushConsumerHandler) Init() {
config.Config.Kafka.ConsumerGroupID.MsgToPush)
}
func (ms *PushConsumerHandler) handleMs2PsChat(msg []byte) {
log.InfoByKv("msg come from kafka And push!!!", "", "msg", string(msg))
log.NewDebug("", "msg come from kafka And push!!!", "msg", string(msg))
msgFromMQ := pbChat.PushMsgDataToMQ{}
if err := proto.Unmarshal(msg, &msgFromMQ); err != nil {
log.ErrorByKv("push Unmarshal msg err", "", "msg", string(msg), "err", err.Error())
log.Error("", "push Unmarshal msg err", "msg", string(msg), "err", err.Error())
return
}
//Call push module to send message to the user
@@ -45,7 +45,7 @@ func (PushConsumerHandler) Cleanup(_ sarama.ConsumerGroupSession) error { return
func (ms *PushConsumerHandler) ConsumeClaim(sess sarama.ConsumerGroupSession,
claim sarama.ConsumerGroupClaim) error {
for msg := range claim.Messages() {
log.InfoByKv("kafka get info to mysql", "", "msgTopic", msg.Topic, "msgPartition", msg.Partition, "msg", string(msg.Value))
log.NewDebug("", "kafka get info to mysql", "msgTopic", msg.Topic, "msgPartition", msg.Partition, "msg", string(msg.Value))
ms.msgHandle[msg.Topic](msg.Value)
}
return nil

View File

@@ -9,6 +9,7 @@ import (
"context"
"google.golang.org/grpc"
"net"
"strconv"
"strings"
)
@@ -26,24 +27,37 @@ func (r *RPCServer) Init(rpcPort int) {
r.etcdAddr = config.Config.Etcd.EtcdAddr
}
func (r *RPCServer) run() {
ip := utils.ServerIP
registerAddress := ip + ":" + utils.IntToString(r.rpcPort)
listener, err := net.Listen("tcp", registerAddress)
listenIP := ""
if config.Config.ListenIP == "" {
listenIP = "0.0.0.0"
} else {
listenIP = config.Config.ListenIP
}
address := listenIP + ":" + strconv.Itoa(r.rpcPort)
listener, err := net.Listen("tcp", address)
if err != nil {
log.ErrorByKv("push module rpc listening port err", "", "err", err.Error())
return
panic("listening err:" + err.Error() + r.rpcRegisterName)
}
defer listener.Close()
srv := grpc.NewServer()
defer srv.GracefulStop()
pbPush.RegisterPushMsgServiceServer(srv, r)
err = getcdv3.RegisterEtcd(r.etcdSchema, strings.Join(r.etcdAddr, ","), ip, r.rpcPort, r.rpcRegisterName, 10)
rpcRegisterIP := ""
if config.Config.RpcRegisterIP == "" {
rpcRegisterIP, err = utils.GetLocalIP()
if err != nil {
log.Error("", "GetLocalIP failed ", err.Error())
}
}
err = getcdv3.RegisterEtcd(r.etcdSchema, strings.Join(r.etcdAddr, ","), rpcRegisterIP, r.rpcPort, r.rpcRegisterName, 10)
if err != nil {
log.ErrorByKv("register push module rpc to etcd err", "", "err", err.Error())
log.Error("", "register push module rpc to etcd err", err.Error(), r.etcdSchema, strings.Join(r.etcdAddr, ","), rpcRegisterIP, r.rpcPort, r.rpcRegisterName)
}
err = srv.Serve(listener)
if err != nil {
log.ErrorByKv("push module rpc start err", "", "err", err.Error())
log.Error("", "push module rpc start err", err.Error())
return
}
}

View File

@@ -37,7 +37,7 @@ type AtContent struct {
func MsgToUser(pushMsg *pbPush.PushMsgReq) {
var wsResult []*pbRelay.SingleMsgToUser
isOfflinePush := utils.GetSwitchFromOptions(pushMsg.MsgData.Options, constant.IsOfflinePush)
log.Debug("Get msg from msg_transfer And push msg", pushMsg.OperationID, "PushData", pushMsg.String())
log.Debug(pushMsg.OperationID, "Get msg from msg_transfer And push msg", pushMsg.String())
grpcCons := getcdv3.GetConn4Unique(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOnlineMessageRelayName)
//Online push message
log.Debug("test", pushMsg.OperationID, "len grpc", len(grpcCons), "data", pushMsg.String())
@@ -45,82 +45,80 @@ func MsgToUser(pushMsg *pbPush.PushMsgReq) {
msgClient := pbRelay.NewOnlineMessageRelayServiceClient(v)
reply, err := msgClient.OnlinePushMsg(context.Background(), &pbRelay.OnlinePushMsgReq{OperationID: pushMsg.OperationID, MsgData: pushMsg.MsgData, PushToUserID: pushMsg.PushToUserID})
if err != nil {
log.InfoByKv("push data to client rpc err", pushMsg.OperationID, "err", err)
log.NewError("push data to client rpc err", pushMsg.OperationID, "err", err)
continue
}
if reply != nil && reply.Resp != nil {
wsResult = append(wsResult, reply.Resp...)
}
}
log.InfoByKv("push_result", pushMsg.OperationID, "result", wsResult, "sendData", pushMsg.MsgData)
count++
log.NewInfo(pushMsg.OperationID, "push_result", wsResult, "sendData", pushMsg.MsgData)
successCount++
if isOfflinePush && pushMsg.PushToUserID != pushMsg.MsgData.SendID {
for _, v := range wsResult {
if v.ResultCode == 0 {
continue
}
//supported terminal
for _, t := range pushTerminal {
if v.RecvPlatFormID == t {
//Use offline push messaging
var UIDList []string
UIDList = append(UIDList, v.RecvID)
customContent := OpenIMContent{
SessionType: int(pushMsg.MsgData.SessionType),
From: pushMsg.MsgData.SendID,
To: pushMsg.MsgData.RecvID,
Seq: pushMsg.MsgData.Seq,
}
bCustomContent, _ := json.Marshal(customContent)
jsonCustomContent := string(bCustomContent)
var content string
if pushMsg.MsgData.OfflinePushInfo != nil {
content = pushMsg.MsgData.OfflinePushInfo.Title
} else {
switch pushMsg.MsgData.ContentType {
case constant.Text:
content = constant.ContentType2PushContent[constant.Text]
case constant.Picture:
content = constant.ContentType2PushContent[constant.Picture]
case constant.Voice:
content = constant.ContentType2PushContent[constant.Voice]
case constant.Video:
content = constant.ContentType2PushContent[constant.Video]
case constant.File:
content = constant.ContentType2PushContent[constant.File]
case constant.AtText:
a := AtContent{}
_ = utils.JsonStringToStruct(string(pushMsg.MsgData.Content), &a)
if utils.IsContain(v.RecvID, a.AtUserList) {
content = constant.ContentType2PushContent[constant.AtText] + constant.ContentType2PushContent[constant.Common]
} else {
content = constant.ContentType2PushContent[constant.GroupMsg]
}
default:
content = constant.ContentType2PushContent[constant.Common]
}
}
var offlinePusher pusher.OfflinePusher
if config.Config.Push.Getui.Enable {
log.NewInfo(pushMsg.OperationID, utils.GetSelfFuncName(), config.Config.Push.Getui)
offlinePusher = getui.GetuiClient
}
if config.Config.Push.Jpns.Enable {
offlinePusher = jpush.JPushClient
}
if offlinePusher == nil {
offlinePusher = jpush.JPushClient
}
pushResult, err := offlinePusher.Push(UIDList, content, jsonCustomContent, constant.PlatformIDToName(t), pushMsg.OperationID)
if err != nil {
log.NewError(pushMsg.OperationID, "offline push error", pushMsg.String(), err.Error(), constant.PlatformIDToName(t))
} else {
log.NewDebug(pushMsg.OperationID, "offline push return result is ", pushResult, pushMsg.MsgData, constant.PlatformIDToName(t))
}
if utils.IsContainInt32(v.RecvPlatFormID, pushTerminal) {
//Use offline push messaging
var UIDList []string
UIDList = append(UIDList, v.RecvID)
customContent := OpenIMContent{
SessionType: int(pushMsg.MsgData.SessionType),
From: pushMsg.MsgData.SendID,
To: pushMsg.MsgData.RecvID,
Seq: pushMsg.MsgData.Seq,
}
bCustomContent, _ := json.Marshal(customContent)
jsonCustomContent := string(bCustomContent)
var content string
if pushMsg.MsgData.OfflinePushInfo != nil {
content = pushMsg.MsgData.OfflinePushInfo.Title
} else {
switch pushMsg.MsgData.ContentType {
case constant.Text:
content = constant.ContentType2PushContent[constant.Text]
case constant.Picture:
content = constant.ContentType2PushContent[constant.Picture]
case constant.Voice:
content = constant.ContentType2PushContent[constant.Voice]
case constant.Video:
content = constant.ContentType2PushContent[constant.Video]
case constant.File:
content = constant.ContentType2PushContent[constant.File]
case constant.AtText:
a := AtContent{}
_ = utils.JsonStringToStruct(string(pushMsg.MsgData.Content), &a)
if utils.IsContain(v.RecvID, a.AtUserList) {
content = constant.ContentType2PushContent[constant.AtText] + constant.ContentType2PushContent[constant.Common]
} else {
content = constant.ContentType2PushContent[constant.GroupMsg]
}
default:
content = constant.ContentType2PushContent[constant.Common]
}
}
var offlinePusher pusher.OfflinePusher
if config.Config.Push.Getui.Enable {
log.NewInfo(pushMsg.OperationID, utils.GetSelfFuncName(), config.Config.Push.Getui)
offlinePusher = getui.GetuiClient
}
if config.Config.Push.Jpns.Enable {
offlinePusher = jpush.JPushClient
}
if offlinePusher == nil {
offlinePusher = jpush.JPushClient
}
pushResult, err := offlinePusher.Push(UIDList, content, jsonCustomContent, pushMsg.OperationID)
if err != nil {
log.NewError(pushMsg.OperationID, "offline push error", pushMsg.String(), err.Error())
} else {
log.NewDebug(pushMsg.OperationID, "offline push return result is ", pushResult, pushMsg.MsgData)
}
break
}
}
}

View File

@@ -1,5 +1,5 @@
package push
type OfflinePusher interface {
Push(userIDList []string, alert, detailContent, platform, operationID string) (resp string, err error)
Push(userIDList []string, alert, detailContent, operationID string) (resp string, err error)
}

View File

@@ -35,22 +35,34 @@ func NewAdminCMSServer(port int) *adminCMSServer {
func (s *adminCMSServer) Run() {
log.NewInfo("0", "AdminCMS rpc start ")
ip := utils.ServerIP
registerAddress := ip + ":" + strconv.Itoa(s.rpcPort)
//listener network
listener, err := net.Listen("tcp", registerAddress)
if err != nil {
log.NewError("0", "Listen failed ", err.Error(), registerAddress)
return
listenIP := ""
if config.Config.ListenIP == "" {
listenIP = "0.0.0.0"
} else {
listenIP = config.Config.ListenIP
}
log.NewInfo("0", "listen network success, ", registerAddress, listener)
address := listenIP + ":" + strconv.Itoa(s.rpcPort)
//listener network
listener, err := net.Listen("tcp", address)
if err != nil {
panic("listening err:" + err.Error() + s.rpcRegisterName)
}
log.NewInfo("0", "listen network success, ", address, listener)
defer listener.Close()
//grpc server
srv := grpc.NewServer()
defer srv.GracefulStop()
//Service registers with etcd
pbAdminCMS.RegisterAdminCMSServer(srv, s)
err = getcdv3.RegisterEtcd(s.etcdSchema, strings.Join(s.etcdAddr, ","), ip, s.rpcPort, s.rpcRegisterName, 10)
rpcRegisterIP := ""
if config.Config.RpcRegisterIP == "" {
rpcRegisterIP, err = utils.GetLocalIP()
if err != nil {
log.Error("", "GetLocalIP failed ", err.Error())
}
}
err = getcdv3.RegisterEtcd(s.etcdSchema, strings.Join(s.etcdAddr, ","), rpcRegisterIP, s.rpcPort, s.rpcRegisterName, 10)
if err != nil {
log.NewError("0", "RegisterEtcd failed ", err.Error())
return
@@ -83,5 +95,6 @@ func (s *adminCMSServer) AdminLogin(_ context.Context, req *pbAdminCMS.AdminLogi
log.NewError(req.OperationID, utils.GetSelfFuncName(), "failed")
return resp, openIMHttp.WrapError(constant.ErrTokenMalformed)
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}

View File

@@ -20,38 +20,41 @@ import (
)
func (rpc *rpcAuth) UserRegister(_ context.Context, req *pbAuth.UserRegisterReq) (*pbAuth.UserRegisterResp, error) {
log.NewInfo(req.OperationID, "UserRegister args ", req.String())
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc args ", req.String())
var user db.User
utils.CopyStructFields(&user, req.UserInfo)
if req.UserInfo.Birth != 0 {
user.Birth = utils.UnixSecondToTime(int64(req.UserInfo.Birth))
}
log.Debug(req.OperationID, "copy ", user, req.UserInfo)
err := imdb.UserRegister(user)
if err != nil {
log.NewError(req.OperationID, "UserRegister failed ", err.Error(), user)
return &pbAuth.UserRegisterResp{CommonResp: &pbAuth.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, nil
errMsg := req.OperationID + " imdb.UserRegister failed " + err.Error() + user.UserID
log.NewError(req.OperationID, errMsg, user)
return &pbAuth.UserRegisterResp{CommonResp: &pbAuth.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg}}, nil
}
log.NewInfo(req.OperationID, "rpc UserRegister return")
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc return ", pbAuth.UserRegisterResp{CommonResp: &pbAuth.CommonResp{}})
return &pbAuth.UserRegisterResp{CommonResp: &pbAuth.CommonResp{}}, nil
}
func (rpc *rpcAuth) UserToken(_ context.Context, req *pbAuth.UserTokenReq) (*pbAuth.UserTokenResp, error) {
log.NewInfo(req.OperationID, "UserToken args ", req.String())
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc args ", req.String())
_, err := imdb.GetUserByUserID(req.FromUserID)
if err != nil {
log.NewError(req.OperationID, "GetUserByUserID failed ", err.Error(), req.FromUserID)
return &pbAuth.UserTokenResp{CommonResp: &pbAuth.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, nil
errMsg := req.OperationID + " imdb.GetUserByUserID failed " + err.Error() + req.FromUserID
log.NewError(req.OperationID, errMsg)
return &pbAuth.UserTokenResp{CommonResp: &pbAuth.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg}}, nil
}
tokens, expTime, err := token_verify.CreateToken(req.FromUserID, req.Platform)
if err != nil {
log.NewError(req.OperationID, "CreateToken failed ", err.Error(), req.FromUserID, req.Platform)
return &pbAuth.UserTokenResp{CommonResp: &pbAuth.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, nil
errMsg := req.OperationID + " token_verify.CreateToken failed " + err.Error() + req.FromUserID + utils.Int32ToString(req.Platform)
log.NewError(req.OperationID, errMsg)
return &pbAuth.UserTokenResp{CommonResp: &pbAuth.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg}}, nil
}
log.NewInfo(req.OperationID, "rpc UserToken return ", tokens, expTime)
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc return ", pbAuth.UserTokenResp{CommonResp: &pbAuth.CommonResp{}, Token: tokens, ExpiredTime: expTime})
return &pbAuth.UserTokenResp{CommonResp: &pbAuth.CommonResp{}, Token: tokens, ExpiredTime: expTime}, nil
}
@@ -73,32 +76,46 @@ func NewRpcAuthServer(port int) *rpcAuth {
}
func (rpc *rpcAuth) Run() {
log.NewInfo("0", "rpc auth start...")
operationID := utils.OperationIDGenerator()
log.NewInfo(operationID, "rpc auth start...")
address := utils.ServerIP + ":" + strconv.Itoa(rpc.rpcPort)
listenIP := ""
if config.Config.ListenIP == "" {
listenIP = "0.0.0.0"
} else {
listenIP = config.Config.ListenIP
}
address := listenIP + ":" + strconv.Itoa(rpc.rpcPort)
listener, err := net.Listen("tcp", address)
if err != nil {
log.NewError("0", "listen network failed ", err.Error(), address)
return
panic("listening err:" + err.Error() + rpc.rpcRegisterName)
}
log.NewInfo("0", "listen network success, ", address, listener)
log.NewInfo(operationID, "listen network success, ", address, listener)
//grpc server
srv := grpc.NewServer()
defer srv.GracefulStop()
//service registers with etcd
pbAuth.RegisterAuthServer(srv, rpc)
err = getcdv3.RegisterEtcd(rpc.etcdSchema, strings.Join(rpc.etcdAddr, ","), utils.ServerIP, rpc.rpcPort, rpc.rpcRegisterName, 10)
rpcRegisterIP := ""
if config.Config.RpcRegisterIP == "" {
rpcRegisterIP, err = utils.GetLocalIP()
if err != nil {
log.Error("", "GetLocalIP failed ", err.Error())
}
}
err = getcdv3.RegisterEtcd(rpc.etcdSchema, strings.Join(rpc.etcdAddr, ","), rpcRegisterIP, rpc.rpcPort, rpc.rpcRegisterName, 10)
if err != nil {
log.NewError("0", "RegisterEtcd failed ", err.Error(),
rpc.etcdSchema, strings.Join(rpc.etcdAddr, ","), utils.ServerIP, rpc.rpcPort, rpc.rpcRegisterName)
log.NewError(operationID, "RegisterEtcd failed ", err.Error(),
rpc.etcdSchema, strings.Join(rpc.etcdAddr, ","), rpcRegisterIP, rpc.rpcPort, rpc.rpcRegisterName)
return
}
log.NewInfo("0", "RegisterAuthServer ok ", rpc.etcdSchema, strings.Join(rpc.etcdAddr, ","), utils.ServerIP, rpc.rpcPort, rpc.rpcRegisterName)
log.NewInfo(operationID, "RegisterAuthServer ok ", rpc.etcdSchema, strings.Join(rpc.etcdAddr, ","), rpcRegisterIP, rpc.rpcPort, rpc.rpcRegisterName)
err = srv.Serve(listener)
if err != nil {
log.NewError("0", "Serve failed ", err.Error())
log.NewError(operationID, "Serve failed ", err.Error())
return
}
log.NewInfo("0", "rpc auth ok")
log.NewInfo(operationID, "rpc auth ok")
}

351
internal/rpc/cache/cache.go vendored Normal file
View File

@@ -0,0 +1,351 @@
package cache
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db"
imdb "Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
pbCache "Open_IM/pkg/proto/cache"
commonPb "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils"
"context"
"net"
"strconv"
"strings"
"google.golang.org/grpc"
)
type cacheServer struct {
rpcPort int
rpcRegisterName string
etcdSchema string
etcdAddr []string
}
func NewCacheServer(port int) *cacheServer {
log.NewPrivateLog(constant.LogFileName)
return &cacheServer{
rpcPort: port,
rpcRegisterName: config.Config.RpcRegisterName.OpenImCacheName,
etcdSchema: config.Config.Etcd.EtcdSchema,
etcdAddr: config.Config.Etcd.EtcdAddr,
}
}
func (s *cacheServer) Run() {
log.NewInfo("0", "cacheServer rpc start ")
listenIP := ""
if config.Config.ListenIP == "" {
listenIP = "0.0.0.0"
} else {
listenIP = config.Config.ListenIP
}
address := listenIP + ":" + strconv.Itoa(s.rpcPort)
//listener network
listener, err := net.Listen("tcp", address)
if err != nil {
panic("listening err:" + err.Error() + s.rpcRegisterName)
}
log.NewInfo("0", "listen network success, ", address, listener)
defer listener.Close()
//grpc server
//to cache
err = SyncDB2Cache()
if err != nil {
log.NewError("", err.Error(), "db to cache failed")
panic(err.Error())
}
srv := grpc.NewServer()
defer srv.GracefulStop()
pbCache.RegisterCacheServer(srv, s)
rpcRegisterIP := ""
if config.Config.RpcRegisterIP == "" {
rpcRegisterIP, err = utils.GetLocalIP()
if err != nil {
log.Error("", "GetLocalIP failed ", err.Error())
}
}
err = getcdv3.RegisterEtcd(s.etcdSchema, strings.Join(s.etcdAddr, ","), rpcRegisterIP, s.rpcPort, s.rpcRegisterName, 10)
if err != nil {
log.NewError("0", "RegisterEtcd failed ", err.Error())
return
}
err = srv.Serve(listener)
if err != nil {
log.NewError("0", "Serve failed ", err.Error())
return
}
log.NewInfo("0", "message cms rpc success")
}
func SyncDB2Cache() error {
var err error
log.NewInfo("0", utils.GetSelfFuncName())
userList, err := imdb.GetAllUser()
log.NewDebug("", utils.GetSelfFuncName(), "userList", userList)
if err != nil {
return utils.Wrap(err, "")
}
//err = updateAllUserToCache(userList)
err = updateAllFriendToCache(userList)
err = updateAllBlackListToCache(userList)
err = updateAllGroupMemberListToCache()
return utils.Wrap(err, "")
}
func DelRelationCache() {}
func updateAllUserToCache(userList []db.User) error {
for _, userInfo := range userList {
userInfoPb := &commonPb.UserInfo{
UserID: userInfo.UserID,
Nickname: userInfo.Nickname,
FaceURL: userInfo.FaceURL,
Gender: userInfo.Gender,
PhoneNumber: userInfo.PhoneNumber,
Birth: uint32(userInfo.Birth.Unix()),
Email: userInfo.Email,
Ex: userInfo.Ex,
CreateTime: uint32(userInfo.CreateTime.Unix()),
AppMangerLevel: userInfo.AppMangerLevel,
}
m, err := utils.Pb2Map(userInfoPb)
if err != nil {
log.NewWarn("", utils.GetSelfFuncName(), err.Error())
}
if err := db.DB.SetUserInfoToCache(userInfo.UserID, m); err != nil {
log.NewWarn("0", utils.GetSelfFuncName(), "set userInfo to cache failed", err.Error())
}
}
log.NewInfo("0", utils.GetSelfFuncName(), "ok")
return nil
}
func updateAllGroupMemberListToCache() error {
log.NewInfo("0", utils.GetSelfFuncName())
groupIDList, err := imdb.GetAllGroupIDList()
if err != nil {
log.NewWarn("0", utils.GetSelfFuncName(), "getAllGroupIDList failed", err.Error())
panic(err.Error())
}
for _, groupID := range groupIDList {
groupMemberIDList, err := imdb.GetGroupMemberIDListByGroupID(groupID)
if err != nil {
log.NewWarn("", utils.GetSelfFuncName(), "GetGroupMemberIDListByGroupID", err.Error())
continue
}
//log.NewDebug("", utils.GetSelfFuncName(), "groupMemberIDList", groupMemberIDList)
if len(groupMemberIDList) > 0 {
if err := db.DB.AddGroupMemberToCache(groupID, groupMemberIDList...); err != nil {
log.NewWarn("", utils.GetSelfFuncName(), "AddGroupMemberToCache", err.Error())
}
}
}
log.NewInfo("0", utils.GetSelfFuncName(), "ok")
return nil
}
func updateAllFriendToCache(userList []db.User) error {
log.NewInfo("0", utils.GetSelfFuncName())
for _, user := range userList {
friendIDList, err := imdb.GetFriendIDListByUserID(user.UserID)
if err != nil {
log.NewWarn("0", utils.GetSelfFuncName(), err.Error())
continue
}
if len(friendIDList) > 0 {
if err := db.DB.AddFriendToCache(user.UserID, friendIDList...); err != nil {
log.NewWarn("0", utils.GetSelfFuncName(), err.Error(), friendIDList, user.UserID)
}
}
}
log.NewInfo("0", utils.GetSelfFuncName(), "ok")
return nil
}
func updateAllBlackListToCache(userList []db.User) error {
log.NewInfo("0", utils.GetSelfFuncName())
for _, user := range userList {
blackIDList, err := imdb.GetBlackIDListByUserID(user.UserID)
if err != nil {
log.NewWarn("", utils.GetSelfFuncName(), err.Error())
continue
}
if len(blackIDList) > 0 {
if err := db.DB.AddBlackUserToCache(user.UserID, blackIDList...); err != nil {
log.NewWarn("0", utils.GetSelfFuncName(), err.Error())
}
}
}
log.NewInfo("0", utils.GetSelfFuncName(), "ok")
return nil
}
func (s *cacheServer) GetUserInfoFromCache(_ context.Context, req *pbCache.GetUserInfoFromCacheReq) (resp *pbCache.GetUserInfoFromCacheResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbCache.GetUserInfoFromCacheResp{
CommonResp: &pbCache.CommonResp{},
}
for _, userID := range req.UserIDList {
userInfo, err := db.DB.GetUserInfoFromCache(userID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "get userInfo from cache failed", err.Error())
continue
}
resp.UserInfoList = append(resp.UserInfoList, userInfo)
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *cacheServer) UpdateUserInfoToCache(_ context.Context, req *pbCache.UpdateUserInfoToCacheReq) (resp *pbCache.UpdateUserInfoToCacheResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbCache.UpdateUserInfoToCacheResp{
CommonResp: &pbCache.CommonResp{},
}
for _, userInfo := range req.UserInfoList {
m, err := utils.Pb2Map(userInfo)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error(), *userInfo)
}
if err := db.DB.SetUserInfoToCache(userInfo.UserID, m); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "set userInfo to cache failed", err.Error())
}
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *cacheServer) GetFriendIDListFromCache(_ context.Context, req *pbCache.GetFriendIDListFromCacheReq) (resp *pbCache.GetFriendIDListFromCacheResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbCache.GetFriendIDListFromCacheResp{CommonResp: &pbCache.CommonResp{}}
friendIDList, err := db.DB.GetFriendIDListFromCache(req.UserID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetFriendIDListFromCache", err.Error())
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg
return resp, nil
}
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), friendIDList)
resp.UserIDList = friendIDList
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *cacheServer) AddFriendToCache(_ context.Context, req *pbCache.AddFriendToCacheReq) (resp *pbCache.AddFriendToCacheResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbCache.AddFriendToCacheResp{CommonResp: &pbCache.CommonResp{}}
if err := db.DB.AddFriendToCache(req.UserID, req.FriendID); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "AddFriendToCache failed", err.Error())
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg
return resp, nil
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *cacheServer) ReduceFriendFromCache(_ context.Context, req *pbCache.ReduceFriendFromCacheReq) (resp *pbCache.ReduceFriendFromCacheResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbCache.ReduceFriendFromCacheResp{CommonResp: &pbCache.CommonResp{}}
if err := db.DB.ReduceFriendToCache(req.UserID, req.FriendID); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "AddFriendToCache failed", err.Error())
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg
return resp, nil
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *cacheServer) GetBlackIDListFromCache(_ context.Context, req *pbCache.GetBlackIDListFromCacheReq) (resp *pbCache.GetBlackIDListFromCacheResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbCache.GetBlackIDListFromCacheResp{CommonResp: &pbCache.CommonResp{}}
blackUserIDList, err := db.DB.GetBlackListFromCache(req.UserID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "AddFriendToCache failed", err.Error())
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg
return resp, nil
}
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), blackUserIDList)
resp.UserIDList = blackUserIDList
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *cacheServer) AddBlackUserToCache(_ context.Context, req *pbCache.AddBlackUserToCacheReq) (resp *pbCache.AddBlackUserToCacheResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbCache.AddBlackUserToCacheResp{CommonResp: &pbCache.CommonResp{}}
if err := db.DB.AddBlackUserToCache(req.UserID, req.BlackUserID); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error())
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg
return resp, nil
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *cacheServer) ReduceBlackUserFromCache(_ context.Context, req *pbCache.ReduceBlackUserFromCacheReq) (resp *pbCache.ReduceBlackUserFromCacheResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbCache.ReduceBlackUserFromCacheResp{CommonResp: &pbCache.CommonResp{}}
if err := db.DB.ReduceBlackUserFromCache(req.UserID, req.BlackUserID); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error())
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg
return resp, nil
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *cacheServer) GetGroupMemberIDListFromCache(_ context.Context, req *pbCache.GetGroupMemberIDListFromCacheReq) (resp *pbCache.GetGroupMemberIDListFromCacheResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbCache.GetGroupMemberIDListFromCacheResp{
CommonResp: &pbCache.CommonResp{},
}
userIDList, err := db.DB.GetGroupMemberIDListFromCache(req.GroupID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetGroupMemberIDListFromCache failed", err.Error())
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg
return resp, nil
}
resp.UserIDList = userIDList
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *cacheServer) AddGroupMemberToCache(_ context.Context, req *pbCache.AddGroupMemberToCacheReq) (resp *pbCache.AddGroupMemberToCacheResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbCache.AddGroupMemberToCacheResp{CommonResp: &pbCache.CommonResp{}}
if err := db.DB.AddGroupMemberToCache(req.GroupID, req.UserIDList...); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "AddGroupMemberToCache failed", err.Error())
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg
return resp, nil
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *cacheServer) ReduceGroupMemberFromCache(_ context.Context, req *pbCache.ReduceGroupMemberFromCacheReq) (resp *pbCache.ReduceGroupMemberFromCacheResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbCache.ReduceGroupMemberFromCacheResp{CommonResp: &pbCache.CommonResp{}}
if err := db.DB.ReduceGroupMemberFromCache(req.GroupID, req.UserIDList...); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "ReduceGroupMemberFromCache failed", err.Error())
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg
return resp, nil
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}

View File

@@ -0,0 +1,180 @@
package conversation
import (
chat "Open_IM/internal/rpc/msg"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db"
imdb "Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
pbConversation "Open_IM/pkg/proto/conversation"
"Open_IM/pkg/utils"
"context"
"net"
"strconv"
"strings"
"Open_IM/pkg/common/config"
"google.golang.org/grpc"
)
type rpcConversation struct {
rpcPort int
rpcRegisterName string
etcdSchema string
etcdAddr []string
}
func (rpc *rpcConversation) ModifyConversationField(c context.Context, req *pbConversation.ModifyConversationFieldReq) (*pbConversation.ModifyConversationFieldResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp := &pbConversation.ModifyConversationFieldResp{}
var err error
if req.Conversation.ConversationType == constant.GroupChatType {
groupInfo, err := imdb.GetGroupInfoByGroupID(req.Conversation.GroupID)
if err != nil {
log.NewError(req.OperationID, "GetGroupInfoByGroupID failed ", req.Conversation.GroupID, err.Error())
resp.CommonResp = &pbConversation.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
if groupInfo.Status == constant.GroupStatusDismissed && !req.Conversation.IsNotInGroup {
errMsg := "group status is dismissed"
resp.CommonResp = &pbConversation.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg}
return resp, nil
}
}
var conversation db.Conversation
if err := utils.CopyStructFields(&conversation, req.Conversation); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", *req.Conversation, err.Error())
}
haveUserID, _ := imdb.GetExistConversationUserIDList(req.UserIDList, req.Conversation.ConversationID)
switch req.FieldType {
case constant.FieldRecvMsgOpt:
for _, v := range req.UserIDList {
if err = db.DB.SetSingleConversationRecvMsgOpt(v, req.Conversation.ConversationID, req.Conversation.RecvMsgOpt); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "cache failed, rpc return", err.Error())
resp.CommonResp = &pbConversation.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
}
err = imdb.UpdateColumnsConversations(haveUserID, req.Conversation.ConversationID, map[string]interface{}{"recv_msg_opt": conversation.RecvMsgOpt})
case constant.FieldGroupAtType:
err = imdb.UpdateColumnsConversations(haveUserID, req.Conversation.ConversationID, map[string]interface{}{"group_at_type": conversation.GroupAtType})
case constant.FieldIsNotInGroup:
err = imdb.UpdateColumnsConversations(haveUserID, req.Conversation.ConversationID, map[string]interface{}{"is_not_in_group": conversation.IsNotInGroup})
case constant.FieldIsPinned:
err = imdb.UpdateColumnsConversations(haveUserID, req.Conversation.ConversationID, map[string]interface{}{"is_pinned": conversation.IsPinned})
case constant.FieldIsPrivateChat:
err = imdb.UpdateColumnsConversations(haveUserID, req.Conversation.ConversationID, map[string]interface{}{"is_private_chat": conversation.IsPrivateChat})
case constant.FieldEx:
err = imdb.UpdateColumnsConversations(haveUserID, req.Conversation.ConversationID, map[string]interface{}{"ex": conversation.Ex})
case constant.FieldAttachedInfo:
err = imdb.UpdateColumnsConversations(haveUserID, req.Conversation.ConversationID, map[string]interface{}{"attached_info": conversation.AttachedInfo})
}
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "UpdateColumnsConversations error", err.Error())
resp.CommonResp = &pbConversation.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
for _, v := range utils.DifferenceString(haveUserID, req.UserIDList) {
conversation.OwnerUserID = v
err := imdb.SetOneConversation(conversation)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "SetConversation error", err.Error())
resp.CommonResp = &pbConversation.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
}
// notification
if req.Conversation.ConversationType == constant.SingleChatType && req.FieldType == constant.FieldIsPrivateChat {
//sync peer user conversation if conversation is singleChatType
if err := syncPeerUserConversation(req.Conversation, req.OperationID); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "syncPeerUserConversation", err.Error())
resp.CommonResp = &pbConversation.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
} else {
for _, v := range req.UserIDList {
chat.ConversationChangeNotification(req.OperationID, v)
}
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "rpc return", resp.String())
resp.CommonResp = &pbConversation.CommonResp{}
return resp, nil
}
func syncPeerUserConversation(conversation *pbConversation.Conversation, operationID string) error {
peerUserConversation := db.Conversation{
OwnerUserID: conversation.UserID,
ConversationID: utils.GetConversationIDBySessionType(conversation.OwnerUserID, constant.SingleChatType),
ConversationType: constant.SingleChatType,
UserID: conversation.OwnerUserID,
GroupID: "",
RecvMsgOpt: 0,
UnreadCount: 0,
DraftTextTime: 0,
IsPinned: false,
IsPrivateChat: conversation.IsPrivateChat,
AttachedInfo: "",
Ex: "",
}
err := imdb.PeerUserSetConversation(peerUserConversation)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "SetConversation error", err.Error())
return err
}
chat.ConversationSetPrivateNotification(operationID, conversation.OwnerUserID, conversation.UserID, conversation.IsPrivateChat)
return nil
}
func NewRpcConversationServer(port int) *rpcConversation {
log.NewPrivateLog(constant.LogFileName)
return &rpcConversation{
rpcPort: port,
rpcRegisterName: config.Config.RpcRegisterName.OpenImConversationName,
etcdSchema: config.Config.Etcd.EtcdSchema,
etcdAddr: config.Config.Etcd.EtcdAddr,
}
}
func (rpc *rpcConversation) Run() {
log.NewInfo("0", "rpc conversation start...")
listenIP := ""
if config.Config.ListenIP == "" {
listenIP = "0.0.0.0"
} else {
listenIP = config.Config.ListenIP
}
address := listenIP + ":" + strconv.Itoa(rpc.rpcPort)
listener, err := net.Listen("tcp", address)
if err != nil {
panic("listening err:" + err.Error() + rpc.rpcRegisterName)
}
log.NewInfo("0", "listen network success, ", address, listener)
//grpc server
srv := grpc.NewServer()
defer srv.GracefulStop()
//service registers with etcd
pbConversation.RegisterConversationServer(srv, rpc)
rpcRegisterIP := ""
if config.Config.RpcRegisterIP == "" {
rpcRegisterIP, err = utils.GetLocalIP()
if err != nil {
log.Error("", "GetLocalIP failed ", err.Error())
}
}
err = getcdv3.RegisterEtcd(rpc.etcdSchema, strings.Join(rpc.etcdAddr, ","), rpcRegisterIP, rpc.rpcPort, rpc.rpcRegisterName, 10)
if err != nil {
log.NewError("0", "RegisterEtcd failed ", err.Error(),
rpc.etcdSchema, strings.Join(rpc.etcdAddr, ","), rpcRegisterIP, rpc.rpcPort, rpc.rpcRegisterName)
return
}
log.NewInfo("0", "RegisterConversationServer ok ", rpc.etcdSchema, strings.Join(rpc.etcdAddr, ","), rpcRegisterIP, rpc.rpcPort, rpc.rpcRegisterName)
err = srv.Serve(listener)
if err != nil {
log.NewError("0", "Serve failed ", err.Error())
return
}
log.NewInfo("0", "rpc conversation ok")
}

View File

@@ -10,6 +10,7 @@ import (
"Open_IM/pkg/common/token_verify"
cp "Open_IM/pkg/common/utils"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
pbCache "Open_IM/pkg/proto/cache"
pbFriend "Open_IM/pkg/proto/friend"
sdkws "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils"
@@ -41,24 +42,37 @@ func NewFriendServer(port int) *friendServer {
func (s *friendServer) Run() {
log.NewInfo("0", "friendServer run...")
ip := utils.ServerIP
registerAddress := ip + ":" + strconv.Itoa(s.rpcPort)
//listener network
listener, err := net.Listen("tcp", registerAddress)
if err != nil {
log.NewError("0", "Listen failed ", err.Error(), registerAddress)
return
listenIP := ""
if config.Config.ListenIP == "" {
listenIP = "0.0.0.0"
} else {
listenIP = config.Config.ListenIP
}
log.NewInfo("0", "listen ok ", registerAddress)
address := listenIP + ":" + strconv.Itoa(s.rpcPort)
//listener network
listener, err := net.Listen("tcp", address)
if err != nil {
panic("listening err:" + err.Error() + s.rpcRegisterName)
}
log.NewInfo("0", "listen ok ", address)
defer listener.Close()
//grpc server
srv := grpc.NewServer()
defer srv.GracefulStop()
//User friend related services register to etcd
pbFriend.RegisterFriendServer(srv, s)
err = getcdv3.RegisterEtcd(s.etcdSchema, strings.Join(s.etcdAddr, ","), ip, s.rpcPort, s.rpcRegisterName, 10)
rpcRegisterIP := ""
if config.Config.RpcRegisterIP == "" {
rpcRegisterIP, err = utils.GetLocalIP()
if err != nil {
log.Error("", "GetLocalIP failed ", err.Error())
}
}
err = getcdv3.RegisterEtcd(s.etcdSchema, strings.Join(s.etcdAddr, ","), rpcRegisterIP, s.rpcPort, s.rpcRegisterName, 10)
if err != nil {
log.NewError("0", "RegisterEtcd failed ", err.Error(), s.etcdSchema, strings.Join(s.etcdAddr, ","), ip, s.rpcPort, s.rpcRegisterName)
log.NewError("0", "RegisterEtcd failed ", err.Error(), s.etcdSchema, strings.Join(s.etcdAddr, ","), rpcRegisterIP, s.rpcPort, s.rpcRegisterName)
return
}
err = srv.Serve(listener)
@@ -83,6 +97,18 @@ func (s *friendServer) AddBlacklist(ctx context.Context, req *pbFriend.AddBlackl
return &pbFriend.AddBlacklistResp{CommonResp: &pbFriend.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, nil
}
log.NewInfo(req.CommID.OperationID, "AddBlacklist rpc ok ", req.CommID.FromUserID, req.CommID.ToUserID)
reqAddBlackUserToCache := &pbCache.AddBlackUserToCacheReq{UserID: req.CommID.FromUserID, BlackUserID: req.CommID.ToUserID, OperationID: req.CommID.OperationID}
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImCacheName)
cacheClient := pbCache.NewCacheClient(etcdConn)
cacheResp, err := cacheClient.AddBlackUserToCache(context.Background(), reqAddBlackUserToCache)
if err != nil {
log.NewError(req.CommID.OperationID, "AddBlackUserToCache rpc call failed ", err.Error())
return &pbFriend.AddBlacklistResp{CommonResp: &pbFriend.CommonResp{ErrCode: 500, ErrMsg: "AddBlackUserToCache rpc call failed"}}, nil
}
if cacheResp.CommonResp.ErrCode != 0 {
log.NewError(req.CommID.OperationID, "AddBlackUserToCache rpc logic call failed ", cacheResp.String())
return &pbFriend.AddBlacklistResp{CommonResp: &pbFriend.CommonResp{ErrCode: cacheResp.CommonResp.ErrCode, ErrMsg: cacheResp.CommonResp.ErrMsg}}, nil
}
chat.BlackAddedNotification(req)
return &pbFriend.AddBlacklistResp{CommonResp: &pbFriend.CommonResp{}}, nil
}
@@ -234,9 +260,37 @@ func (s *friendServer) AddFriendResponse(ctx context.Context, req *pbFriend.AddF
log.NewError(req.CommID.OperationID, "InsertToFriend failed ", err.Error(), toInsertFollow)
return &pbFriend.AddFriendResponseResp{CommonResp: &pbFriend.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, nil
}
// cache rpc
addFriendToCacheReq := &pbCache.AddFriendToCacheReq{OperationID: req.CommID.OperationID}
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImCacheName)
client := pbCache.NewCacheClient(etcdConn)
addFriendToCacheReq.UserID = req.CommID.ToUserID
addFriendToCacheReq.FriendID = req.CommID.FromUserID
respPb, err := client.AddFriendToCache(context.Background(), addFriendToCacheReq)
if err != nil {
log.NewError(req.CommID.OperationID, utils.GetSelfFuncName(), "AddFriendToCache failed", err.Error(), addFriendToCacheReq.String())
return &pbFriend.AddFriendResponseResp{CommonResp: &pbFriend.CommonResp{ErrCode: constant.ErrServer.ErrCode, ErrMsg: constant.ErrServer.ErrMsg}}, nil
}
if respPb.CommonResp.ErrCode != 0 {
log.NewError(req.CommID.OperationID, utils.GetSelfFuncName(), "AddFriendToCache failed", addFriendToCacheReq.String())
return &pbFriend.AddFriendResponseResp{CommonResp: &pbFriend.CommonResp{ErrCode: respPb.CommonResp.ErrCode, ErrMsg: respPb.CommonResp.ErrMsg}}, nil
}
addFriendToCacheReq.UserID = req.CommID.FromUserID
addFriendToCacheReq.FriendID = req.CommID.ToUserID
respPb, err = client.AddFriendToCache(context.Background(), addFriendToCacheReq)
if err != nil {
log.NewError(req.CommID.OperationID, utils.GetSelfFuncName(), "AddFriendToCache failed", err.Error(), addFriendToCacheReq.String())
return &pbFriend.AddFriendResponseResp{CommonResp: &pbFriend.CommonResp{ErrCode: constant.ErrServer.ErrCode, ErrMsg: constant.ErrServer.ErrMsg}}, nil
}
if respPb.CommonResp.ErrCode != 0 {
log.NewError(req.CommID.OperationID, utils.GetSelfFuncName(), "AddFriendToCache failed", addFriendToCacheReq.String())
return &pbFriend.AddFriendResponseResp{CommonResp: &pbFriend.CommonResp{ErrCode: respPb.CommonResp.ErrCode, ErrMsg: respPb.CommonResp.ErrMsg}}, nil
}
chat.FriendAddedNotification(req.CommID.OperationID, req.CommID.OpUserID, req.CommID.FromUserID, req.CommID.ToUserID)
}
}
if req.HandleResult == constant.FriendResponseAgree {
chat.FriendApplicationApprovedNotification(req)
} else if req.HandleResult == constant.FriendResponseRefuse {
@@ -244,6 +298,7 @@ func (s *friendServer) AddFriendResponse(ctx context.Context, req *pbFriend.AddF
} else {
log.Error(req.CommID.OperationID, "HandleResult failed ", req.HandleResult)
}
log.NewInfo(req.CommID.OperationID, "rpc AddFriendResponse ok")
return &pbFriend.AddFriendResponseResp{CommonResp: &pbFriend.CommonResp{}}, nil
}
@@ -261,6 +316,18 @@ func (s *friendServer) DeleteFriend(ctx context.Context, req *pbFriend.DeleteFri
return &pbFriend.DeleteFriendResp{CommonResp: &pbFriend.CommonResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: constant.ErrAccess.ErrMsg}}, nil
}
log.NewInfo(req.CommID.OperationID, "DeleteFriend rpc ok")
reduceFriendFromCache := &pbCache.ReduceFriendFromCacheReq{OperationID: req.CommID.OperationID, UserID: req.CommID.FromUserID, FriendID: req.CommID.ToUserID}
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImCacheName)
client := pbCache.NewCacheClient(etcdConn)
respPb, err := client.ReduceFriendFromCache(context.Background(), reduceFriendFromCache)
if err != nil {
log.NewError(req.CommID.OperationID, utils.GetSelfFuncName(), "AddFriendToCache rpc failed", err.Error())
return &pbFriend.DeleteFriendResp{CommonResp: &pbFriend.CommonResp{ErrCode: constant.ErrServer.ErrCode, ErrMsg: constant.ErrServer.ErrMsg}}, nil
}
if respPb.CommonResp.ErrCode != 0 {
log.NewError(req.CommID.OperationID, utils.GetSelfFuncName(), "AddFriendToCache failed")
return &pbFriend.DeleteFriendResp{CommonResp: &pbFriend.CommonResp{ErrCode: respPb.CommonResp.ErrCode, ErrMsg: respPb.CommonResp.ErrMsg}}, nil
}
chat.FriendDeletedNotification(req)
return &pbFriend.DeleteFriendResp{CommonResp: &pbFriend.CommonResp{}}, nil
}
@@ -330,6 +397,18 @@ func (s *friendServer) RemoveBlacklist(ctx context.Context, req *pbFriend.Remove
}
log.NewInfo(req.CommID.OperationID, "rpc RemoveBlacklist ok ")
reqReduceBlackUserFromCache := &pbCache.ReduceBlackUserFromCacheReq{UserID: req.CommID.FromUserID, BlackUserID: req.CommID.ToUserID, OperationID: req.CommID.OperationID}
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImCacheName)
cacheClient := pbCache.NewCacheClient(etcdConn)
cacheResp, err := cacheClient.ReduceBlackUserFromCache(context.Background(), reqReduceBlackUserFromCache)
if err != nil {
log.NewError(req.CommID.OperationID, "ReduceBlackUserFromCache rpc call failed ", err.Error())
return &pbFriend.RemoveBlacklistResp{CommonResp: &pbFriend.CommonResp{ErrCode: 500, ErrMsg: "ReduceBlackUserFromCache rpc call failed"}}, nil
}
if cacheResp.CommonResp.ErrCode != 0 {
log.NewError(req.CommID.OperationID, "ReduceBlackUserFromCache rpc logic call failed ", cacheResp.String())
return &pbFriend.RemoveBlacklistResp{CommonResp: &pbFriend.CommonResp{ErrCode: cacheResp.CommonResp.ErrCode, ErrMsg: cacheResp.CommonResp.ErrMsg}}, nil
}
chat.BlackDeletedNotification(req)
return &pbFriend.RemoveBlacklistResp{CommonResp: &pbFriend.CommonResp{}}, nil
}

View File

@@ -11,8 +11,10 @@ import (
"Open_IM/pkg/common/token_verify"
cp "Open_IM/pkg/common/utils"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
pbCache "Open_IM/pkg/proto/cache"
pbGroup "Open_IM/pkg/proto/group"
open_im_sdk "Open_IM/pkg/proto/sdk_ws"
pbUser "Open_IM/pkg/proto/user"
"Open_IM/pkg/utils"
"context"
"net"
@@ -42,26 +44,39 @@ func NewGroupServer(port int) *groupServer {
func (s *groupServer) Run() {
log.NewInfo("", "group rpc start ")
ip := utils.ServerIP
registerAddress := ip + ":" + strconv.Itoa(s.rpcPort)
//listener network
listener, err := net.Listen("tcp", registerAddress)
if err != nil {
log.NewError("", "Listen failed ", err.Error(), registerAddress)
return
listenIP := ""
if config.Config.ListenIP == "" {
listenIP = "0.0.0.0"
} else {
listenIP = config.Config.ListenIP
}
log.NewInfo("", "listen network success, ", registerAddress, listener)
address := listenIP + ":" + strconv.Itoa(s.rpcPort)
//listener network
listener, err := net.Listen("tcp", address)
if err != nil {
panic("listening err:" + err.Error() + s.rpcRegisterName)
}
log.NewInfo("", "listen network success, ", address, listener)
defer listener.Close()
//grpc server
srv := grpc.NewServer()
defer srv.GracefulStop()
//Service registers with etcd
pbGroup.RegisterGroupServer(srv, s)
err = getcdv3.RegisterEtcd(s.etcdSchema, strings.Join(s.etcdAddr, ","), ip, s.rpcPort, s.rpcRegisterName, 10)
rpcRegisterIP := config.Config.RpcRegisterIP
if rpcRegisterIP == "" {
rpcRegisterIP, err = utils.GetLocalIP()
if err != nil {
log.Error("", "GetLocalIP failed ", err.Error())
}
}
err = getcdv3.RegisterEtcd(s.etcdSchema, strings.Join(s.etcdAddr, ","), rpcRegisterIP, s.rpcPort, s.rpcRegisterName, 10)
if err != nil {
log.NewError("", "RegisterEtcd failed ", err.Error())
return
}
log.Info("", "RegisterEtcd ", s.etcdSchema, strings.Join(s.etcdAddr, ","), rpcRegisterIP, s.rpcPort, s.rpcRegisterName)
err = srv.Serve(listener)
if err != nil {
log.NewError("", "Serve failed ", err.Error())
@@ -82,8 +97,11 @@ func (s *groupServer) CreateGroup(ctx context.Context, req *pbGroup.CreateGroupR
log.NewError(req.OperationID, utils.GetSelfFuncName(), "callbackBeforeCreateGroup failed")
}
}
//Time stamp + MD5 to generate group chat id
groupId := utils.Md5(strconv.FormatInt(time.Now().UnixNano(), 10))
groupId := req.GroupInfo.GroupID
if groupId == "" {
groupId = utils.Md5(strconv.FormatInt(time.Now().UnixNano(), 10))
}
//to group
groupInfo := db.Group{}
utils.CopyStructFields(&groupInfo, req.GroupInfo)
@@ -94,15 +112,19 @@ func (s *groupServer) CreateGroup(ctx context.Context, req *pbGroup.CreateGroupR
log.NewError(req.OperationID, "InsertIntoGroup failed, ", err.Error(), groupInfo)
return &pbGroup.CreateGroupResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}, http.WrapError(constant.ErrDB)
}
us, err := imdb.GetUserByUserID(req.OwnerUserID)
groupMember := db.GroupMember{}
us := &db.User{}
if req.OwnerUserID == "" {
goto initMemberList
}
us, err = imdb.GetUserByUserID(req.OwnerUserID)
if err != nil {
log.NewError(req.OperationID, "GetUserByUserID failed ", err.Error(), req.OwnerUserID)
return &pbGroup.CreateGroupResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}, http.WrapError(constant.ErrDB)
}
//to group member
groupMember := db.GroupMember{GroupID: groupId, RoleLevel: constant.GroupOwner, OperatorUserID: req.OpUserID}
groupMember = db.GroupMember{GroupID: groupId, RoleLevel: constant.GroupOwner, OperatorUserID: req.OpUserID}
utils.CopyStructFields(&groupMember, us)
err = imdb.InsertIntoGroupMember(groupMember)
if err != nil {
@@ -110,10 +132,7 @@ func (s *groupServer) CreateGroup(ctx context.Context, req *pbGroup.CreateGroupR
return &pbGroup.CreateGroupResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}, http.WrapError(constant.ErrDB)
}
err = db.DB.AddGroupMember(groupId, req.OwnerUserID)
if err != nil {
log.NewError(req.OperationID, "AddGroupMember failed ", err.Error(), groupId, req.OwnerUserID)
}
initMemberList:
var okUserIDList []string
//to group member
for _, user := range req.InitMemberList {
@@ -133,20 +152,14 @@ func (s *groupServer) CreateGroup(ctx context.Context, req *pbGroup.CreateGroupR
log.NewError(req.OperationID, "InsertIntoGroupMember failed ", err.Error(), groupMember)
continue
}
okUserIDList = append(okUserIDList, user.UserID)
err = db.DB.AddGroupMember(groupId, user.UserID)
if err != nil {
log.NewError(req.OperationID, "add mongo group member failed, db.DB.AddGroupMember failed ", err.Error())
}
}
resp := &pbGroup.CreateGroupResp{GroupInfo: &open_im_sdk.GroupInfo{}}
group, err := imdb.GetGroupInfoByGroupID(groupId)
if err != nil {
log.NewError(req.OperationID, "GetGroupInfoByGroupID failed ", err.Error(), groupId)
resp.ErrCode = constant.ErrDB.ErrCode
resp.ErrMsg = constant.ErrDB.ErrMsg
resp.ErrMsg = err.Error()
return resp, nil
}
utils.CopyStructFields(resp.GroupInfo, group)
@@ -154,14 +167,39 @@ func (s *groupServer) CreateGroup(ctx context.Context, req *pbGroup.CreateGroupR
if err != nil {
log.NewError(req.OperationID, "GetGroupMemberNumByGroupID failed ", err.Error(), groupId)
resp.ErrCode = constant.ErrDB.ErrCode
resp.ErrMsg = constant.ErrDB.ErrMsg
resp.ErrMsg = err.Error()
return resp, nil
}
resp.GroupInfo.OwnerUserID = req.OwnerUserID
if req.OwnerUserID != "" {
resp.GroupInfo.OwnerUserID = req.OwnerUserID
okUserIDList = append(okUserIDList, req.OwnerUserID)
}
log.NewInfo(req.OperationID, "rpc CreateGroup return ", resp.String())
chat.GroupCreatedNotification(req.OperationID, req.OpUserID, groupId, okUserIDList)
return resp, nil
if len(okUserIDList) != 0 {
addGroupMemberToCacheReq := &pbCache.AddGroupMemberToCacheReq{
UserIDList: okUserIDList,
GroupID: groupId,
OperationID: req.OperationID,
}
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImCacheName)
cacheClient := pbCache.NewCacheClient(etcdConn)
cacheResp, err := cacheClient.AddGroupMemberToCache(context.Background(), addGroupMemberToCacheReq)
if err != nil {
log.NewError(req.OperationID, "AddGroupMemberToCache rpc call failed ", err.Error())
return &pbGroup.CreateGroupResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}, nil
}
if cacheResp.CommonResp.ErrCode != 0 {
log.NewError(req.OperationID, "AddGroupMemberToCache rpc logic call failed ", cacheResp.String())
return &pbGroup.CreateGroupResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}, nil
}
log.NewInfo(req.OperationID, "rpc CreateGroup return ", resp.String())
chat.GroupCreatedNotification(req.OperationID, req.OpUserID, groupId, okUserIDList)
return resp, nil
} else {
log.NewInfo(req.OperationID, "rpc CreateGroup return ", resp.String())
return resp, nil
}
}
func (s *groupServer) GetJoinedGroupList(ctx context.Context, req *pbGroup.GetJoinedGroupListReq) (*pbGroup.GetJoinedGroupListResp, error) {
@@ -202,15 +240,19 @@ func (s *groupServer) GetJoinedGroupList(ctx context.Context, req *pbGroup.GetJo
func (s *groupServer) InviteUserToGroup(ctx context.Context, req *pbGroup.InviteUserToGroupReq) (*pbGroup.InviteUserToGroupResp, error) {
log.NewInfo(req.OperationID, "InviteUserToGroup args ", req.String())
if !imdb.IsExistGroupMember(req.GroupID, req.OpUserID) && !token_verify.IsMangerUserID(req.OpUserID) {
if !imdb.IsExistGroupMember(req.GroupID, req.OpUserID) && !token_verify.IsManagerUserID(req.OpUserID) {
log.NewError(req.OperationID, "no permission InviteUserToGroup ", req.GroupID, req.OpUserID)
return &pbGroup.InviteUserToGroupResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: constant.ErrAccess.ErrMsg}, nil
}
_, err := imdb.GetGroupInfoByGroupID(req.GroupID)
groupInfo, err := imdb.GetGroupInfoByGroupID(req.GroupID)
if err != nil {
log.NewError(req.OperationID, "GetGroupInfoByGroupID failed ", req.GroupID, err)
return &pbGroup.InviteUserToGroupResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: constant.ErrAccess.ErrMsg}, nil
return &pbGroup.InviteUserToGroupResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}, nil
}
if groupInfo.Status == constant.GroupStatusDismissed {
errMsg := " group status is dismissed "
return &pbGroup.InviteUserToGroupResp{ErrCode: constant.ErrStatus.ErrCode, ErrMsg: errMsg}, nil
}
//
//from User: invite: applicant
@@ -254,6 +296,70 @@ func (s *groupServer) InviteUserToGroup(ctx context.Context, req *pbGroup.Invite
}
resp.Id2ResultList = append(resp.Id2ResultList, &resultNode)
}
var haveConUserID []string
conversations, err := imdb.GetConversationsByConversationIDMultipleOwner(okUserIDList, utils.GetConversationIDBySessionType(req.GroupID, constant.GroupChatType))
for _, v := range conversations {
haveConUserID = append(haveConUserID, v.OwnerUserID)
}
var reqPb pbUser.SetConversationReq
var c pbUser.Conversation
for _, v := range conversations {
reqPb.OperationID = req.OperationID
c.OwnerUserID = v.OwnerUserID
c.ConversationID = utils.GetConversationIDBySessionType(req.GroupID, constant.GroupChatType)
c.RecvMsgOpt = v.RecvMsgOpt
c.ConversationType = constant.GroupChatType
c.GroupID = req.GroupID
c.IsPinned = v.IsPinned
c.AttachedInfo = v.AttachedInfo
c.IsPrivateChat = v.IsPrivateChat
c.GroupAtType = v.GroupAtType
c.IsNotInGroup = false
c.Ex = v.Ex
reqPb.Conversation = &c
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pbUser.NewUserClient(etcdConn)
respPb, err := client.SetConversation(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "SetConversation rpc failed, ", reqPb.String(), err.Error(), v.OwnerUserID)
} else {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "SetConversation success", respPb.String(), v.OwnerUserID)
}
}
for _, v := range utils.DifferenceString(haveConUserID, okUserIDList) {
reqPb.OperationID = req.OperationID
c.OwnerUserID = v
c.ConversationID = utils.GetConversationIDBySessionType(req.GroupID, constant.GroupChatType)
c.ConversationType = constant.GroupChatType
c.GroupID = req.GroupID
c.IsNotInGroup = false
reqPb.Conversation = &c
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pbUser.NewUserClient(etcdConn)
respPb, err := client.SetConversation(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "SetConversation rpc failed, ", reqPb.String(), err.Error(), v)
} else {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "SetConversation success", respPb.String(), v)
}
}
addGroupMemberToCacheReq := &pbCache.AddGroupMemberToCacheReq{
UserIDList: okUserIDList,
GroupID: req.GroupID,
OperationID: req.OperationID,
}
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImCacheName)
cacheClient := pbCache.NewCacheClient(etcdConn)
cacheResp, err := cacheClient.AddGroupMemberToCache(context.Background(), addGroupMemberToCacheReq)
if err != nil {
log.NewError(req.OperationID, "AddGroupMemberToCache rpc call failed ", err.Error())
return &pbGroup.InviteUserToGroupResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}, nil
}
if cacheResp.CommonResp.ErrCode != 0 {
log.NewError(req.OperationID, "AddGroupMemberToCache rpc logic call failed ", cacheResp.String())
return &pbGroup.InviteUserToGroupResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}, nil
}
chat.MemberInvitedNotification(req.OperationID, req.GroupID, req.OpUserID, req.Reason, okUserIDList)
resp.ErrCode = 0
@@ -331,7 +437,7 @@ func (s *groupServer) KickGroupMember(ctx context.Context, req *pbGroup.KickGrou
//op is app manager
if flag != 1 {
if token_verify.IsMangerUserID(req.OpUserID) {
if token_verify.IsManagerUserID(req.OpUserID) {
flag = 1
log.NewDebug(req.OperationID, "is app manager ", req.OpUserID)
}
@@ -374,11 +480,48 @@ func (s *groupServer) KickGroupMember(ctx context.Context, req *pbGroup.KickGrou
okUserIDList = append(okUserIDList, v)
}
err = db.DB.DelGroupMember(req.GroupID, v)
//err = db.DB.DelGroupMember(req.GroupID, v)
//if err != nil {
// log.NewError(req.OperationID, "DelGroupMember failed ", err.Error(), req.GroupID, v)
//}
}
var reqPb pbUser.SetConversationReq
var c pbUser.Conversation
for _, v := range okUserIDList {
reqPb.OperationID = req.OperationID
c.OwnerUserID = v
c.ConversationID = utils.GetConversationIDBySessionType(req.GroupID, constant.GroupChatType)
c.ConversationType = constant.GroupChatType
c.GroupID = req.GroupID
c.IsNotInGroup = true
reqPb.Conversation = &c
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pbUser.NewUserClient(etcdConn)
respPb, err := client.SetConversation(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, "DelGroupMember failed ", err.Error(), req.GroupID, v)
log.NewError(req.OperationID, utils.GetSelfFuncName(), "SetConversation rpc failed, ", reqPb.String(), err.Error(), v)
} else {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "SetConversation success", respPb.String(), v)
}
}
reduceGroupMemberFromCacheReq := &pbCache.ReduceGroupMemberFromCacheReq{
UserIDList: okUserIDList,
GroupID: req.GroupID,
OperationID: req.OperationID,
}
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImCacheName)
cacheClient := pbCache.NewCacheClient(etcdConn)
cacheResp, err := cacheClient.ReduceGroupMemberFromCache(context.Background(), reduceGroupMemberFromCacheReq)
if err != nil {
log.NewError(req.OperationID, "ReduceGroupMemberFromCache rpc call failed ", err.Error())
return &pbGroup.KickGroupMemberResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}, nil
}
if cacheResp.CommonResp.ErrCode != 0 {
log.NewError(req.OperationID, "ReduceGroupMemberFromCache rpc logic call failed ", cacheResp.String())
return &pbGroup.KickGroupMemberResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}, nil
}
chat.MemberKickedNotification(req, okUserIDList)
log.NewInfo(req.OperationID, "GetGroupMemberList rpc return ", resp.String())
return &resp, nil
@@ -455,7 +598,7 @@ func (s *groupServer) GetGroupsInfo(ctx context.Context, req *pbGroup.GetGroupsI
}
resp := pbGroup.GetGroupsInfoResp{GroupInfoList: groupsInfoList}
log.NewInfo(req.OperationID, "GetGroupsInfo rpc return ", resp)
log.NewInfo(req.OperationID, "GetGroupsInfo rpc return ", resp.String())
return &resp, nil
}
@@ -467,8 +610,8 @@ func (s *groupServer) GroupApplicationResponse(_ context.Context, req *pbGroup.G
groupRequest.UserID = req.FromUserID
groupRequest.HandleUserID = req.OpUserID
groupRequest.HandledTime = time.Now()
if !token_verify.IsMangerUserID(req.OpUserID) && !imdb.IsGroupOwnerAdmin(req.GroupID, req.OpUserID) {
log.NewError(req.OperationID, "IsMangerUserID IsGroupOwnerAdmin false ", req.GroupID, req.OpUserID)
if !token_verify.IsManagerUserID(req.OpUserID) && !imdb.IsGroupOwnerAdmin(req.GroupID, req.OpUserID) {
log.NewError(req.OperationID, "IsManagerUserID IsGroupOwnerAdmin false ", req.GroupID, req.OpUserID)
return &pbGroup.GroupApplicationResponseResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: constant.ErrAccess.ErrMsg}}, nil
}
err := imdb.UpdateGroupRequest(groupRequest)
@@ -497,6 +640,50 @@ func (s *groupServer) GroupApplicationResponse(_ context.Context, req *pbGroup.G
log.NewError(req.OperationID, "GroupApplicationResponse failed ", err.Error(), member)
return &pbGroup.GroupApplicationResponseResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, nil
}
var reqPb pbUser.SetConversationReq
reqPb.OperationID = req.OperationID
var c pbUser.Conversation
conversation, err := imdb.GetConversation(req.FromUserID, utils.GetConversationIDBySessionType(req.GroupID, constant.GroupChatType))
if err != nil {
c.OwnerUserID = req.FromUserID
c.ConversationID = utils.GetConversationIDBySessionType(req.GroupID, constant.GroupChatType)
c.ConversationType = constant.GroupChatType
c.GroupID = req.GroupID
c.IsNotInGroup = false
} else {
c.OwnerUserID = conversation.OwnerUserID
c.ConversationID = utils.GetConversationIDBySessionType(req.GroupID, constant.GroupChatType)
c.RecvMsgOpt = conversation.RecvMsgOpt
c.ConversationType = constant.GroupChatType
c.GroupID = req.GroupID
c.IsPinned = conversation.IsPinned
c.AttachedInfo = conversation.AttachedInfo
c.IsPrivateChat = conversation.IsPrivateChat
c.GroupAtType = conversation.GroupAtType
c.IsNotInGroup = false
c.Ex = conversation.Ex
}
reqPb.Conversation = &c
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pbUser.NewUserClient(etcdConn)
respPb, err := client.SetConversation(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "SetConversation rpc failed, ", reqPb.String(), err.Error())
} else {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "SetConversation success", respPb.String())
}
addGroupMemberToCacheReq := &pbCache.AddGroupMemberToCacheReq{OperationID: req.OperationID, GroupID: req.GroupID, UserIDList: []string{req.FromUserID}}
etcdCacheConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImCacheName)
cacheClient := pbCache.NewCacheClient(etcdCacheConn)
cacheResp, err := cacheClient.AddGroupMemberToCache(context.Background(), addGroupMemberToCacheReq)
if err != nil {
log.NewError(req.OperationID, "AddGroupMemberToCache rpc call failed ", err.Error())
return &pbGroup.GroupApplicationResponseResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, nil
}
if cacheResp.CommonResp.ErrCode != 0 {
log.NewError(req.OperationID, "AddGroupMemberToCache rpc logic call failed ", cacheResp.String())
return &pbGroup.GroupApplicationResponseResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, nil
}
chat.GroupApplicationAcceptedNotification(req)
chat.MemberEnterNotification(req)
} else if req.HandleResult == constant.GroupResponseRefuse {
@@ -518,6 +705,16 @@ func (s *groupServer) JoinGroup(ctx context.Context, req *pbGroup.JoinGroupReq)
return &pbGroup.JoinGroupResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, nil
}
groupInfo, err := imdb.GetGroupInfoByGroupID(req.GroupID)
if err != nil {
log.NewError(req.OperationID, "GetGroupInfoByGroupID failed ", req.GroupID, err)
return &pbGroup.JoinGroupResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, nil
}
if groupInfo.Status == constant.GroupStatusDismissed {
errMsg := " group status is dismissed "
return &pbGroup.JoinGroupResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrStatus.ErrCode, ErrMsg: errMsg}}, nil
}
var groupRequest db.GroupRequest
groupRequest.UserID = req.OpUserID
groupRequest.ReqMsg = req.ReqMessage
@@ -542,7 +739,7 @@ func (s *groupServer) JoinGroup(ctx context.Context, req *pbGroup.JoinGroupReq)
}
func (s *groupServer) QuitGroup(ctx context.Context, req *pbGroup.QuitGroupReq) (*pbGroup.QuitGroupResp, error) {
log.NewError(req.OperationID, "QuitGroup args ", req.String())
log.NewInfo(req.OperationID, "QuitGroup args ", req.String())
_, err := imdb.GetGroupMemberInfoByGroupIDAndUserID(req.GroupID, req.OpUserID)
if err != nil {
log.NewError(req.OperationID, "GetGroupMemberInfoByGroupIDAndUserID failed ", err.Error(), req.GroupID, req.OpUserID)
@@ -560,6 +757,41 @@ func (s *groupServer) QuitGroup(ctx context.Context, req *pbGroup.QuitGroupReq)
log.NewError(req.OperationID, "DelGroupMember failed ", req.GroupID, req.OpUserID)
// return &pbGroup.CommonResp{ErrorCode: constant.ErrQuitGroup.ErrCode, ErrorMsg: constant.ErrQuitGroup.ErrMsg}, nil
}
//modify quitter conversation info
var reqPb pbUser.SetConversationReq
var c pbUser.Conversation
reqPb.OperationID = req.OperationID
c.OwnerUserID = req.OpUserID
c.ConversationID = utils.GetConversationIDBySessionType(req.GroupID, constant.GroupChatType)
c.ConversationType = constant.GroupChatType
c.GroupID = req.GroupID
c.IsNotInGroup = true
reqPb.Conversation = &c
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pbUser.NewUserClient(etcdConn)
respPb, err := client.SetConversation(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "SetConversation rpc failed, ", reqPb.String(), err.Error())
} else {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "SetConversation success", respPb.String())
}
reduceGroupMemberFromCacheReq := &pbCache.ReduceGroupMemberFromCacheReq{
UserIDList: []string{req.OpUserID},
GroupID: req.GroupID,
OperationID: req.OperationID,
}
etcdConnCache := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImCacheName)
cacheClient := pbCache.NewCacheClient(etcdConnCache)
cacheResp, err := cacheClient.ReduceGroupMemberFromCache(context.Background(), reduceGroupMemberFromCacheReq)
if err != nil {
log.NewError(req.OperationID, "ReduceGroupMemberFromCache rpc call failed ", err.Error())
return &pbGroup.QuitGroupResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, nil
}
if cacheResp.CommonResp.ErrCode != 0 {
log.NewError(req.OperationID, "ReduceGroupMemberFromCache rpc logic call failed ", cacheResp.String())
return &pbGroup.QuitGroupResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, nil
}
chat.MemberQuitNotification(req)
log.NewInfo(req.OperationID, "rpc QuitGroup return ", pbGroup.QuitGroupResp{CommonResp: &pbGroup.CommonResp{ErrCode: 0, ErrMsg: ""}})
@@ -595,6 +827,11 @@ func (s *groupServer) SetGroupInfo(ctx context.Context, req *pbGroup.SetGroupInf
return &pbGroup.SetGroupInfoResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrAccess.ErrMsg}}, http.WrapError(constant.ErrDB)
}
if group.Status == constant.GroupStatusDismissed {
errMsg := " group status is dismissed "
return &pbGroup.SetGroupInfoResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrStatus.ErrCode, ErrMsg: errMsg}}, nil
}
////bitwise operators: 0001:groupName; 0010:Notification 0100:Introduction; 1000:FaceUrl; 10000:owner
var changedType int32
if group.GroupName != req.GroupInfo.GroupName && req.GroupInfo.GroupName != "" {
@@ -627,12 +864,22 @@ func (s *groupServer) SetGroupInfo(ctx context.Context, req *pbGroup.SetGroupInf
func (s *groupServer) TransferGroupOwner(_ context.Context, req *pbGroup.TransferGroupOwnerReq) (*pbGroup.TransferGroupOwnerResp, error) {
log.NewInfo(req.OperationID, "TransferGroupOwner ", req.String())
groupInfo, err := imdb.GetGroupInfoByGroupID(req.GroupID)
if err != nil {
log.NewError(req.OperationID, "GetGroupInfoByGroupID failed ", req.GroupID, err)
return &pbGroup.TransferGroupOwnerResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, nil
}
if groupInfo.Status == constant.GroupStatusDismissed {
errMsg := " group status is dismissed "
return &pbGroup.TransferGroupOwnerResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrStatus.ErrCode, ErrMsg: errMsg}}, nil
}
if req.OldOwnerUserID == req.NewOwnerUserID {
log.NewError(req.OperationID, "same owner ", req.OldOwnerUserID, req.NewOwnerUserID)
return &pbGroup.TransferGroupOwnerResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrArgs.ErrCode, ErrMsg: constant.ErrArgs.ErrMsg}}, nil
}
groupMemberInfo := db.GroupMember{GroupID: req.GroupID, UserID: req.OldOwnerUserID, RoleLevel: constant.GroupOrdinaryUsers}
err := imdb.UpdateGroupMemberInfo(groupMemberInfo)
err = imdb.UpdateGroupMemberInfo(groupMemberInfo)
if err != nil {
log.NewError(req.OperationID, "UpdateGroupMemberInfo failed ", groupMemberInfo)
return &pbGroup.TransferGroupOwnerResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, nil
@@ -656,7 +903,7 @@ func (s *groupServer) GetGroupById(_ context.Context, req *pbGroup.GetGroupByIdR
}}
group, err := imdb.GetGroupById(req.GroupId)
if err != nil {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "GetGroupById error", err.Error())
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetGroupById error", err.Error())
return resp, http.WrapError(constant.ErrDB)
}
resp.CMSGroup.GroupInfo = &open_im_sdk.GroupInfo{
@@ -749,7 +996,8 @@ func (s *groupServer) GetGroups(_ context.Context, req *pbGroup.GetGroupsReq) (*
for _, v := range groups {
groupMember, err := imdb.GetGroupMaster(v.GroupID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error())
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetGroupMaster failed", err.Error(), v)
continue
}
resp.CMSGroups = append(resp.CMSGroups, &pbGroup.CMSGroup{
GroupInfo: &open_im_sdk.GroupInfo{
@@ -765,7 +1013,7 @@ func (s *groupServer) GetGroups(_ context.Context, req *pbGroup.GetGroupsReq) (*
GroupMasterName: groupMember.Nickname,
})
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "GetGroups ", resp.String())
return resp, nil
}
@@ -845,6 +1093,7 @@ func (s *groupServer) GetGroupMembersCMS(_ context.Context, req *pbGroup.GetGrou
CurrentPage: req.Pagination.PageNumber,
ShowNumber: req.Pagination.ShowNumber,
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp:", resp.String())
return resp, nil
}
@@ -867,9 +1116,45 @@ func (s *groupServer) RemoveGroupMembersCMS(_ context.Context, req *pbGroup.Remo
OperationID: req.OperationID,
OpUserID: req.OpUserId,
}
var reqPb pbUser.SetConversationReq
var c pbUser.Conversation
for _, v := range resp.Success {
reqPb.OperationID = req.OperationID
c.OwnerUserID = v
c.ConversationID = utils.GetConversationIDBySessionType(req.GroupId, constant.GroupChatType)
c.ConversationType = constant.GroupChatType
c.GroupID = req.GroupId
c.IsNotInGroup = true
reqPb.Conversation = &c
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pbUser.NewUserClient(etcdConn)
respPb, err := client.SetConversation(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "SetConversation rpc failed, ", reqPb.String(), err.Error(), v)
} else {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "SetConversation success", respPb.String(), v)
}
}
reduceGroupMemberFromCacheReq := &pbCache.ReduceGroupMemberFromCacheReq{
UserIDList: resp.Success,
GroupID: req.GroupId,
OperationID: req.OperationID,
}
etcdConnCache := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImCacheName)
cacheClient := pbCache.NewCacheClient(etcdConnCache)
cacheResp, err := cacheClient.ReduceGroupMemberFromCache(context.Background(), reduceGroupMemberFromCacheReq)
if err != nil {
log.NewError(req.OperationID, "ReduceGroupMemberFromCache rpc call failed ", err.Error())
return resp, http.WrapError(constant.ErrDB)
}
if cacheResp.CommonResp.ErrCode != 0 {
log.NewError(req.OperationID, "ReduceGroupMemberFromCache rpc logic call failed ", cacheResp.String())
return resp, http.WrapError(constant.ErrDB)
}
chat.MemberKickedNotification(reqKick, resp.Success)
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "success: ", resp.Success)
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "failed: ", resp.Failed)
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
return resp, nil
}
@@ -906,6 +1191,24 @@ func (s *groupServer) AddGroupMembersCMS(_ context.Context, req *pbGroup.AddGrou
resp.Success = append(resp.Success, userId)
}
}
addGroupMemberToCacheReq := &pbCache.AddGroupMemberToCacheReq{
UserIDList: resp.Success,
GroupID: req.GroupId,
OperationID: req.OperationId,
}
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImCacheName)
cacheClient := pbCache.NewCacheClient(etcdConn)
cacheResp, err := cacheClient.AddGroupMemberToCache(context.Background(), addGroupMemberToCacheReq)
if err != nil {
log.NewError(req.OperationId, "AddGroupMemberToCache rpc call failed ", err.Error())
return resp, http.WrapError(constant.ErrDB)
}
if cacheResp.CommonResp.ErrCode != 0 {
log.NewError(req.OperationId, "AddGroupMemberToCache rpc logic call failed ", cacheResp.String())
return resp, http.WrapError(constant.ErrDB)
}
chat.MemberInvitedNotification(req.OperationId, req.GroupId, req.OpUserId, "admin add you to group", resp.Success)
return resp, nil
}
@@ -948,7 +1251,7 @@ func (s *groupServer) GetUserReqApplicationList(_ context.Context, req *pbGroup.
func (s *groupServer) DismissGroup(ctx context.Context, req *pbGroup.DismissGroupReq) (*pbGroup.DismissGroupResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "rpc args ", req.String())
if !token_verify.IsMangerUserID(req.OpUserID) && !imdb.IsGroupOwnerAdmin(req.GroupID, req.OpUserID) {
if !token_verify.IsManagerUserID(req.OpUserID) && !imdb.IsGroupOwnerAdmin(req.GroupID, req.OpUserID) {
log.NewError(req.OperationID, "verify failed ", req.OpUserID, req.GroupID)
return &pbGroup.DismissGroupResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: constant.ErrAccess.ErrMsg}}, nil
}
@@ -958,14 +1261,38 @@ func (s *groupServer) DismissGroup(ctx context.Context, req *pbGroup.DismissGrou
log.NewError(req.OperationID, "OperateGroupStatus failed ", req.GroupID, constant.GroupStatusDismissed)
return &pbGroup.DismissGroupResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, nil
}
memberList, err := imdb.GetGroupMemberListByGroupID(req.GroupID)
if err != nil {
log.NewError(req.OperationID, "GetGroupMemberListByGroupID failed,", err.Error(), req.GroupID)
}
//modify quitter conversation info
var reqPb pbUser.SetConversationReq
var c pbUser.Conversation
for _, v := range memberList {
reqPb.OperationID = req.OperationID
c.OwnerUserID = v.UserID
c.ConversationID = utils.GetConversationIDBySessionType(req.GroupID, constant.GroupChatType)
c.ConversationType = constant.GroupChatType
c.GroupID = req.GroupID
c.IsNotInGroup = true
reqPb.Conversation = &c
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pbUser.NewUserClient(etcdConn)
respPb, err := client.SetConversation(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "SetConversation rpc failed, ", reqPb.String(), err.Error(), v.UserID)
} else {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "SetConversation success", respPb.String(), v.UserID)
}
}
chat.GroupDismissedNotification(req)
err = imdb.DeleteGroupMemberByGroupID(req.GroupID)
if err != nil {
log.NewError(req.OperationID, "DeleteGroupMemberByGroupID failed ", req.GroupID)
return &pbGroup.DismissGroupResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, nil
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "rpc return ", pbGroup.CommonResp{ErrCode: 0, ErrMsg: ""})
return &pbGroup.DismissGroupResp{CommonResp: &pbGroup.CommonResp{ErrCode: 0, ErrMsg: ""}}, nil
}
@@ -977,7 +1304,7 @@ func (s *groupServer) DismissGroup(ctx context.Context, req *pbGroup.DismissGrou
func (s *groupServer) MuteGroupMember(ctx context.Context, req *pbGroup.MuteGroupMemberReq) (*pbGroup.MuteGroupMemberResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "rpc args ", req.String())
if !imdb.IsGroupOwnerAdmin(req.GroupID, req.OpUserID) && !token_verify.IsMangerUserID(req.OpUserID) {
if !imdb.IsGroupOwnerAdmin(req.GroupID, req.OpUserID) && !token_verify.IsManagerUserID(req.OpUserID) {
log.Error(req.OperationID, "verify failed ", req.GroupID, req.UserID)
return &pbGroup.MuteGroupMemberResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: constant.ErrAccess.ErrMsg}}, nil
}
@@ -996,7 +1323,7 @@ func (s *groupServer) MuteGroupMember(ctx context.Context, req *pbGroup.MuteGrou
func (s *groupServer) CancelMuteGroupMember(ctx context.Context, req *pbGroup.CancelMuteGroupMemberReq) (*pbGroup.CancelMuteGroupMemberResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "rpc args ", req.String())
if !imdb.IsGroupOwnerAdmin(req.GroupID, req.OpUserID) && !token_verify.IsMangerUserID(req.OpUserID) {
if !imdb.IsGroupOwnerAdmin(req.GroupID, req.OpUserID) && !token_verify.IsManagerUserID(req.OpUserID) {
log.Error(req.OperationID, "verify failed ", req.OpUserID, req.GroupID)
return &pbGroup.CancelMuteGroupMemberResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: constant.ErrAccess.ErrMsg}}, nil
}
@@ -1014,7 +1341,7 @@ func (s *groupServer) CancelMuteGroupMember(ctx context.Context, req *pbGroup.Ca
func (s *groupServer) MuteGroup(ctx context.Context, req *pbGroup.MuteGroupReq) (*pbGroup.MuteGroupResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "rpc args ", req.String())
if !imdb.IsGroupOwnerAdmin(req.GroupID, req.OpUserID) && !token_verify.IsMangerUserID(req.OpUserID) {
if !imdb.IsGroupOwnerAdmin(req.GroupID, req.OpUserID) && !token_verify.IsManagerUserID(req.OpUserID) {
log.Error(req.OperationID, "verify failed ", req.GroupID, req.GroupID)
return &pbGroup.MuteGroupResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: constant.ErrAccess.ErrMsg}}, nil
}
@@ -1030,7 +1357,7 @@ func (s *groupServer) MuteGroup(ctx context.Context, req *pbGroup.MuteGroupReq)
func (s *groupServer) CancelMuteGroup(ctx context.Context, req *pbGroup.CancelMuteGroupReq) (*pbGroup.CancelMuteGroupResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "rpc args ", req.String())
if !imdb.IsGroupOwnerAdmin(req.GroupID, req.OpUserID) && !token_verify.IsMangerUserID(req.OpUserID) {
if !imdb.IsGroupOwnerAdmin(req.GroupID, req.OpUserID) && !token_verify.IsManagerUserID(req.OpUserID) {
log.Error(req.OperationID, "verify failed ", req.OpUserID, req.GroupID)
return &pbGroup.CancelMuteGroupResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: constant.ErrAccess.ErrMsg}}, nil
}
@@ -1044,3 +1371,36 @@ func (s *groupServer) CancelMuteGroup(ctx context.Context, req *pbGroup.CancelMu
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "rpc return ", pbGroup.CommonResp{ErrCode: 0, ErrMsg: ""})
return &pbGroup.CancelMuteGroupResp{CommonResp: &pbGroup.CommonResp{ErrCode: 0, ErrMsg: ""}}, nil
}
func (s *groupServer) SetGroupMemberNickname(ctx context.Context, req *pbGroup.SetGroupMemberNicknameReq) (*pbGroup.SetGroupMemberNicknameResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "rpc args ", req.String())
if req.OpUserID != req.UserID && !token_verify.IsManagerUserID(req.OpUserID) {
errMsg := req.OperationID + " verify failed " + req.OpUserID + req.GroupID
log.Error(req.OperationID, errMsg)
return &pbGroup.SetGroupMemberNicknameResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: constant.ErrAccess.ErrMsg}}, nil
}
groupMemberInfo := db.GroupMember{}
groupMemberInfo.UserID = req.UserID
groupMemberInfo.GroupID = req.GroupID
if req.Nickname == "" {
userNickname, err := imdb.GetUserNameByUserID(groupMemberInfo.UserID)
if err != nil {
errMsg := req.OperationID + " GetUserNameByUserID failed " + err.Error()
log.Error(req.OperationID, errMsg)
return &pbGroup.SetGroupMemberNicknameResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, nil
}
groupMemberInfo.Nickname = userNickname
} else {
groupMemberInfo.Nickname = req.Nickname
}
err := imdb.UpdateGroupMemberInfo(groupMemberInfo)
if err != nil {
errMsg := req.OperationID + " UpdateGroupMemberInfo failed " + err.Error()
log.Error(req.OperationID, errMsg)
return &pbGroup.SetGroupMemberNicknameResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, nil
}
chat.GroupMemberInfoSetNotification(req.OperationID, req.OpUserID, req.GroupID, req.UserID)
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "rpc return ", pbGroup.CommonResp{ErrCode: 0, ErrMsg: ""})
return &pbGroup.SetGroupMemberNicknameResp{CommonResp: &pbGroup.CommonResp{ErrCode: 0, ErrMsg: ""}}, nil
}

View File

@@ -6,6 +6,7 @@ import (
"Open_IM/pkg/common/db"
errors "Open_IM/pkg/common/http"
"context"
"strconv"
"Open_IM/pkg/common/log"
@@ -17,7 +18,6 @@ import (
"Open_IM/pkg/utils"
"net"
"strconv"
"strings"
"google.golang.org/grpc"
@@ -42,22 +42,35 @@ func NewMessageCMSServer(port int) *messageCMSServer {
func (s *messageCMSServer) Run() {
log.NewInfo("0", "messageCMS rpc start ")
ip := utils.ServerIP
registerAddress := ip + ":" + strconv.Itoa(s.rpcPort)
//listener network
listener, err := net.Listen("tcp", registerAddress)
if err != nil {
log.NewError("0", "Listen failed ", err.Error(), registerAddress)
return
listenIP := ""
if config.Config.ListenIP == "" {
listenIP = "0.0.0.0"
} else {
listenIP = config.Config.ListenIP
}
log.NewInfo("0", "listen network success, ", registerAddress, listener)
address := listenIP + ":" + strconv.Itoa(s.rpcPort)
//listener network
listener, err := net.Listen("tcp", address)
if err != nil {
panic("listening err:" + err.Error() + s.rpcRegisterName)
}
log.NewInfo("0", "listen network success, ", address, listener)
defer listener.Close()
//grpc server
srv := grpc.NewServer()
defer srv.GracefulStop()
//Service registers with etcd
pbMessageCMS.RegisterMessageCMSServer(srv, s)
err = getcdv3.RegisterEtcd(s.etcdSchema, strings.Join(s.etcdAddr, ","), ip, s.rpcPort, s.rpcRegisterName, 10)
rpcRegisterIP := ""
if config.Config.RpcRegisterIP == "" {
rpcRegisterIP, err = utils.GetLocalIP()
if err != nil {
log.Error("", "GetLocalIP failed ", err.Error())
}
}
err = getcdv3.RegisterEtcd(s.etcdSchema, strings.Join(s.etcdAddr, ","), rpcRegisterIP, s.rpcPort, s.rpcRegisterName, 10)
if err != nil {
log.NewError("0", "RegisterEtcd failed ", err.Error())
return
@@ -96,6 +109,7 @@ func (s *messageCMSServer) GetChatLogs(_ context.Context, req *pbMessageCMS.GetC
chatLog.RecvID = req.GroupId
chatLog.SendID = req.UserId
}
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "chat_log: ", chatLog)
nums, err := imdb.GetChatLogCount(chatLog)
resp.ChatLogsNum = int32(nums)
if err != nil {

View File

@@ -31,6 +31,7 @@ func callbackBeforeSendSingleMsg(msg *pbChat.SendMsgReq) (canSend bool, err erro
if !config.Config.Callback.CallbackBeforeSendSingleMsg.Enable {
return true, nil
}
log.NewDebug(msg.OperationID, utils.GetSelfFuncName(), msg)
commonCallbackReq := copyCallbackCommonReqStruct(msg)
commonCallbackReq.CallbackCommand = constant.CallbackBeforeSendSingleMsgCommand

View File

@@ -12,12 +12,13 @@ import (
func (rpc *rpcChat) DelMsgList(_ context.Context, req *commonPb.DelMsgListReq) (*commonPb.DelMsgListResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp := &commonPb.DelMsgListResp{}
if err := db.DB.DelMsgLogic(req.UserID, req.SeqList, req.OperationID); err != nil {
if err := db.DB.DelMsgBySeqList(req.UserID, req.SeqList, req.OperationID); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "DelMsg failed", err.Error())
resp.ErrMsg = constant.ErrDB.ErrMsg
resp.ErrCode = constant.ErrDB.ErrCode
return resp, nil
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}

View File

@@ -22,7 +22,7 @@ import (
//} creator->group
func setOpUserInfo(opUserID, groupID string, groupMemberInfo *open_im_sdk.GroupMemberFullInfo) error {
if token_verify.IsMangerUserID(opUserID) {
if token_verify.IsManagerUserID(opUserID) {
u, err := imdb.GetUserByUserID(opUserID)
if err != nil {
return utils.Wrap(err, "GetUserByUserID failed")
@@ -168,6 +168,9 @@ func groupNotification(contentType int32, m proto.Message, sendID, groupID, recv
tips.DefaultTips = toNickname + "" + cn.GroupMemberMuted.DefaultTips.Tips
case constant.GroupMemberCancelMutedNotification:
tips.DefaultTips = toNickname + "" + cn.GroupMemberCancelMuted.DefaultTips.Tips
case constant.GroupMemberInfoSetNotification:
tips.DefaultTips = toNickname + "" + cn.GroupMemberInfoSet.DefaultTips.Tips
default:
log.Error(operationID, "contentType failed ", contentType)
return
@@ -282,6 +285,24 @@ func GroupMemberMutedNotification(operationID, opUserID, groupID, groupMemberUse
groupNotification(constant.GroupMemberMutedNotification, &tips, opUserID, groupID, "", operationID)
}
func GroupMemberInfoSetNotification(operationID, opUserID, groupID, groupMemberUserID string) {
tips := open_im_sdk.GroupMemberInfoSetTips{Group: &open_im_sdk.GroupInfo{},
OpUser: &open_im_sdk.GroupMemberFullInfo{}, ChangedUser: &open_im_sdk.GroupMemberFullInfo{}}
if err := setGroupInfo(groupID, tips.Group); err != nil {
log.Error(operationID, "setGroupInfo failed ", err.Error(), groupID)
return
}
if err := setOpUserInfo(opUserID, groupID, tips.OpUser); err != nil {
log.Error(operationID, "setOpUserInfo failed ", err.Error(), opUserID, groupID)
return
}
if err := setGroupMemberInfo(groupID, groupMemberUserID, tips.ChangedUser); err != nil {
log.Error(operationID, "setGroupMemberInfo failed ", err.Error(), groupID, groupMemberUserID)
return
}
groupNotification(constant.GroupMemberInfoSetNotification, &tips, opUserID, groupID, "", operationID)
}
func GroupMemberCancelMutedNotification(operationID, opUserID, groupID, groupMemberUserID string) {
tips := open_im_sdk.GroupMemberCancelMutedTips{Group: &open_im_sdk.GroupInfo{},
OpUser: &open_im_sdk.GroupMemberFullInfo{}, MutedUser: &open_im_sdk.GroupMemberFullInfo{}}

View File

@@ -0,0 +1,76 @@
package msg
import (
"Open_IM/pkg/common/constant"
imdb "Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
utils2 "Open_IM/pkg/common/utils"
open_im_sdk "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
)
func OrganizationNotificationToAll(opUserID string, operationID string) {
err, userIDList := imdb.GetAllOrganizationUserID()
if err != nil {
log.Error(operationID, "GetAllOrganizationUserID failed ", err.Error())
return
}
tips := open_im_sdk.OrganizationChangedTips{OpUser: &open_im_sdk.UserInfo{}}
user, err := imdb.GetUserByUserID(opUserID)
if err != nil {
log.NewError(operationID, "GetUserByUserID failed ", err.Error(), opUserID)
return
}
utils2.UserDBCopyOpenIM(tips.OpUser, user)
for _, v := range userIDList {
log.Debug(operationID, "OrganizationNotification", opUserID, v, constant.OrganizationChangedNotification, &tips, operationID)
OrganizationNotification(opUserID, v, constant.OrganizationChangedNotification, &tips, operationID)
}
}
func OrganizationNotification(opUserID string, recvUserID string, contentType int32, m proto.Message, operationID string) {
log.Info(operationID, utils.GetSelfFuncName(), "args: ", contentType, opUserID)
var err error
var tips open_im_sdk.TipsComm
tips.Detail, err = proto.Marshal(m)
if err != nil {
log.Error(operationID, "Marshal failed ", err.Error(), m.String())
return
}
marshaler := jsonpb.Marshaler{
OrigName: true,
EnumsAsInts: false,
EmitDefaults: false,
}
tips.JsonDetail, _ = marshaler.MarshalToString(m)
switch contentType {
case constant.OrganizationChangedNotification:
tips.DefaultTips = "OrganizationChangedNotification"
default:
log.Error(operationID, "contentType failed ", contentType)
return
}
var n NotificationMsg
n.SendID = opUserID
n.RecvID = recvUserID
n.ContentType = contentType
n.SessionType = constant.SingleChatType
n.MsgFrom = constant.SysMsgType
n.OperationID = operationID
n.Content, err = proto.Marshal(&tips)
if err != nil {
log.Error(operationID, "Marshal failed ", err.Error(), tips.String())
return
}
Notification(&n)
}

View File

@@ -11,7 +11,7 @@ import (
)
func (rpc *rpcChat) GetMaxAndMinSeq(_ context.Context, in *pbMsg.GetMaxAndMinSeqReq) (*pbMsg.GetMaxAndMinSeqResp, error) {
log.InfoByKv("rpc getMaxAndMinSeq is arriving", in.OperationID, in.String())
log.NewInfo(in.OperationID, "rpc getMaxAndMinSeq is arriving", in.String())
//seq, err := model.GetBiggestSeqFromReceive(in.UserID)
maxSeq, err1 := commonDB.DB.GetUserMaxSeq(in.UserID)
minSeq, err2 := commonDB.DB.GetUserMinSeq(in.UserID)
@@ -42,7 +42,7 @@ func (rpc *rpcChat) PullMessageBySeqList(_ context.Context, in *open_im_sdk.Pull
//msgList, err := commonDB.DB.GetMsgBySeqList(in.UserID, in.SeqList, in.OperationID)
msgList, err := commonDB.DB.GetMsgBySeqListMongo2(in.UserID, in.SeqList, in.OperationID)
if err != nil {
log.ErrorByKv("PullMessageBySeqList data error", in.OperationID, in.String())
log.Error(in.OperationID, "PullMessageBySeqList data error", in.String(), err.Error())
resp.ErrCode = 201
resp.ErrMsg = err.Error()
return resp, nil

View File

@@ -19,7 +19,8 @@ type rpcChat struct {
rpcRegisterName string
etcdSchema string
etcdAddr []string
producer *kafka.Producer
onlineProducer *kafka.Producer
offlineProducer *kafka.Producer
}
func NewRpcChatServer(port int) *rpcChat {
@@ -30,38 +31,47 @@ func NewRpcChatServer(port int) *rpcChat {
etcdSchema: config.Config.Etcd.EtcdSchema,
etcdAddr: config.Config.Etcd.EtcdAddr,
}
rc.producer = kafka.NewKafkaProducer(config.Config.Kafka.Ws2mschat.Addr, config.Config.Kafka.Ws2mschat.Topic)
rc.onlineProducer = kafka.NewKafkaProducer(config.Config.Kafka.Ws2mschat.Addr, config.Config.Kafka.Ws2mschat.Topic)
rc.offlineProducer = kafka.NewKafkaProducer(config.Config.Kafka.Ws2mschatOffline.Addr, config.Config.Kafka.Ws2mschatOffline.Topic)
return &rc
}
func (rpc *rpcChat) Run() {
log.Info("", "", "rpc get_token init...")
address := utils.ServerIP + ":" + strconv.Itoa(rpc.rpcPort)
log.Info("", "rpcChat init...")
listenIP := ""
if config.Config.ListenIP == "" {
listenIP = "0.0.0.0"
} else {
listenIP = config.Config.ListenIP
}
address := listenIP + ":" + strconv.Itoa(rpc.rpcPort)
listener, err := net.Listen("tcp", address)
if err != nil {
log.Error("", "", "listen network failed, err = %s, address = %s", err.Error(), address)
return
panic("listening err:" + err.Error() + rpc.rpcRegisterName)
}
log.Info("", "", "listen network success, address = ", address)
log.Info("", "listen network success, address ", address)
//grpc server
srv := grpc.NewServer()
defer srv.GracefulStop()
//service registers with etcd
rpcRegisterIP := ""
pbChat.RegisterChatServer(srv, rpc)
err = getcdv3.RegisterEtcd(rpc.etcdSchema, strings.Join(rpc.etcdAddr, ","), utils.ServerIP, rpc.rpcPort, rpc.rpcRegisterName, 10)
if config.Config.RpcRegisterIP == "" {
rpcRegisterIP, err = utils.GetLocalIP()
if err != nil {
log.Error("", "GetLocalIP failed ", err.Error())
}
}
err = getcdv3.RegisterEtcd(rpc.etcdSchema, strings.Join(rpc.etcdAddr, ","), rpcRegisterIP, rpc.rpcPort, rpc.rpcRegisterName, 10)
if err != nil {
log.Error("", "", "register rpc get_token to etcd failed, err = %s", err.Error())
log.Error("", "register rpcChat to etcd failed ", err.Error())
return
}
err = srv.Serve(listener)
if err != nil {
log.Info("", "", "rpc get_token fail, err = %s", err.Error())
log.Error("", "rpc rpcChat failed ", err.Error())
return
}
log.Info("", "", "rpc get_token init success")
log.Info("", "rpc rpcChat init success")
}

View File

@@ -6,20 +6,27 @@ import (
"Open_IM/pkg/common/db"
"Open_IM/pkg/common/log"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
cacheRpc "Open_IM/pkg/proto/cache"
pbCache "Open_IM/pkg/proto/cache"
pbChat "Open_IM/pkg/proto/chat"
rpc "Open_IM/pkg/proto/friend"
pbGroup "Open_IM/pkg/proto/group"
pbConversation "Open_IM/pkg/proto/conversation"
pbRelay "Open_IM/pkg/proto/relay"
sdk_ws "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils"
"context"
"errors"
"github.com/garyburd/redigo/redis"
"github.com/golang/protobuf/proto"
"math/rand"
"strconv"
"strings"
"sync"
"time"
)
//When the number of group members is greater than this valueOnline users will be sent firstGuaranteed service availability
const GroupMemberNum = 500
type MsgCallBackReq struct {
SendID string `json:"sendID"`
RecvID string `json:"recvID"`
@@ -47,36 +54,38 @@ func userRelationshipVerification(data *pbChat.SendMsgReq) (bool, int32, string)
return true, 0, ""
}
log.NewDebug(data.OperationID, config.Config.MessageVerify.FriendVerify)
req := &rpc.IsInBlackListReq{CommID: &rpc.CommID{}}
req.CommID.OperationID = data.OperationID
req.CommID.OpUserID = data.MsgData.RecvID
req.CommID.FromUserID = data.MsgData.RecvID
req.CommID.ToUserID = data.MsgData.SendID
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImFriendName)
client := rpc.NewFriendClient(etcdConn)
reply, err := client.IsInBlackList(context.Background(), req)
reqGetBlackIDListFromCache := &cacheRpc.GetBlackIDListFromCacheReq{UserID: data.MsgData.RecvID, OperationID: data.OperationID}
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImCacheName)
cacheClient := cacheRpc.NewCacheClient(etcdConn)
cacheResp, err := cacheClient.GetBlackIDListFromCache(context.Background(), reqGetBlackIDListFromCache)
if err != nil {
log.NewDebug(data.OperationID, "IsInBlackListReq rpc failed, ", req.String(), err.Error())
} else if reply.Response == true {
log.NewDebug(data.OperationID, "IsInBlackListReq ", req.String())
return false, 600, "in black list"
log.NewError(data.OperationID, "GetBlackIDListFromCache rpc call failed ", err.Error())
} else {
if cacheResp.CommonResp.ErrCode != 0 {
log.NewError(data.OperationID, "GetBlackIDListFromCache rpc logic call failed ", cacheResp.String())
} else {
if utils.IsContain(data.MsgData.SendID, cacheResp.UserIDList) {
return false, 600, "in black list"
}
}
}
log.NewDebug(data.OperationID, config.Config.MessageVerify.FriendVerify)
if config.Config.MessageVerify.FriendVerify {
friendReq := &rpc.IsFriendReq{CommID: &rpc.CommID{}}
friendReq.CommID.OperationID = data.OperationID
friendReq.CommID.OpUserID = data.MsgData.RecvID
friendReq.CommID.FromUserID = data.MsgData.RecvID
friendReq.CommID.ToUserID = data.MsgData.SendID
friendReply, err := client.IsFriend(context.Background(), friendReq)
reqGetFriendIDListFromCache := &cacheRpc.GetFriendIDListFromCacheReq{UserID: data.MsgData.RecvID, OperationID: data.OperationID}
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImCacheName)
cacheClient := cacheRpc.NewCacheClient(etcdConn)
cacheResp, err := cacheClient.GetFriendIDListFromCache(context.Background(), reqGetFriendIDListFromCache)
if err != nil {
log.NewDebug(data.OperationID, "IsFriendReq rpc failed, ", req.String(), err.Error())
return true, 0, ""
} else if friendReply.Response == false {
log.NewDebug(data.OperationID, "not friend ", req.String())
return friendReply.Response, 601, "not friend"
log.NewError(data.OperationID, "GetFriendIDListFromCache rpc call failed ", err.Error())
} else {
if cacheResp.CommonResp.ErrCode != 0 {
log.NewError(data.OperationID, "GetFriendIDListFromCache rpc logic call failed ", cacheResp.String())
} else {
if !utils.IsContain(data.MsgData.SendID, cacheResp.UserIDList) {
return false, 601, "not friend"
}
}
}
log.NewDebug(data.OperationID, config.Config.MessageVerify.FriendVerify, friendReply.Response)
return true, 0, ""
} else {
return true, 0, ""
@@ -142,7 +151,7 @@ func (rpc *rpcChat) SendMsg(_ context.Context, pb *pbChat.SendMsgReq) (*pbChat.S
// return returnMsg(&replay, pb, http.StatusUnauthorized, "token validate err,not authorized", "", 0)
rpc.encapsulateMsgData(pb.MsgData)
log.Info("", "this is a test MsgData ", pb.MsgData)
msgToMQ := pbChat.MsgDataToMQ{Token: pb.Token, OperationID: pb.OperationID, MsgData: pb.MsgData}
msgToMQSingle := pbChat.MsgDataToMQ{Token: pb.Token, OperationID: pb.OperationID, MsgData: pb.MsgData}
//options := utils.JsonStringToMap(pbData.Options)
isHistory := utils.GetSwitchFromOptions(pb.MsgData.Options, constant.IsHistory)
mReq := MsgCallBackReq{
@@ -182,18 +191,18 @@ func (rpc *rpcChat) SendMsg(_ context.Context, pb *pbChat.SendMsgReq) (*pbChat.S
}
isSend := modifyMessageByUserMessageReceiveOpt(pb.MsgData.RecvID, pb.MsgData.SendID, constant.SingleChatType, pb)
if isSend {
msgToMQ.MsgData = pb.MsgData
log.NewInfo(msgToMQ.OperationID, msgToMQ)
err1 := rpc.sendMsgToKafka(&msgToMQ, msgToMQ.MsgData.RecvID)
msgToMQSingle.MsgData = pb.MsgData
log.NewInfo(msgToMQSingle.OperationID, msgToMQSingle)
err1 := rpc.sendMsgToKafka(&msgToMQSingle, msgToMQSingle.MsgData.RecvID, constant.OnlineStatus)
if err1 != nil {
log.NewError(msgToMQ.OperationID, "kafka send msg err:RecvID", msgToMQ.MsgData.RecvID, msgToMQ.String())
log.NewError(msgToMQSingle.OperationID, "kafka send msg err:RecvID", msgToMQSingle.MsgData.RecvID, msgToMQSingle.String())
return returnMsg(&replay, pb, 201, "kafka send msg err", "", 0)
}
}
if msgToMQ.MsgData.SendID != msgToMQ.MsgData.RecvID { //Filter messages sent to yourself
err2 := rpc.sendMsgToKafka(&msgToMQ, msgToMQ.MsgData.SendID)
if msgToMQSingle.MsgData.SendID != msgToMQSingle.MsgData.RecvID { //Filter messages sent to yourself
err2 := rpc.sendMsgToKafka(&msgToMQSingle, msgToMQSingle.MsgData.SendID, constant.OnlineStatus)
if err2 != nil {
log.NewError(msgToMQ.OperationID, "kafka send msg err:SendID", msgToMQ.MsgData.SendID, msgToMQ.String())
log.NewError(msgToMQSingle.OperationID, "kafka send msg err:SendID", msgToMQSingle.MsgData.SendID, msgToMQSingle.String())
return returnMsg(&replay, pb, 201, "kafka send msg err", "", 0)
}
}
@@ -201,7 +210,7 @@ func (rpc *rpcChat) SendMsg(_ context.Context, pb *pbChat.SendMsgReq) (*pbChat.S
if err := callbackAfterSendSingleMsg(pb); err != nil {
log.NewError(pb.OperationID, utils.GetSelfFuncName(), "callbackAfterSendSingleMsg failed", err.Error())
}
return returnMsg(&replay, pb, 0, "", msgToMQ.MsgData.ServerMsgID, msgToMQ.MsgData.SendTime)
return returnMsg(&replay, pb, 0, "", msgToMQSingle.MsgData.ServerMsgID, msgToMQSingle.MsgData.SendTime)
case constant.GroupChatType:
// callback
canSend, err := callbackBeforeSendGroupMsg(pb)
@@ -212,21 +221,20 @@ func (rpc *rpcChat) SendMsg(_ context.Context, pb *pbChat.SendMsgReq) (*pbChat.S
log.NewDebug(pb.OperationID, utils.GetSelfFuncName(), "callbackBeforeSendGroupMsg result", canSend, "end rpc and return")
return returnMsg(&replay, pb, 201, "callbackBeforeSendGroupMsg result stop rpc and return", "", 0)
}
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := pbGroup.NewGroupClient(etcdConn)
req := &pbGroup.GetGroupAllMemberReq{
GroupID: pb.MsgData.GroupID,
OperationID: pb.OperationID,
}
reply, err := client.GetGroupAllMember(context.Background(), req)
getGroupMemberIDListFromCacheReq := &pbCache.GetGroupMemberIDListFromCacheReq{OperationID: pb.OperationID, GroupID: pb.MsgData.GroupID}
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImCacheName)
client := pbCache.NewCacheClient(etcdConn)
cacheResp, err := client.GetGroupMemberIDListFromCache(context.Background(), getGroupMemberIDListFromCacheReq)
if err != nil {
log.Error(pb.Token, pb.OperationID, "rpc send_msg getGroupInfo failed, err = %s", err.Error())
return returnMsg(&replay, pb, 201, err.Error(), "", 0)
log.NewError(pb.OperationID, "GetGroupMemberIDListFromCache rpc call failed ", err.Error())
return returnMsg(&replay, pb, 201, "GetGroupMemberIDListFromCache failed", "", 0)
}
if reply.ErrCode != 0 {
log.Error(pb.Token, pb.OperationID, "rpc send_msg getGroupInfo failed, err = %s", reply.ErrMsg)
return returnMsg(&replay, pb, reply.ErrCode, reply.ErrMsg, "", 0)
if cacheResp.CommonResp.ErrCode != 0 {
log.NewError(pb.OperationID, "GetGroupMemberIDListFromCache rpc logic call failed ", cacheResp.String())
return returnMsg(&replay, pb, 201, "GetGroupMemberIDListFromCache logic failed", "", 0)
}
memberUserIDList := cacheResp.UserIDList
log.Debug(pb.OperationID, "GetGroupAllMember userID list", cacheResp.UserIDList)
var addUidList []string
switch pb.MsgData.ContentType {
case constant.MemberKickedNotification:
@@ -246,69 +254,134 @@ func (rpc *rpcChat) SendMsg(_ context.Context, pb *pbChat.SendMsgReq) (*pbChat.S
}
case constant.MemberQuitNotification:
addUidList = append(addUidList, pb.MsgData.SendID)
default:
}
groupID := pb.MsgData.GroupID
for _, v := range reply.MemberList {
pb.MsgData.RecvID = v.UserID
isSend := modifyMessageByUserMessageReceiveOpt(v.UserID, groupID, constant.GroupChatType, pb)
if isSend {
msgToMQ.MsgData = pb.MsgData
err := rpc.sendMsgToKafka(&msgToMQ, v.UserID)
if err != nil {
log.NewError(msgToMQ.OperationID, "kafka send msg err:UserId", v.UserID, msgToMQ.String())
return returnMsg(&replay, pb, 201, "kafka send msg err", "", 0)
}
}
m := make(map[string][]string, 2)
if len(memberUserIDList) > GroupMemberNum {
getOnlineAndOfflineUserIDList(memberUserIDList, m, pb.OperationID)
log.Debug(pb.OperationID, m[constant.OnlineStatus], m[constant.OfflineStatus])
} else {
m[constant.OnlineStatus] = memberUserIDList
}
}
log.Info(msgToMQ.OperationID, "addUidList", addUidList)
for _, v := range addUidList {
pb.MsgData.RecvID = v
isSend := modifyMessageByUserMessageReceiveOpt(v, groupID, constant.GroupChatType, pb)
log.Info(msgToMQ.OperationID, "isSend", isSend)
if isSend {
msgToMQ.MsgData = pb.MsgData
err := rpc.sendMsgToKafka(&msgToMQ, v)
if err != nil {
log.NewError(msgToMQ.OperationID, "kafka send msg err:UserId", v, msgToMQ.String())
return returnMsg(&replay, pb, 201, "kafka send msg err", "", 0)
}
//split parallel send
var wg sync.WaitGroup
var sendTag bool
var split = 50
for k, v := range m {
remain := len(v) % split
for i := 0; i < len(v)/split; i++ {
wg.Add(1)
go rpc.sendMsgToGroup(v[i*split:(i+1)*split], *pb, k, &sendTag, &wg)
}
if remain > 0 {
wg.Add(1)
go rpc.sendMsgToGroup(v[split*(len(v)/split):], *pb, k, &sendTag, &wg)
}
}
wg.Add(1)
go rpc.sendMsgToGroup(addUidList, *pb, constant.OnlineStatus, &sendTag, &wg)
wg.Wait()
// callback
if err := callbackAfterSendGroupMsg(pb); err != nil {
log.NewError(pb.OperationID, utils.GetSelfFuncName(), "callbackAfterSendGroupMsg failed", err.Error())
}
return returnMsg(&replay, pb, 0, "", msgToMQ.MsgData.ServerMsgID, msgToMQ.MsgData.SendTime)
if !sendTag {
return returnMsg(&replay, pb, 201, "kafka send msg err", "", 0)
} else {
if pb.MsgData.ContentType == constant.AtText {
go func() {
var conversationReq pbConversation.ModifyConversationFieldReq
var tag bool
var atUserID []string
conversation := pbConversation.Conversation{
OwnerUserID: pb.MsgData.SendID,
ConversationID: utils.GetConversationIDBySessionType(pb.MsgData.GroupID, constant.GroupChatType),
ConversationType: constant.GroupChatType,
GroupID: pb.MsgData.GroupID,
}
conversationReq.Conversation = &conversation
conversationReq.OperationID = pb.OperationID
conversationReq.FieldType = constant.FieldGroupAtType
tagAll := utils.IsContain(constant.AtAllString, pb.MsgData.AtUserIDList)
if tagAll {
atUserID = utils.DifferenceString([]string{constant.AtAllString}, pb.MsgData.AtUserIDList)
if len(atUserID) == 0 { //just @everyone
conversationReq.UserIDList = memberUserIDList
conversation.GroupAtType = constant.AtAll
} else { //@Everyone and @other people
conversationReq.UserIDList = atUserID
conversation.GroupAtType = constant.AtAllAtMe
tag = true
}
} else {
conversationReq.UserIDList = pb.MsgData.AtUserIDList
conversation.GroupAtType = constant.AtMe
}
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImConversationName)
client := pbConversation.NewConversationClient(etcdConn)
conversationReply, err := client.ModifyConversationField(context.Background(), &conversationReq)
if err != nil {
log.NewError(conversationReq.OperationID, "ModifyConversationField rpc failed, ", conversationReq.String(), err.Error())
} else if conversationReply.CommonResp.ErrCode != 0 {
log.NewError(conversationReq.OperationID, "ModifyConversationField rpc failed, ", conversationReq.String(), conversationReply.String())
}
if tag {
conversationReq.UserIDList = utils.DifferenceString(atUserID, memberUserIDList)
conversation.GroupAtType = constant.AtAll
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImConversationName)
client := pbConversation.NewConversationClient(etcdConn)
conversationReply, err := client.ModifyConversationField(context.Background(), &conversationReq)
if err != nil {
log.NewError(conversationReq.OperationID, "ModifyConversationField rpc failed, ", conversationReq.String(), err.Error())
} else if conversationReply.CommonResp.ErrCode != 0 {
log.NewError(conversationReq.OperationID, "ModifyConversationField rpc failed, ", conversationReq.String(), conversationReply.String())
}
}
}()
}
return returnMsg(&replay, pb, 0, "", msgToMQSingle.MsgData.ServerMsgID, msgToMQSingle.MsgData.SendTime)
}
case constant.NotificationChatType:
msgToMQ.MsgData = pb.MsgData
log.NewInfo(msgToMQ.OperationID, msgToMQ)
err1 := rpc.sendMsgToKafka(&msgToMQ, msgToMQ.MsgData.RecvID)
msgToMQSingle.MsgData = pb.MsgData
log.NewInfo(msgToMQSingle.OperationID, msgToMQSingle)
err1 := rpc.sendMsgToKafka(&msgToMQSingle, msgToMQSingle.MsgData.RecvID, constant.OnlineStatus)
if err1 != nil {
log.NewError(msgToMQ.OperationID, "kafka send msg err:RecvID", msgToMQ.MsgData.RecvID, msgToMQ.String())
log.NewError(msgToMQSingle.OperationID, "kafka send msg err:RecvID", msgToMQSingle.MsgData.RecvID, msgToMQSingle.String())
return returnMsg(&replay, pb, 201, "kafka send msg err", "", 0)
}
if msgToMQ.MsgData.SendID != msgToMQ.MsgData.RecvID { //Filter messages sent to yourself
err2 := rpc.sendMsgToKafka(&msgToMQ, msgToMQ.MsgData.SendID)
if msgToMQSingle.MsgData.SendID != msgToMQSingle.MsgData.RecvID { //Filter messages sent to yourself
err2 := rpc.sendMsgToKafka(&msgToMQSingle, msgToMQSingle.MsgData.SendID, constant.OnlineStatus)
if err2 != nil {
log.NewError(msgToMQ.OperationID, "kafka send msg err:SendID", msgToMQ.MsgData.SendID, msgToMQ.String())
log.NewError(msgToMQSingle.OperationID, "kafka send msg err:SendID", msgToMQSingle.MsgData.SendID, msgToMQSingle.String())
return returnMsg(&replay, pb, 201, "kafka send msg err", "", 0)
}
}
return returnMsg(&replay, pb, 0, "", msgToMQ.MsgData.ServerMsgID, msgToMQ.MsgData.SendTime)
return returnMsg(&replay, pb, 0, "", msgToMQSingle.MsgData.ServerMsgID, msgToMQSingle.MsgData.SendTime)
default:
return returnMsg(&replay, pb, 203, "unkonwn sessionType", "", 0)
}
}
func (rpc *rpcChat) sendMsgToKafka(m *pbChat.MsgDataToMQ, key string) error {
pid, offset, err := rpc.producer.SendMessage(m, key)
if err != nil {
log.ErrorByKv("kafka send failed", m.OperationID, "send data", m.String(), "pid", pid, "offset", offset, "err", err.Error(), "key", key)
func (rpc *rpcChat) sendMsgToKafka(m *pbChat.MsgDataToMQ, key string, status string) error {
switch status {
case constant.OnlineStatus:
pid, offset, err := rpc.onlineProducer.SendMessage(m, key)
if err != nil {
log.Error(m.OperationID, "kafka send failed", "send data", m.String(), "pid", pid, "offset", offset, "err", err.Error(), "key", key, status)
}
return err
case constant.OfflineStatus:
pid, offset, err := rpc.offlineProducer.SendMessage(m, key)
if err != nil {
log.Error(m.OperationID, "kafka send failed", "send data", m.String(), "pid", pid, "offset", offset, "err", err.Error(), "key", key, status)
}
return err
}
return err
return errors.New("status error")
}
func GetMsgID(sendID string) string {
t := time.Now().Format("2006-01-02 15:04:05")
@@ -562,6 +635,38 @@ func Notification(n *NotificationMsg) {
ex = config.Config.Notification.GroupMemberCancelMuted.OfflinePush.Ext
reliabilityLevel = config.Config.Notification.GroupMemberCancelMuted.Conversation.ReliabilityLevel
unReadCount = config.Config.Notification.GroupMemberCancelMuted.Conversation.UnreadCount
case constant.GroupMemberInfoSetNotification:
pushSwitch = config.Config.Notification.GroupMemberInfoSet.OfflinePush.PushSwitch
title = config.Config.Notification.GroupMemberInfoSet.OfflinePush.Title
desc = config.Config.Notification.GroupMemberInfoSet.OfflinePush.Desc
ex = config.Config.Notification.GroupMemberInfoSet.OfflinePush.Ext
reliabilityLevel = config.Config.Notification.GroupMemberInfoSet.Conversation.ReliabilityLevel
unReadCount = config.Config.Notification.GroupMemberInfoSet.Conversation.UnreadCount
case constant.OrganizationChangedNotification:
pushSwitch = config.Config.Notification.OrganizationChanged.OfflinePush.PushSwitch
title = config.Config.Notification.OrganizationChanged.OfflinePush.Title
desc = config.Config.Notification.OrganizationChanged.OfflinePush.Desc
ex = config.Config.Notification.OrganizationChanged.OfflinePush.Ext
reliabilityLevel = config.Config.Notification.OrganizationChanged.Conversation.ReliabilityLevel
unReadCount = config.Config.Notification.OrganizationChanged.Conversation.UnreadCount
case constant.WorkMomentNotification:
pushSwitch = config.Config.Notification.WorkMomentsNotification.OfflinePush.PushSwitch
title = config.Config.Notification.WorkMomentsNotification.OfflinePush.Title
desc = config.Config.Notification.WorkMomentsNotification.OfflinePush.Desc
ex = config.Config.Notification.WorkMomentsNotification.OfflinePush.Ext
reliabilityLevel = config.Config.Notification.WorkMomentsNotification.Conversation.ReliabilityLevel
unReadCount = config.Config.Notification.WorkMomentsNotification.Conversation.UnreadCount
case constant.ConversationPrivateChatNotification:
pushSwitch = config.Config.Notification.ConversationSetPrivate.OfflinePush.PushSwitch
title = config.Config.Notification.ConversationSetPrivate.OfflinePush.Title
desc = config.Config.Notification.ConversationSetPrivate.OfflinePush.Desc
ex = config.Config.Notification.ConversationSetPrivate.OfflinePush.Ext
reliabilityLevel = config.Config.Notification.ConversationSetPrivate.Conversation.ReliabilityLevel
unReadCount = config.Config.Notification.ConversationSetPrivate.Conversation.UnreadCount
}
switch reliabilityLevel {
case constant.UnreliableNotification:
@@ -591,3 +696,79 @@ func Notification(n *NotificationMsg) {
log.NewError(req.OperationID, "SendMsg rpc failed, ", req.String(), reply.ErrCode, reply.ErrMsg)
}
}
func getOnlineAndOfflineUserIDList(memberList []string, m map[string][]string, operationID string) {
var onllUserIDList, offlUserIDList []string
var wsResult []*pbRelay.GetUsersOnlineStatusResp_SuccessResult
req := &pbRelay.GetUsersOnlineStatusReq{}
req.UserIDList = memberList
req.OperationID = operationID
req.OpUserID = config.Config.Manager.AppManagerUid[0]
flag := false
grpcCons := getcdv3.GetConn4Unique(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOnlineMessageRelayName)
for _, v := range grpcCons {
client := pbRelay.NewOnlineMessageRelayServiceClient(v)
reply, err := client.GetUsersOnlineStatus(context.Background(), req)
if err != nil {
log.NewError(operationID, "GetUsersOnlineStatus rpc err", req.String(), err.Error())
continue
} else {
if reply.ErrCode == 0 {
wsResult = append(wsResult, reply.SuccessResult...)
}
}
}
log.NewInfo(operationID, "call GetUsersOnlineStatus rpc server is success", wsResult)
//Online data merge of each node
for _, v1 := range memberList {
flag = false
for _, v2 := range wsResult {
if v2.UserID == v1 {
flag = true
onllUserIDList = append(onllUserIDList, v1)
}
}
if !flag {
offlUserIDList = append(offlUserIDList, v1)
}
}
m[constant.OnlineStatus] = onllUserIDList
m[constant.OfflineStatus] = offlUserIDList
}
func (rpc *rpcChat) sendMsgToGroup(list []string, pb pbChat.SendMsgReq, status string, sendTag *bool, wg *sync.WaitGroup) {
// log.Debug(pb.OperationID, "split userID ", list)
offlinePushInfo := sdk_ws.OfflinePushInfo{}
if pb.MsgData.OfflinePushInfo != nil {
offlinePushInfo = *pb.MsgData.OfflinePushInfo
}
msgData := sdk_ws.MsgData{}
msgData = *pb.MsgData
msgData.OfflinePushInfo = &offlinePushInfo
groupPB := pbChat.SendMsgReq{Token: pb.Token, OperationID: pb.OperationID, MsgData: &msgData}
msgToMQGroup := pbChat.MsgDataToMQ{Token: pb.Token, OperationID: pb.OperationID, MsgData: &msgData}
for _, v := range list {
options := make(map[string]bool, 10)
for key, value := range pb.MsgData.Options {
options[key] = value
}
groupPB.MsgData.RecvID = v
groupPB.MsgData.Options = options
isSend := modifyMessageByUserMessageReceiveOpt(v, msgData.GroupID, constant.GroupChatType, &groupPB)
if isSend {
msgToMQGroup.MsgData = groupPB.MsgData
// log.Debug(groupPB.OperationID, "sendMsgToKafka, ", v, groupID, msgToMQGroup.String())
err := rpc.sendMsgToKafka(&msgToMQGroup, v, status)
if err != nil {
log.NewError(msgToMQGroup.OperationID, "kafka send msg err:UserId", v, msgToMQGroup.String())
} else {
*sendTag = true
}
} else {
log.Debug(groupPB.OperationID, "not sendMsgToKafka, ", v)
}
}
wg.Done()
}

View File

@@ -0,0 +1,42 @@
package msg
import (
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/log"
pbOffice "Open_IM/pkg/proto/office"
sdk "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
)
func WorkMomentSendNotification(operationID, recvID string, notificationMsg *pbOffice.WorkMomentNotificationMsg) {
log.NewInfo(operationID, utils.GetSelfFuncName(), recvID, notificationMsg)
WorkMomentNotification(operationID, recvID, recvID, notificationMsg)
}
func WorkMomentNotification(operationID, sendID, recvID string, m proto.Message) {
var tips sdk.TipsComm
var err error
marshaler := jsonpb.Marshaler{
OrigName: true,
EnumsAsInts: false,
EmitDefaults: false,
}
tips.JsonDetail, _ = marshaler.MarshalToString(m)
n := &NotificationMsg{
SendID: sendID,
RecvID: recvID,
MsgFrom: constant.UserMsgType,
ContentType: constant.WorkMomentNotification,
SessionType: constant.SingleChatType,
OperationID: operationID,
}
n.Content, err = proto.Marshal(&tips)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "proto.Marshal failed")
return
}
log.NewInfo(operationID, utils.GetSelfFuncName(), string(n.Content))
Notification(n)
}

View File

@@ -9,6 +9,7 @@ import (
imdb "Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
pbCache "Open_IM/pkg/proto/cache"
pbOffice "Open_IM/pkg/proto/office"
pbCommon "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils"
@@ -17,6 +18,7 @@ import (
"net"
"strconv"
"strings"
"sync"
"time"
)
@@ -39,22 +41,34 @@ func NewOfficeServer(port int) *officeServer {
func (s *officeServer) Run() {
log.NewInfo("0", "officeServer rpc start ")
ip := utils.ServerIP
registerAddress := ip + ":" + strconv.Itoa(s.rpcPort)
//listener network
listener, err := net.Listen("tcp", registerAddress)
if err != nil {
log.NewError("0", "Listen failed ", err.Error(), registerAddress)
return
listenIP := ""
if config.Config.ListenIP == "" {
listenIP = "0.0.0.0"
} else {
listenIP = config.Config.ListenIP
}
log.NewInfo("0", "listen network success, ", registerAddress, listener)
address := listenIP + ":" + strconv.Itoa(s.rpcPort)
//listener network
listener, err := net.Listen("tcp", address)
if err != nil {
panic("listening err:" + err.Error() + s.rpcRegisterName)
}
log.NewInfo("0", "listen network success, ", address, listener)
defer listener.Close()
//grpc server
srv := grpc.NewServer()
defer srv.GracefulStop()
//Service registers with etcd
pbOffice.RegisterOfficeServiceServer(srv, s)
err = getcdv3.RegisterEtcd(s.etcdSchema, strings.Join(s.etcdAddr, ","), ip, s.rpcPort, s.rpcRegisterName, 10)
rpcRegisterIP := ""
if config.Config.RpcRegisterIP == "" {
rpcRegisterIP, err = utils.GetLocalIP()
if err != nil {
log.Error("", "GetLocalIP failed ", err.Error())
}
}
err = getcdv3.RegisterEtcd(s.etcdSchema, strings.Join(s.etcdAddr, ","), rpcRegisterIP, s.rpcPort, s.rpcRegisterName, 10)
if err != nil {
log.NewError("0", "RegisterEtcd failed ", err.Error())
return
@@ -134,10 +148,10 @@ func (s *officeServer) DeleteTag(_ context.Context, req *pbOffice.DeleteTagReq)
func (s *officeServer) SetTag(_ context.Context, req *pbOffice.SetTagReq) (resp *pbOffice.SetTagResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.SetTagResp{CommonResp: &pbOffice.CommonResp{}}
IncreaseUserIDList := utils.RemoveRepeatedStringInList(req.IncreaseUserIDList)
increaseUserIDList := utils.RemoveRepeatedStringInList(req.IncreaseUserIDList)
reduceUserIDList := utils.RemoveRepeatedStringInList(req.ReduceUserIDList)
if err := db.DB.SetTag(req.UserID, req.TagID, req.NewName, IncreaseUserIDList, reduceUserIDList); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "SetTag failed", err.Error())
if err := db.DB.SetTag(req.UserID, req.TagID, req.NewName, increaseUserIDList, reduceUserIDList); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "SetTag failed", increaseUserIDList, reduceUserIDList, err.Error())
resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
return resp, nil
@@ -160,15 +174,29 @@ func (s *officeServer) SendMsg2Tag(_ context.Context, req *pbOffice.SendMsg2TagR
}
var groupUserIDList []string
for _, groupID := range req.GroupList {
userIDList, err := im_mysql_model.GetGroupMemberIDListByGroupID(groupID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetGroupMemberIDListByGroupID failed", err.Error())
continue
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImCacheName)
cacheClient := pbCache.NewCacheClient(etcdConn)
req := pbCache.GetGroupMemberIDListFromCacheReq{
OperationID: req.OperationID,
GroupID: groupID,
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), userIDList)
groupUserIDList = append(groupUserIDList, userIDList...)
getGroupMemberIDListFromCacheResp, err := cacheClient.GetGroupMemberIDListFromCache(context.Background(), &req)
if err != nil {
log.NewError(req.OperationID, "GetGroupMemberIDListFromCache rpc call failed ", err.Error(), req.String())
resp.CommonResp.ErrCode = constant.ErrServer.ErrCode
resp.CommonResp.ErrMsg = err.Error()
return resp, nil
}
if getGroupMemberIDListFromCacheResp.CommonResp.ErrCode != 0 {
log.NewError(req.OperationID, "GetGroupMemberIDListFromCache rpc logic call failed ", getGroupMemberIDListFromCacheResp.CommonResp.ErrCode)
resp.CommonResp.ErrCode = getGroupMemberIDListFromCacheResp.CommonResp.ErrCode
resp.CommonResp.ErrMsg = getGroupMemberIDListFromCacheResp.CommonResp.ErrMsg
return resp, nil
}
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), getGroupMemberIDListFromCacheResp.UserIDList)
groupUserIDList = append(groupUserIDList, getGroupMemberIDListFromCacheResp.UserIDList...)
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), groupUserIDList, req.GroupList)
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), groupUserIDList, req.GroupList)
var userIDList []string
userIDList = append(userIDList, tagUserIDList...)
userIDList = append(userIDList, groupUserIDList...)
@@ -179,32 +207,47 @@ func (s *officeServer) SendMsg2Tag(_ context.Context, req *pbOffice.SendMsg2TagR
userIDList = append(userIDList[:i], userIDList[i+1:]...)
}
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "total userIDList result: ", userIDList)
us, err := imdb.GetUserByUserID(req.SendID)
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "total userIDList result: ", userIDList)
user, err := imdb.GetUserByUserID(req.SendID)
if err != nil {
log.NewError(req.OperationID, "GetUserByUserID failed ", err.Error(), req.SendID)
resp.CommonResp.ErrMsg = err.Error()
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
return resp, nil
}
var wg sync.WaitGroup
wg.Add(len(userIDList))
for _, userID := range userIDList {
msg.TagSendMessage(req.OperationID, us, userID, req.Content, req.SenderPlatformID)
go func(userID string) {
defer wg.Done()
msg.TagSendMessage(req.OperationID, user, userID, req.Content, req.SenderPlatformID)
}(userID)
}
wg.Wait()
var tagSendLogs db.TagSendLog
wg.Add(len(userIDList))
for _, userID := range userIDList {
userName, err := im_mysql_model.GetUserNameByUserID(userID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserNameByUserID failed", err.Error())
continue
}
tagSendLogs.UserList = append(tagSendLogs.UserList, db.TagUser{
UserID: userID,
UserName: userName,
})
go func(userID string) {
defer wg.Done()
userName, err := im_mysql_model.GetUserNameByUserID(userID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserNameByUserID failed", err.Error())
return
}
tagSendLogs.UserList = append(tagSendLogs.UserList, db.TagUser{
UserID: userID,
UserName: userName,
})
}(userID)
}
wg.Wait()
tagSendLogs.SendID = req.SendID
tagSendLogs.Content = req.Content
tagSendLogs.SenderPlatformID = req.SenderPlatformID
tagSendLogs.SendTime = time.Now().Unix()
if err := db.DB.SaveTagSendLog(&tagSendLogs); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "SaveTagSendLog failed", err.Error())
log.NewError(req.OperationID, utils.GetSelfFuncName(), "SaveTagSendLog failed", tagSendLogs, err.Error())
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg
return resp, nil
@@ -266,3 +309,306 @@ func (s *officeServer) GetUserTagByID(_ context.Context, req *pbOffice.GetUserTa
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *officeServer) CreateOneWorkMoment(_ context.Context, req *pbOffice.CreateOneWorkMomentReq) (resp *pbOffice.CreateOneWorkMomentResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.CreateOneWorkMomentResp{CommonResp: &pbOffice.CommonResp{}}
workMoment := db.WorkMoment{
Comments: []*db.Comment{},
LikeUserList: []*db.WorkMomentUser{},
PermissionUserList: []*db.WorkMomentUser{},
}
createUser, err := imdb.GetUserByUserID(req.WorkMoment.UserID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserByUserID", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
if err := utils.CopyStructFields(&workMoment, req.WorkMoment); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
workMoment.UserName = createUser.Nickname
workMoment.FaceURL = createUser.FaceURL
workMoment.PermissionUserIDList = s.getPermissionUserIDList(req.OperationID, req.WorkMoment.PermissionGroupList, req.WorkMoment.PermissionUserList)
workMoment.PermissionUserList = []*db.WorkMomentUser{}
for _, userID := range workMoment.PermissionUserIDList {
userName, err := imdb.GetUserNameByUserID(userID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserNameByUserID failed", err.Error())
continue
}
workMoment.PermissionUserList = append(workMoment.PermissionUserList, &db.WorkMomentUser{
UserID: userID,
UserName: userName,
})
}
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "workMoment to create", workMoment)
err = db.DB.CreateOneWorkMoment(&workMoment)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "CreateOneWorkMoment", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
// send notification to at users
for _, atUser := range req.WorkMoment.AtUserList {
workMomentNotificationMsg := &pbOffice.WorkMomentNotificationMsg{
NotificationMsgType: constant.WorkMomentAtUserNotification,
WorkMomentID: workMoment.WorkMomentID,
WorkMomentContent: workMoment.Content,
UserID: workMoment.UserID,
FaceURL: createUser.FaceURL,
UserName: createUser.Nickname,
CreateTime: workMoment.CreateTime,
}
msg.WorkMomentSendNotification(req.OperationID, atUser.UserID, workMomentNotificationMsg)
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *officeServer) DeleteComment(_ context.Context, req *pbOffice.DeleteCommentReq) (resp *pbOffice.DeleteCommentResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.DeleteCommentResp{CommonResp: &pbOffice.CommonResp{}}
err = db.DB.DeleteComment(req.WorkMomentID, req.ContentID, req.OpUserID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetWorkMomentByID failed", err.Error())
resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
return resp, nil
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
// count and distinct permission users
func (s *officeServer) getPermissionUserIDList(operationID string, groupList []*pbOffice.PermissionGroup, userList []*pbOffice.WorkMomentUser) []string {
var permissionUserIDList []string
for _, group := range groupList {
groupMemberIDList, err := imdb.GetGroupMemberIDListByGroupID(group.GroupID)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "GetGroupMemberIDListByGroupID failed", group, err.Error())
continue
}
log.NewDebug(operationID, utils.GetSelfFuncName(), "groupMemberIDList: ", groupMemberIDList)
permissionUserIDList = append(permissionUserIDList, groupMemberIDList...)
}
var userIDList []string
for _, user := range userList {
userIDList = append(userIDList, user.UserID)
}
permissionUserIDList = append(permissionUserIDList, userIDList...)
permissionUserIDList = utils.RemoveRepeatedStringInList(permissionUserIDList)
return permissionUserIDList
}
func (s *officeServer) DeleteOneWorkMoment(_ context.Context, req *pbOffice.DeleteOneWorkMomentReq) (resp *pbOffice.DeleteOneWorkMomentResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.DeleteOneWorkMomentResp{CommonResp: &pbOffice.CommonResp{}}
workMoment, err := db.DB.GetWorkMomentByID(req.WorkMomentID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetWorkMomentByID failed", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "workMoment", workMoment)
if workMoment.UserID != req.UserID {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "workMoment.UserID != req.WorkMomentID, delete failed", workMoment, req.WorkMomentID)
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: constant.ErrAccess.ErrMsg}
return resp, nil
}
err = db.DB.DeleteOneWorkMoment(req.WorkMomentID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "DeleteOneWorkMoment", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func isUserCanSeeWorkMoment(userID string, workMoment db.WorkMoment) bool {
if userID != workMoment.UserID {
switch workMoment.Permission {
case constant.WorkMomentPublic:
return true
case constant.WorkMomentPrivate:
return false
case constant.WorkMomentPermissionCanSee:
return utils.IsContain(userID, workMoment.PermissionUserIDList)
case constant.WorkMomentPermissionCantSee:
return !utils.IsContain(userID, workMoment.PermissionUserIDList)
}
return false
}
return true
}
func (s *officeServer) LikeOneWorkMoment(_ context.Context, req *pbOffice.LikeOneWorkMomentReq) (resp *pbOffice.LikeOneWorkMomentResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.LikeOneWorkMomentResp{CommonResp: &pbOffice.CommonResp{}}
user, err := imdb.GetUserByUserID(req.UserID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserNameByUserID failed", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
workMoment, like, err := db.DB.LikeOneWorkMoment(req.UserID, user.Nickname, req.WorkMomentID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "LikeOneWorkMoment failed ", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
workMomentNotificationMsg := &pbOffice.WorkMomentNotificationMsg{
NotificationMsgType: constant.WorkMomentLikeNotification,
WorkMomentID: workMoment.WorkMomentID,
WorkMomentContent: workMoment.Content,
UserID: user.UserID,
FaceURL: user.FaceURL,
UserName: user.Nickname,
CreateTime: int32(time.Now().Unix()),
}
// send notification
if like && workMoment.UserID != req.UserID {
msg.WorkMomentSendNotification(req.OperationID, workMoment.UserID, workMomentNotificationMsg)
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *officeServer) CommentOneWorkMoment(_ context.Context, req *pbOffice.CommentOneWorkMomentReq) (resp *pbOffice.CommentOneWorkMomentResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.CommentOneWorkMomentResp{CommonResp: &pbOffice.CommonResp{}}
commentUser, err := imdb.GetUserByUserID(req.UserID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserNameByUserID commentUserName failed", req.UserID, err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
var replyUserName string
if req.ReplyUserID != "" {
replyUserName, err = imdb.GetUserNameByUserID(req.ReplyUserID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserNameByUserID get replyUserName failed", req.ReplyUserID, err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
}
comment := &db.Comment{
UserID: req.UserID,
UserName: commentUser.Nickname,
ReplyUserID: req.ReplyUserID,
ReplyUserName: replyUserName,
Content: req.Content,
CreateTime: int32(time.Now().Unix()),
}
workMoment, err := db.DB.CommentOneWorkMoment(comment, req.WorkMomentID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "CommentOneWorkMoment failed", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
workMomentNotificationMsg := &pbOffice.WorkMomentNotificationMsg{
NotificationMsgType: constant.WorkMomentCommentNotification,
WorkMomentID: workMoment.WorkMomentID,
WorkMomentContent: workMoment.Content,
UserID: commentUser.UserID,
FaceURL: commentUser.FaceURL,
UserName: commentUser.Nickname,
ReplyUserID: comment.ReplyUserID,
ReplyUserName: comment.ReplyUserName,
ContentID: comment.ContentID,
Content: comment.Content,
CreateTime: comment.CreateTime,
}
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "msg: ", *workMomentNotificationMsg)
if req.UserID != workMoment.UserID {
msg.WorkMomentSendNotification(req.OperationID, workMoment.UserID, workMomentNotificationMsg)
}
if req.ReplyUserID != "" && req.ReplyUserID != workMoment.UserID && req.ReplyUserID != req.UserID {
msg.WorkMomentSendNotification(req.OperationID, req.ReplyUserID, workMomentNotificationMsg)
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *officeServer) GetWorkMomentByID(_ context.Context, req *pbOffice.GetWorkMomentByIDReq) (resp *pbOffice.GetWorkMomentByIDResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.GetWorkMomentByIDResp{
WorkMoment: &pbOffice.WorkMoment{},
CommonResp: &pbOffice.CommonResp{},
}
workMoment, err := db.DB.GetWorkMomentByID(req.WorkMomentID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetWorkMomentByID failed", err.Error())
return resp, nil
}
canSee := isUserCanSeeWorkMoment(req.OpUserID, *workMoment)
log.Debug(req.OperationID, utils.GetSelfFuncName(), canSee, req.OpUserID, *workMoment)
if !canSee {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "workMoments not access to user", canSee, workMoment, req.OpUserID)
}
if err := utils.CopyStructFields(resp.WorkMoment, workMoment); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields", err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *officeServer) GetUserWorkMoments(_ context.Context, req *pbOffice.GetUserWorkMomentsReq) (resp *pbOffice.GetUserWorkMomentsResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.GetUserWorkMomentsResp{CommonResp: &pbOffice.CommonResp{}, WorkMoments: []*pbOffice.WorkMoment{}}
resp.Pagination = &pbCommon.ResponsePagination{CurrentPage: req.Pagination.PageNumber, ShowNumber: req.Pagination.ShowNumber}
var workMoments []db.WorkMoment
if req.UserID == req.OpUserID {
workMoments, err = db.DB.GetUserSelfWorkMoments(req.UserID, req.Pagination.ShowNumber, req.Pagination.PageNumber)
} else {
workMoments, err = db.DB.GetUserWorkMoments(req.OpUserID, req.UserID, req.Pagination.ShowNumber, req.Pagination.PageNumber)
}
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserWorkMoments failed", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
if err := utils.CopyStructFields(&resp.WorkMoments, workMoments); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *officeServer) GetUserFriendWorkMoments(_ context.Context, req *pbOffice.GetUserFriendWorkMomentsReq) (resp *pbOffice.GetUserFriendWorkMomentsResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.GetUserFriendWorkMomentsResp{CommonResp: &pbOffice.CommonResp{}, WorkMoments: []*pbOffice.WorkMoment{}}
resp.Pagination = &pbCommon.ResponsePagination{CurrentPage: req.Pagination.PageNumber, ShowNumber: req.Pagination.ShowNumber}
workMoments, err := db.DB.GetUserFriendWorkMoments(req.Pagination.ShowNumber, req.Pagination.PageNumber, req.UserID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserFriendWorkMoments", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
if err := utils.CopyStructFields(&resp.WorkMoments, workMoments); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *officeServer) SetUserWorkMomentsLevel(_ context.Context, req *pbOffice.SetUserWorkMomentsLevelReq) (resp *pbOffice.SetUserWorkMomentsLevelResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.SetUserWorkMomentsLevelResp{CommonResp: &pbOffice.CommonResp{}}
if err := db.DB.SetUserWorkMomentsLevel(req.UserID, req.Level); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "SetUserWorkMomentsLevel failed", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *officeServer) ChangeWorkMomentPermission(_ context.Context, req *pbOffice.ChangeWorkMomentPermissionReq) (resp *pbOffice.ChangeWorkMomentPermissionResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.ChangeWorkMomentPermissionResp{CommonResp: &pbOffice.CommonResp{}}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}

View File

@@ -0,0 +1,497 @@
package organization
import (
chat "Open_IM/internal/rpc/msg"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db"
imdb "Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
"Open_IM/pkg/proto/auth"
groupRpc "Open_IM/pkg/proto/group"
rpc "Open_IM/pkg/proto/organization"
open_im_sdk "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils"
"context"
"google.golang.org/grpc"
"net"
"strconv"
"strings"
"time"
)
type organizationServer struct {
rpcPort int
rpcRegisterName string
etcdSchema string
etcdAddr []string
}
func NewServer(port int) *organizationServer {
log.NewPrivateLog(constant.LogFileName)
return &organizationServer{
rpcPort: port,
rpcRegisterName: config.Config.RpcRegisterName.OpenImOrganizationName,
etcdSchema: config.Config.Etcd.EtcdSchema,
etcdAddr: config.Config.Etcd.EtcdAddr,
}
}
func (s *organizationServer) Run() {
log.NewInfo("", "organization rpc start ")
listenIP := ""
if config.Config.ListenIP == "" {
listenIP = "0.0.0.0"
} else {
listenIP = config.Config.ListenIP
}
address := listenIP + ":" + strconv.Itoa(s.rpcPort)
//listener network
listener, err := net.Listen("tcp", address)
if err != nil {
panic("listening err:" + err.Error() + s.rpcRegisterName)
}
log.NewInfo("", "listen network success, ", address, listener)
defer listener.Close()
//grpc server
srv := grpc.NewServer()
defer srv.GracefulStop()
//Service registers with etcd
rpc.RegisterOrganizationServer(srv, s)
rpcRegisterIP := ""
if config.Config.RpcRegisterIP == "" {
rpcRegisterIP, err = utils.GetLocalIP()
if err != nil {
log.Error("", "GetLocalIP failed ", err.Error())
}
}
err = getcdv3.RegisterEtcd(s.etcdSchema, strings.Join(s.etcdAddr, ","), rpcRegisterIP, s.rpcPort, s.rpcRegisterName, 10)
if err != nil {
log.NewError("", "RegisterEtcd failed ", err.Error())
return
}
log.NewInfo("", "organization rpc RegisterEtcd success", rpcRegisterIP, s.rpcPort, s.rpcRegisterName, 10)
err = srv.Serve(listener)
if err != nil {
log.NewError("", "Serve failed ", err.Error())
return
}
log.NewInfo("", "organization rpc success")
}
func (s *organizationServer) CreateDepartment(ctx context.Context, req *rpc.CreateDepartmentReq) (*rpc.CreateDepartmentResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc args ", req.String())
if !token_verify.IsManagerUserID(req.OpUserID) {
errMsg := req.OperationID + " " + req.OpUserID + " is not app manager"
log.Error(req.OperationID, errMsg)
return &rpc.CreateDepartmentResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: errMsg}, nil
}
department := db.Department{}
utils.CopyStructFields(&department, req.DepartmentInfo)
if department.DepartmentID == "" {
department.DepartmentID = utils.Md5(strconv.FormatInt(time.Now().UnixNano(), 10))
}
log.Debug(req.OperationID, "dst ", department, "src ", req.DepartmentInfo)
if err := imdb.CreateDepartment(&department); err != nil {
errMsg := req.OperationID + " " + "CreateDepartment failed " + err.Error()
log.Error(req.OperationID, errMsg)
return &rpc.CreateDepartmentResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg}, nil
}
err, createdDepartment := imdb.GetDepartment(department.DepartmentID)
if err != nil {
errMsg := req.OperationID + " " + "GetDepartment failed " + err.Error() + department.DepartmentID
log.Error(req.OperationID, errMsg)
return &rpc.CreateDepartmentResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg}, nil
}
log.Debug(req.OperationID, "GetDepartment ", department.DepartmentID, *createdDepartment)
resp := &rpc.CreateDepartmentResp{DepartmentInfo: &open_im_sdk.Department{}}
utils.CopyStructFields(resp.DepartmentInfo, createdDepartment)
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc return ", *resp)
chat.OrganizationNotificationToAll(req.OpUserID, req.OperationID)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := groupRpc.NewGroupClient(etcdConn)
createGroupReq := &groupRpc.CreateGroupReq{
InitMemberList: nil,
GroupInfo: &open_im_sdk.GroupInfo{
GroupName: req.DepartmentInfo.Name,
FaceURL: req.DepartmentInfo.FaceURL,
CreateTime: uint32(time.Now().Unix()),
CreatorUserID: req.OpUserID,
GroupType: constant.DepartmentGroup,
},
OperationID: req.OperationID,
OpUserID: req.OpUserID,
}
createGroupResp, err := client.CreateGroup(context.Background(), createGroupReq)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "CreateGroup rpc failed", createGroupReq, err.Error())
resp.ErrCode = constant.ErrDB.ErrCode
resp.ErrMsg = constant.ErrDB.ErrMsg + " createGroup failed " + err.Error()
return resp, nil
}
if createGroupResp.ErrCode != 0 {
log.NewError(req.OperationID, utils.GetSelfFuncName(), resp)
resp.ErrCode = constant.ErrDB.ErrCode
resp.ErrMsg = constant.ErrDB.ErrMsg + " createGroup failed " + createGroupResp.ErrMsg
return resp, nil
}
return resp, nil
}
func (s *organizationServer) UpdateDepartment(ctx context.Context, req *rpc.UpdateDepartmentReq) (*rpc.UpdateDepartmentResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc args ", req.String())
if !token_verify.IsManagerUserID(req.OpUserID) {
errMsg := req.OperationID + " " + req.OpUserID + " is not app manager"
log.Error(req.OperationID, errMsg)
return &rpc.UpdateDepartmentResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: errMsg}, nil
}
department := db.Department{}
utils.CopyStructFields(&department, req.DepartmentInfo)
log.Debug(req.OperationID, "dst ", department, "src ", req.DepartmentInfo)
if err := imdb.UpdateDepartment(&department, nil); err != nil {
errMsg := req.OperationID + " " + "UpdateDepartment failed " + err.Error()
log.Error(req.OperationID, errMsg)
return &rpc.UpdateDepartmentResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg}, nil
}
resp := &rpc.UpdateDepartmentResp{}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc return ", *resp)
chat.OrganizationNotificationToAll(req.OpUserID, req.OperationID)
return resp, nil
}
func (s *organizationServer) GetSubDepartment(ctx context.Context, req *rpc.GetSubDepartmentReq) (*rpc.GetSubDepartmentResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc args ", req.String())
err, departmentList := imdb.GetSubDepartmentList(req.DepartmentID)
if err != nil {
errMsg := req.OperationID + " " + "GetDepartment failed " + err.Error()
log.Error(req.OperationID, errMsg)
return &rpc.GetSubDepartmentResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg}, nil
}
log.Debug(req.OperationID, "GetSubDepartmentList ", req.DepartmentID, departmentList)
resp := &rpc.GetSubDepartmentResp{}
for _, v := range departmentList {
v1 := open_im_sdk.Department{}
utils.CopyStructFields(&v1, v)
log.Debug(req.OperationID, "src ", v, "dst ", v1)
err, v1.MemberNum = imdb.GetDepartmentMemberNum(v1.DepartmentID)
if err != nil {
log.Error(req.OperationID, "GetDepartmentMemberNum failed ", err.Error(), v1.DepartmentID)
continue
}
err, v1.SubDepartmentNum = imdb.GetSubDepartmentNum(v1.DepartmentID)
if err != nil {
log.Error(req.OperationID, "GetSubDepartmentNum failed ", err.Error(), v1.DepartmentID)
continue
}
resp.DepartmentList = append(resp.DepartmentList, &v1)
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc return ", *resp)
return resp, nil
}
func (s *organizationServer) DeleteDepartment(ctx context.Context, req *rpc.DeleteDepartmentReq) (*rpc.DeleteDepartmentResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc args ", req.String())
if !token_verify.IsManagerUserID(req.OpUserID) {
errMsg := req.OperationID + " " + req.OpUserID + " is not app manager"
log.Error(req.OperationID, errMsg)
return &rpc.DeleteDepartmentResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: errMsg}, nil
}
err := imdb.DeleteDepartment(req.DepartmentID)
if err != nil {
errMsg := req.OperationID + " " + "DeleteDepartment failed " + err.Error()
log.Error(req.OperationID, errMsg, req.DepartmentID)
return &rpc.DeleteDepartmentResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg}, nil
}
log.Debug(req.OperationID, "DeleteDepartment ", req.DepartmentID)
resp := &rpc.DeleteDepartmentResp{}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc return ", resp)
chat.OrganizationNotificationToAll(req.OpUserID, req.OperationID)
return resp, nil
}
func (s *organizationServer) CreateOrganizationUser(ctx context.Context, req *rpc.CreateOrganizationUserReq) (*rpc.CreateOrganizationUserResp, error) {
authReq := &pbAuth.UserRegisterReq{UserInfo: &open_im_sdk.UserInfo{}}
utils.CopyStructFields(authReq.UserInfo, req.OrganizationUser)
authReq.OperationID = req.OperationID
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImAuthName)
client := pbAuth.NewAuthClient(etcdConn)
reply, err := client.UserRegister(context.Background(), authReq)
if err != nil {
errMsg := "UserRegister failed " + err.Error()
log.NewError(req.OperationID, errMsg)
return &rpc.CreateOrganizationUserResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg}, nil
}
if reply.CommonResp.ErrCode != 0 {
errMsg := "UserRegister failed " + reply.CommonResp.ErrMsg
log.NewError(req.OperationID, errMsg)
return &rpc.CreateOrganizationUserResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg}, nil
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc args ", req.String())
if !token_verify.IsManagerUserID(req.OpUserID) {
errMsg := req.OperationID + " " + req.OpUserID + " is not app manager"
log.Error(req.OperationID, errMsg)
return &rpc.CreateOrganizationUserResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: errMsg}, nil
}
organizationUser := db.OrganizationUser{}
utils.CopyStructFields(&organizationUser, req.OrganizationUser)
organizationUser.Birth = utils.UnixSecondToTime(int64(req.OrganizationUser.Birth))
log.Debug(req.OperationID, "src ", *req.OrganizationUser, "dst ", organizationUser)
err = imdb.CreateOrganizationUser(&organizationUser)
if err != nil {
errMsg := req.OperationID + " " + "CreateOrganizationUser failed " + err.Error()
log.Error(req.OperationID, errMsg, organizationUser)
return &rpc.CreateOrganizationUserResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg}, nil
}
log.Debug(req.OperationID, "CreateOrganizationUser ", organizationUser)
resp := &rpc.CreateOrganizationUserResp{}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc return ", *resp)
chat.OrganizationNotificationToAll(req.OpUserID, req.OperationID)
return resp, nil
}
func (s *organizationServer) UpdateOrganizationUser(ctx context.Context, req *rpc.UpdateOrganizationUserReq) (*rpc.UpdateOrganizationUserResp, error) {
authReq := &pbAuth.UserRegisterReq{UserInfo: &open_im_sdk.UserInfo{}}
utils.CopyStructFields(authReq.UserInfo, req.OrganizationUser)
authReq.OperationID = req.OperationID
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImAuthName)
client := pbAuth.NewAuthClient(etcdConn)
reply, err := client.UserRegister(context.Background(), authReq)
if err != nil {
errMsg := "UserRegister failed " + err.Error()
log.NewError(req.OperationID, errMsg)
return &rpc.UpdateOrganizationUserResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg}, nil
}
if reply.CommonResp.ErrCode != 0 {
errMsg := "UserRegister failed " + reply.CommonResp.ErrMsg
log.NewError(req.OperationID, errMsg)
return &rpc.UpdateOrganizationUserResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg}, nil
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc args ", req.String())
if !token_verify.IsManagerUserID(req.OpUserID) {
errMsg := req.OperationID + " " + req.OpUserID + " is not app manager"
log.Error(req.OperationID, errMsg)
return &rpc.UpdateOrganizationUserResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: errMsg}, nil
}
organizationUser := db.OrganizationUser{}
utils.CopyStructFields(&organizationUser, req.OrganizationUser)
if req.OrganizationUser.Birth != 0 {
organizationUser.Birth = utils.UnixSecondToTime(int64(req.OrganizationUser.Birth))
log.Debug(req.OperationID, "time: ", organizationUser.Birth, req.OrganizationUser.Birth)
}
log.Debug(req.OperationID, "src ", *req.OrganizationUser, "dst ", organizationUser)
err = imdb.UpdateOrganizationUser(&organizationUser, nil)
if err != nil {
errMsg := req.OperationID + " " + "CreateOrganizationUser failed " + err.Error()
log.Error(req.OperationID, errMsg, organizationUser)
return &rpc.UpdateOrganizationUserResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg}, nil
}
log.Debug(req.OperationID, "UpdateOrganizationUser ", organizationUser)
resp := &rpc.UpdateOrganizationUserResp{}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc return ", resp)
chat.OrganizationNotificationToAll(req.OpUserID, req.OperationID)
return resp, nil
}
func (s *organizationServer) CreateDepartmentMember(ctx context.Context, req *rpc.CreateDepartmentMemberReq) (*rpc.CreateDepartmentMemberResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc args ", req.String())
if !token_verify.IsManagerUserID(req.OpUserID) {
errMsg := req.OperationID + " " + req.OpUserID + " is not app manager"
log.Error(req.OperationID, errMsg)
return &rpc.CreateDepartmentMemberResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: errMsg}, nil
}
err, _ := imdb.GetOrganizationUser(req.DepartmentMember.UserID)
if err != nil {
errMsg := req.OperationID + " " + req.DepartmentMember.UserID + " is not exist"
log.Error(req.OperationID, errMsg)
return &rpc.CreateDepartmentMemberResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: errMsg}, nil
}
departmentMember := db.DepartmentMember{}
utils.CopyStructFields(&departmentMember, req.DepartmentMember)
log.Debug(req.OperationID, "src ", *req.DepartmentMember, "dst ", departmentMember)
err = imdb.CreateDepartmentMember(&departmentMember)
if err != nil {
errMsg := req.OperationID + " " + "CreateDepartmentMember failed " + err.Error()
log.Error(req.OperationID, errMsg, departmentMember)
return &rpc.CreateDepartmentMemberResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg}, nil
}
log.Debug(req.OperationID, "UpdateOrganizationUser ", departmentMember)
resp := &rpc.CreateDepartmentMemberResp{}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc return ", *resp)
chat.OrganizationNotificationToAll(req.OpUserID, req.OperationID)
return resp, nil
}
func (s *organizationServer) GetDepartmentParentIDList(_ context.Context, req *rpc.GetDepartmentParentIDListReq) (resp *rpc.GetDepartmentParentIDListResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req:", req.String())
resp = &rpc.GetDepartmentParentIDListResp{}
resp.ParentIDList, err = imdb.GetDepartmentParentIDList(req.DepartmentID)
if err != nil {
resp.ErrMsg = constant.ErrDB.ErrMsg + ": " + err.Error()
resp.ErrCode = constant.ErrDB.ErrCode
return resp, nil
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp:", resp.String())
return resp, nil
}
func (s *organizationServer) GetUserInDepartmentByUserID(userID string, operationID string) (*open_im_sdk.UserInDepartment, error) {
err, organizationUser := imdb.GetOrganizationUser(userID)
if err != nil {
return nil, utils.Wrap(err, "GetOrganizationUser failed")
}
err, departmentMemberList := imdb.GetUserInDepartment(userID)
if err != nil {
return nil, utils.Wrap(err, "GetUserInDepartment failed")
}
log.Debug(operationID, "GetUserInDepartment ", departmentMemberList)
resp := &open_im_sdk.UserInDepartment{OrganizationUser: &open_im_sdk.OrganizationUser{}}
utils.CopyStructFields(resp.OrganizationUser, organizationUser)
for _, v := range departmentMemberList {
v1 := open_im_sdk.DepartmentMember{}
utils.CopyStructFields(&v1, v)
log.Debug(operationID, "DepartmentMember src ", v, "dst ", v1)
resp.DepartmentMemberList = append(resp.DepartmentMemberList, &v1)
}
return resp, nil
}
func (s *organizationServer) GetUserInDepartment(ctx context.Context, req *rpc.GetUserInDepartmentReq) (*rpc.GetUserInDepartmentResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc args ", req.String())
r, err := s.GetUserInDepartmentByUserID(req.UserID, req.OperationID)
if err != nil {
errMsg := req.OperationID + " " + "GetUserInDepartmentByUserID failed " + err.Error()
log.Error(req.OperationID, errMsg, req.UserID)
return &rpc.GetUserInDepartmentResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg}, nil
}
log.Debug(req.OperationID, "GetUserInDepartmentByUserID success ", req.UserID, r)
resp := rpc.GetUserInDepartmentResp{UserInDepartment: &open_im_sdk.UserInDepartment{OrganizationUser: &open_im_sdk.OrganizationUser{}}}
resp.UserInDepartment.DepartmentMemberList = r.DepartmentMemberList
resp.UserInDepartment.OrganizationUser = r.OrganizationUser
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc return ", resp)
return &resp, nil
}
func (s *organizationServer) UpdateUserInDepartment(ctx context.Context, req *rpc.UpdateUserInDepartmentReq) (*rpc.UpdateUserInDepartmentResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc args ", req.String())
if !token_verify.IsManagerUserID(req.OpUserID) {
errMsg := req.OperationID + " " + req.OpUserID + " is not app manager"
log.Error(req.OperationID, errMsg)
return &rpc.UpdateUserInDepartmentResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: errMsg}, nil
}
departmentMember := &db.DepartmentMember{}
utils.CopyStructFields(departmentMember, req.DepartmentMember)
log.Debug(req.OperationID, "dst ", departmentMember, "src ", req.DepartmentMember)
err := imdb.UpdateUserInDepartment(departmentMember, nil)
if err != nil {
errMsg := req.OperationID + " " + "UpdateUserInDepartment failed " + err.Error()
log.Error(req.OperationID, errMsg, *departmentMember)
return &rpc.UpdateUserInDepartmentResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg}, nil
}
resp := &rpc.UpdateUserInDepartmentResp{}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc return ", *resp)
chat.OrganizationNotificationToAll(req.OpUserID, req.OperationID)
return resp, nil
}
func (s *organizationServer) DeleteUserInDepartment(ctx context.Context, req *rpc.DeleteUserInDepartmentReq) (*rpc.DeleteUserInDepartmentResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc args ", req.String())
if !token_verify.IsManagerUserID(req.OpUserID) {
errMsg := req.OperationID + " " + req.OpUserID + " is not app manager"
log.Error(req.OperationID, errMsg)
return &rpc.DeleteUserInDepartmentResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: errMsg}, nil
}
err := imdb.DeleteUserInDepartment(req.DepartmentID, req.UserID)
if err != nil {
errMsg := req.OperationID + " " + "DeleteUserInDepartment failed " + err.Error()
log.Error(req.OperationID, errMsg, req.DepartmentID, req.UserID)
return &rpc.DeleteUserInDepartmentResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg}, nil
}
log.Debug(req.OperationID, "DeleteUserInDepartment success ", req.DepartmentID, req.UserID)
resp := &rpc.DeleteUserInDepartmentResp{}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc return ", *resp)
chat.OrganizationNotificationToAll(req.OpUserID, req.OperationID)
return resp, nil
}
func (s *organizationServer) DeleteOrganizationUser(ctx context.Context, req *rpc.DeleteOrganizationUserReq) (*rpc.DeleteOrganizationUserResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc args ", req.String())
if !token_verify.IsManagerUserID(req.OpUserID) {
errMsg := req.OperationID + " " + req.OpUserID + " is not app manager"
log.Error(req.OperationID, errMsg)
return &rpc.DeleteOrganizationUserResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: errMsg}, nil
}
err := imdb.DeleteOrganizationUser(req.UserID)
if err != nil {
errMsg := req.OperationID + " " + "DeleteOrganizationUser failed " + err.Error()
log.Error(req.OperationID, errMsg, req.UserID)
return &rpc.DeleteOrganizationUserResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg}, nil
}
log.Debug(req.OperationID, "DeleteOrganizationUser success ", req.UserID)
resp := &rpc.DeleteOrganizationUserResp{}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc return ", *resp)
chat.OrganizationNotificationToAll(req.OpUserID, req.OperationID)
return resp, nil
}
func (s *organizationServer) GetDepartmentMember(ctx context.Context, req *rpc.GetDepartmentMemberReq) (*rpc.GetDepartmentMemberResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc args ", req.String())
err, departmentMemberList := imdb.GetDepartmentMemberList(req.DepartmentID)
if err != nil {
errMsg := req.OperationID + " " + req.OpUserID + " is not app manager"
log.Error(req.OperationID, errMsg)
return &rpc.GetDepartmentMemberResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: errMsg}, nil
}
log.Debug(req.OperationID, "GetDepartmentMemberList ", departmentMemberList)
resp := rpc.GetDepartmentMemberResp{}
for _, v := range departmentMemberList {
err, organizationUser := imdb.GetOrganizationUser(v.UserID)
if err != nil {
log.Error(req.OperationID, "GetOrganizationUser failed ", err.Error())
continue
}
respOrganizationUser := &open_im_sdk.OrganizationUser{}
respDepartmentMember := &open_im_sdk.DepartmentMember{}
utils.CopyStructFields(respOrganizationUser, organizationUser)
utils.CopyStructFields(respDepartmentMember, &v)
userDepartmentMember := open_im_sdk.UserDepartmentMember{OrganizationUser: respOrganizationUser, DepartmentMember: respDepartmentMember}
log.Debug(req.OperationID, "GetUserInDepartmentByUserID success ", userDepartmentMember)
resp.UserDepartmentMemberList = append(resp.UserDepartmentMemberList, &userDepartmentMember)
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc return ", resp)
return &resp, nil
}
func (s *organizationServer) GetDepartmentRelatedGroupIDList(ctx context.Context, req *rpc.GetDepartmentRelatedGroupIDListReq) (resp *rpc.GetDepartmentRelatedGroupIDListResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &rpc.GetDepartmentRelatedGroupIDListResp{}
groupIDList, err := imdb.GetDepartmentRelatedGroupIDList(req.DepartmentIDList)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error())
resp.ErrMsg = constant.ErrDB.ErrMsg + " GetDepartMentRelatedGroupIDList failed " + err.Error()
resp.ErrCode = constant.ErrDB.ErrCode
return resp, nil
}
resp.GroupIDList = groupIDList
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}

View File

@@ -4,6 +4,7 @@ import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"context"
"strconv"
"sync"
"time"
@@ -21,7 +22,6 @@ import (
//"context"
errors "Open_IM/pkg/common/http"
"net"
"strconv"
"strings"
"google.golang.org/grpc"
@@ -46,22 +46,35 @@ func NewStatisticsServer(port int) *statisticsServer {
func (s *statisticsServer) Run() {
log.NewInfo("0", "Statistics rpc start ")
ip := utils.ServerIP
registerAddress := ip + ":" + strconv.Itoa(s.rpcPort)
//listener network
listener, err := net.Listen("tcp", registerAddress)
if err != nil {
log.NewError("0", "Listen failed ", err.Error(), registerAddress)
return
listenIP := ""
if config.Config.ListenIP == "" {
listenIP = "0.0.0.0"
} else {
listenIP = config.Config.ListenIP
}
log.NewInfo("0", "listen network success, ", registerAddress, listener)
address := listenIP + ":" + strconv.Itoa(s.rpcPort)
//listener network
listener, err := net.Listen("tcp", address)
if err != nil {
panic("listening err:" + err.Error() + s.rpcRegisterName)
}
log.NewInfo("0", "listen network success, ", address, listener)
defer listener.Close()
//grpc server
srv := grpc.NewServer()
defer srv.GracefulStop()
//Service registers with etcd
pbStatistics.RegisterUserServer(srv, s)
err = getcdv3.RegisterEtcd(s.etcdSchema, strings.Join(s.etcdAddr, ","), ip, s.rpcPort, s.rpcRegisterName, 10)
rpcRegisterIP := ""
if config.Config.RpcRegisterIP == "" {
rpcRegisterIP, err = utils.GetLocalIP()
if err != nil {
log.Error("", "GetLocalIP failed ", err.Error())
}
}
err = getcdv3.RegisterEtcd(s.etcdSchema, strings.Join(s.etcdAddr, ","), rpcRegisterIP, s.rpcPort, s.rpcRegisterName, 10)
if err != nil {
log.NewError("0", "RegisterEtcd failed ", err.Error())
return
@@ -75,13 +88,14 @@ func (s *statisticsServer) Run() {
}
func (s *statisticsServer) GetActiveGroup(_ context.Context, req *pbStatistics.GetActiveGroupReq) (*pbStatistics.GetActiveGroupResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), req.String())
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req", req.String())
resp := &pbStatistics.GetActiveGroupResp{}
fromTime, toTime, err := ParseTimeFromTo(req.StatisticsReq.From, req.StatisticsReq.To)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "ParseTimeFromTo failed", err.Error())
return resp, errors.WrapError(constant.ErrArgs)
}
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "time: ", fromTime, toTime)
activeGroups, err := imdb.GetActiveGroups(fromTime, toTime, 12)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetActiveGroups failed", err.Error())
@@ -95,6 +109,7 @@ func (s *statisticsServer) GetActiveGroup(_ context.Context, req *pbStatistics.G
MessageNum: int32(activeGroup.MessageNum),
})
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), resp.String())
return resp, nil
}
@@ -106,6 +121,7 @@ func (s *statisticsServer) GetActiveUser(_ context.Context, req *pbStatistics.Ge
log.NewError(req.OperationID, utils.GetSelfFuncName(), "ParseTimeFromTo failed", err.Error())
return resp, errors.WrapError(constant.ErrDB)
}
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "time: ", fromTime, toTime)
activeUsers, err := imdb.GetActiveUsers(fromTime, toTime, 12)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetActiveUsers failed", err.Error())
@@ -120,6 +136,7 @@ func (s *statisticsServer) GetActiveUser(_ context.Context, req *pbStatistics.Ge
},
)
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), resp.String())
return resp, nil
}
@@ -219,7 +236,7 @@ func (s *statisticsServer) GetGroupStatistics(_ context.Context, req *pbStatisti
}
increaseGroupNum, err := imdb.GetIncreaseGroupNum(fromTime, toTime.Add(time.Hour*24))
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetIncreaseGroupNum failed", err.Error())
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetIncreaseGroupNum failed", err.Error(), fromTime, toTime)
return resp, errors.WrapError(constant.ErrDB)
}
totalGroupNum, err := imdb.GetTotalGroupNum()
@@ -230,7 +247,7 @@ func (s *statisticsServer) GetGroupStatistics(_ context.Context, req *pbStatisti
resp.IncreaseGroupNum = increaseGroupNum
resp.TotalGroupNum = totalGroupNum
times := GetRangeDate(fromTime, toTime)
log.NewInfo(req.OperationID, "times:", times)
log.NewDebug(req.OperationID, "times:", times)
wg := &sync.WaitGroup{}
resp.IncreaseGroupNumList = make([]*pbStatistics.DateNumList, len(times), len(times))
resp.TotalGroupNumList = make([]*pbStatistics.DateNumList, len(times), len(times))
@@ -257,6 +274,7 @@ func (s *statisticsServer) GetGroupStatistics(_ context.Context, req *pbStatisti
}(wg, i, v)
}
wg.Wait()
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
return resp, nil
}
@@ -264,6 +282,7 @@ func (s *statisticsServer) GetMessageStatistics(_ context.Context, req *pbStatis
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), req.String())
resp := &pbStatistics.GetMessageStatisticsResp{}
fromTime, toTime, err := ParseTimeFromTo(req.StatisticsReq.From, req.StatisticsReq.To)
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "times: ", fromTime, toTime)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "ParseTimeFromTo failed", err.Error())
return resp, errors.WrapError(constant.ErrArgs)
@@ -278,6 +297,7 @@ func (s *statisticsServer) GetMessageStatistics(_ context.Context, req *pbStatis
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetGroupMessageNum failed", err.Error())
return resp, errors.WrapError(constant.ErrDB)
}
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), privateMessageNum, groupMessageNum)
resp.PrivateMessageNum = privateMessageNum
resp.GroupMessageNum = groupMessageNum
times := GetRangeDate(fromTime, toTime)
@@ -312,7 +332,7 @@ func (s *statisticsServer) GetMessageStatistics(_ context.Context, req *pbStatis
}
func (s *statisticsServer) GetUserStatistics(_ context.Context, req *pbStatistics.GetUserStatisticsReq) (*pbStatistics.GetUserStatisticsResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), req.String())
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp := &pbStatistics.GetUserStatisticsResp{}
fromTime, toTime, err := ParseTimeFromTo(req.StatisticsReq.From, req.StatisticsReq.To)
if err != nil {
@@ -374,5 +394,6 @@ func (s *statisticsServer) GetUserStatistics(_ context.Context, req *pbStatistic
}(wg, i, v)
}
wg.Wait()
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
return resp, nil
}

View File

@@ -16,7 +16,6 @@ import (
pbUser "Open_IM/pkg/proto/user"
"Open_IM/pkg/utils"
"context"
"fmt"
"net"
"strconv"
"strings"
@@ -42,26 +41,38 @@ func NewUserServer(port int) *userServer {
}
func (s *userServer) Run() {
log.NewInfo("0", "", "rpc user start...")
log.NewInfo("0", "rpc user start...")
ip := utils.ServerIP
registerAddress := ip + ":" + strconv.Itoa(s.rpcPort)
//listener network
listener, err := net.Listen("tcp", registerAddress)
if err != nil {
log.NewError("0", "listen network failed ", err.Error(), registerAddress)
return
listenIP := ""
if config.Config.ListenIP == "" {
listenIP = "0.0.0.0"
} else {
listenIP = config.Config.ListenIP
}
log.NewInfo("0", "listen network success, address ", registerAddress, listener)
address := listenIP + ":" + strconv.Itoa(s.rpcPort)
//listener network
listener, err := net.Listen("tcp", address)
if err != nil {
panic("listening err:" + err.Error() + s.rpcRegisterName)
}
log.NewInfo("0", "listen network success, address ", address, listener)
defer listener.Close()
//grpc server
srv := grpc.NewServer()
defer srv.GracefulStop()
//Service registers with etcd
pbUser.RegisterUserServer(srv, s)
err = getcdv3.RegisterEtcd(s.etcdSchema, strings.Join(s.etcdAddr, ","), ip, s.rpcPort, s.rpcRegisterName, 10)
rpcRegisterIP := ""
if config.Config.RpcRegisterIP == "" {
rpcRegisterIP, err = utils.GetLocalIP()
if err != nil {
log.Error("", "GetLocalIP failed ", err.Error())
}
}
err = getcdv3.RegisterEtcd(s.etcdSchema, strings.Join(s.etcdAddr, ","), rpcRegisterIP, s.rpcPort, s.rpcRegisterName, 10)
if err != nil {
log.NewError("0", "RegisterEtcd failed ", err.Error(), s.etcdSchema, strings.Join(s.etcdAddr, ","), ip, s.rpcPort, s.rpcRegisterName)
log.NewError("0", "RegisterEtcd failed ", err.Error(), s.etcdSchema, strings.Join(s.etcdAddr, ","), rpcRegisterIP, s.rpcPort, s.rpcRegisterName)
return
}
err = srv.Serve(listener)
@@ -75,7 +86,7 @@ func (s *userServer) Run() {
func syncPeerUserConversation(conversation *pbUser.Conversation, operationID string) error {
peerUserConversation := db.Conversation{
OwnerUserID: conversation.UserID,
ConversationID: "single_" + conversation.OwnerUserID,
ConversationID: utils.GetConversationIDBySessionType(conversation.OwnerUserID, constant.SingleChatType),
ConversationType: constant.SingleChatType,
UserID: conversation.OwnerUserID,
GroupID: "",
@@ -129,6 +140,7 @@ func (s *userServer) BatchSetConversations(ctx context.Context, req *pbUser.Batc
if err := utils.CopyStructFields(&conversation, v); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), v.String(), "CopyStructFields failed", err.Error())
}
//redis op
if err := db.DB.SetSingleConversationRecvMsgOpt(req.OwnerUserID, v.ConversationID, v.RecvMsgOpt); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "cache failed, rpc return", err.Error())
resp.CommonResp = &pbUser.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
@@ -157,6 +169,7 @@ func (s *userServer) GetAllConversations(ctx context.Context, req *pbUser.GetAll
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp := &pbUser.GetAllConversationsResp{Conversations: []*pbUser.Conversation{}}
conversations, err := imdb.GetUserAllConversations(req.OwnerUserID)
log.NewDebug(req.OperationID, "conversations: ", conversations)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetConversations error", err.Error())
resp.CommonResp = &pbUser.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
@@ -174,6 +187,7 @@ func (s *userServer) GetConversation(ctx context.Context, req *pbUser.GetConvers
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp := &pbUser.GetConversationResp{Conversation: &pbUser.Conversation{}}
conversation, err := imdb.GetConversation(req.OwnerUserID, req.ConversationID)
log.NewDebug("", utils.GetSelfFuncName(), "conversation", conversation)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetConversation error", err.Error())
resp.CommonResp = &pbUser.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
@@ -191,6 +205,7 @@ func (s *userServer) GetConversations(ctx context.Context, req *pbUser.GetConver
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp := &pbUser.GetConversationsResp{Conversations: []*pbUser.Conversation{}}
conversations, err := imdb.GetConversations(req.OwnerUserID, req.ConversationIDs)
log.NewDebug("", utils.GetSelfFuncName(), "conversations", conversations)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetConversations error", err.Error())
resp.CommonResp = &pbUser.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
@@ -206,10 +221,24 @@ func (s *userServer) GetConversations(ctx context.Context, req *pbUser.GetConver
func (s *userServer) SetConversation(ctx context.Context, req *pbUser.SetConversationReq) (*pbUser.SetConversationResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp := &pbUser.SetConversationResp{}
if req.NotificationType == 0 {
req.NotificationType = constant.ConversationOptChangeNotification
}
resp := &pbUser.SetConversationResp{}
if req.Conversation.ConversationType == constant.GroupChatType {
groupInfo, err := imdb.GetGroupInfoByGroupID(req.Conversation.GroupID)
if err != nil {
log.NewError(req.OperationID, "GetGroupInfoByGroupID failed ", req.Conversation.GroupID, err.Error())
resp.CommonResp = &pbUser.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
if groupInfo.Status == constant.GroupStatusDismissed && !req.Conversation.IsNotInGroup {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "group status is dismissed", groupInfo)
errMsg := "group status is dismissed"
resp.CommonResp = &pbUser.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg}
return resp, nil
}
}
var conversation db.Conversation
if err := utils.CopyStructFields(&conversation, req.Conversation); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", *req.Conversation, err.Error())
@@ -278,8 +307,8 @@ func (s *userServer) SetRecvMsgOpt(ctx context.Context, req *pbUser.SetRecvMsgOp
func (s *userServer) DeleteUsers(_ context.Context, req *pbUser.DeleteUsersReq) (*pbUser.DeleteUsersResp, error) {
log.NewInfo(req.OperationID, "DeleteUsers args ", req.String())
if !token_verify.IsMangerUserID(req.OpUserID) {
log.NewError(req.OperationID, "IsMangerUserID false ", req.OpUserID)
if !token_verify.IsManagerUserID(req.OpUserID) {
log.NewError(req.OperationID, "IsManagerUserID false ", req.OpUserID)
return &pbUser.DeleteUsersResp{CommonResp: &pbUser.CommonResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: constant.ErrAccess.ErrMsg}, FailedUserIDList: req.DeleteUserIDList}, nil
}
var common pbUser.CommonResp
@@ -299,8 +328,8 @@ func (s *userServer) DeleteUsers(_ context.Context, req *pbUser.DeleteUsersReq)
func (s *userServer) GetAllUserID(_ context.Context, req *pbUser.GetAllUserIDReq) (*pbUser.GetAllUserIDResp, error) {
log.NewInfo(req.OperationID, "GetAllUserID args ", req.String())
if !token_verify.IsMangerUserID(req.OpUserID) {
log.NewError(req.OperationID, "IsMangerUserID false ", req.OpUserID)
if !token_verify.IsManagerUserID(req.OpUserID) {
log.NewError(req.OperationID, "IsManagerUserID false ", req.OpUserID)
return &pbUser.GetAllUserIDResp{CommonResp: &pbUser.CommonResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: constant.ErrAccess.ErrMsg}}, nil
}
uidList, err := imdb.SelectAllUserID()
@@ -315,8 +344,8 @@ func (s *userServer) GetAllUserID(_ context.Context, req *pbUser.GetAllUserIDReq
func (s *userServer) AccountCheck(_ context.Context, req *pbUser.AccountCheckReq) (*pbUser.AccountCheckResp, error) {
log.NewInfo(req.OperationID, "AccountCheck args ", req.String())
if !token_verify.IsMangerUserID(req.OpUserID) {
log.NewError(req.OperationID, "IsMangerUserID false ", req.OpUserID)
if !token_verify.IsManagerUserID(req.OpUserID) {
log.NewError(req.OperationID, "IsManagerUserID false ", req.OpUserID)
return &pbUser.AccountCheckResp{CommonResp: &pbUser.CommonResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: constant.ErrAccess.ErrMsg}}, nil
}
uidList, err := imdb.SelectSomeUserID(req.CheckUserIDList)
@@ -375,11 +404,29 @@ func (s *userServer) UpdateUserInfo(ctx context.Context, req *pbUser.UpdateUserI
log.Info(req.OperationID, "UserInfoUpdatedNotification ", req.UserInfo.UserID, v.FriendUser.UserID)
chat.UserInfoUpdatedNotification(req.OperationID, req.UserInfo.UserID, v.FriendUser.UserID)
}
chat.UserInfoUpdatedNotification(req.OperationID, req.UserInfo.UserID, req.OpUserID)
log.Info(req.OperationID, "UserInfoUpdatedNotification ", req.UserInfo.UserID, req.OpUserID)
if req.UserInfo.FaceURL != "" {
go s.SyncJoinedGroupMemberFaceURL(req.UserInfo.UserID, req.UserInfo.FaceURL, req.OperationID, req.OpUserID)
}
return &pbUser.UpdateUserInfoResp{CommonResp: &pbUser.CommonResp{}}, nil
}
func (s *userServer) SyncJoinedGroupMemberFaceURL(userID string, faceURL string, operationID string, opUserID string) {
joinedGroupIDList, err := imdb.GetJoinedGroupIDListByUserID(userID)
if err != nil {
log.NewWarn(operationID, "GetJoinedGroupIDListByUserID failed ", userID, err.Error())
return
}
for _, v := range joinedGroupIDList {
groupMemberInfo := db.GroupMember{UserID: userID, GroupID: v, FaceURL: faceURL}
imdb.UpdateGroupMemberInfo(groupMemberInfo)
chat.GroupMemberInfoSetNotification(operationID, opUserID, v, userID)
}
}
func (s *userServer) GetUsersByName(ctx context.Context, req *pbUser.GetUsersByNameReq) (*pbUser.GetUsersByNameResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req:", req.String())
resp := &pbUser.GetUsersByNameResp{}
@@ -413,6 +460,7 @@ func (s *userServer) GetUsersByName(ctx context.Context, req *pbUser.GetUsersByN
CurrentPage: req.Pagination.PageNumber,
ShowNumber: req.Pagination.ShowNumber,
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
return resp, nil
}
@@ -436,6 +484,7 @@ func (s *userServer) GetUserById(ctx context.Context, req *pbUser.GetUserByIdReq
CreateTime: user.CreateTime.String(),
IsBlock: isBlock,
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
@@ -444,6 +493,7 @@ func (s *userServer) GetUsers(ctx context.Context, req *pbUser.GetUsersReq) (*pb
resp := &pbUser.GetUsersResp{User: []*pbUser.User{}}
users, err := imdb.GetUsers(req.Pagination.ShowNumber, req.Pagination.PageNumber)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUsers failed", err.Error())
return resp, errors.WrapError(constant.ErrDB)
}
for _, v := range users {
@@ -457,16 +507,19 @@ func (s *userServer) GetUsers(ctx context.Context, req *pbUser.GetUsersReq) (*pb
IsBlock: isBlock,
}
resp.User = append(resp.User, user)
} else {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "UserIsBlock failed", err.Error())
}
}
user := db.User{}
nums, err := imdb.GetUsersCount(user)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUsersCount failed", err.Error())
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUsersCount failed", err.Error(), user)
return resp, errors.WrapError(constant.ErrDB)
}
resp.UserNums = nums
resp.Pagination = &sdkws.ResponsePagination{ShowNumber: req.Pagination.ShowNumber, CurrentPage: req.Pagination.PageNumber}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
@@ -476,7 +529,7 @@ func (s *userServer) ResignUser(ctx context.Context, req *pbUser.ResignUserReq)
}
func (s *userServer) AlterUser(ctx context.Context, req *pbUser.AlterUserReq) (*pbUser.AlterUserResp, error) {
log.NewInfo(req.OperationID, "AlterUser args ", req.String())
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp := &pbUser.AlterUserResp{}
user := db.User{
PhoneNumber: strconv.FormatInt(req.PhoneNumber, 10),
@@ -489,11 +542,12 @@ func (s *userServer) AlterUser(ctx context.Context, req *pbUser.AlterUserReq) (*
return resp, errors.WrapError(constant.ErrDB)
}
chat.UserInfoUpdatedNotification(req.OperationID, req.UserId, req.OpUserId)
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *userServer) AddUser(ctx context.Context, req *pbUser.AddUserReq) (*pbUser.AddUserResp, error) {
log.NewInfo(req.OperationID, "AddUser args ", req.String())
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp := &pbUser.AddUserResp{}
err := imdb.AddUser(req.UserId, req.PhoneNumber, req.Name)
if err != nil {
@@ -504,8 +558,7 @@ func (s *userServer) AddUser(ctx context.Context, req *pbUser.AddUserReq) (*pbUs
}
func (s *userServer) BlockUser(ctx context.Context, req *pbUser.BlockUserReq) (*pbUser.BlockUserResp, error) {
log.NewInfo(req.OperationID, "BlockUser args ", req.String())
fmt.Println("BlockUser args ", req.String())
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp := &pbUser.BlockUserResp{}
err := imdb.BlockUser(req.UserId, req.EndDisableTime)
if err != nil {
@@ -516,7 +569,7 @@ func (s *userServer) BlockUser(ctx context.Context, req *pbUser.BlockUserReq) (*
}
func (s *userServer) UnBlockUser(ctx context.Context, req *pbUser.UnBlockUserReq) (*pbUser.UnBlockUserResp, error) {
log.NewInfo(req.OperationID, "UnBlockUser args ", req.String())
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp := &pbUser.UnBlockUserResp{}
err := imdb.UnBlockUser(req.UserId)
if err != nil {
@@ -527,7 +580,7 @@ func (s *userServer) UnBlockUser(ctx context.Context, req *pbUser.UnBlockUserReq
}
func (s *userServer) GetBlockUsers(ctx context.Context, req *pbUser.GetBlockUsersReq) (*pbUser.GetBlockUsersResp, error) {
log.NewInfo(req.OperationID, "GetBlockUsers args ", req.String())
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp := &pbUser.GetBlockUsersResp{}
blockUsers, err := imdb.GetBlockUsers(req.Pagination.ShowNumber, req.Pagination.PageNumber)
if err != nil {
@@ -555,11 +608,12 @@ func (s *userServer) GetBlockUsers(ctx context.Context, req *pbUser.GetBlockUser
return resp, errors.WrapError(constant.ErrDB)
}
resp.UserNums = nums
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
return resp, nil
}
func (s *userServer) GetBlockUserById(_ context.Context, req *pbUser.GetBlockUserByIdReq) (*pbUser.GetBlockUserByIdResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "GetBlockUserById args ", req.String())
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp := &pbUser.GetBlockUserByIdResp{}
user, err := imdb.GetBlockUserById(req.UserId)
if err != nil {
@@ -576,6 +630,7 @@ func (s *userServer) GetBlockUserById(_ context.Context, req *pbUser.GetBlockUse
BeginDisableTime: (user.BeginDisableTime).String(),
EndDisableTime: (user.EndDisableTime).String(),
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", req.String())
return resp, nil
}

View File

@@ -1,13 +1 @@
package utils
import (
"Open_IM/pkg/utils"
"net"
"testing"
)
func TestServerIP(t *testing.T) {
if net.ParseIP(utils.ServerIP) == nil {
t.Fail()
}
}

View File

@@ -37,3 +37,22 @@ type UserTokenResp struct {
CommResp
UserToken UserTokenInfo `json:"data"`
}
type ParseTokenReq struct {
OperationID string `json:"operationID" binding:"required"`
}
//type ParseTokenResp struct {
// CommResp
// ExpireTime int64 `json:"expireTime" binding:"required"`
//}
type ExpireTime struct {
ExpireTimeSeconds uint32 `json:"expireTimeSeconds" `
}
type ParseTokenResp struct {
CommResp
Data map[string]interface{} `json:"data"`
ExpireTime ExpireTime `json:"-"`
}

View File

@@ -43,6 +43,8 @@ type Conversation struct {
DraftTextTime int64 `json:"draftTextTime"`
IsPinned bool `json:"isPinned" binding:"omitempty"`
IsPrivateChat bool `json:"isPrivateChat"`
GroupAtType int32 `json:"groupAtType"`
IsNotInGroup bool `json:"isNotInGroup"`
AttachedInfo string `json:"attachedInfo"`
Ex string `json:"ex"`
}
@@ -56,6 +58,15 @@ type SetConversationReq struct {
type SetConversationResp struct {
CommResp
}
type ModifyConversationFieldReq struct {
Conversation
FieldType int32 `json:"fieldType" binding:"required"`
UserIDList []string `json:"userIDList" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type ModifyConversationFieldResp struct {
CommResp
}
type BatchSetConversationsReq struct {
Conversations []Conversation `json:"conversations" binding:"required"`

View File

@@ -81,8 +81,8 @@ type GetGroupAllMemberResp struct {
}
type CreateGroupReq struct {
MemberList []*GroupAddMemberInfo `json:"memberList" binding:"required"`
OwnerUserID string `json:"ownerUserID" binding:"required"`
MemberList []*GroupAddMemberInfo `json:"memberList"`
OwnerUserID string `json:"ownerUserID"`
GroupType int32 `json:"groupType"`
GroupName string `json:"groupName"`
Notification string `json:"notification"`
@@ -90,6 +90,7 @@ type CreateGroupReq struct {
FaceURL string `json:"faceURL"`
Ex string `json:"ex"`
OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID"`
}
type CreateGroupResp struct {
CommResp
@@ -220,3 +221,14 @@ type CancelMuteGroupReq struct {
type CancelMuteGroupResp struct {
CommResp
}
type SetGroupMemberNicknameReq struct {
OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
UserID string `json:"userID" binding:"required"`
Nickname string `json:"nickname"`
}
type SetGroupMemberNicknameResp struct {
CommResp
}

View File

@@ -1,5 +1,7 @@
package base_info
import "mime/multipart"
type MinioStorageCredentialReq struct {
OperationID string `json:"operationID"`
}
@@ -23,3 +25,35 @@ type MinioUploadFileResp struct {
SnapshotURL string `json:"snapshotURL,omitempty"`
SnapshotNewName string `json:"snapshotName,omitempty"`
}
type UploadUpdateAppReq struct {
OperationID string `form:"operationID" binding:"required"`
Type int `form:"type" binding:"required"`
Version string `form:"version" binding:"required"`
File *multipart.FileHeader `form:"file" binding:"required"`
Yaml *multipart.FileHeader `form:"yaml"`
ForceUpdate bool `form:"forceUpdate"`
UpdateLog string `form:"updateLog" binding:"required"`
}
type UploadUpdateAppResp struct {
CommResp
}
type GetDownloadURLReq struct {
OperationID string `json:"operationID" binding:"required"`
Type int `json:"type" binding:"required"`
Version string `json:"version" binding:"required"`
}
type GetDownloadURLResp struct {
CommResp
Data struct {
HasNewVersion bool `json:"hasNewVersion"`
ForceUpdate bool `json:"forceUpdate"`
FileURL string `json:"fileURL"`
YamlURL string `json:"yamlURL"`
Version string `json:"version"`
UpdateLog string `json:"update_log"`
} `json:"data"`
}

View File

@@ -0,0 +1,110 @@
package base_info
import open_im_sdk "Open_IM/pkg/proto/sdk_ws"
type CreateDepartmentReq struct {
*open_im_sdk.Department
OperationID string `json:"operationID" binding:"required"`
}
type CreateDepartmentResp struct {
CommResp
Department *open_im_sdk.Department `json:"-"`
Data map[string]interface{} `json:"data"`
}
type UpdateDepartmentReq struct {
*open_im_sdk.Department
DepartmentID string `json:"departmentID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type UpdateDepartmentResp struct {
CommResp
}
type GetSubDepartmentReq struct {
OperationID string `json:"operationID" binding:"required"`
DepartmentID string `json:"departmentID" binding:"required"`
}
type GetSubDepartmentResp struct {
CommResp
DepartmentList []*open_im_sdk.Department `json:"-"`
Data []map[string]interface{} `json:"data"`
}
type DeleteDepartmentReq struct {
OperationID string `json:"operationID" binding:"required"`
DepartmentID string `json:"departmentID" binding:"required"`
}
type DeleteDepartmentResp struct {
CommResp
}
type CreateOrganizationUserReq struct {
OperationID string `json:"operationID" binding:"required"`
*open_im_sdk.OrganizationUser
}
type CreateOrganizationUserResp struct {
CommResp
}
type UpdateOrganizationUserReq struct {
OperationID string `json:"operationID" binding:"required"`
*open_im_sdk.OrganizationUser
}
type UpdateOrganizationUserResp struct {
CommResp
}
type CreateDepartmentMemberReq struct {
OperationID string `json:"operationID" binding:"required"`
*open_im_sdk.DepartmentMember
}
type CreateDepartmentMemberResp struct {
CommResp
}
type GetUserInDepartmentReq struct {
UserID string `json:"userID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type GetUserInDepartmentResp struct {
CommResp
UserInDepartment *open_im_sdk.UserInDepartment `json:"-"`
Data map[string]interface{} `json:"data"`
}
type UpdateUserInDepartmentReq struct {
OperationID string `json:"operationID" binding:"required"`
*open_im_sdk.DepartmentMember
}
type UpdateUserInDepartmentResp struct {
CommResp
}
type DeleteOrganizationUserReq struct {
UserID string `json:"userID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type DeleteOrganizationUserResp struct {
CommResp
}
type GetDepartmentMemberReq struct {
DepartmentID string `json:"departmentID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type GetDepartmentMemberResp struct {
CommResp
UserInDepartmentList []*open_im_sdk.UserDepartmentMember `json:"-"`
Data []map[string]interface{} `json:"data"`
}
type DeleteUserInDepartmentReq struct {
DepartmentID string `json:"departmentID" binding:"required"`
UserID string `json:"userID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type DeleteUserInDepartmentResp struct {
CommResp
}

View File

@@ -32,3 +32,21 @@ type GetSelfUserInfoResp struct {
UserInfo *open_im_sdk.UserInfo `json:"-"`
Data map[string]interface{} `json:"data"`
}
type GetFriendIDListFromCacheReq struct {
OperationID string `json:"operationID" binding:"required"`
}
type GetFriendIDListFromCacheResp struct {
CommResp
UserIDList []string `json:"userIDList" binding:"required"`
}
type GetBlackIDListFromCacheReq struct {
OperationID string `json:"operationID" binding:"required"`
}
type GetBlackIDListFromCacheResp struct {
CommResp
UserIDList []string `json:"userIDList" binding:"required"`
}

View File

@@ -0,0 +1,130 @@
package base_info
import "Open_IM/pkg/proto/office"
type CreateOneWorkMomentReq struct {
office.CreateOneWorkMomentReq
}
type CreateOneWorkMomentResp struct {
CommResp
Data struct{} `json:"data"`
}
type DeleteOneWorkMomentReq struct {
office.DeleteOneWorkMomentReq
}
type DeleteOneWorkMomentResp struct {
CommResp
Data struct{} `json:"data"`
}
type LikeOneWorkMomentReq struct {
office.LikeOneWorkMomentReq
}
type LikeOneWorkMomentResp struct {
CommResp
Data struct{} `json:"data"`
}
type CommentOneWorkMomentReq struct {
office.CommentOneWorkMomentReq
}
type CommentOneWorkMomentResp struct {
CommResp
Data struct{} `json:"data"`
}
type DeleteCommentReq struct {
office.DeleteCommentReq
}
type DeleteCommentResp struct {
CommResp
Data struct{} `json:"data"`
}
type WorkMomentsUserCommonReq struct {
PageNumber int32 `json:"pageNumber" binding:"required"`
ShowNumber int32 `json:"showNumber" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type GetWorkMomentByIDReq struct {
office.GetWorkMomentByIDReq
}
type WorkMoment struct {
WorkMomentID string `json:"workMomentID"`
UserID string `json:"userID"`
Content string `json:"content"`
LikeUserList []*WorkMomentUser `json:"likeUsers"`
Comments []*Comment `json:"comments"`
FaceURL string `json:"faceURL"`
UserName string `json:"userName"`
AtUserList []*WorkMomentUser `json:"atUsers"`
PermissionUserList []*WorkMomentUser `json:"permissionUsers"`
CreateTime int32 `json:"createTime"`
Permission int32 `json:"permission"`
}
type WorkMomentUser struct {
UserID string `json:"userID"`
UserName string `json:"userName"`
}
type Comment struct {
UserID string `json:"userID"`
UserName string `json:"userName"`
ReplyUserID string `json:"replyUserID"`
ReplyUserName string `json:"replyUserName"`
ContentID string `json:"contentID"`
Content string `json:"content"`
CreateTime int32 `json:"createTime"`
}
type GetWorkMomentByIDResp struct {
CommResp
Data struct {
WorkMoment *WorkMoment `json:"workMoment"`
} `json:"data"`
}
type GetUserWorkMomentsReq struct {
WorkMomentsUserCommonReq
UserID string `json:"userID"`
}
type GetUserWorkMomentsResp struct {
CommResp
Data struct {
WorkMoments []*WorkMoment `json:"workMoments"`
CurrentPage int32 `json:"currentPage"`
ShowNumber int32 `json:"showNumber"`
} `json:"data"`
}
type GetUserFriendWorkMomentsReq struct {
WorkMomentsUserCommonReq
}
type GetUserFriendWorkMomentsResp struct {
CommResp
Data struct {
WorkMoments []*WorkMoment `json:"workMoments"`
CurrentPage int32 `json:"currentPage"`
ShowNumber int32 `json:"showNumber"`
} `json:"data"`
}
type SetUserWorkMomentsLevelReq struct {
office.SetUserWorkMomentsLevelReq
}
type SetUserWorkMomentsLevelResp struct {
CommResp
Data struct{} `json:"data"`
}

View File

@@ -1,10 +1,43 @@
package cms_api_struct
import (
apiStruct "Open_IM/pkg/base_info"
)
type AdminLoginRequest struct {
AdminName string `json:"admin_name" binding:"required"`
Secret string `json:"secret" binding:"required"`
Secret string `json:"secret" binding:"required"`
}
type AdminLoginResponse struct {
Token string `json:"token"`
}
}
type UploadUpdateAppReq struct {
OperationID string `form:"operationID" binding:"required"`
Type int `form:"type" binding:"required"`
Version string `form:"version" binding:"required"`
//File *multipart.FileHeader `form:"file" binding:"required"`
//Yaml *multipart.FileHeader `form:"yaml" binding:"required"`
ForceUpdate bool `form:"forceUpdate" binding:"required"`
}
type UploadUpdateAppResp struct {
apiStruct.CommResp
}
type GetDownloadURLReq struct {
OperationID string `json:"operationID" binding:"required"`
Type int `json:"type" binding:"required"`
Version string `json:"version" binding:"required"`
}
type GetDownloadURLResp struct {
apiStruct.CommResp
Data struct {
HasNewVersion bool `json:"hasNewVersion"`
ForceUpdate bool `json:"forceUpdate"`
FileURL string `json:"fileURL"`
YamlURL string `json:"yamlURL"`
} `json:"data"`
}

View File

@@ -6,7 +6,6 @@ import (
"path/filepath"
"runtime"
"github.com/spf13/viper"
"gopkg.in/yaml.v3"
)
@@ -25,16 +24,23 @@ type callBackConfig struct {
}
type config struct {
ServerIP string `yaml:"serverip"`
ServerIP string `yaml:"serverip"`
RpcRegisterIP string `yaml:"rpcRegisterIP"`
ListenIP string `yaml:"listenIP"`
ServerVersion string `yaml:"serverversion"`
Api struct {
GinPort []int `yaml:"openImApiPort"`
GinPort []int `yaml:"openImApiPort"`
ListenIP string `yaml:"listenIP"`
}
CmsApi struct {
GinPort []int `yaml:"openImCmsApiPort"`
GinPort []int `yaml:"openImCmsApiPort"`
ListenIP string `yaml:"listenIP"`
}
Sdk struct {
WsPort []int `yaml:"openImSdkWsPort"`
WsPort []int `yaml:"openImSdkWsPort"`
DataDir []string `yaml:"dataDir"`
}
Credential struct {
Tencent struct {
@@ -56,11 +62,14 @@ type config struct {
OssRoleArn string `yaml:"OssRoleArn"`
}
Minio struct {
Bucket string `yaml:"bucket"`
Location string `yaml:"location"`
Endpoint string `yaml:"endpoint"`
AccessKeyID string `yaml:"accessKeyID"`
SecretAccessKey string `yaml:"secretAccessKey"`
Bucket string `yaml:"bucket"`
AppBucket string `yaml:"appBucket"`
Location string `yaml:"location"`
Endpoint string `yaml:"endpoint"`
AccessKeyID string `yaml:"accessKeyID"`
SecretAccessKey string `yaml:"secretAccessKey"`
EndpointInner string `yaml:"endpointInner"`
EndpointInnerEnable bool `yaml:"endpointInnerEnable"`
} `yaml:"minio"`
}
@@ -76,7 +85,7 @@ type config struct {
DBMaxLifeTime int `yaml:"dbMaxLifeTime"`
}
Mongo struct {
DBUri string `yaml:"dbUri"` // 当dbUri值不为空则直接使用该值
DBUri string `yaml:"dbUri"`
DBAddress []string `yaml:"dbAddress"`
DBDirect bool `yaml:"dbDirect"`
DBTimeout int `yaml:"dbTimeout"`
@@ -104,7 +113,7 @@ type config struct {
RpcGetTokenPort []int `yaml:"rpcGetTokenPort"`
}
RpcRegisterName struct {
OpenImStatisticsName string `yaml:"OpenImStatisticsName"`
OpenImStatisticsName string `yaml:"openImStatisticsName"`
OpenImUserName string `yaml:"openImUserName"`
OpenImFriendName string `yaml:"openImFriendName"`
OpenImOfflineMessageName string `yaml:"openImOfflineMessageName"`
@@ -115,6 +124,10 @@ type config struct {
OpenImMessageCMSName string `yaml:"openImMessageCMSName"`
OpenImAdminCMSName string `yaml:"openImAdminCMSName"`
OpenImOfficeName string `yaml:"openImOfficeName"`
OpenImOrganizationName string `yaml:"openImOrganizationName"`
OpenImConversationName string `yaml:"openImConversationName"`
OpenImCacheName string `yaml:"openImCacheName"`
OpenImRealTimeCommName string `yaml:"openImRealTimeCommName"`
}
Etcd struct {
EtcdSchema string `yaml:"etcdSchema"`
@@ -173,24 +186,32 @@ type config struct {
AppManagerUid []string `yaml:"appManagerUid"`
Secrets []string `yaml:"secrets"`
}
Kafka struct {
Ws2mschat struct {
Addr []string `yaml:"addr"`
Topic string `yaml:"topic"`
}
Ws2mschatOffline struct {
Addr []string `yaml:"addr"`
Topic string `yaml:"topic"`
}
Ms2pschat struct {
Addr []string `yaml:"addr"`
Topic string `yaml:"topic"`
}
ConsumerGroupID struct {
MsgToMongo string `yaml:"msgToMongo"`
MsgToMySql string `yaml:"msgToMySql"`
MsgToPush string `yaml:"msgToPush"`
MsgToMongo string `yaml:"msgToMongo"`
MsgToMongoOffline string `yaml:"msgToMongoOffline"`
MsgToMySql string `yaml:"msgToMySql"`
MsgToPush string `yaml:"msgToPush"`
}
}
Secret string `yaml:"secret"`
MultiLoginPolicy int `yaml:"multiloginpolicy"`
TokenPolicy struct {
Secret string `yaml:"secret"`
MultiLoginPolicy int `yaml:"multiloginpolicy"`
ChatPersistenceMysql bool `yaml:"chatPersistenceMysql"`
TokenPolicy struct {
AccessSecret string `yaml:"accessSecret"`
AccessExpire int64 `yaml:"accessExpire"`
}
@@ -301,6 +322,16 @@ type config struct {
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"groupMemberCancelMuted"`
GroupMemberInfoSet struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"groupMemberInfoSet"`
OrganizationChanged struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"organizationChanged"`
////////////////////////user///////////////////////
UserInfoUpdated struct {
@@ -366,9 +397,20 @@ type config struct {
CloseTips string `yaml:"closeTips"`
} `yaml:"defaultTips"`
} `yaml:"conversationSetPrivate"`
WorkMomentsNotification struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"workMomentsNotification"`
JoinDepartmentNotification struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"joinDepartmentNotification"`
}
Demo struct {
Port []int `yaml:"openImDemoPort"`
Port []int `yaml:"openImDemoPort"`
ListenIP string `yaml:"listenIP"`
AliSMSVerify struct {
AccessKeyID string `yaml:"accessKeyId"`
AccessKeySecret string `yaml:"accessKeySecret"`
@@ -384,6 +426,7 @@ type config struct {
SmtpAddr string `yaml:"smtpAddr"`
SmtpPort int `yaml:"smtpPort"`
}
TestDepartMentID string `yaml:"testDepartMentID"`
}
Rtc struct {
Port int `yaml:"port"`
@@ -406,21 +449,11 @@ type PDefaultTips struct {
}
func init() {
//path, _ := os.Getwd()
//bytes, err := ioutil.ReadFile(path + "/config/config.yaml")
// if we cd Open-IM-Server/src/utils and run go test
// it will panic cannot find config/config.yaml
cfgName := os.Getenv("CONFIG_NAME")
if len(cfgName) == 0 {
cfgName = Root + "/config/config.yaml"
}
viper.SetConfigFile(cfgName)
err := viper.ReadInConfig()
if err != nil {
panic(err.Error())
}
bytes, err := ioutil.ReadFile(cfgName)
if err != nil {
panic(err.Error())

View File

@@ -81,6 +81,7 @@ const (
GroupMemberCancelMutedNotification = 1513
GroupMutedNotification = 1514
GroupCancelMutedNotification = 1515
GroupMemberInfoSetNotification = 1516
SignalingNotificationBegin = 1600
SignalingNotification = 1601
@@ -88,6 +89,11 @@ const (
ConversationPrivateChatNotification = 1701
OrganizationChangedNotification = 1801
WorkMomentNotificationBegin = 1900
WorkMomentNotification = 1901
NotificationEnd = 2000
//status
@@ -145,6 +151,10 @@ const (
GroupStatusDismissed = 2
GroupStatusMuted = 3
//GroupType
NormalGroup = 0
DepartmentGroup = 1
GroupBaned = 3
GroupBanPrivateChat = 4
@@ -177,6 +187,24 @@ const (
OtherType = 1
VideoType = 2
ImageType = 3
// workMoment permission
WorkMomentPublic = 0
WorkMomentPrivate = 1
WorkMomentPermissionCanSee = 2
WorkMomentPermissionCantSee = 3
// workMoment sdk notification type
WorkMomentCommentNotification = 0
WorkMomentLikeNotification = 1
WorkMomentAtUserNotification = 2
)
const (
AtAllString = "AtAllTag"
AtNormal = 0
AtMe = 1
AtAll = 2
AtAllAtMe = 3
)
var ContentType2PushContent = map[int64]string{
@@ -190,6 +218,16 @@ var ContentType2PushContent = map[int64]string{
Common: "你收到一条新消息",
}
const (
FieldRecvMsgOpt = 1
FieldIsPinned = 2
FieldAttachedInfo = 3
FieldIsPrivateChat = 4
FieldGroupAtType = 5
FieldIsNotInGroup = 6
FieldEx = 7
)
const (
AppOrdinaryUsers = 1
AppAdmin = 2
@@ -233,3 +271,5 @@ func GroupIsBanPrivateChat(status int32) bool {
const BigVersion = "v3"
const LogFileName = "OpenIM.log"
const StatisticsTimeInterval = 300

View File

@@ -51,7 +51,8 @@ var (
ErrAccess = ErrInfo{ErrCode: 801, ErrMsg: AccessMsg.Error()}
ErrDB = ErrInfo{ErrCode: 802, ErrMsg: DBMsg.Error()}
ErrArgs = ErrInfo{ErrCode: 8003, ErrMsg: ArgsMsg.Error()}
ErrArgs = ErrInfo{ErrCode: 803, ErrMsg: ArgsMsg.Error()}
ErrStatus = ErrInfo{ErrCode: 804, ErrMsg: StatusMsg.Error()}
ErrCallback = ErrInfo{ErrCode: 809, ErrMsg: CallBackMsg.Error()}
)
@@ -64,6 +65,7 @@ var (
TokenUnknownMsg = errors.New("couldn't handle this token")
TokenUserKickedMsg = errors.New("user has been kicked")
AccessMsg = errors.New("no permission")
StatusMsg = errors.New("status is abnormal")
DBMsg = errors.New("db failed")
ArgsMsg = errors.New("args failed")
CallBackMsg = errors.New("callback failed")

View File

@@ -2,6 +2,9 @@ package db
import (
"Open_IM/pkg/common/config"
"go.mongodb.org/mongo-driver/x/bsonx"
"strings"
//"Open_IM/pkg/common/log"
"Open_IM/pkg/utils"
"fmt"
@@ -34,7 +37,6 @@ func key(dbAddress, dbName string) string {
func init() {
//log.NewPrivateLog(constant.LogFileName)
//var mgoSession *mgo.Session
var mongoClient *mongo.Client
var err1 error
//mysql init
@@ -46,11 +48,15 @@ func init() {
// 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.DBUri
} else {
uri = fmt.Sprintf("mongodb://%s/%s/?maxPoolSize=%d",
config.Config.Mongo.DBAddress[0], config.Config.Mongo.DBDatabase,
config.Config.Mongo.DBMaxPoolSize)
if config.Config.Mongo.DBPassword != "" && config.Config.Mongo.DBUserName != "" {
uri = fmt.Sprintf("mongodb://%s:%s@%s/%s?maxPoolSize=%d", config.Config.Mongo.DBUserName, config.Config.Mongo.DBPassword, config.Config.Mongo.DBAddress[0],
config.Config.Mongo.DBDatabase, config.Config.Mongo.DBMaxPoolSize)
} else {
uri = fmt.Sprintf("mongodb://%s/%s/?maxPoolSize=%d",
config.Config.Mongo.DBAddress[0], config.Config.Mongo.DBDatabase,
config.Config.Mongo.DBMaxPoolSize)
}
}
mongoClient, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
if err != nil {
fmt.Println(" mongo.Connect failed, try ", utils.GetSelfFuncName(), err.Error(), uri)
@@ -61,40 +67,34 @@ func init() {
panic(err1.Error())
}
}
fmt.Println("0", utils.GetSelfFuncName(), "mongo driver client init success")
fmt.Println("0", utils.GetSelfFuncName(), "mongo driver client init success: ", uri)
// mongodb create index
if err := createMongoIndex(mongoClient, cSendLog, false, "send_id", "-send_time"); err != nil {
fmt.Println("send_id", "-send_time", "index create failed", err.Error())
}
if err := createMongoIndex(mongoClient, cChat, true, "uid"); err != nil {
fmt.Println("uid", " index create failed", err.Error())
}
if err := createMongoIndex(mongoClient, cWorkMoment, true, "-create_time", "work_moment_id"); err != nil {
fmt.Println("-create_time", "work_moment_id", "index create failed", err.Error())
}
if err := createMongoIndex(mongoClient, cWorkMoment, true, "work_moment_id"); err != nil {
fmt.Println("work_moment_id", "index create failed", err.Error())
}
if err := createMongoIndex(mongoClient, cWorkMoment, false, "user_id", "-create_time"); err != nil {
fmt.Println("user_id", "-create_time", "index create failed", err.Error())
}
if err := createMongoIndex(mongoClient, cTag, false, "user_id", "-create_time"); err != nil {
fmt.Println("user_id", "-create_time", "index create failed", err.Error())
}
if err := createMongoIndex(mongoClient, cTag, true, "tag_id"); err != nil {
fmt.Println("user_id", "-create_time", "index create failed", err.Error())
}
fmt.Println("create index success")
DB.mongoClient = mongoClient
//mgoDailInfo := &mgo.DialInfo{
// Addrs: config.Config.Mongo.DBAddress,
// Direct: config.Config.Mongo.DBDirect,
// Timeout: time.Second * time.Duration(config.Config.Mongo.DBTimeout),
// Database: config.Config.Mongo.DBDatabase,
// Source: config.Config.Mongo.DBSource,
// Username: config.Config.Mongo.DBUserName,
// Password: config.Config.Mongo.DBPassword,
// PoolLimit: config.Config.Mongo.DBMaxPoolSize,
//}
//mgoSession, err = mgo.DialWithInfo(mgoDailInfo)
//
//if err != nil {
//
// mgoSession, err1 = mgo.DialWithInfo(mgoDailInfo)
// if err1 != nil {
// log.NewError(" mongo.Connect failed, panic", err.Error())
// panic(err1.Error())
// }
//}
//DB.mgoSession = mgoSession
//DB.mgoSession.SetMode(mgo.Monotonic, true)
//c := DB.mgoSession.DB(config.Config.Mongo.DBDatabase).C(cChat)
//err = c.EnsureIndexKey("uid")
//if err != nil {
// panic(err.Error())
//}
//
// redis pool init
DB.redisPool = &redis.Pool{
MaxIdle: config.Config.Redis.DBMaxIdle,
@@ -113,3 +113,37 @@ func init() {
},
}
}
func createMongoIndex(client *mongo.Client, collection string, isUnique bool, keys ...string) error {
db := client.Database(config.Config.Mongo.DBDatabase).Collection(collection)
opts := options.CreateIndexes().SetMaxTime(10 * time.Second)
indexView := db.Indexes()
keysDoc := bsonx.Doc{}
// 复合索引
for _, key := range keys {
if strings.HasPrefix(key, "-") {
keysDoc = keysDoc.Append(strings.TrimLeft(key, "-"), bsonx.Int32(-1))
} else {
keysDoc = keysDoc.Append(key, bsonx.Int32(1))
}
}
// 创建索引
index := mongo.IndexModel{
Keys: keysDoc,
}
if isUnique == true {
index.Options = options.Index().SetUnique(true)
}
result, err := indexView.CreateOne(
context.Background(),
index,
opts,
)
if err != nil {
return utils.Wrap(err, result)
}
return nil
}

View File

@@ -215,6 +215,8 @@ type Conversation struct {
DraftTextTime int64 `gorm:"column:draft_text_time" json:"draftTextTime"`
IsPinned bool `gorm:"column:is_pinned" json:"isPinned"`
IsPrivateChat bool `gorm:"column:is_private_chat" json:"isPrivateChat"`
GroupAtType int32 `gorm:"column:group_at_type" json:"groupAtType"`
IsNotInGroup bool `gorm:"column:is_not_in_group" json:"isNotInGroup"`
AttachedInfo string `gorm:"column:attached_info;type:varchar(1024)" json:"attachedInfo"`
Ex string `gorm:"column:ex;type:varchar(1024)" json:"ex"`
}
@@ -222,3 +224,66 @@ type Conversation struct {
func (Conversation) TableName() string {
return "conversations"
}
type Department struct {
DepartmentID string `gorm:"column:department_id;primary_key;size:64" json:"departmentID"`
FaceURL string `gorm:"column:face_url;size:255" json:"faceURL"`
Name string `gorm:"column:name;size:256" json:"name" binding:"required"`
ParentID string `gorm:"column:parent_id;size:64" json:"parentID" binding:"required"` // "0" or Real parent id
Order int32 `gorm:"column:order" json:"order" ` // 1, 2, ...
DepartmentType int32 `gorm:"column:department_type" json:"departmentType"` //1, 2...
RelatedGroupID string `gorm:"column:related_group_id;size:64" json:"relatedGroupID"`
CreateTime time.Time `gorm:"column:create_time" json:"createTime"`
Ex string `gorm:"column:ex;type:varchar(1024)" json:"ex"`
}
func (Department) TableName() string {
return "departments"
}
type OrganizationUser struct {
UserID string `gorm:"column:user_id;primary_key;size:64"`
Nickname string `gorm:"column:nickname;size:256"`
EnglishName string `gorm:"column:english_name;size:256"`
FaceURL string `gorm:"column:face_url;size:256"`
Gender int32 `gorm:"column:gender"` //1 ,2
Mobile string `gorm:"column:mobile;size:32"`
Telephone string `gorm:"column:telephone;size:32"`
Birth time.Time `gorm:"column:birth"`
Email string `gorm:"column:email;size:64"`
CreateTime time.Time `gorm:"column:create_time"`
Ex string `gorm:"column:ex;size:1024"`
}
func (OrganizationUser) TableName() string {
return "organization_users"
}
type DepartmentMember struct {
UserID string `gorm:"column:user_id;primary_key;size:64"`
DepartmentID string `gorm:"column:department_id;primary_key;size:64"`
Order int32 `gorm:"column:order" json:"order"` //1,2
Position string `gorm:"column:position;size:256" json:"position"`
Leader int32 `gorm:"column:leader" json:"leader"` //-1, 1
Status int32 `gorm:"column:status" json:"status"` //-1, 1
CreateTime time.Time `gorm:"column:create_time"`
Ex string `gorm:"column:ex;type:varchar(1024)" json:"ex"`
}
func (DepartmentMember) TableName() string {
return "department_members"
}
type AppVersion struct {
Version string `gorm:"column:version;size:64" json:"version"`
Type int `gorm:"column:type;primary_key" json:"type"`
UpdateTime int `gorm:"column:update_time" json:"update_time"`
ForceUpdate bool `gorm:"column:force_update" json:"force_update"`
FileName string `gorm:"column:file_name" json:"file_name"`
YamlName string `gorm:"column:yaml_name" json:"yaml_name"`
UpdateLog string `gorm:"column:update_log" json:"update_log"`
}
func (AppVersion) TableName() string {
return "app_version"
}

View File

@@ -13,10 +13,11 @@ import (
"github.com/gogo/protobuf/sortkeys"
"go.mongodb.org/mongo-driver/mongo/options"
"math/rand"
"sync"
//"github.com/garyburd/redigo/redis"
"github.com/golang/protobuf/proto"
"gopkg.in/mgo.v2/bson"
"go.mongodb.org/mongo-driver/bson"
"strconv"
"time"
@@ -26,6 +27,8 @@ const cChat = "msg"
const cGroup = "group"
const cTag = "tag"
const cSendLog = "send_log"
const cWorkMoment = "work_moment"
const cCommentMsg = "comment_msg"
const singleGocMsgNum = 5000
type MsgInfo struct {
@@ -77,6 +80,53 @@ func (d *DataBases) GetMinSeqFromMongo2(uid string) (MinSeq uint32, err error) {
return 1, nil
}
// deleteMsgByLogic
func (d *DataBases) DelMsgBySeqList(userID string, seqList []uint32, operationID string) (err error) {
log.Debug(operationID, utils.GetSelfFuncName(), "args ", userID, seqList)
sortkeys.Uint32s(seqList)
suffixUserID2SubSeqList := func(uid string, seqList []uint32) map[string][]uint32 {
t := make(map[string][]uint32)
for i := 0; i < len(seqList); i++ {
seqUid := getSeqUid(uid, seqList[i])
if value, ok := t[seqUid]; !ok {
var temp []uint32
t[seqUid] = append(temp, seqList[i])
} else {
t[seqUid] = append(value, seqList[i])
}
}
return t
}(userID, seqList)
var wg sync.WaitGroup
wg.Add(len(suffixUserID2SubSeqList))
for k, v := range suffixUserID2SubSeqList {
go func(suffixUserID string, subSeqList []uint32, operationID string) {
if e := d.DelMsgBySeqListInOneDoc(suffixUserID, subSeqList, operationID); e != nil {
log.Error(operationID, "DelMsgBySeqListInOneDoc failed ", e.Error(), suffixUserID, subSeqList)
err = e
}
wg.Done()
}(k, v, operationID)
}
wg.Wait()
return err
}
func (d *DataBases) DelMsgBySeqListInOneDoc(suffixUserID string, seqList []uint32, operationID string) error {
log.Debug(operationID, utils.GetSelfFuncName(), "args ", suffixUserID, seqList)
seqMsgList, indexList, err := d.GetMsgAndIndexBySeqListInOneMongo2(suffixUserID, seqList, operationID)
if err != nil {
return utils.Wrap(err, "")
}
for i, v := range seqMsgList {
if err := d.ReplaceMsgByIndex(suffixUserID, v, operationID, indexList[i]); err != nil {
return utils.Wrap(err, "")
}
}
return nil
}
// deleteMsgByLogic
func (d *DataBases) DelMsgLogic(uid string, seqList []uint32, operationID string) error {
sortkeys.Uint32s(seqList)
@@ -94,6 +144,27 @@ func (d *DataBases) DelMsgLogic(uid string, seqList []uint32, operationID string
return nil
}
func (d *DataBases) ReplaceMsgByIndex(suffixUserID string, msg *open_im_sdk.MsgData, operationID string, seqIndex int) error {
log.NewInfo(operationID, utils.GetSelfFuncName(), suffixUserID, *msg)
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
s := fmt.Sprintf("msg.%d.msg", seqIndex)
log.NewDebug(operationID, utils.GetSelfFuncName(), seqIndex, s)
msg.Status = constant.MsgDeleted
bytes, err := proto.Marshal(msg)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "proto marshal failed ", err.Error(), msg.String())
return utils.Wrap(err, "")
}
updateResult, err := c.UpdateOne(ctx, bson.M{"uid": suffixUserID}, bson.M{"$set": bson.M{s: bytes}})
log.NewInfo(operationID, utils.GetSelfFuncName(), updateResult)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "UpdateOne", err.Error())
return utils.Wrap(err, "")
}
return nil
}
func (d *DataBases) ReplaceMsgBySeq(uid string, msg *open_im_sdk.MsgData, operationID string) error {
log.NewInfo(operationID, utils.GetSelfFuncName(), uid, *msg)
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
@@ -107,6 +178,7 @@ func (d *DataBases) ReplaceMsgBySeq(uid string, msg *open_im_sdk.MsgData, operat
log.NewError(operationID, utils.GetSelfFuncName(), "proto marshal", err.Error())
return utils.Wrap(err, "")
}
updateResult, err := c.UpdateOne(
ctx, bson.M{"uid": uid},
bson.M{"$set": bson.M{s: bytes}})
@@ -226,6 +298,36 @@ func (d *DataBases) GetMsgBySeqListMongo2(uid string, seqList []uint32, operatio
return seqMsg, nil
}
func (d *DataBases) GetMsgAndIndexBySeqListInOneMongo2(suffixUserID string, seqList []uint32, operationID string) (seqMsg []*open_im_sdk.MsgData, indexList []int, err error) {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
sChat := UserChat{}
if err = c.FindOne(ctx, bson.M{"uid": suffixUserID}).Decode(&sChat); err != nil {
log.NewError(operationID, "not find seqUid", suffixUserID, err.Error())
return nil, nil, utils.Wrap(err, "")
}
singleCount := 0
var hasSeqList []uint32
for i := 0; i < len(sChat.Msg); i++ {
msg := new(open_im_sdk.MsgData)
if err = proto.Unmarshal(sChat.Msg[i].Msg, msg); err != nil {
log.NewError(operationID, "Unmarshal err", msg.String(), err.Error())
return nil, nil, err
}
if isContainInt32(msg.Seq, seqList) {
indexList = append(indexList, i)
seqMsg = append(seqMsg, msg)
hasSeqList = append(hasSeqList, msg.Seq)
singleCount++
if singleCount == len(seqList) {
break
}
}
}
return seqMsg, indexList, nil
}
func genExceptionMessageBySeqList(seqList []uint32) (exceptionMsg []*open_im_sdk.MsgData) {
for _, v := range seqList {
msg := new(open_im_sdk.MsgData)
@@ -563,10 +665,177 @@ func (d *DataBases) GetTagSendLogs(userID string, showNumber, pageNumber int32)
return tagSendLogs, nil
}
type WorkMoment struct {
WorkMomentID string `bson:"work_moment_id"`
UserID string `bson:"user_id"`
UserName string `bson:"user_name"`
FaceURL string `bson:"face_url"`
Content string `bson:"content"`
LikeUserList []*WorkMomentUser `bson:"like_user_list"`
AtUserList []*WorkMomentUser `bson:"at_user_list"`
PermissionUserList []*WorkMomentUser `bson:"permission_user_list"`
Comments []*Comment `bson:"comments"`
PermissionUserIDList []string `bson:"permission_user_id_list"`
Permission int32 `bson:"permission"`
CreateTime int32 `bson:"create_time"`
}
type WorkMomentUser struct {
UserID string `bson:"user_id"`
UserName string `bson:"user_name"`
}
type Comment struct {
UserID string `bson:"user_id" json:"user_id"`
UserName string `bson:"user_name" json:"user_name"`
ReplyUserID string `bson:"reply_user_id" json:"reply_user_id"`
ReplyUserName string `bson:"reply_user_name" json:"reply_user_name"`
ContentID string `bson:"content_id" json:"content_id"`
Content string `bson:"content" json:"content"`
CreateTime int32 `bson:"create_time" json:"create_time"`
}
func (d *DataBases) CreateOneWorkMoment(workMoment *WorkMoment) error {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cWorkMoment)
workMomentID := generateWorkMomentID(workMoment.UserID)
workMoment.WorkMomentID = workMomentID
workMoment.CreateTime = int32(time.Now().Unix())
_, err := c.InsertOne(ctx, workMoment)
return err
}
func (d *DataBases) DeleteOneWorkMoment(workMomentID string) error {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cWorkMoment)
_, err := c.DeleteOne(ctx, bson.M{"work_moment_id": workMomentID})
return err
}
func (d *DataBases) DeleteComment(workMomentID, contentID, opUserID string) error {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cWorkMoment)
_, err := c.UpdateOne(ctx, bson.D{{"work_moment_id", workMomentID},
{"$or", bson.A{
bson.D{{"user_id", opUserID}},
bson.D{{"comments", bson.M{"$elemMatch": bson.M{"user_id": opUserID}}}},
},
}}, bson.M{"$pull": bson.M{"comments": bson.M{"content_id": contentID}}})
return err
}
func (d *DataBases) GetWorkMomentByID(workMomentID string) (*WorkMoment, error) {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cWorkMoment)
workMoment := &WorkMoment{}
err := c.FindOne(ctx, bson.M{"work_moment_id": workMomentID}).Decode(workMoment)
return workMoment, err
}
func (d *DataBases) LikeOneWorkMoment(likeUserID, userName, workMomentID string) (*WorkMoment, bool, error) {
workMoment, err := d.GetWorkMomentByID(workMomentID)
if err != nil {
return nil, false, err
}
var isAlreadyLike bool
for i, user := range workMoment.LikeUserList {
if likeUserID == user.UserID {
isAlreadyLike = true
workMoment.LikeUserList = append(workMoment.LikeUserList[0:i], workMoment.LikeUserList[i+1:]...)
}
}
if !isAlreadyLike {
workMoment.LikeUserList = append(workMoment.LikeUserList, &WorkMomentUser{UserID: likeUserID, UserName: userName})
}
log.NewDebug("", utils.GetSelfFuncName(), workMoment)
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cWorkMoment)
_, err = c.UpdateOne(ctx, bson.M{"work_moment_id": workMomentID}, bson.M{"$set": bson.M{"like_user_list": workMoment.LikeUserList}})
return workMoment, !isAlreadyLike, err
}
func (d *DataBases) SetUserWorkMomentsLevel(userID string, level int32) error {
return nil
}
func (d *DataBases) CommentOneWorkMoment(comment *Comment, workMomentID string) (WorkMoment, error) {
comment.ContentID = generateWorkMomentCommentID(workMomentID)
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cWorkMoment)
var workMoment WorkMoment
err := c.FindOneAndUpdate(ctx, bson.M{"work_moment_id": workMomentID}, bson.M{"$push": bson.M{"comments": comment}}).Decode(&workMoment)
return workMoment, err
}
func (d *DataBases) GetUserSelfWorkMoments(userID string, showNumber, pageNumber int32) ([]WorkMoment, error) {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cWorkMoment)
var workMomentList []WorkMoment
findOpts := options.Find().SetLimit(int64(showNumber)).SetSkip(int64(showNumber) * (int64(pageNumber) - 1)).SetSort(bson.M{"create_time": -1})
result, err := c.Find(ctx, bson.M{"user_id": userID}, findOpts)
if err != nil {
return workMomentList, nil
}
err = result.All(ctx, &workMomentList)
return workMomentList, err
}
func (d *DataBases) GetUserWorkMoments(opUserID, userID string, showNumber, pageNumber int32) ([]WorkMoment, error) {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cWorkMoment)
var workMomentList []WorkMoment
findOpts := options.Find().SetLimit(int64(showNumber)).SetSkip(int64(showNumber) * (int64(pageNumber) - 1)).SetSort(bson.M{"create_time": -1})
result, err := c.Find(ctx, bson.D{ // 等价条件: select * from
{"user_id", userID},
{"$or", bson.A{
bson.D{{"permission", constant.WorkMomentPermissionCantSee}, {"permission_user_id_list", bson.D{{"$nin", bson.A{userID}}}}},
bson.D{{"permission", constant.WorkMomentPermissionCanSee}, {"permission_user_id_list", bson.D{{"$in", bson.A{userID}}}}},
bson.D{{"permission", constant.WorkMomentPublic}},
}},
}, findOpts)
if err != nil {
return workMomentList, nil
}
err = result.All(ctx, &workMomentList)
return workMomentList, err
}
func (d *DataBases) GetUserFriendWorkMoments(showNumber, pageNumber int32, userID string) ([]WorkMoment, error) {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cWorkMoment)
var workMomentList []WorkMoment
findOpts := options.Find().SetLimit(int64(showNumber)).SetSkip(int64(showNumber) * (int64(pageNumber) - 1)).SetSort(bson.M{"create_time": -1})
result, err := c.Find(ctx, bson.D{
{"$or", bson.A{
bson.D{{"user_id", userID}}, //self
bson.D{
{"$or", bson.A{
bson.D{{"permission", constant.WorkMomentPermissionCantSee}, {"permission_user_id_list", bson.D{{"$nin", bson.A{userID}}}}},
bson.D{{"permission", constant.WorkMomentPermissionCanSee}, {"permission_user_id_list", bson.D{{"$in", bson.A{userID}}}}},
bson.D{{"permission", constant.WorkMomentPublic}},
}}},
},
},
}, findOpts)
if err != nil {
return workMomentList, err
}
err = result.All(ctx, &workMomentList)
return workMomentList, err
}
func generateTagID(tagName, userID string) string {
return utils.Md5(tagName + userID + strconv.Itoa(rand.Int()) + time.Now().String())
}
func generateWorkMomentID(userID string) string {
return utils.Md5(userID + strconv.Itoa(rand.Int()) + time.Now().String())
}
func generateWorkMomentCommentID(workMomentID string) string {
return utils.Md5(workMomentID + strconv.Itoa(rand.Int()) + time.Now().String())
}
func getCurrentTimestampByMill() int64 {
return time.Now().UnixNano() / 1e6
}
@@ -580,7 +849,7 @@ func getMsgIndex(seq uint32) int {
seqSuffix := seq / singleGocMsgNum
var index uint32
if seqSuffix == 0 {
index = (seq - seqSuffix*5000) - 1
index = (seq - seqSuffix*singleGocMsgNum) - 1
} else {
index = seq - seqSuffix*singleGocMsgNum
}
@@ -588,9 +857,7 @@ func getMsgIndex(seq uint32) int {
}
func isContainInt32(target uint32, List []uint32) bool {
for _, element := range List {
if target == element {
return true
}

View File

@@ -59,7 +59,7 @@ func initMysqlDB() {
&GroupMember{},
&GroupRequest{},
&User{},
&Black{}, &ChatLog{}, &Register{}, &Conversation{})
&Black{}, &ChatLog{}, &Register{}, &Conversation{}, &AppVersion{}, &Department{})
db.Set("gorm:table_options", "CHARSET=utf8")
db.Set("gorm:table_options", "collation=utf8_unicode_ci")
@@ -82,169 +82,48 @@ func initMysqlDB() {
fmt.Println("CreateTable GroupMember")
db.CreateTable(&GroupMember{})
}
if !db.HasTable(&GroupRequest{}) {
fmt.Println("CreateTable GroupRequest")
db.CreateTable(&GroupRequest{})
}
if !db.HasTable(&User{}) {
fmt.Println("CreateTable User")
db.CreateTable(&User{})
}
if !db.HasTable(&Black{}) {
fmt.Println("CreateTable Black")
db.CreateTable(&Black{})
}
if !db.HasTable(&ChatLog{}) {
fmt.Println("CreateTable Black")
fmt.Println("CreateTable ChatLog")
db.CreateTable(&ChatLog{})
}
if !db.HasTable(&Register{}) {
fmt.Println("CreateTable Black")
fmt.Println("CreateTable Register")
db.CreateTable(&Register{})
}
if !db.HasTable(&Conversation{}) {
fmt.Println("CreateTable Black")
fmt.Println("CreateTable Conversation")
db.CreateTable(&Conversation{})
}
if !db.HasTable(&Department{}) {
fmt.Println("CreateTable Department")
db.CreateTable(&Department{})
}
if !db.HasTable(&OrganizationUser{}) {
fmt.Println("CreateTable OrganizationUser")
db.CreateTable(&OrganizationUser{})
}
if !db.HasTable(&DepartmentMember{}) {
fmt.Println("CreateTable DepartmentMember")
db.CreateTable(&DepartmentMember{})
}
if !db.HasTable(&AppVersion{}) {
fmt.Println("CreateTable DepartmentMember")
db.CreateTable(&AppVersion{})
}
return
sqlTable := "CREATE TABLE IF NOT EXISTS `user` (" +
" `uid` varchar(64) NOT NULL," +
" `name` varchar(64) DEFAULT NULL," +
" `icon` varchar(1024) DEFAULT NULL," +
" `gender` tinyint(4) unsigned zerofill DEFAULT NULL," +
" `mobile` varchar(32) DEFAULT NULL," +
" `birth` varchar(16) DEFAULT NULL," +
" `email` varchar(64) DEFAULT NULL," +
" `ex` varchar(1024) DEFAULT NULL," +
" `create_time` datetime DEFAULT NULL," +
" PRIMARY KEY (`uid`)," +
" UNIQUE KEY `uk_uid` (`uid`)" +
" ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"
err = db.Exec(sqlTable).Error
if err != nil {
panic(err.Error())
}
sqlTable = "CREATE TABLE IF NOT EXISTS `friend` (" +
" `owner_id` varchar(64) NOT NULL," +
" `friend_id` varchar(64) NOT NULL," +
" `comment` varchar(255) DEFAULT NULL," +
" `friend_flag` int(11) NOT NULL," +
" `create_time` datetime NOT NULL," +
" PRIMARY KEY (`owner_id`,`friend_id`) USING BTREE" +
" ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;"
err = db.Exec(sqlTable).Error
if err != nil {
panic(err.Error())
}
sqlTable = "CREATE TABLE IF NOT EXISTS `friend_request` (" +
" `req_id` varchar(64) NOT NULL," +
" `user_id` varchar(64) NOT NULL," +
" `flag` int(11) NOT NULL DEFAULT '0'," +
" `req_message` varchar(255) DEFAULT NULL," +
" `create_time` datetime NOT NULL," +
" PRIMARY KEY (`user_id`,`req_id`) USING BTREE" +
" ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;"
err = db.Exec(sqlTable).Error
if err != nil {
panic(err.Error())
}
sqlTable = "CREATE TABLE IF NOT EXISTS `user_black_list` (" +
" `owner_id` varchar(64) NOT NULL," +
" `block_id` varchar(64) NOT NULL," +
" `create_time` datetime NOT NULL," +
" PRIMARY KEY (`owner_id`,`block_id`) USING BTREE" +
" ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;"
err = db.Exec(sqlTable).Error
if err != nil {
panic(err.Error())
}
sqlTable = "CREATE TABLE IF NOT EXISTS `group` (" +
" `group_id` varchar(64) NOT NULL," +
" `name` varchar(255) DEFAULT NULL," +
" `introduction` varchar(255) DEFAULT NULL," +
" `notification` varchar(255) DEFAULT NULL," +
" `face_url` varchar(255) DEFAULT NULL," +
" `create_time` datetime DEFAULT NULL," +
" `ex` varchar(255) DEFAULT NULL," +
" PRIMARY KEY (`group_id`)" +
" ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;"
err = db.Exec(sqlTable).Error
if err != nil {
panic(err.Error())
}
sqlTable = "CREATE TABLE IF NOT EXISTS `group_member` (" +
" `group_id` varchar(64) NOT NULL," +
" `uid` varchar(64) NOT NULL," +
" `nickname` varchar(255) DEFAULT NULL," +
" `user_group_face_url` varchar(255) DEFAULT NULL," +
" `administrator_level` int(11) NOT NULL," +
" `join_time` datetime NOT NULL," +
" PRIMARY KEY (`group_id`,`uid`) USING BTREE" +
" ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;"
err = db.Exec(sqlTable).Error
if err != nil {
panic(err.Error())
}
sqlTable = "CREATE TABLE IF NOT EXISTS `group_request` (" +
" `id` int(11) NOT NULL AUTO_INCREMENT," +
" `group_id` varchar(64) NOT NULL," +
" `from_user_id` varchar(255) NOT NULL," +
" `to_user_id` varchar(255) NOT NULL," +
" `flag` int(10) NOT NULL DEFAULT '0'," +
" `req_msg` varchar(255) DEFAULT ''," +
" `handled_msg` varchar(255) DEFAULT ''," +
" `create_time` datetime NOT NULL," +
" `from_user_nickname` varchar(255) DEFAULT ''," +
" `to_user_nickname` varchar(255) DEFAULT NULL," +
" `from_user_face_url` varchar(255) DEFAULT ''," +
" `to_user_face_url` varchar(255) DEFAULT ''," +
" `handled_user` varchar(255) DEFAULT ''," +
" PRIMARY KEY (`id`)" +
" ) ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=utf8mb4;"
err = db.Exec(sqlTable).Error
if err != nil {
panic(err.Error())
}
sqlTable = "CREATE TABLE IF NOT EXISTS `chat_log` (" +
" `msg_id` varchar(128) NOT NULL," +
" `send_id` varchar(255) NOT NULL," +
" `session_type` int(11) NOT NULL," +
" `recv_id` varchar(255) NOT NULL," +
" `content_type` int(11) NOT NULL," +
" `msg_from` int(11) NOT NULL," +
" `content` varchar(1000) NOT NULL," +
" `remark` varchar(100) DEFAULT NULL," +
" `sender_platform_id` int(11) NOT NULL," +
" `send_time` datetime NOT NULL," +
" PRIMARY KEY (`msg_id`) USING BTREE" +
" ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;"
err = db.Exec(sqlTable).Error
if err != nil {
panic(err.Error())
}
sqlTable = "CREATE TABLE IF NOT EXISTS `register` (" +
" `account` varchar(255) NOT NULL," +
" `password` varchar(255) NOT NULL," +
" PRIMARY KEY (`account`) USING BTREE" +
" ) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC;"
err = db.Exec(sqlTable).Error
if err != nil {
panic(err.Error())
}
}
func (m *mysqlDB) DefaultGormDB() (*gorm.DB, error) {

View File

@@ -0,0 +1,145 @@
package im_mysql_model
import (
"Open_IM/pkg/common/db"
"Open_IM/pkg/common/log"
"Open_IM/pkg/utils"
)
func SetConversation(conversation db.Conversation) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
dbConn.LogMode(false)
newConversation := conversation
if dbConn.Model(&db.Conversation{}).Find(&newConversation).RowsAffected == 0 {
log.NewDebug("", utils.GetSelfFuncName(), "conversation", conversation, "not exist in db, create")
return dbConn.Model(&db.Conversation{}).Create(conversation).Error
// if exist, then update record
} else {
log.NewDebug("", utils.GetSelfFuncName(), "conversation", conversation, "exist in db, update")
//force update
return dbConn.Model(conversation).Where("owner_user_id = ? and conversation_id = ?", conversation.OwnerUserID, conversation.ConversationID).
Update(map[string]interface{}{"recv_msg_opt": conversation.RecvMsgOpt, "is_pinned": conversation.IsPinned, "is_private_chat": conversation.IsPrivateChat,
"group_at_type": conversation.GroupAtType, "is_not_in_group": conversation.IsNotInGroup}).Error
}
}
func SetOneConversation(conversation db.Conversation) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
dbConn.LogMode(false)
return dbConn.Model(&db.Conversation{}).Create(conversation).Error
}
func PeerUserSetConversation(conversation db.Conversation) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
dbConn.LogMode(false)
newConversation := conversation
if dbConn.Model(&db.Conversation{}).Find(&newConversation).RowsAffected == 0 {
log.NewDebug("", utils.GetSelfFuncName(), "conversation", conversation, "not exist in db, create")
return dbConn.Model(&db.Conversation{}).Create(conversation).Error
// if exist, then update record
}
log.NewDebug("", utils.GetSelfFuncName(), "conversation", conversation, "exist in db, update")
//force update
return dbConn.Model(conversation).Where("owner_user_id = ? and conversation_id = ?", conversation.OwnerUserID, conversation.ConversationID).
Update(map[string]interface{}{"is_private_chat": conversation.IsPrivateChat}).Error
}
func SetRecvMsgOpt(conversation db.Conversation) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
dbConn.LogMode(false)
newConversation := conversation
if dbConn.Model(&db.Conversation{}).Find(&newConversation).RowsAffected == 0 {
log.NewDebug("", utils.GetSelfFuncName(), "conversation", conversation, "not exist in db, create")
return dbConn.Model(&db.Conversation{}).Create(conversation).Error
// if exist, then update record
} else {
log.NewDebug("", utils.GetSelfFuncName(), "conversation", conversation, "exist in db, update")
//force update
return dbConn.Model(conversation).Where("owner_user_id = ? and conversation_id = ?", conversation.OwnerUserID, conversation.ConversationID).
Update(map[string]interface{}{"recv_msg_opt": conversation.RecvMsgOpt}).Error
}
}
func GetUserAllConversations(ownerUserID string) ([]db.Conversation, error) {
var conversations []db.Conversation
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return conversations, err
}
dbConn.LogMode(false)
err = dbConn.Model(&db.Conversation{}).Where("owner_user_id=?", ownerUserID).Find(&conversations).Error
return conversations, err
}
func GetMultipleUserConversationByConversationID(ownerUserIDList []string, conversationID string) ([]db.Conversation, error) {
var conversations []db.Conversation
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return conversations, err
}
dbConn.LogMode(false)
err = dbConn.Model(&db.Conversation{}).Where("owner_user_id IN ? and conversation_id=?", ownerUserIDList, conversationID).Find(&conversations).Error
return conversations, err
}
func GetExistConversationUserIDList(ownerUserIDList []string, conversationID string) ([]string, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var resultArr []string
err = dbConn.Table("conversations").Where(" owner_user_id IN (?) and conversation_id=?", ownerUserIDList, conversationID).Pluck("owner_user_id", &resultArr).Error
if err != nil {
return nil, err
}
return resultArr, nil
}
func GetConversation(OwnerUserID, conversationID string) (db.Conversation, error) {
var conversation db.Conversation
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return conversation, err
}
err = dbConn.Table("conversations").Where("owner_user_id=? and conversation_id=?", OwnerUserID, conversationID).Take(&conversation).Error
return conversation, err
}
func GetConversations(OwnerUserID string, conversationIDs []string) ([]db.Conversation, error) {
var conversations []db.Conversation
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return conversations, err
}
err = dbConn.Model(&db.Conversation{}).Where("conversation_id IN (?) and owner_user_id=?", conversationIDs, OwnerUserID).Find(&conversations).Error
return conversations, err
}
func GetConversationsByConversationIDMultipleOwner(OwnerUserIDList []string, conversationID string) ([]db.Conversation, error) {
var conversations []db.Conversation
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return conversations, err
}
err = dbConn.Model(&db.Conversation{}).Where("owner_user_id IN (?) and conversation_id=?", OwnerUserIDList, conversationID).Find(&conversations).Error
return conversations, err
}
func UpdateColumnsConversations(ownerUserIDList []string, conversationID string, args map[string]interface{}) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
dbConn.LogMode(false)
return dbConn.Debug().Model(&db.Conversation{}).Where("owner_user_id IN (?) and conversation_id=?", ownerUserIDList, conversationID).Updates(args).Error
}

View File

@@ -0,0 +1,43 @@
package im_mysql_model
import (
"Open_IM/pkg/common/db"
"time"
)
func UpdateAppVersion(appType int, version string, forceUpdate bool, fileName, yamlName, updateLog string) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
updateTime := int(time.Now().Unix())
app := db.AppVersion{
Version: version,
Type: appType,
UpdateTime: updateTime,
FileName: fileName,
YamlName: yamlName,
ForceUpdate: forceUpdate,
UpdateLog: updateLog,
}
result := dbConn.Model(db.AppVersion{}).Where("type = ?", appType).Update(map[string]interface{}{"force_update": forceUpdate,
"version": version, "update_time": int(time.Now().Unix()), "file_name": fileName, "yaml_name": yamlName, "type": appType, "update_log": updateLog})
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
err := dbConn.Create(&app).Error
return err
}
return nil
}
func GetNewestVersion(appType int) (*db.AppVersion, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
app := db.AppVersion{}
if err != nil {
return &app, err
}
dbConn.LogMode(true)
return &app, dbConn.Model(db.AppVersion{}).First(&app, appType).Error
}

View File

@@ -49,6 +49,19 @@ func GetFriendListByUserID(OwnerUserID string) ([]db.Friend, error) {
return friends, nil
}
func GetFriendIDListByUserID(OwnerUserID string) ([]string, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var friendIDList []string
err = dbConn.Table("friends").Where("owner_user_id=?", OwnerUserID).Pluck("friend_user_id", &friendIDList).Error
if err != nil {
return nil, err
}
return friendIDList, nil
}
func UpdateFriendComment(OwnerUserID, FriendUserID, Remark string) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {

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