Compare commits

...

305 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
skiffer-git
2bdaaa5a33 log 2022-04-20 20:58:51 +08:00
122 changed files with 7286 additions and 2712 deletions

View File

@@ -30,7 +30,7 @@ func main() {
gin.SetMode(gin.ReleaseMode) gin.SetMode(gin.ReleaseMode)
f, _ := os.Create("../logs/api.log") f, _ := os.Create("../logs/api.log")
gin.DefaultWriter = io.MultiWriter(f) gin.DefaultWriter = io.MultiWriter(f)
gin.SetMode(gin.DebugMode)
r := gin.Default() r := gin.Default()
r.Use(utils.CorsHandler()) r.Use(utils.CorsHandler())
@@ -42,6 +42,9 @@ func main() {
userRouterGroup.POST("/get_users_info", user.GetUsersInfo) //1 userRouterGroup.POST("/get_users_info", user.GetUsersInfo) //1
userRouterGroup.POST("/get_self_user_info", user.GetSelfUserInfo) //1 userRouterGroup.POST("/get_self_user_info", user.GetSelfUserInfo) //1
userRouterGroup.POST("/get_users_online_status", user.GetUsersOnlineStatus) //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 //friend routing group
friendRouterGroup := r.Group("/friend") friendRouterGroup := r.Group("/friend")
@@ -94,6 +97,7 @@ func main() {
{ {
authRouterGroup.POST("/user_register", apiAuth.UserRegister) //1 authRouterGroup.POST("/user_register", apiAuth.UserRegister) //1
authRouterGroup.POST("/user_token", apiAuth.UserToken) //1 authRouterGroup.POST("/user_token", apiAuth.UserToken) //1
authRouterGroup.POST("/parse_token", apiAuth.ParseToken) //1
} }
//Third service //Third service
thirdGroup := r.Group("/third") thirdGroup := r.Group("/third")
@@ -102,6 +106,8 @@ func main() {
thirdGroup.POST("/ali_oss_credential", apiThird.AliOSSCredential) thirdGroup.POST("/ali_oss_credential", apiThird.AliOSSCredential)
thirdGroup.POST("/minio_storage_credential", apiThird.MinioStorageCredential) thirdGroup.POST("/minio_storage_credential", apiThird.MinioStorageCredential)
thirdGroup.POST("/minio_upload", apiThird.MinioUploadFile) thirdGroup.POST("/minio_upload", apiThird.MinioUploadFile)
thirdGroup.POST("/upload_update_app", apiThird.UploadUpdateApp)
thirdGroup.POST("/get_download_url", apiThird.GetDownloadURL)
} }
//Message //Message
chatGroup := r.Group("/msg") chatGroup := r.Group("/msg")
@@ -119,6 +125,7 @@ func main() {
managementGroup.POST("/get_all_users_uid", manage.GetAllUsersUid) //1 managementGroup.POST("/get_all_users_uid", manage.GetAllUsersUid) //1
managementGroup.POST("/account_check", manage.AccountCheck) //1 managementGroup.POST("/account_check", manage.AccountCheck) //1
managementGroup.POST("/get_users_online_status", manage.GetUsersOnlineStatus) //1 managementGroup.POST("/get_users_online_status", manage.GetUsersOnlineStatus) //1
} }
//Conversation //Conversation
conversationGroup := r.Group("/conversation") conversationGroup := r.Group("/conversation")
@@ -129,6 +136,7 @@ func main() {
conversationGroup.POST("/set_conversation", conversation.SetConversation) conversationGroup.POST("/set_conversation", conversation.SetConversation)
conversationGroup.POST("/batch_set_conversation", conversation.BatchSetConversations) conversationGroup.POST("/batch_set_conversation", conversation.BatchSetConversations)
conversationGroup.POST("/set_recv_msg_opt", conversation.SetRecvMsgOpt) conversationGroup.POST("/set_recv_msg_opt", conversation.SetRecvMsgOpt)
conversationGroup.POST("/modify_conversation_field", conversation.ModifyConversationField)
} }
// office // office
officeGroup := r.Group("/office") officeGroup := r.Group("/office")
@@ -149,6 +157,7 @@ func main() {
officeGroup.POST("/get_user_work_moments", office.GetUserWorkMoments) officeGroup.POST("/get_user_work_moments", office.GetUserWorkMoments)
officeGroup.POST("/get_user_friend_work_moments", office.GetUserFriendWorkMoments) officeGroup.POST("/get_user_friend_work_moments", office.GetUserFriendWorkMoments)
officeGroup.POST("/set_user_work_moments_level", office.SetUserWorkMomentsLevel) officeGroup.POST("/set_user_work_moments_level", office.SetUserWorkMomentsLevel)
officeGroup.POST("/delete_comment", office.DeleteComment)
} }
organizationGroup := r.Group("/organization") organizationGroup := r.Group("/organization")
@@ -173,10 +182,15 @@ func main() {
} }
go apiThird.MinioInit() 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() flag.Parse()
fmt.Println("start api server, port: ", *ginPort) address := "0.0.0.0:" + strconv.Itoa(*ginPort)
err := r.Run(":" + 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 { if err != nil {
log.Error("", "run failed ", *ginPort, err.Error()) log.Error("", "run failed ", *ginPort, err.Error())
} }

View File

@@ -3,8 +3,11 @@ package main
import ( import (
"Open_IM/internal/cms_api" "Open_IM/internal/cms_api"
"Open_IM/pkg/utils" "Open_IM/pkg/utils"
"flag"
"fmt" "fmt"
"strconv"
"Open_IM/pkg/common/config"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@@ -12,6 +15,13 @@ func main() {
gin.SetMode(gin.ReleaseMode) gin.SetMode(gin.ReleaseMode)
router := cms_api.NewGinRouter() router := cms_api.NewGinRouter()
router.Use(utils.CorsHandler()) router.Use(utils.CorsHandler())
fmt.Println("start cms api server, port: ", 8000) ginPort := flag.Int("port", 10006, "get ginServerPort from cmd,default 10006 as port")
router.Run(":" + "8000") 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" "os"
"strconv" "strconv"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant" "Open_IM/pkg/common/constant"
"Open_IM/pkg/common/log" "Open_IM/pkg/common/log"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -23,7 +24,7 @@ func main() {
r := gin.Default() r := gin.Default()
r.Use(utils.CorsHandler()) r.Use(utils.CorsHandler())
authRouterGroup := r.Group("/auth") authRouterGroup := r.Group("/demo")
{ {
authRouterGroup.POST("/code", register.SendVerificationCode) authRouterGroup.POST("/code", register.SendVerificationCode)
authRouterGroup.POST("/verify", register.Verify) authRouterGroup.POST("/verify", register.Verify)
@@ -35,7 +36,13 @@ func main() {
ginPort := flag.Int("port", 42233, "get ginServerPort from cmd,default 42233 as port") ginPort := flag.Int("port", 42233, "get ginServerPort from cmd,default 42233 as port")
flag.Parse() flag.Parse()
fmt.Println("start demo api server, port: ", *ginPort) 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 { if err != nil {
log.Error("", "run failed ", *ginPort, err.Error()) 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 .PHONY: all build run gotool install clean help
BINARY_NAME=open_im_timer_task BINARY_NAME=open_im_cache
BIN_DIR=../../bin/ BIN_DIR=../../../bin/
all: gotool build all: gotool build
@@ -22,4 +22,3 @@ install:
clean: clean:
@if [ -f ${BINARY_NAME} ] ; then rm ${BINARY_NAME} ; fi @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

@@ -4,7 +4,7 @@
serverversion: 2.0.0 serverversion: 2.0.0
#---------------Infrastructure configuration---------------------# #---------------Infrastructure configuration---------------------#
etcd: etcd:
etcdSchema: openIM #默认即可 etcdSchema: openim #默认即可
etcdAddr: [ 127.0.0.1:2379 ] #单机部署时,默认即可 etcdAddr: [ 127.0.0.1:2379 ] #单机部署时,默认即可
mysql: mysql:
@@ -41,11 +41,15 @@ kafka:
ws2mschat: ws2mschat:
addr: [ 127.0.0.1:9092 ] #kafka配置默认即可 addr: [ 127.0.0.1:9092 ] #kafka配置默认即可
topic: "ws2ms_chat" topic: "ws2ms_chat"
ws2mschatoffline:
addr: [ 127.0.0.1:9092 ] #kafka配置默认即可
topic: "ws2ms_chat_offline"
ms2pschat: ms2pschat:
addr: [ 127.0.0.1:9092 ] #kafka配置默认即可 addr: [ 127.0.0.1:9092 ] #kafka配置默认即可
topic: "ms2ps_chat" topic: "ms2ps_chat"
consumergroupid: consumergroupid:
msgToMongo: mongo msgToMongo: mongo
msgToMongoOffline: mongo_offline
msgToMySql: mysql msgToMySql: mysql
msgToPush: push msgToPush: push
@@ -59,6 +63,11 @@ kafka:
#如果是单机模式用0.0.0.0或者不填,默认即可 #如果是单机模式用0.0.0.0或者不填,默认即可
serverip: 0.0.0.0 serverip: 0.0.0.0
rpcRegisterIP: 127.0.0.1
listenIP: 0.0.0.0
# endpoints 内部组件间访问的端点host名称访问时可以内部直接访问 host:port 来访问 # endpoints 内部组件间访问的端点host名称访问时可以内部直接访问 host:port 来访问
endpoints: endpoints:
api: openim_api api: openim_api
@@ -76,24 +85,28 @@ endpoints:
rpc_office: openim_rpc_office rpc_office: openim_rpc_office
api: api:
openImApiPort: [ 10000 ] #api服务端口默认即可需要开放此端口或做nginx转发 openImApiPort: [ 10002 ] #api服务端口默认即可需要开放此端口或做nginx转发
listenIP: 0.0.0.0
cmsapi: cmsapi:
openImCmsApiPort: [ 8000 ] #管理后台api服务端口默认即可需要开放此端口或做nginx转发 openImCmsApiPort: [ 10006 ] #管理后台api服务端口默认即可需要开放此端口或做nginx转发
listenIP: 0.0.0.0
sdk: sdk:
openImSdkWsPort: [ 30000 ] #jssdk服务端口默认即可项目中使用jssdk才需开放此端口或做nginx转发 openImSdkWsPort: [ 10003 ] #jssdk服务端口默认即可项目中使用jssdk才需开放此端口或做nginx转发
dataDir: [ ../db/sdk/ ]
#对象存储服务以下配置二选一目前支持两种腾讯云和minio二者配置好其中一种即可如果使用minio参考https://doc.rentsoft.cn/#/qa/minio搭建minio服务器 #对象存储服务以下配置二选一目前支持两种腾讯云和minio二者配置好其中一种即可如果使用minio参考https://doc.rentsoft.cn/#/qa/minio搭建minio服务器
credential: #腾讯cos发送图片、视频、文件时需要请自行申请后替换必须修改 credential: #腾讯cos发送图片、视频、文件时需要请自行申请后替换必须修改
tencent: tencent:
appID: 1302656840 appID: 1302656840
region: ap-chengdu region: ap-chengdu
bucket: echat-1302656840 bucket: echat-1302656840
secretID: AKIDGNYVChzIQinu7QEgtNp0hnNgqcV8vZTC secretID: AKIDGNYVChzIQinu7QEgtNp0hnNgqcV8vZTC1
secretKey: kz15vW83qM6dBUWIq681eBZA0c0vlIbe secretKey: kz15vW83qM6dBUWIq681eBZA0c0vlIbe1
minio: #MinIO 发送图片、视频、文件时需要,请自行申请后替换,必须修改。 客户端初始化InitSDK中 object_storage参数为minio minio: #MinIO 发送图片、视频、文件时需要,请自行申请后替换,必须修改。 客户端初始化InitSDK中 object_storage参数为minio
bucket: openim bucket: openim # 存储内容桶
appBucket: app # 存储app的桶
location: us-east-1 location: us-east-1
endpoint: http://127.0.0.1:9000 #minio外网ip 这个ip是给客户端访问的 endpoint: http://127.0.0.1:10005 #minio外网ip 这个ip是给客户端访问的
endpointInner: http://127.0.0.1:9000 #minio内网地址 如果im server 可以通过内网访问到 minio就可以填写 endpointInner: http://127.0.0.1:10005 #minio内网地址 如果im server 可以通过内网访问到 minio就可以填写
endpointInnerEnable: true #是否启用minio内网地址 启用可以让桶初始化IM server连接minio走内网地址访问 endpointInnerEnable: true #是否启用minio内网地址 启用可以让桶初始化IM server连接minio走内网地址访问
accessKeyID: user12345 accessKeyID: user12345
secretAccessKey: key12345 secretAccessKey: key12345
@@ -111,18 +124,20 @@ credential: #腾讯cos发送图片、视频、文件时需要请自行申
rpcport: #rpc服务端口 默认即可 rpcport: #rpc服务端口 默认即可
openImUserPort: [ 10100 ] openImUserPort: [ 10110 ]
openImFriendPort: [ 10200 ] openImFriendPort: [ 10120 ]
openImOfflineMessagePort: [ 10300 ] openImMessagePort: [ 10130 ]
openImOnlineRelayPort: [ 10400 ] openImMessageGatewayPort: [ 10140 ]
openImGroupPort: [ 10500 ] openImGroupPort: [ 10150 ]
openImAuthPort: [ 10600 ] openImAuthPort: [ 10160 ]
openImPushPort: [ 10700 ] openImPushPort: [ 10170 ]
openImStatisticsPort: [ 10800 ] openImStatisticsPort: [ 10180 ]
openImMessageCmsPort: [ 10900 ] openImMessageCmsPort: [ 10190 ]
openImAdminCmsPort: [ 11000 ] openImAdminCmsPort: [ 10200 ]
openImOfficePort: [ 11100 ] openImOfficePort: [ 10210 ]
openImOrganizationPort: [ 11200 ] openImOrganizationPort: [ 10220 ]
openImConversationPort: [ 10230 ]
openImCachePort: [10240]
c2c: c2c:
callbackBeforeSendMsg: callbackBeforeSendMsg:
switch: false switch: false
@@ -141,12 +156,14 @@ rpcregistername: #rpc注册服务名默认即可
openImOnlineMessageRelayName: OnlineMessageRelay openImOnlineMessageRelayName: OnlineMessageRelay
openImGroupName: Group openImGroupName: Group
openImAuthName: Auth openImAuthName: Auth
OpenImStatisticsName: Statistics openImStatisticsName: Statistics
OpenImMessageCMSName: MessageCMS openImMessageCMSName: MessageCMS
openImAdminCMSName: AdminCMS openImAdminCMSName: AdminCMS
openImOfficeName: Office openImOfficeName: Office
openImOrganizationName: Organization openImOrganizationName: Organization
openImConversationName: Conversation
openImCacheName: Cache
openImRealTimeCommName: RealTimeComm
log: log:
storageLocation: ../logs/ storageLocation: ../logs/
rotationTime: 24 rotationTime: 24
@@ -164,7 +181,7 @@ modulename: #日志文件按模块命名,默认即可
pushName: push pushName: push
longconnsvr: longconnsvr:
openImWsPort: [ 17778 ] # ws服务端口默认即可要开放此端口或做nginx转发 openImWsPort: [ 10001 ] # ws服务端口默认即可要开放此端口或做nginx转发
websocketMaxConnNum: 10000 websocketMaxConnNum: 10000
websocketMaxMsgLen: 4096 websocketMaxMsgLen: 4096
websocketTimeOut: 10 websocketTimeOut: 10
@@ -625,14 +642,28 @@ notification:
openTips: "burn after reading was opened" openTips: "burn after reading was opened"
closeTips: "burn after reading was closed" 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---------------------# #---------------demo configuration---------------------#
#The following configuration items are applied to openIM Demo configuration #The following configuration items are applied to openIM Demo configuration
#是否启动demo如果自身没有账号体系设置为true #是否启动demo如果自身没有账号体系设置为true
demoswitch: true demoswitch: true
demo: demo:
listenIP: 0.0.0.0
#demo对外服务端口默认即可需要开放此端口或做nginx转发 #demo对外服务端口默认即可需要开放此端口或做nginx转发
openImDemoPort: [ 42233 ] openImDemoPort: [ 10004 ]
alismsverify: #阿里云短信配置,在阿里云申请成功后修改以下四项,必须修改 alismsverify: #阿里云短信配置,在阿里云申请成功后修改以下四项,必须修改
accessKeyId: LTAI5tJPkn4HuuePdiLdGqe7 accessKeyId: LTAI5tJPkn4HuuePdiLdGqe7
accessKeySecret: 4n9OJ7ZCVN1U6KeHDAtOyNeVZcjOuV accessKeySecret: 4n9OJ7ZCVN1U6KeHDAtOyNeVZcjOuV
@@ -647,6 +678,7 @@ demo:
senderAuthorizationCode: "gxyausfoevlzbfag" senderAuthorizationCode: "gxyausfoevlzbfag"
smtpAddr: "smtp.qq.com" smtpAddr: "smtp.qq.com"
smtpPort: 25 #需开放此端口 出口方向 smtpPort: 25 #需开放此端口 出口方向
testDepartMentID: 001
rtc: rtc:
port: 11300 port: 11300

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 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: open_im_server:
image: openim/open_im_server:v2.0.7 image: openim/open_im_server:v2.0.9
container_name: open_im_server container_name: open_im_server
volumes: volumes:
- ./logs:/Open-IM-Server/logs - ./logs:/Open-IM-Server/logs

20
go.mod
View File

@@ -3,7 +3,7 @@ module Open_IM
go 1.15 go 1.15
require ( 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/Shopify/toxiproxy v2.1.4+incompatible // indirect
github.com/alibabacloud-go/darabonba-openapi v0.1.11 github.com/alibabacloud-go/darabonba-openapi v0.1.11
github.com/alibabacloud-go/dysmsapi-20170525/v2 v2.0.8 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/alibabacloud-go/tea v1.1.17
github.com/antonfisher/nested-logrus-formatter v1.3.0 github.com/antonfisher/nested-logrus-formatter v1.3.0
github.com/bwmarrin/snowflake v0.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-resiliency v1.2.0 // indirect
github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21 // indirect github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21 // indirect
github.com/eapache/queue v1.1.0 // indirect github.com/eapache/queue v1.1.0 // indirect
github.com/fatih/structs v1.1.0 github.com/fatih/structs v1.1.0
github.com/frankban/quicktest v1.14.0 // indirect
github.com/garyburd/redigo v1.6.2 github.com/garyburd/redigo v1.6.2
github.com/gin-gonic/gin v1.7.0 github.com/gin-gonic/gin v1.7.0
github.com/go-playground/validator/v10 v10.4.1 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/file-rotatelogs v2.4.0+incompatible
github.com/lestrrat-go/strftime v1.0.4 // indirect github.com/lestrrat-go/strftime v1.0.4 // indirect
github.com/lib/pq v1.2.0 // 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/mattn/go-sqlite3 v1.14.6 // indirect
github.com/minio/minio-go/v7 v7.0.22 github.com/minio/minio-go/v7 v7.0.22
github.com/mitchellh/mapstructure v1.4.2 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/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5 github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5
github.com/sirupsen/logrus v1.8.1 github.com/sirupsen/logrus v1.8.1
github.com/spf13/viper v1.9.0
github.com/stretchr/testify v1.7.0 github.com/stretchr/testify v1.7.0
github.com/tencentyun/qcloud-cos-sts-sdk v0.0.0-20210325043845-84a0811633ca 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/api/v3 v3.5.4
//go.etcd.io/etcd v3.3.27+incompatible go.etcd.io/etcd/client/v3 v3.5.4
go.etcd.io/etcd v0.0.0-20200402134248-51bdeb39e698
go.mongodb.org/mongo-driver v1.8.3 go.mongodb.org/mongo-driver v1.8.3
golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd
google.golang.org/grpc v1.42.0 google.golang.org/genproto v0.0.0-20210828152312-66f60bf46e71 // indirect
google.golang.org/grpc/examples v0.0.0-20220311002955-722367c4a737 // indirect google.golang.org/grpc v1.45.0
google.golang.org/protobuf v1.27.1 google.golang.org/protobuf v1.27.1
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
gopkg.in/ini.v1 v1.66.2 // indirect gopkg.in/ini.v1 v1.66.2 // indirect
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22 gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b 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" api "Open_IM/pkg/base_info"
"Open_IM/pkg/common/config" "Open_IM/pkg/common/config"
"Open_IM/pkg/common/log" "Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
"Open_IM/pkg/grpc-etcdv3/getcdv3" "Open_IM/pkg/grpc-etcdv3/getcdv3"
rpc "Open_IM/pkg/proto/auth" rpc "Open_IM/pkg/proto/auth"
open_im_sdk "Open_IM/pkg/proto/sdk_ws" open_im_sdk "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils" "Open_IM/pkg/utils"
"context" "context"
"github.com/fatih/structs"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"net/http" "net/http"
"strings" "strings"
@@ -17,8 +19,9 @@ import (
func UserRegister(c *gin.Context) { func UserRegister(c *gin.Context) {
params := api.UserRegisterReq{} params := api.UserRegisterReq{}
if err := c.BindJSON(&params); err != nil { if err := c.BindJSON(&params); err != nil {
log.NewError("0", "BindJSON failed ", err.Error()) errMsg := " BindJSON failed " + err.Error()
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()}) log.NewError("0", errMsg)
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": errMsg})
return return
} }
@@ -37,22 +40,24 @@ func UserRegister(c *gin.Context) {
client := rpc.NewAuthClient(etcdConn) client := rpc.NewAuthClient(etcdConn)
reply, err := client.UserRegister(context.Background(), req) reply, err := client.UserRegister(context.Background(), req)
if err != nil { if err != nil {
log.NewError(req.OperationID, "call rpc err ", err.Error()) errMsg := req.OperationID + " " + "UserRegister failed " + err.Error() + req.String()
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "internal service err"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
if reply.CommonResp.ErrCode != 0 { if reply.CommonResp.ErrCode != 0 {
log.NewError(req.OperationID, "UserRegister failed ", err) errMsg := req.OperationID + " " + " UserRegister failed " + reply.CommonResp.ErrMsg + req.String()
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": reply.CommonResp.ErrMsg}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
pbDataToken := &rpc.UserTokenReq{Platform: params.Platform, FromUserID: params.UserID, OperationID: params.OperationID} pbDataToken := &rpc.UserTokenReq{Platform: params.Platform, FromUserID: params.UserID, OperationID: params.OperationID}
replyToken, err := client.UserToken(context.Background(), pbDataToken) replyToken, err := client.UserToken(context.Background(), pbDataToken)
if err != nil { if err != nil {
log.NewError(req.OperationID, "UserToken failed ", err.Error(), pbDataToken) errMsg := req.OperationID + " " + " client.UserToken failed " + err.Error() + pbDataToken.String()
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": err.Error()}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
resp := api.UserRegisterResp{CommResp: api.CommResp{ErrCode: replyToken.CommonResp.ErrCode, ErrMsg: replyToken.CommonResp.ErrMsg}, resp := api.UserRegisterResp{CommResp: api.CommResp{ErrCode: replyToken.CommonResp.ErrCode, ErrMsg: replyToken.CommonResp.ErrMsg},
@@ -65,14 +70,16 @@ func UserRegister(c *gin.Context) {
func UserToken(c *gin.Context) { func UserToken(c *gin.Context) {
params := api.UserTokenReq{} params := api.UserTokenReq{}
if err := c.BindJSON(&params); err != nil { if err := c.BindJSON(&params); err != nil {
log.NewError("0", "BindJSON failed ", err.Error()) errMsg := " BindJSON failed " + err.Error()
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()}) log.NewError("0", errMsg)
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": errMsg})
return return
} }
if params.Secret != config.Config.Secret { 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) 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 return
} }
req := &rpc.UserTokenReq{Platform: params.Platform, FromUserID: params.UserID, OperationID: params.OperationID} req := &rpc.UserTokenReq{Platform: params.Platform, FromUserID: params.UserID, OperationID: params.OperationID}
@@ -81,8 +88,9 @@ func UserToken(c *gin.Context) {
client := rpc.NewAuthClient(etcdConn) client := rpc.NewAuthClient(etcdConn)
reply, err := client.UserToken(context.Background(), req) reply, err := client.UserToken(context.Background(), req)
if err != nil { if err != nil {
log.NewError(req.OperationID, "UserToken failed ", err.Error(), req.String()) errMsg := req.OperationID + " UserToken failed " + err.Error() + req.String()
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": err.Error()}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
resp := api.UserTokenResp{CommResp: api.CommResp{ErrCode: reply.CommonResp.ErrCode, ErrMsg: reply.CommonResp.ErrMsg}, resp := api.UserTokenResp{CommResp: api.CommResp{ErrCode: reply.CommonResp.ErrCode, ErrMsg: reply.CommonResp.ErrMsg},
@@ -90,3 +98,29 @@ func UserToken(c *gin.Context) {
log.NewInfo(req.OperationID, "UserToken return ", resp) log.NewInfo(req.OperationID, "UserToken return ", resp)
c.JSON(http.StatusOK, 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()}) c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return return
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req:", req)
if err := utils.CopyStructFields(&reqPb, &req); err != nil { if err := utils.CopyStructFields(&reqPb, &req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields", err.Error()) 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) grpcConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfflineMessageName)
msgClient := pbChat.NewChatClient(grpcConn) msgClient := pbChat.NewChatClient(grpcConn)
respPb, err := msgClient.DelMsgList(context.Background(), &reqPb) respPb, err := msgClient.DelMsgList(context.Background(), &reqPb)
@@ -39,5 +39,6 @@ func DelMsg(c *gin.Context) {
} }
resp.ErrCode = respPb.ErrCode resp.ErrCode = respPb.ErrCode
resp.ErrMsg = respPb.ErrMsg resp.ErrMsg = respPb.ErrMsg
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), resp)
c.JSON(http.StatusOK, resp) c.JSON(http.StatusOK, resp)
} }

View File

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

View File

@@ -55,10 +55,10 @@ func PullMsgBySeqList(c *gin.Context) {
msgClient := pbChat.NewChatClient(grpcConn) msgClient := pbChat.NewChatClient(grpcConn)
reply, err := msgClient.PullMessageBySeqList(context.Background(), &pbData) reply, err := msgClient.PullMessageBySeqList(context.Background(), &pbData)
if err != nil { if err != nil {
log.ErrorByKv("PullMessageBySeqList error", pbData.OperationID, "err", err.Error()) log.Error(pbData.OperationID, "PullMessageBySeqList error", err.Error())
return 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{ c.JSON(http.StatusOK, gin.H{
"errCode": reply.ErrCode, "errCode": reply.ErrCode,
"errMsg": reply.ErrMsg, "errMsg": reply.ErrMsg,

View File

@@ -62,14 +62,12 @@ func SendMsg(c *gin.Context) {
params := paramsUserSendMsg{} params := paramsUserSendMsg{}
if err := c.BindJSON(&params); err != nil { if err := c.BindJSON(&params); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()}) 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 return
} }
token := c.Request.Header.Get("token") token := c.Request.Header.Get("token")
log.NewInfo(params.OperationID, "api call success to sendMsgReq", params)
log.InfoByKv("api call success to sendMsgReq", params.OperationID, "Parameters", params)
pbData := newUserSendMsgReq(token, &params) pbData := newUserSendMsgReq(token, &params)
log.Info("", "", "api SendMsg call start..., [data: %s]", pbData.String()) 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/config"
"Open_IM/pkg/common/log" "Open_IM/pkg/common/log"
"Open_IM/pkg/grpc-etcdv3/getcdv3" "Open_IM/pkg/grpc-etcdv3/getcdv3"
pbConversation "Open_IM/pkg/proto/conversation"
pbUser "Open_IM/pkg/proto/user" pbUser "Open_IM/pkg/proto/user"
"Open_IM/pkg/utils" "Open_IM/pkg/utils"
"context" "context"
@@ -24,13 +25,13 @@ func SetConversation(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()}) c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return return
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
reqPb.Conversation = &pbUser.Conversation{} reqPb.Conversation = &pbUser.Conversation{}
err := utils.CopyStructFields(&reqPb, req) err := utils.CopyStructFields(&reqPb, req)
err = utils.CopyStructFields(reqPb.Conversation, req.Conversation) err = utils.CopyStructFields(reqPb.Conversation, req.Conversation)
if err != nil { if err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) 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) etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pbUser.NewUserClient(etcdConn) client := pbUser.NewUserClient(etcdConn)
respPb, err := client.SetConversation(context.Background(), &reqPb) respPb, err := client.SetConversation(context.Background(), &reqPb)
@@ -44,6 +45,37 @@ func SetConversation(c *gin.Context) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, 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) { func BatchSetConversations(c *gin.Context) {
var ( var (
@@ -56,10 +88,10 @@ func BatchSetConversations(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()}) c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return return
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
if err := utils.CopyStructFields(&reqPb, req); err != nil { if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) 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) etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pbUser.NewUserClient(etcdConn) client := pbUser.NewUserClient(etcdConn)
respPb, err := client.BatchSetConversations(context.Background(), &reqPb) 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()}) c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return return
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
if err := utils.CopyStructFields(&reqPb, req); err != nil { if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) 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) etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pbUser.NewUserClient(etcdConn) client := pbUser.NewUserClient(etcdConn)
respPb, err := client.GetAllConversations(context.Background(), &reqPb) 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()}) c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return return
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
if err := utils.CopyStructFields(&reqPb, req); err != nil { if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) 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) etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pbUser.NewUserClient(etcdConn) client := pbUser.NewUserClient(etcdConn)
respPb, err := client.GetConversation(context.Background(), &reqPb) 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()}) c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return return
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
if err := utils.CopyStructFields(&reqPb, req); err != nil { if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) 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) etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pbUser.NewUserClient(etcdConn) client := pbUser.NewUserClient(etcdConn)
respPb, err := client.GetConversations(context.Background(), &reqPb) 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()}) c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return return
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
if err := utils.CopyStructFields(&reqPb, req); err != nil { if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) 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) etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pbUser.NewUserClient(etcdConn) client := pbUser.NewUserClient(etcdConn)
respPb, err := client.SetRecvMsgOpt(context.Background(), &reqPb) respPb, err := client.SetRecvMsgOpt(context.Background(), &reqPb)

View File

@@ -26,10 +26,12 @@ func AddBlack(c *gin.Context) {
req := &rpc.AddBlacklistReq{CommID: &rpc.CommID{}} req := &rpc.AddBlacklistReq{CommID: &rpc.CommID{}}
utils.CopyStructFields(req.CommID, &params) utils.CopyStructFields(req.CommID, &params)
var ok bool 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 { if !ok {
log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.CommID.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.CommID.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(params.OperationID, "AddBlacklist args ", req.String()) log.NewInfo(params.OperationID, "AddBlacklist args ", req.String())
@@ -57,12 +59,15 @@ func ImportFriend(c *gin.Context) {
req := &rpc.ImportFriendReq{} req := &rpc.ImportFriendReq{}
utils.CopyStructFields(req, &params) utils.CopyStructFields(req, &params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.OperationID, "ImportFriend args ", req.String()) 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) 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{}} req := &rpc.AddFriendReq{CommID: &rpc.CommID{}}
utils.CopyStructFields(req.CommID, &params.ParamsCommFriend) utils.CopyStructFields(req.CommID, &params.ParamsCommFriend)
req.ReqMsg = params.ReqMsg req.ReqMsg = params.ReqMsg
var ok bool 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 { if !ok {
log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.CommID.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.CommID.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.CommID.OperationID, "AddFriend args ", req.String()) 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) 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) utils.CopyStructFields(req.CommID, &params.ParamsCommFriend)
req.HandleMsg = params.HandleMsg req.HandleMsg = params.HandleMsg
req.HandleResult = params.Flag req.HandleResult = params.Flag
var ok bool 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 { if !ok {
log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.CommID.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.CommID.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
utils.CopyStructFields(req, &params) utils.CopyStructFields(req, &params)
log.NewInfo(req.CommID.OperationID, "AddFriendResponse args ", req.String()) log.NewInfo(req.CommID.OperationID, "AddFriendResponse args ", req.String())
@@ -163,13 +176,17 @@ func DeleteFriend(c *gin.Context) {
} }
req := &rpc.DeleteFriendReq{CommID: &rpc.CommID{}} req := &rpc.DeleteFriendReq{CommID: &rpc.CommID{}}
utils.CopyStructFields(req.CommID, &params.ParamsCommFriend) utils.CopyStructFields(req.CommID, &params.ParamsCommFriend)
var ok bool 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 { if !ok {
log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.CommID.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.CommID.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.CommID.OperationID, "DeleteFriend args ", req.String()) 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) 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{}} req := &rpc.GetBlacklistReq{CommID: &rpc.CommID{}}
utils.CopyStructFields(req.CommID, &params) utils.CopyStructFields(req.CommID, &params)
var ok bool 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 { if !ok {
log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.CommID.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.CommID.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.CommID.OperationID, "GetBlacklist args ", req.String()) 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) 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{}} req := &rpc.SetFriendRemarkReq{CommID: &rpc.CommID{}}
utils.CopyStructFields(req.CommID, &params.ParamsCommFriend) utils.CopyStructFields(req.CommID, &params.ParamsCommFriend)
req.Remark = params.Remark req.Remark = params.Remark
var ok bool 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 { if !ok {
log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.CommID.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.CommID.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.CommID.OperationID, "SetFriendComment args ", req.String()) 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) 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{}} req := &rpc.RemoveBlacklistReq{CommID: &rpc.CommID{}}
utils.CopyStructFields(req.CommID, &params.ParamsCommFriend) utils.CopyStructFields(req.CommID, &params.ParamsCommFriend)
var ok bool 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 { if !ok {
log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.CommID.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.CommID.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
@@ -297,13 +325,17 @@ func IsFriend(c *gin.Context) {
} }
req := &rpc.IsFriendReq{CommID: &rpc.CommID{}} req := &rpc.IsFriendReq{CommID: &rpc.CommID{}}
utils.CopyStructFields(req.CommID, &params.ParamsCommFriend) utils.CopyStructFields(req.CommID, &params.ParamsCommFriend)
var ok bool 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 { if !ok {
log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.CommID.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.CommID.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.CommID.OperationID, "IsFriend args ", req.String()) 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) 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) 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) { func GetFriendList(c *gin.Context) {
params := api.GetFriendListReq{} params := api.GetFriendListReq{}
if err := c.BindJSON(&params); err != nil { if err := c.BindJSON(&params); err != nil {
@@ -364,13 +362,17 @@ func GetFriendList(c *gin.Context) {
} }
req := &rpc.GetFriendListReq{CommID: &rpc.CommID{}} req := &rpc.GetFriendListReq{CommID: &rpc.CommID{}}
utils.CopyStructFields(req.CommID, &params) utils.CopyStructFields(req.CommID, &params)
var ok bool 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 { if !ok {
log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.CommID.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.CommID.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.CommID.OperationID, "GetFriendList args ", req.String()) 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) 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{}} req := &rpc.GetFriendApplyListReq{CommID: &rpc.CommID{}}
utils.CopyStructFields(req.CommID, &params) utils.CopyStructFields(req.CommID, &params)
var ok bool 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 { if !ok {
log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.CommID.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.CommID.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.CommID.OperationID, "GetFriendApplyList args ", req.String()) 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) 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{}} req := &rpc.GetSelfApplyListReq{CommID: &rpc.CommID{}}
utils.CopyStructFields(req.CommID, &params) utils.CopyStructFields(req.CommID, &params)
var ok bool 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 { if !ok {
log.NewError(req.CommID.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.CommID.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.CommID.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.CommID.OperationID, "GetSelfApplyList args ", req.String()) 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) 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{} req := &rpc.KickGroupMemberReq{}
utils.CopyStructFields(req, &params) utils.CopyStructFields(req, &params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
@@ -71,14 +74,17 @@ func GetGroupMembersInfo(c *gin.Context) {
} }
req := &rpc.GetGroupMembersInfoReq{} req := &rpc.GetGroupMembersInfoReq{}
utils.CopyStructFields(req, params) utils.CopyStructFields(req, params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
//c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
api.SetErrCodeMsg(c, http.StatusInternalServerError) c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.OperationID, "GetGroupMembersInfo args ", req.String()) 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) 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{} req := &rpc.GetGroupMemberListReq{}
utils.CopyStructFields(req, params) utils.CopyStructFields(req, params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.OperationID, "GetGroupMemberList args ", req.String()) 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) 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{} req := &rpc.GetGroupAllMemberReq{}
utils.CopyStructFields(req, &params) utils.CopyStructFields(req, &params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.OperationID, "GetGroupAllMember args ", req.String()) 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) 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{} req := &rpc.GetJoinedGroupListReq{}
utils.CopyStructFields(req, params) utils.CopyStructFields(req, params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.OperationID, "GetJoinedGroupList args ", req.String()) 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) 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{} req := &rpc.InviteUserToGroupReq{}
utils.CopyStructFields(req, &params) utils.CopyStructFields(req, &params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.OperationID, "InviteUserToGroup args ", req.String()) 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) 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 { for _, v := range params.MemberList {
req.InitMemberList = append(req.InitMemberList, &rpc.GroupAddMemberInfo{UserID: v.UserID, RoleLevel: v.RoleLevel}) req.InitMemberList = append(req.InitMemberList, &rpc.GroupAddMemberInfo{UserID: v.UserID, RoleLevel: v.RoleLevel})
} }
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
req.OwnerUserID = params.OwnerUserID req.OwnerUserID = params.OwnerUserID
req.OperationID = params.OperationID req.OperationID = params.OperationID
log.NewInfo(req.OperationID, "CreateGroup args ", req.String()) 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) 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{} req := &rpc.GetGroupsInfoReq{}
utils.CopyStructFields(req, &params) utils.CopyStructFields(req, &params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.OperationID, "GetGroupsInfo args ", req.String()) 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) etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := rpc.NewGroupClient(etcdConn) client := rpc.NewGroupClient(etcdConn)
@@ -388,13 +419,17 @@ func ApplicationGroupResponse(c *gin.Context) {
} }
req := &rpc.GroupApplicationResponseReq{} req := &rpc.GroupApplicationResponseReq{}
utils.CopyStructFields(req, &params) utils.CopyStructFields(req, &params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.OperationID, "ApplicationGroupResponse args ", req.String()) 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) 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{} req := &rpc.JoinGroupReq{}
utils.CopyStructFields(req, params) utils.CopyStructFields(req, params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.OperationID, "JoinGroup args ", req.String()) 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) etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := rpc.NewGroupClient(etcdConn) client := rpc.NewGroupClient(etcdConn)
@@ -451,13 +490,17 @@ func QuitGroup(c *gin.Context) {
} }
req := &rpc.QuitGroupReq{} req := &rpc.QuitGroupReq{}
utils.CopyStructFields(req, &params) utils.CopyStructFields(req, &params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.OperationID, "QuitGroup args ", req.String()) 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) 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{}} req := &rpc.SetGroupInfoReq{GroupInfo: &open_im_sdk.GroupInfo{}}
utils.CopyStructFields(req.GroupInfo, &params) utils.CopyStructFields(req.GroupInfo, &params)
req.OperationID = params.OperationID req.OperationID = params.OperationID
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.OperationID, "SetGroupInfo args ", req.String()) 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) 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{} req := &rpc.TransferGroupOwnerReq{}
utils.CopyStructFields(req, &params) utils.CopyStructFields(req, &params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.OperationID, "TransferGroupOwner args ", req.String()) 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) 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{} req := &rpc.DismissGroupReq{}
utils.CopyStructFields(req, &params) utils.CopyStructFields(req, &params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " args ", req.String()) 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) 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{} req := &rpc.MuteGroupMemberReq{}
utils.CopyStructFields(req, &params) utils.CopyStructFields(req, &params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " api args ", req.String()) 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) 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{} req := &rpc.CancelMuteGroupMemberReq{}
utils.CopyStructFields(req, &params) utils.CopyStructFields(req, &params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " api args ", req.String()) 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) 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{} req := &rpc.MuteGroupReq{}
utils.CopyStructFields(req, &params) utils.CopyStructFields(req, &params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " api args ", req.String()) 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) 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{} req := &rpc.CancelMuteGroupReq{}
utils.CopyStructFields(req, &params) utils.CopyStructFields(req, &params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " api args ", req.String()) 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) etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -708,13 +779,17 @@ func SetGroupMemberNickname(c *gin.Context) {
} }
req := &rpc.SetGroupMemberNicknameReq{} req := &rpc.SetGroupMemberNicknameReq{}
utils.CopyStructFields(req, &params) utils.CopyStructFields(req, &params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " api args ", req.String()) 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) etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
@@ -730,3 +805,7 @@ func SetGroupMemberNickname(c *gin.Context) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " api return ", resp) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " api return ", resp)
c.JSON(http.StatusOK, resp) c.JSON(http.StatusOK, resp)
} }
func GetGroupMemberIDListFromCache(c *gin.Context) {
}

View File

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

View File

@@ -30,13 +30,17 @@ func DeleteUser(c *gin.Context) {
} }
req := &rpc.DeleteUsersReq{} req := &rpc.DeleteUsersReq{}
utils.CopyStructFields(req, &params) utils.CopyStructFields(req, &params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(params.OperationID, "DeleteUser args ", req.String()) 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) etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := rpc.NewUserClient(etcdConn) client := rpc.NewUserClient(etcdConn)
@@ -62,13 +66,17 @@ func GetAllUsersUid(c *gin.Context) {
} }
req := &rpc.GetAllUserIDReq{} req := &rpc.GetAllUserIDReq{}
utils.CopyStructFields(req, &params) utils.CopyStructFields(req, &params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(params.OperationID, "GetAllUsersUid args ", req.String()) 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) etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := rpc.NewUserClient(etcdConn) client := rpc.NewUserClient(etcdConn)
@@ -94,13 +102,17 @@ func AccountCheck(c *gin.Context) {
} }
req := &rpc.AccountCheckReq{} req := &rpc.AccountCheckReq{}
utils.CopyStructFields(req, &params) utils.CopyStructFields(req, &params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(params.OperationID, "AccountCheck args ", req.String()) 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) etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := rpc.NewUserClient(etcdConn) client := rpc.NewUserClient(etcdConn)
@@ -127,11 +139,14 @@ func GetUsersOnlineStatus(c *gin.Context) {
} }
req := &pbRelay.GetUsersOnlineStatusReq{} req := &pbRelay.GetUsersOnlineStatusReq{}
utils.CopyStructFields(req, &params) utils.CopyStructFields(req, &params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }

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()}) c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
reqPb.UserID = userID reqPb.UserID = userID
reqPb.OperationID = req.OperationID reqPb.OperationID = req.OperationID
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName) 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 { if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
reqPb.UserID = userID reqPb.UserID = userID
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName) etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName)
client := pbOffice.NewOfficeServiceClient(etcdConn) client := pbOffice.NewOfficeServiceClient(etcdConn)
@@ -105,12 +117,18 @@ func DeleteTag(c *gin.Context) {
if err := utils.CopyStructFields(&reqPb, req); err != nil { if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
reqPb.UserID = userID reqPb.UserID = userID
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName) etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName)
client := pbOffice.NewOfficeServiceClient(etcdConn) client := pbOffice.NewOfficeServiceClient(etcdConn)
@@ -141,12 +159,18 @@ func SetTag(c *gin.Context) {
if err := utils.CopyStructFields(&reqPb, req); err != nil { if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
reqPb.UserID = userID reqPb.UserID = userID
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName) etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName)
client := pbOffice.NewOfficeServiceClient(etcdConn) client := pbOffice.NewOfficeServiceClient(etcdConn)
@@ -177,12 +201,18 @@ func SendMsg2Tag(c *gin.Context) {
if err := utils.CopyStructFields(&reqPb, req); err != nil { if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
reqPb.SendID = userID reqPb.SendID = userID
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName) etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName)
client := pbOffice.NewOfficeServiceClient(etcdConn) 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()}) c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
reqPb.UserID = userID reqPb.UserID = userID
reqPb.OperationID = req.OperationID reqPb.OperationID = req.OperationID
reqPb.Pagination = &pbCommon.RequestPagination{ 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()}) c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
reqPb.UserID = userID reqPb.UserID = userID
reqPb.OperationID = req.OperationID reqPb.OperationID = req.OperationID
reqPb.TagID = req.TagID reqPb.TagID = req.TagID

View File

@@ -28,12 +28,18 @@ func CreateOneWorkMoment(c *gin.Context) {
return return
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
if err := utils.CopyStructFields(&reqPb, req); err != nil { if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
} }
@@ -67,12 +73,18 @@ func DeleteOneWorkMoment(c *gin.Context) {
return return
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
if err := utils.CopyStructFields(&reqPb, req); err != nil { if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
} }
@@ -105,12 +117,18 @@ func LikeOneWorkMoment(c *gin.Context) {
return return
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
if err := utils.CopyStructFields(&reqPb, req); err != nil { if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
} }
@@ -143,12 +161,18 @@ func CommentOneWorkMoment(c *gin.Context) {
return return
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
if err := utils.CopyStructFields(&reqPb, req); err != nil { if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
} }
@@ -168,6 +192,48 @@ func CommentOneWorkMoment(c *gin.Context) {
c.JSON(http.StatusOK, 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) { func GetWorkMomentByID(c *gin.Context) {
var ( var (
req apiStruct.GetWorkMomentByIDReq req apiStruct.GetWorkMomentByIDReq
@@ -181,12 +247,18 @@ func GetWorkMomentByID(c *gin.Context) {
return return
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
reqPb.OperationID = req.OperationID reqPb.OperationID = req.OperationID
reqPb.OpUserID = userID reqPb.OpUserID = userID
reqPb.WorkMomentID = req.WorkMomentID reqPb.WorkMomentID = req.WorkMomentID
@@ -201,8 +273,8 @@ func GetWorkMomentByID(c *gin.Context) {
if err := utils.CopyStructFields(&resp, respPb.CommonResp); err != nil { if err := utils.CopyStructFields(&resp, respPb.CommonResp); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
} }
//resp.Data.WorkMoment = respPb.WorkMoment resp.Data.WorkMoment = &apiStruct.WorkMoment{LikeUserList: []*apiStruct.WorkMomentUser{}, Comments: []*apiStruct.Comment{},
resp.Data.WorkMoment = &apiStruct.WorkMoment{} AtUserList: []*apiStruct.WorkMomentUser{}, PermissionUserList: []*apiStruct.WorkMomentUser{}}
if err := utils.CopyStructFields(&resp.Data.WorkMoment, respPb.WorkMoment); err != nil { if err := utils.CopyStructFields(&resp.Data.WorkMoment, respPb.WorkMoment); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
} }
@@ -223,18 +295,25 @@ func GetUserWorkMoments(c *gin.Context) {
return return
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
ok, userID := token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
var ok bool
var errInfo string
var opUserID string
ok, opUserID, errInfo = token_verify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
reqPb.OperationID = req.OperationID reqPb.OperationID = req.OperationID
reqPb.Pagination = &pbCommon.RequestPagination{ reqPb.Pagination = &pbCommon.RequestPagination{
PageNumber: req.PageNumber, PageNumber: req.PageNumber,
ShowNumber: req.ShowNumber, ShowNumber: req.ShowNumber,
} }
reqPb.UserID = userID reqPb.OpUserID = opUserID
reqPb.UserID = req.UserID
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName) etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName)
client := pbOffice.NewOfficeServiceClient(etcdConn) client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.GetUserWorkMoments(context.Background(), &reqPb) respPb, err := client.GetUserWorkMoments(context.Background(), &reqPb)
@@ -243,11 +322,57 @@ func GetUserWorkMoments(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserWorkMoments rpc server failed" + err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserWorkMoments rpc server failed" + err.Error()})
return return
} }
resp.Data.WorkMoments = []*apiStruct.WorkMoment{}
if err := utils.CopyStructFields(&resp, respPb.CommonResp); err != nil { if err := utils.CopyStructFields(&resp, respPb.CommonResp); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
} }
if err := utils.CopyStructFields(&resp.Data.WorkMoments, respPb.WorkMoments); err != nil { //if err := utils.CopyStructFields(&resp.Data.WorkMoments, respPb.WorkMoments); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) // 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.ShowNumber = respPb.Pagination.ShowNumber
resp.Data.CurrentPage = respPb.Pagination.CurrentPage resp.Data.CurrentPage = respPb.Pagination.CurrentPage
@@ -268,12 +393,18 @@ func GetUserFriendWorkMoments(c *gin.Context) {
return return
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
reqPb.OperationID = req.OperationID reqPb.OperationID = req.OperationID
reqPb.Pagination = &pbCommon.RequestPagination{ reqPb.Pagination = &pbCommon.RequestPagination{
PageNumber: req.PageNumber, PageNumber: req.PageNumber,
@@ -291,8 +422,54 @@ func GetUserFriendWorkMoments(c *gin.Context) {
if err := utils.CopyStructFields(&resp, respPb.CommonResp); err != nil { if err := utils.CopyStructFields(&resp, respPb.CommonResp); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
} }
if err := utils.CopyStructFields(&resp.Data.WorkMoments, respPb.WorkMoments); err != nil { //if err := utils.CopyStructFields(&resp.Data.WorkMoments, respPb.WorkMoments); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) // 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.ShowNumber = respPb.Pagination.ShowNumber
resp.Data.CurrentPage = respPb.Pagination.CurrentPage resp.Data.CurrentPage = respPb.Pagination.CurrentPage
@@ -313,12 +490,18 @@ func SetUserWorkMomentsLevel(c *gin.Context) {
return return
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
if err := utils.CopyStructFields(&reqPb, req); err != nil { if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
} }

View File

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

View File

@@ -11,7 +11,7 @@ import (
) )
var ( var (
minioClient *minio.Client MinioClient *minio.Client
) )
func MinioInit() { func MinioInit() {
@@ -29,11 +29,16 @@ func MinioInit() {
log.NewError(operationID, utils.GetSelfFuncName(), "parse failed, please check config/config.yaml", err.Error()) log.NewError(operationID, utils.GetSelfFuncName(), "parse failed, please check config/config.yaml", err.Error())
return return
} }
log.NewInfo(operationID, utils.GetSelfFuncName(), "Parse ok ", config.Config.Credential.Minio) opts := &minio.Options{
minioClient, err = minio.New(minioUrl.Host, &minio.Options{
Creds: credentials.NewStaticV4(config.Config.Credential.Minio.AccessKeyID, config.Config.Credential.Minio.SecretAccessKey, ""), Creds: credentials.NewStaticV4(config.Config.Credential.Minio.AccessKeyID, config.Config.Credential.Minio.SecretAccessKey, ""),
Secure: false, }
}) 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) log.NewInfo(operationID, utils.GetSelfFuncName(), "new ok ", config.Config.Credential.Minio)
if err != nil { if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "init minio client failed", err.Error()) log.NewError(operationID, utils.GetSelfFuncName(), "init minio client failed", err.Error())
@@ -43,10 +48,25 @@ func MinioInit() {
Region: config.Config.Credential.Minio.Location, Region: config.Config.Credential.Minio.Location,
ObjectLocking: false, 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 { if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "MakeBucket failed ", err.Error()) 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 { if err == nil && exists {
log.NewWarn(operationID, utils.GetSelfFuncName(), "We already own ", config.Config.Credential.Minio.Bucket) log.NewWarn(operationID, utils.GetSelfFuncName(), "We already own ", config.Config.Credential.Minio.Bucket)
} else { } else {
@@ -58,9 +78,10 @@ func MinioInit() {
} }
} }
// 自动化桶public的代码 // 自动化桶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 { //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 // return
//} //}
log.NewInfo(operationID, utils.GetSelfFuncName(), "minio create and set policy success") log.NewInfo(operationID, utils.GetSelfFuncName(), "minio create and set policy success")

View File

@@ -4,6 +4,7 @@ import (
apiStruct "Open_IM/pkg/base_info" apiStruct "Open_IM/pkg/base_info"
"Open_IM/pkg/common/config" "Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant" "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/log"
"Open_IM/pkg/common/token_verify" "Open_IM/pkg/common/token_verify"
_ "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()}) c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return 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 { if !ok {
log.NewError("", utils.GetSelfFuncName(), "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), req) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), req)
switch req.FileType { switch req.FileType {
// videoType upload snapShot // videoType upload snapShot
@@ -56,7 +62,7 @@ func MinioUploadFile(c *gin.Context) {
} }
snapShotNewName, snapShotNewType := utils.GetNewFileNameAndContentType(snapShotFile.Filename, constant.ImageType) snapShotNewName, snapShotNewType := utils.GetNewFileNameAndContentType(snapShotFile.Filename, constant.ImageType)
log.Debug(req.OperationID, utils.GetSelfFuncName(), snapShotNewName, snapShotNewType) 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 { if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "PutObject snapShotFile error", err.Error()) log.NewError(req.OperationID, utils.GetSelfFuncName(), "PutObject snapShotFile error", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": 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") file, err := c.FormFile("file")
if err != nil { 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()}) c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "missing file arg: " + err.Error()})
return return
} }
@@ -77,11 +84,11 @@ func MinioUploadFile(c *gin.Context) {
return return
} }
newName, newType := utils.GetNewFileNameAndContentType(file.Filename, req.FileType) newName, newType := utils.GetNewFileNameAndContentType(file.Filename, req.FileType)
log.Debug(req.OperationID, utils.GetSelfFuncName(), newName, 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}) _, err = MinioClient.PutObject(context.Background(), config.Config.Credential.Minio.Bucket, newName, fileObj, file.Size, minio.PutObjectOptions{ContentType: newType})
if err != nil { if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "open file error") log.NewError(req.OperationID, utils.GetSelfFuncName(), "upload file error")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "invalid file path" + err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "upload file error" + err.Error()})
return return
} }
resp.NewName = newName resp.NewName = newName
@@ -101,12 +108,17 @@ func MinioStorageCredential(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()}) c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return 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 { if !ok {
log.NewError("", utils.GetSelfFuncName(), "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
var stsOpts cr.STSAssumeRoleOptions var stsOpts cr.STSAssumeRoleOptions
stsOpts.AccessKey = config.Config.Credential.Minio.AccessKeyID stsOpts.AccessKey = config.Config.Credential.Minio.AccessKeyID
stsOpts.SecretKey = config.Config.Credential.Minio.SecretAccessKey stsOpts.SecretKey = config.Config.Credential.Minio.SecretAccessKey
@@ -136,3 +148,98 @@ func MinioStorageCredential(c *gin.Context) {
resp.StsEndpointURL = config.Config.Credential.Minio.Endpoint resp.StsEndpointURL = config.Config.Credential.Minio.Endpoint
c.JSON(http.StatusOK, gin.H{"errCode": 0, "errMsg": "", "data": resp}) 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()}) c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(req.OperationID, "TencentCloudStorageCredential args ", userID) log.NewInfo(req.OperationID, "TencentCloudStorageCredential args ", userID)
cli := sts.NewClient( cli := sts.NewClient(

View File

@@ -8,6 +8,7 @@ import (
"Open_IM/pkg/common/log" "Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify" "Open_IM/pkg/common/token_verify"
"Open_IM/pkg/grpc-etcdv3/getcdv3" "Open_IM/pkg/grpc-etcdv3/getcdv3"
cacheRpc "Open_IM/pkg/proto/cache"
pbRelay "Open_IM/pkg/proto/relay" pbRelay "Open_IM/pkg/proto/relay"
open_im_sdk "Open_IM/pkg/proto/sdk_ws" open_im_sdk "Open_IM/pkg/proto/sdk_ws"
rpc "Open_IM/pkg/proto/user" rpc "Open_IM/pkg/proto/user"
@@ -18,6 +19,116 @@ import (
"strings" "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) { func GetUsersInfo(c *gin.Context) {
params := api.GetUsersInfoReq{} params := api.GetUsersInfoReq{}
if err := c.BindJSON(&params); err != nil { if err := c.BindJSON(&params); err != nil {
@@ -27,13 +138,17 @@ func GetUsersInfo(c *gin.Context) {
} }
req := &rpc.GetUserInfoReq{} req := &rpc.GetUserInfoReq{}
utils.CopyStructFields(req, &params) utils.CopyStructFields(req, &params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(params.OperationID, "GetUserInfo args ", req.String()) 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) etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
@@ -65,13 +180,14 @@ func UpdateUserInfo(c *gin.Context) {
} }
req := &rpc.UpdateUserInfoReq{UserInfo: &open_im_sdk.UserInfo{}} req := &rpc.UpdateUserInfoReq{UserInfo: &open_im_sdk.UserInfo{}}
utils.CopyStructFields(req.UserInfo, &params) utils.CopyStructFields(req.UserInfo, &params)
req.OperationID = params.OperationID req.OperationID = params.OperationID
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
log.NewInfo(params.OperationID, "UpdateUserInfo args ", req.String()) log.NewInfo(params.OperationID, "UpdateUserInfo args ", req.String())
@@ -99,13 +215,17 @@ func GetSelfUserInfo(c *gin.Context) {
req := &rpc.GetUserInfoReq{} req := &rpc.GetUserInfoReq{}
utils.CopyStructFields(req, &params) utils.CopyStructFields(req, &params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
req.UserIDList = append(req.UserIDList, req.OpUserID) req.UserIDList = append(req.UserIDList, req.OpUserID)
log.NewInfo(params.OperationID, "GetUserInfo args ", req.String()) log.NewInfo(params.OperationID, "GetUserInfo args ", req.String())
@@ -138,13 +258,17 @@ func GetUsersOnlineStatus(c *gin.Context) {
} }
req := &pbRelay.GetUsersOnlineStatusReq{} req := &pbRelay.GetUsersOnlineStatusReq{}
utils.CopyStructFields(req, &params) utils.CopyStructFields(req, &params)
var ok bool 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 { if !ok {
log.NewError(req.OperationID, "GetUserIDFromToken false ", c.Request.Header.Get("token")) errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserIDFromToken failed"}) log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return return
} }
if len(config.Config.Manager.AppManagerUid) == 0 { if len(config.Config.Manager.AppManagerUid) == 0 {
log.NewError(req.OperationID, "Manager == 0") log.NewError(req.OperationID, "Manager == 0")
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "Manager == 0"}) c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "Manager == 0"})

View File

@@ -1,7 +1,7 @@
package admin package admin
import ( import (
"Open_IM/pkg/cms_api_struct" apiStruct "Open_IM/pkg/cms_api_struct"
"Open_IM/pkg/common/config" "Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant" "Open_IM/pkg/common/constant"
openIMHttp "Open_IM/pkg/common/http" openIMHttp "Open_IM/pkg/common/http"
@@ -10,16 +10,55 @@ import (
pbAdmin "Open_IM/pkg/proto/admin_cms" pbAdmin "Open_IM/pkg/proto/admin_cms"
"Open_IM/pkg/utils" "Open_IM/pkg/utils"
"context" "context"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"strings" "strings"
"github.com/gin-gonic/gin" "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 // register
func AdminLogin(c *gin.Context) { func AdminLogin(c *gin.Context) {
var ( var (
req cms_api_struct.AdminLoginRequest req apiStruct.AdminLoginRequest
resp cms_api_struct.AdminLoginResponse resp apiStruct.AdminLoginResponse
reqPb pbAdmin.AdminLoginReq reqPb pbAdmin.AdminLoginReq
) )
if err := c.BindJSON(&req); err != nil { if err := c.BindJSON(&req); err != nil {

View File

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

View File

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

View File

@@ -11,7 +11,7 @@ import (
func JWTAuth() gin.HandlerFunc { func JWTAuth() gin.HandlerFunc {
return func(c *gin.Context) { 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) log.NewInfo("0", utils.GetSelfFuncName(), "userID: ", userID)
c.Set("userID", userID) c.Set("userID", userID)
if !ok { if !ok {
@@ -19,6 +19,8 @@ func JWTAuth() gin.HandlerFunc {
c.Abort() c.Abort()
http.RespHttp200(c, constant.ErrParseToken, nil) http.RespHttp200(c, constant.ErrParseToken, nil)
return return
} else {
log.NewInfo("0", utils.GetSelfFuncName(), "failed: ", errInfo)
} }
} }
} }

View File

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

View File

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

View File

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

View File

@@ -46,7 +46,7 @@ func Login(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"errCode": constant.PasswordErr, "errMsg": "password err"}) c.JSON(http.StatusOK, gin.H{"errCode": constant.PasswordErr, "errMsg": "password err"})
return 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 := api.UserTokenReq{}
openIMGetUserToken.OperationID = params.OperationID openIMGetUserToken.OperationID = params.OperationID
openIMGetUserToken.Platform = params.Platform 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

@@ -77,7 +77,7 @@ func SendVerificationCode(c *gin.Context) {
m.SetHeader(`Subject`, config.Config.Demo.Mail.Title) m.SetHeader(`Subject`, config.Config.Demo.Mail.Title)
m.SetBody(`text/html`, fmt.Sprintf("%d", code)) 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 { 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": ""}) c.JSON(http.StatusOK, gin.H{"errCode": constant.MailSendCodeErr, "errMsg": ""})
return return
} }

View File

@@ -53,7 +53,7 @@ func SetPassword(c *gin.Context) {
return 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 := api.UserRegisterReq{}
openIMRegisterReq.OperationID = params.OperationID openIMRegisterReq.OperationID = params.OperationID
openIMRegisterReq.Platform = params.Platform openIMRegisterReq.Platform = params.Platform
@@ -84,6 +84,8 @@ func SetPassword(c *gin.Context) {
return return
} }
log.Info(params.OperationID, "end setPassword", account, params.Password) 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}) c.JSON(http.StatusOK, gin.H{"errCode": constant.NoError, "errMsg": "", "data": openIMRegisterResp.UserToken})
return return
} }

View File

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

View File

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

View File

@@ -14,9 +14,7 @@ import (
"encoding/gob" "encoding/gob"
"github.com/golang/protobuf/proto" "github.com/golang/protobuf/proto"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
"google.golang.org/grpc"
"runtime" "runtime"
"strconv"
"strings" "strings"
) )
@@ -62,7 +60,7 @@ func (ws *WServer) msgParse(conn *UserConn, binaryMsg []byte) {
ws.pullMsgBySeqListReq(conn, &m) ws.pullMsgBySeqListReq(conn, &m)
default: 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) { 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) 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.UserID = m.SendID
rpcReq.OperationID = m.OperationID rpcReq.OperationID = m.OperationID
grpcConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfflineMessageName) 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) msgClient := pbChat.NewChatClient(grpcConn)
rpcReply, err := msgClient.GetMaxAndMinSeq(context.Background(), &rpcReq) rpcReply, err := msgClient.GetMaxAndMinSeq(context.Background(), &rpcReq)
if err != nil { if err != nil {
@@ -82,7 +77,7 @@ func (ws *WServer) getSeqReq(conn *UserConn, m *Req) {
nReply.ErrMsg = err.Error() nReply.ErrMsg = err.Error()
ws.getSeqResp(conn, m, nReply) ws.getSeqResp(conn, m, nReply)
} else { } 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) 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) { 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) log.NewInfo(m.OperationID, "Ws call success to sendMsgReq start", m.MsgIncr, m.ReqIdentifier, m.SendID, m.Data)
nReply := new(pbChat.SendMsgResp) nReply := new(pbChat.SendMsgResp)
isPass, errCode, errMsg, pData := ws.argsValidate(m, constant.WSSendMsg) 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) isPass, errCode, errMsg, pData := ws.argsValidate(m, constant.WSSendSignalMsg)
if isPass { if isPass {
signalResp := pbRtc.SignalResp{} signalResp := pbRtc.SignalResp{}
//isPass2, errCode2, errMsg2, signalResp, msgData := ws.signalMessageAssemble(pData.(*sdk_ws.SignalReq), m.OperationID) etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImRealTimeCommName)
connGrpc, err := grpc.Dial(config.Config.Rtc.Address+":"+strconv.Itoa(config.Config.Rtc.Port), grpc.WithInsecure()) rtcClient := pbRtc.NewRtcServiceClient(etcdConn)
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)
req := &pbRtc.SignalMessageAssembleReq{ req := &pbRtc.SignalMessageAssembleReq{
SignalReq: pData.(*pbRtc.SignalReq), SignalReq: pData.(*pbRtc.SignalReq),
OperationID: m.OperationID, OperationID: m.OperationID,
} }
respPb, err := rtcClient.SignalMessageAssemble(context.Background(), req) respPb, err := rtcClient.SignalMessageAssemble(context.Background(), req)
if err != nil { 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) ws.sendSignalMsgResp(conn, 204, "grpc SignalMessageAssemble failed: "+err.Error(), m, &signalResp)
return return
} }

View File

@@ -11,9 +11,9 @@ import (
"bytes" "bytes"
"context" "context"
"encoding/gob" "encoding/gob"
"fmt"
"github.com/golang/protobuf/proto" "github.com/golang/protobuf/proto"
"net" "net"
"strconv"
"strings" "strings"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
@@ -34,29 +34,41 @@ func (r *RPCServer) onInit(rpcPort int) {
r.etcdAddr = config.Config.Etcd.EtcdAddr r.etcdAddr = config.Config.Etcd.EtcdAddr
} }
func (r *RPCServer) run() { func (r *RPCServer) run() {
ip := utils.ServerIP listenIP := ""
registerAddress := ip + ":" + utils.IntToString(r.rpcPort) if config.Config.ListenIP == "" {
listener, err := net.Listen("tcp", registerAddress) 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 { if err != nil {
log.ErrorByArgs(fmt.Sprintf("fail to listening consumer, err:%v\n", err)) panic("listening err:" + err.Error() + r.rpcRegisterName)
return
} }
defer listener.Close() defer listener.Close()
srv := grpc.NewServer() srv := grpc.NewServer()
defer srv.GracefulStop() defer srv.GracefulStop()
pbRelay.RegisterOnlineMessageRelayServiceServer(srv, r) 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 { if err != nil {
log.ErrorByKv("register push message rpc to etcd err", "", "err", err.Error()) 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.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) err = srv.Serve(listener)
if err != nil { if err != nil {
log.ErrorByKv("push message rpc listening err", "", "err", err.Error()) log.Error("", "push message rpc listening err", "", "err", err.Error())
return return
} }
} }
func (r *RPCServer) OnlinePushMsg(_ context.Context, in *pbRelay.OnlinePushMsgReq) (*pbRelay.OnlinePushMsgResp, error) { 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 var resp []*pbRelay.SingleMsgToUser
msgBytes, _ := proto.Marshal(in.MsgData) msgBytes, _ := proto.Marshal(in.MsgData)
mReply := Resp{ mReply := Resp{
@@ -93,7 +105,7 @@ func (r *RPCServer) OnlinePushMsg(_ context.Context, in *pbRelay.OnlinePushMsgRe
} }
} }
if !tag { 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{ return &pbRelay.OnlinePushMsgResp{
Resp: resp, Resp: resp,
@@ -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) { func sendMsgToUser(conn *UserConn, bMsg []byte, in *pbRelay.OnlinePushMsgReq, RecvPlatForm, RecvID string) (ResultCode int64) {
err := ws.writeMsg(conn, websocket.BinaryMessage, bMsg) err := ws.writeMsg(conn, websocket.BinaryMessage, bMsg)
if err != nil { 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) "error", err, "senderPlatform", constant.PlatformIDToName(in.MsgData.SenderPlatformID), "recvPlatform", RecvPlatForm, "args", in.String(), "recvID", RecvID)
ResultCode = -2 ResultCode = -2
return ResultCode return ResultCode
} else { } 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 ResultCode = 0
return ResultCode return ResultCode
} }

View File

@@ -62,11 +62,11 @@ func (ws *WServer) argsValidate(m *Req, r int32) (isPass bool, errCode int32, er
case constant.WSSendMsg: case constant.WSSendMsg:
data := open_im_sdk.MsgData{} data := open_im_sdk.MsgData{}
if err := proto.Unmarshal(m.Data, &data); err != nil { 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 return false, 203, err.Error(), nil
} }
if err := validate.Struct(data); err != 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 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: case constant.WSSendSignalMsg:
data := pbRtc.SignalReq{} data := pbRtc.SignalReq{}
if err := proto.Unmarshal(m.Data, &data); err != nil { 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 return false, 203, err.Error(), nil
} }
if err := validate.Struct(data); err != 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 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: case constant.WSPullMsgBySeqList:
data := open_im_sdk.PullMessageBySeqListReq{} data := open_im_sdk.PullMessageBySeqListReq{}
if err := proto.Unmarshal(m.Data, &data); err != nil { 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 return false, 203, err.Error(), nil
} }
if err := validate.Struct(data); err != 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 return false, 204, err.Error(), nil
} }
@@ -114,140 +114,3 @@ func (ws *WServer) argsValidate(m *Req, r int32) (isPass bool, errCode int32, er
//} else //} 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 http.HandleFunc("/", ws.wsHandler) //Get request from client to handle by wsHandler
err := http.ListenAndServe(ws.wsAddr, nil) //Start listening err := http.ListenAndServe(ws.wsAddr, nil) //Start listening
if err != nil { 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() query := r.URL.Query()
conn, err := ws.wsUpGrader.Upgrade(w, r, nil) //Conn is obtained through the upgraded escalator conn, err := ws.wsUpGrader.Upgrade(w, r, nil) //Conn is obtained through the upgraded escalator
if err != nil { if err != nil {
log.ErrorByKv("upgrade http conn err", "", "err", err) log.Error("", "upgrade http conn err", err, query)
return return
} else { } else {
//Connection mapping relationship, //Connection mapping relationship,
@@ -62,6 +62,7 @@ func (ws *WServer) wsHandler(w http.ResponseWriter, r *http.Request) {
//Initialize a lock for each user //Initialize a lock for each user
newConn := &UserConn{conn, new(sync.Mutex)} newConn := &UserConn{conn, new(sync.Mutex)}
userCount++
ws.addUserConn(query["sendID"][0], int32(utils.StringToInt64(query["platformID"][0])), newConn, query["token"][0]) ws.addUserConn(query["sendID"][0], int32(utils.StringToInt64(query["platformID"][0])), newConn, query["token"][0])
go ws.readMsg(newConn) go ws.readMsg(newConn)
} }
@@ -76,7 +77,8 @@ func (ws *WServer) readMsg(conn *UserConn) {
} }
if err != nil { if err != nil {
uid, platform := ws.getUserUid(conn) 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) ws.delUserConn(conn)
return return
} else { } else {
@@ -189,13 +191,13 @@ func (ws *WServer) addUserConn(uid string, platformID int32, conn *UserConn, tok
count = count + len(v) 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) 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) { func (ws *WServer) delUserConn(conn *UserConn) {
rwLock.Lock() rwLock.Lock()
defer rwLock.Unlock() defer rwLock.Unlock()
operationID := utils.OperationIDGenerator()
var platform, uid string var platform, uid string
if oldStringMap, ok := ws.wsConnToUser[conn]; ok { if oldStringMap, ok := ws.wsConnToUser[conn]; ok {
for k, v := range oldStringMap { for k, v := range oldStringMap {
@@ -212,18 +214,16 @@ func (ws *WServer) delUserConn(conn *UserConn) {
for _, v := range ws.wsUserToConn { for _, v := range ws.wsUserToConn {
count = count + len(v) 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 { } 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) delete(ws.wsConnToUser, conn)
} }
err := conn.Close() err := conn.Close()
if err != nil { if err != nil {
log.ErrorByKv("close err", "", "uid", uid, "platform", platform) log.Error(operationID, " close err", "", "uid", uid, "platform", platform)
} }
} }
@@ -267,7 +267,7 @@ func (ws *WServer) headerCheck(w http.ResponseWriter, r *http.Request) bool {
operationID = query["operationID"][0] operationID = query["operationID"][0]
} }
if len(query["token"]) != 0 && len(query["sendID"]) != 0 && len(query["platformID"]) != 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 { if ok, err, msg := token_verify.WsVerifyToken(query["token"][0], query["sendID"][0], query["platformID"][0], operationID); !ok {
// e := err.(*constant.ErrInfo) // e := err.(*constant.ErrInfo)
log.Error(operationID, "Token verify failed ", "query ", query, msg, err.Error()) log.Error(operationID, "Token verify failed ", "query ", query, msg, err.Error())
w.Header().Set("Sec-Websocket-Version", "13") w.Header().Set("Sec-Websocket-Version", "13")
@@ -281,7 +281,7 @@ func (ws *WServer) headerCheck(w http.ResponseWriter, r *http.Request) bool {
} else { } else {
log.Error(operationID, "Args err", "query", query) log.Error(operationID, "Args err", "query", query)
w.Header().Set("Sec-Websocket-Version", "13") w.Header().Set("Sec-Websocket-Version", "13")
w.Header().Set("ws_err_msg", "args err") w.Header().Set("ws_err_msg", "args err, need token, sendID, platformID")
http.Error(w, http.StatusText(status), status) http.Error(w, http.StatusText(status), status)
return false return false
} }

View File

@@ -2,20 +2,40 @@ package logic
import ( import (
"Open_IM/pkg/common/config" "Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/kafka" "Open_IM/pkg/common/kafka"
"Open_IM/pkg/common/log"
"Open_IM/pkg/statistics"
"fmt" "fmt"
"sync"
) )
const OnlineTopicBusy = 1
const OnlineTopicVacancy = 0
var ( var (
persistentCH PersistentConsumerHandler persistentCH PersistentConsumerHandler
historyCH HistoryConsumerHandler historyCH OnlineHistoryConsumerHandler
offlineHistoryCH OfflineHistoryConsumerHandler
producer *kafka.Producer producer *kafka.Producer
cmdCh chan Cmd2Value
onlineTopicStatus int
w *sync.Mutex
singleMsgSuccessCount uint64
groupMsgCount uint64
singleMsgFailedCount uint64
) )
func Init() { func Init() {
cmdCh = make(chan Cmd2Value, 10000)
w = new(sync.Mutex)
persistentCH.Init() 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) producer = kafka.NewKafkaProducer(config.Config.Kafka.Ms2pschat.Addr, config.Config.Kafka.Ms2pschat.Topic)
} }
func Run() { func Run() {
@@ -26,4 +46,15 @@ func Run() {
fmt.Println("not start mysql consumer") fmt.Println("not start mysql consumer")
} }
go historyCH.historyConsumerGroup.RegisterHandleAndConsumer(&historyCH) 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" "Open_IM/pkg/grpc-etcdv3/getcdv3"
pbMsg "Open_IM/pkg/proto/chat" pbMsg "Open_IM/pkg/proto/chat"
pbPush "Open_IM/pkg/proto/push" pbPush "Open_IM/pkg/proto/push"
"Open_IM/pkg/statistics"
"Open_IM/pkg/utils" "Open_IM/pkg/utils"
"context" "context"
"errors"
"github.com/Shopify/sarama" "github.com/Shopify/sarama"
"github.com/golang/protobuf/proto" "github.com/golang/protobuf/proto"
"strings" "strings"
"time"
) )
type fcb func(msg []byte, msgKey string) type fcb func(msg []byte, msgKey string)
type Cmd2Value struct {
type HistoryConsumerHandler struct { Cmd int
Value interface{}
}
type OnlineHistoryConsumerHandler struct {
msgHandle map[string]fcb msgHandle map[string]fcb
historyConsumerGroup *kfk.MConsumerGroup historyConsumerGroup *kfk.MConsumerGroup
singleMsgCount uint64 cmdCh chan Cmd2Value
groupMsgCount uint64
} }
func (mc *HistoryConsumerHandler) Init() { func (och *OnlineHistoryConsumerHandler) Init(cmdCh chan Cmd2Value) {
statistics.NewStatistics(&mc.singleMsgCount, config.Config.ModuleName.MsgTransferName, "singleMsgCount insert to mongo ", 300) och.msgHandle = make(map[string]fcb)
statistics.NewStatistics(&mc.groupMsgCount, config.Config.ModuleName.MsgTransferName, "groupMsgCount insert to mongo ", 300) och.cmdCh = cmdCh
och.msgHandle[config.Config.Kafka.Ws2mschat.Topic] = och.handleChatWs2Mongo
mc.msgHandle = make(map[string]fcb) och.historyConsumerGroup = kfk.NewMConsumerGroup(&kfk.MConsumerGroupConfig{KafkaVersion: sarama.V0_10_2_0,
mc.msgHandle[config.Config.Kafka.Ws2mschat.Topic] = mc.handleChatWs2Mongo
mc.historyConsumerGroup = kfk.NewMConsumerGroup(&kfk.MConsumerGroupConfig{KafkaVersion: sarama.V0_10_2_0,
OffsetsInitial: sarama.OffsetNewest, IsReturnErr: false}, []string{config.Config.Kafka.Ws2mschat.Topic}, OffsetsInitial: sarama.OffsetNewest, IsReturnErr: false}, []string{config.Config.Kafka.Ws2mschat.Topic},
config.Config.Kafka.Ws2mschat.Addr, config.Config.Kafka.ConsumerGroupID.MsgToMongo) 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{} msgFromMQ := pbMsg.MsgDataToMQ{}
err := proto.Unmarshal(msg, &msgFromMQ) err := proto.Unmarshal(msg, &msgFromMQ)
if err != nil { if err != nil {
@@ -58,17 +82,18 @@ func (mc *HistoryConsumerHandler) handleChatWs2Mongo(msg []byte, msgKey string)
if isHistory { if isHistory {
err := saveUserChat(msgKey, &msgFromMQ) err := saveUserChat(msgKey, &msgFromMQ)
if err != nil { if err != nil {
singleMsgFailedCount++
log.NewError(operationID, "single data insert to mongo err", err.Error(), msgFromMQ.String()) log.NewError(operationID, "single data insert to mongo err", err.Error(), msgFromMQ.String())
return return
} }
mc.singleMsgCount++ singleMsgSuccessCount++
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 { if !isSenderSync && msgKey == msgFromMQ.MsgData.SendID {
} else { } else {
go sendMessageToPush(&msgFromMQ, msgKey) 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: case constant.GroupChatType:
log.NewDebug(msgFromMQ.OperationID, "msg_transfer msg type = GroupChatType", isHistory, isPersist) log.NewDebug(msgFromMQ.OperationID, "msg_transfer msg type = GroupChatType", isHistory, isPersist)
if isHistory { 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()) log.NewError(operationID, "group data insert to mongo err", msgFromMQ.String(), msgFromMQ.MsgData.RecvID, err.Error())
return return
} }
mc.groupMsgCount++ groupMsgCount++
} }
go sendMessageToPush(&msgFromMQ, msgFromMQ.MsgData.RecvID) go sendMessageToPush(&msgFromMQ, msgFromMQ.MsgData.RecvID)
case constant.NotificationChatType: 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()) log.NewError(operationID, "single data insert to mongo err", err.Error(), msgFromMQ.String())
return return
} }
mc.singleMsgCount++ log.NewDebug(msgFromMQ.OperationID, "sendMessageToPush cost time ", time.Since(now))
log.NewDebug(msgFromMQ.OperationID, "sendMessageToPush cost time ", utils.GetCurrentTimestampByNano()-time)
} }
if !isSenderSync && msgKey == msgFromMQ.MsgData.SendID { if !isSenderSync && msgKey == msgFromMQ.MsgData.SendID {
} else { } else {
go sendMessageToPush(&msgFromMQ, msgKey) go sendMessageToPush(&msgFromMQ, msgKey)
} }
log.NewDebug(operationID, "saveUserChat cost time ", utils.GetCurrentTimestampByNano()-time) log.NewDebug(operationID, "saveUserChat cost time ", time.Since(now))
default: default:
log.NewError(msgFromMQ.OperationID, "SessionType error", msgFromMQ.String()) log.NewError(msgFromMQ.OperationID, "SessionType error", msgFromMQ.String())
return 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()) log.NewDebug(msgFromMQ.OperationID, "msg_transfer handle topic data to database success...", msgFromMQ.String())
} }
func (HistoryConsumerHandler) Setup(_ sarama.ConsumerGroupSession) error { return nil } func (OnlineHistoryConsumerHandler) Setup(_ sarama.ConsumerGroupSession) error { return nil }
func (HistoryConsumerHandler) Cleanup(_ sarama.ConsumerGroupSession) error { return nil } func (OnlineHistoryConsumerHandler) Cleanup(_ sarama.ConsumerGroupSession) error { return nil }
func (mc *HistoryConsumerHandler) ConsumeClaim(sess sarama.ConsumerGroupSession, func (och *OnlineHistoryConsumerHandler) ConsumeClaim(sess sarama.ConsumerGroupSession,
claim sarama.ConsumerGroupClaim) error { 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() { for msg := range claim.Messages() {
log.InfoByKv("kafka get info to mongo", "", "msgTopic", msg.Topic, "msgPartition", msg.Partition, "msg", string(msg.Value)) SetOnlineTopicStatus(OnlineTopicBusy)
mc.msgHandle[msg.Topic](msg.Value, string(msg.Key)) //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, "") 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 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()) log.Error(rpcPushMsg.OperationID, "rpc send failed", rpcPushMsg.OperationID, "push data", rpcPushMsg.String(), "err", err.Error())
pid, offset, err := producer.SendMessage(&mqPushMsg) pid, offset, err := producer.SendMessage(&mqPushMsg)
if err != nil { 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 { } 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 tag = true
} }
case constant.GroupChatType: case constant.GroupChatType:
if msgKey == msgFromMQ.MsgData.SendID || utils.IsContain(msgFromMQ.MsgData.SendID, config.Config.Manager.AppManagerUid) { if msgKey == msgFromMQ.MsgData.SendID {
tag = true tag = true
} }
} }
@@ -70,7 +70,7 @@ func (PersistentConsumerHandler) Cleanup(_ sarama.ConsumerGroupSession) error {
func (pc *PersistentConsumerHandler) ConsumeClaim(sess sarama.ConsumerGroupSession, func (pc *PersistentConsumerHandler) ConsumeClaim(sess sarama.ConsumerGroupSession,
claim sarama.ConsumerGroupClaim) error { claim sarama.ConsumerGroupClaim) error {
for msg := range claim.Messages() { 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)) pc.msgHandle[msg.Topic](msg.Value, string(msg.Key))
sess.MarkMessage(msg, "") sess.MarkMessage(msg, "")
} }

View File

@@ -19,7 +19,7 @@ var (
pushCh PushConsumerHandler pushCh PushConsumerHandler
pushTerminal []int32 pushTerminal []int32
producer *kafka.Producer producer *kafka.Producer
count uint64 successCount uint64
) )
func Init(rpcPort int) { func Init(rpcPort int) {
@@ -30,7 +30,7 @@ func Init(rpcPort int) {
} }
func init() { func init() {
producer = kafka.NewKafkaProducer(config.Config.Kafka.Ws2mschat.Addr, config.Config.Kafka.Ws2mschat.Topic) 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() { func Run() {

View File

@@ -31,10 +31,10 @@ func (ms *PushConsumerHandler) Init() {
config.Config.Kafka.ConsumerGroupID.MsgToPush) config.Config.Kafka.ConsumerGroupID.MsgToPush)
} }
func (ms *PushConsumerHandler) handleMs2PsChat(msg []byte) { 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{} msgFromMQ := pbChat.PushMsgDataToMQ{}
if err := proto.Unmarshal(msg, &msgFromMQ); err != nil { 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 return
} }
//Call push module to send message to the user //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, func (ms *PushConsumerHandler) ConsumeClaim(sess sarama.ConsumerGroupSession,
claim sarama.ConsumerGroupClaim) error { claim sarama.ConsumerGroupClaim) error {
for msg := range claim.Messages() { 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) ms.msgHandle[msg.Topic](msg.Value)
} }
return nil return nil

View File

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

View File

@@ -37,7 +37,7 @@ type AtContent struct {
func MsgToUser(pushMsg *pbPush.PushMsgReq) { func MsgToUser(pushMsg *pbPush.PushMsgReq) {
var wsResult []*pbRelay.SingleMsgToUser var wsResult []*pbRelay.SingleMsgToUser
isOfflinePush := utils.GetSwitchFromOptions(pushMsg.MsgData.Options, constant.IsOfflinePush) 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) grpcCons := getcdv3.GetConn4Unique(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOnlineMessageRelayName)
//Online push message //Online push message
log.Debug("test", pushMsg.OperationID, "len grpc", len(grpcCons), "data", pushMsg.String()) log.Debug("test", pushMsg.OperationID, "len grpc", len(grpcCons), "data", pushMsg.String())
@@ -45,15 +45,15 @@ func MsgToUser(pushMsg *pbPush.PushMsgReq) {
msgClient := pbRelay.NewOnlineMessageRelayServiceClient(v) msgClient := pbRelay.NewOnlineMessageRelayServiceClient(v)
reply, err := msgClient.OnlinePushMsg(context.Background(), &pbRelay.OnlinePushMsgReq{OperationID: pushMsg.OperationID, MsgData: pushMsg.MsgData, PushToUserID: pushMsg.PushToUserID}) reply, err := msgClient.OnlinePushMsg(context.Background(), &pbRelay.OnlinePushMsgReq{OperationID: pushMsg.OperationID, MsgData: pushMsg.MsgData, PushToUserID: pushMsg.PushToUserID})
if err != nil { 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 continue
} }
if reply != nil && reply.Resp != nil { if reply != nil && reply.Resp != nil {
wsResult = append(wsResult, reply.Resp...) wsResult = append(wsResult, reply.Resp...)
} }
} }
log.InfoByKv("push_result", pushMsg.OperationID, "result", wsResult, "sendData", pushMsg.MsgData) log.NewInfo(pushMsg.OperationID, "push_result", wsResult, "sendData", pushMsg.MsgData)
count++ successCount++
if isOfflinePush && pushMsg.PushToUserID != pushMsg.MsgData.SendID { if isOfflinePush && pushMsg.PushToUserID != pushMsg.MsgData.SendID {
for _, v := range wsResult { for _, v := range wsResult {
if v.ResultCode == 0 { if v.ResultCode == 0 {

View File

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

View File

@@ -20,38 +20,41 @@ import (
) )
func (rpc *rpcAuth) UserRegister(_ context.Context, req *pbAuth.UserRegisterReq) (*pbAuth.UserRegisterResp, error) { 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 var user db.User
utils.CopyStructFields(&user, req.UserInfo) utils.CopyStructFields(&user, req.UserInfo)
if req.UserInfo.Birth != 0 { if req.UserInfo.Birth != 0 {
user.Birth = utils.UnixSecondToTime(int64(req.UserInfo.Birth)) user.Birth = utils.UnixSecondToTime(int64(req.UserInfo.Birth))
} }
log.Debug(req.OperationID, "copy ", user, req.UserInfo)
err := imdb.UserRegister(user) err := imdb.UserRegister(user)
if err != nil { if err != nil {
log.NewError(req.OperationID, "UserRegister failed ", err.Error(), user) errMsg := req.OperationID + " imdb.UserRegister failed " + err.Error() + user.UserID
return &pbAuth.UserRegisterResp{CommonResp: &pbAuth.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, nil 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 return &pbAuth.UserRegisterResp{CommonResp: &pbAuth.CommonResp{}}, nil
} }
func (rpc *rpcAuth) UserToken(_ context.Context, req *pbAuth.UserTokenReq) (*pbAuth.UserTokenResp, error) { 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) _, err := imdb.GetUserByUserID(req.FromUserID)
if err != nil { if err != nil {
log.NewError(req.OperationID, "GetUserByUserID failed ", err.Error(), req.FromUserID) errMsg := req.OperationID + " imdb.GetUserByUserID failed " + err.Error() + req.FromUserID
return &pbAuth.UserTokenResp{CommonResp: &pbAuth.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, nil 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) tokens, expTime, err := token_verify.CreateToken(req.FromUserID, req.Platform)
if err != nil { if err != nil {
log.NewError(req.OperationID, "CreateToken failed ", err.Error(), req.FromUserID, req.Platform) errMsg := req.OperationID + " token_verify.CreateToken failed " + err.Error() + req.FromUserID + utils.Int32ToString(req.Platform)
return &pbAuth.UserTokenResp{CommonResp: &pbAuth.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, nil 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 return &pbAuth.UserTokenResp{CommonResp: &pbAuth.CommonResp{}, Token: tokens, ExpiredTime: expTime}, nil
} }
@@ -73,32 +76,46 @@ func NewRpcAuthServer(port int) *rpcAuth {
} }
func (rpc *rpcAuth) Run() { 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) listener, err := net.Listen("tcp", address)
if err != nil { if err != nil {
log.NewError("0", "listen network failed ", err.Error(), address) panic("listening err:" + err.Error() + rpc.rpcRegisterName)
return
} }
log.NewInfo("0", "listen network success, ", address, listener) log.NewInfo(operationID, "listen network success, ", address, listener)
//grpc server //grpc server
srv := grpc.NewServer() srv := grpc.NewServer()
defer srv.GracefulStop() defer srv.GracefulStop()
//service registers with etcd //service registers with etcd
pbAuth.RegisterAuthServer(srv, rpc) 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 { if err != nil {
log.NewError("0", "RegisterEtcd failed ", err.Error(), log.Error("", "GetLocalIP failed ", err.Error())
rpc.etcdSchema, strings.Join(rpc.etcdAddr, ","), utils.ServerIP, rpc.rpcPort, rpc.rpcRegisterName) }
}
err = getcdv3.RegisterEtcd(rpc.etcdSchema, strings.Join(rpc.etcdAddr, ","), rpcRegisterIP, rpc.rpcPort, rpc.rpcRegisterName, 10)
if err != nil {
log.NewError(operationID, "RegisterEtcd failed ", err.Error(),
rpc.etcdSchema, strings.Join(rpc.etcdAddr, ","), rpcRegisterIP, rpc.rpcPort, rpc.rpcRegisterName)
return 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) err = srv.Serve(listener)
if err != nil { if err != nil {
log.NewError("0", "Serve failed ", err.Error()) log.NewError(operationID, "Serve failed ", err.Error())
return 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" "Open_IM/pkg/common/token_verify"
cp "Open_IM/pkg/common/utils" cp "Open_IM/pkg/common/utils"
"Open_IM/pkg/grpc-etcdv3/getcdv3" "Open_IM/pkg/grpc-etcdv3/getcdv3"
pbCache "Open_IM/pkg/proto/cache"
pbFriend "Open_IM/pkg/proto/friend" pbFriend "Open_IM/pkg/proto/friend"
sdkws "Open_IM/pkg/proto/sdk_ws" sdkws "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils" "Open_IM/pkg/utils"
@@ -41,24 +42,37 @@ func NewFriendServer(port int) *friendServer {
func (s *friendServer) Run() { func (s *friendServer) Run() {
log.NewInfo("0", "friendServer run...") log.NewInfo("0", "friendServer run...")
ip := utils.ServerIP listenIP := ""
registerAddress := ip + ":" + strconv.Itoa(s.rpcPort) if config.Config.ListenIP == "" {
//listener network listenIP = "0.0.0.0"
listener, err := net.Listen("tcp", registerAddress) } else {
if err != nil { listenIP = config.Config.ListenIP
log.NewError("0", "Listen failed ", err.Error(), registerAddress)
return
} }
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() defer listener.Close()
//grpc server //grpc server
srv := grpc.NewServer() srv := grpc.NewServer()
defer srv.GracefulStop() defer srv.GracefulStop()
//User friend related services register to etcd //User friend related services register to etcd
pbFriend.RegisterFriendServer(srv, s) 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 { if err != nil {
log.NewError("0", "RegisterEtcd failed ", err.Error(), s.etcdSchema, strings.Join(s.etcdAddr, ","), ip, s.rpcPort, s.rpcRegisterName) 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, ","), rpcRegisterIP, s.rpcPort, s.rpcRegisterName)
return return
} }
err = srv.Serve(listener) 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 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) 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) chat.BlackAddedNotification(req)
return &pbFriend.AddBlacklistResp{CommonResp: &pbFriend.CommonResp{}}, nil 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) 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 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) chat.FriendAddedNotification(req.CommID.OperationID, req.CommID.OpUserID, req.CommID.FromUserID, req.CommID.ToUserID)
} }
} }
if req.HandleResult == constant.FriendResponseAgree { if req.HandleResult == constant.FriendResponseAgree {
chat.FriendApplicationApprovedNotification(req) chat.FriendApplicationApprovedNotification(req)
} else if req.HandleResult == constant.FriendResponseRefuse { } else if req.HandleResult == constant.FriendResponseRefuse {
@@ -244,6 +298,7 @@ func (s *friendServer) AddFriendResponse(ctx context.Context, req *pbFriend.AddF
} else { } else {
log.Error(req.CommID.OperationID, "HandleResult failed ", req.HandleResult) log.Error(req.CommID.OperationID, "HandleResult failed ", req.HandleResult)
} }
log.NewInfo(req.CommID.OperationID, "rpc AddFriendResponse ok") log.NewInfo(req.CommID.OperationID, "rpc AddFriendResponse ok")
return &pbFriend.AddFriendResponseResp{CommonResp: &pbFriend.CommonResp{}}, nil 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 return &pbFriend.DeleteFriendResp{CommonResp: &pbFriend.CommonResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: constant.ErrAccess.ErrMsg}}, nil
} }
log.NewInfo(req.CommID.OperationID, "DeleteFriend rpc ok") 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) chat.FriendDeletedNotification(req)
return &pbFriend.DeleteFriendResp{CommonResp: &pbFriend.CommonResp{}}, nil 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 ") 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) chat.BlackDeletedNotification(req)
return &pbFriend.RemoveBlacklistResp{CommonResp: &pbFriend.CommonResp{}}, nil return &pbFriend.RemoveBlacklistResp{CommonResp: &pbFriend.CommonResp{}}, nil
} }

View File

@@ -11,6 +11,7 @@ import (
"Open_IM/pkg/common/token_verify" "Open_IM/pkg/common/token_verify"
cp "Open_IM/pkg/common/utils" cp "Open_IM/pkg/common/utils"
"Open_IM/pkg/grpc-etcdv3/getcdv3" "Open_IM/pkg/grpc-etcdv3/getcdv3"
pbCache "Open_IM/pkg/proto/cache"
pbGroup "Open_IM/pkg/proto/group" pbGroup "Open_IM/pkg/proto/group"
open_im_sdk "Open_IM/pkg/proto/sdk_ws" open_im_sdk "Open_IM/pkg/proto/sdk_ws"
pbUser "Open_IM/pkg/proto/user" pbUser "Open_IM/pkg/proto/user"
@@ -43,26 +44,39 @@ func NewGroupServer(port int) *groupServer {
func (s *groupServer) Run() { func (s *groupServer) Run() {
log.NewInfo("", "group rpc start ") log.NewInfo("", "group rpc start ")
ip := utils.ServerIP listenIP := ""
registerAddress := ip + ":" + strconv.Itoa(s.rpcPort) if config.Config.ListenIP == "" {
//listener network listenIP = "0.0.0.0"
listener, err := net.Listen("tcp", registerAddress) } else {
if err != nil { listenIP = config.Config.ListenIP
log.NewError("", "Listen failed ", err.Error(), registerAddress)
return
} }
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() defer listener.Close()
//grpc server //grpc server
srv := grpc.NewServer() srv := grpc.NewServer()
defer srv.GracefulStop() defer srv.GracefulStop()
//Service registers with etcd //Service registers with etcd
pbGroup.RegisterGroupServer(srv, s) 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 { if err != nil {
log.NewError("", "RegisterEtcd failed ", err.Error()) log.NewError("", "RegisterEtcd failed ", err.Error())
return return
} }
log.Info("", "RegisterEtcd ", s.etcdSchema, strings.Join(s.etcdAddr, ","), rpcRegisterIP, s.rpcPort, s.rpcRegisterName)
err = srv.Serve(listener) err = srv.Serve(listener)
if err != nil { if err != nil {
log.NewError("", "Serve failed ", err.Error()) log.NewError("", "Serve failed ", err.Error())
@@ -83,8 +97,11 @@ func (s *groupServer) CreateGroup(ctx context.Context, req *pbGroup.CreateGroupR
log.NewError(req.OperationID, utils.GetSelfFuncName(), "callbackBeforeCreateGroup failed") 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 //to group
groupInfo := db.Group{} groupInfo := db.Group{}
utils.CopyStructFields(&groupInfo, req.GroupInfo) utils.CopyStructFields(&groupInfo, req.GroupInfo)
@@ -95,15 +112,19 @@ func (s *groupServer) CreateGroup(ctx context.Context, req *pbGroup.CreateGroupR
log.NewError(req.OperationID, "InsertIntoGroup failed, ", err.Error(), groupInfo) log.NewError(req.OperationID, "InsertIntoGroup failed, ", err.Error(), groupInfo)
return &pbGroup.CreateGroupResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}, http.WrapError(constant.ErrDB) return &pbGroup.CreateGroupResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}, http.WrapError(constant.ErrDB)
} }
groupMember := db.GroupMember{}
us, err := imdb.GetUserByUserID(req.OwnerUserID) us := &db.User{}
if req.OwnerUserID == "" {
goto initMemberList
}
us, err = imdb.GetUserByUserID(req.OwnerUserID)
if err != nil { if err != nil {
log.NewError(req.OperationID, "GetUserByUserID failed ", err.Error(), req.OwnerUserID) 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) return &pbGroup.CreateGroupResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}, http.WrapError(constant.ErrDB)
} }
//to group member //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) utils.CopyStructFields(&groupMember, us)
err = imdb.InsertIntoGroupMember(groupMember) err = imdb.InsertIntoGroupMember(groupMember)
if err != nil { if err != nil {
@@ -111,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) return &pbGroup.CreateGroupResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}, http.WrapError(constant.ErrDB)
} }
err = db.DB.AddGroupMember(groupId, req.OwnerUserID) initMemberList:
if err != nil {
log.NewError(req.OperationID, "AddGroupMember failed ", err.Error(), groupId, req.OwnerUserID)
}
var okUserIDList []string var okUserIDList []string
//to group member //to group member
for _, user := range req.InitMemberList { for _, user := range req.InitMemberList {
@@ -134,20 +152,14 @@ func (s *groupServer) CreateGroup(ctx context.Context, req *pbGroup.CreateGroupR
log.NewError(req.OperationID, "InsertIntoGroupMember failed ", err.Error(), groupMember) log.NewError(req.OperationID, "InsertIntoGroupMember failed ", err.Error(), groupMember)
continue continue
} }
okUserIDList = append(okUserIDList, user.UserID) 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{}} resp := &pbGroup.CreateGroupResp{GroupInfo: &open_im_sdk.GroupInfo{}}
group, err := imdb.GetGroupInfoByGroupID(groupId) group, err := imdb.GetGroupInfoByGroupID(groupId)
if err != nil { if err != nil {
log.NewError(req.OperationID, "GetGroupInfoByGroupID failed ", err.Error(), groupId) log.NewError(req.OperationID, "GetGroupInfoByGroupID failed ", err.Error(), groupId)
resp.ErrCode = constant.ErrDB.ErrCode resp.ErrCode = constant.ErrDB.ErrCode
resp.ErrMsg = constant.ErrDB.ErrMsg resp.ErrMsg = err.Error()
return resp, nil return resp, nil
} }
utils.CopyStructFields(resp.GroupInfo, group) utils.CopyStructFields(resp.GroupInfo, group)
@@ -155,14 +167,39 @@ func (s *groupServer) CreateGroup(ctx context.Context, req *pbGroup.CreateGroupR
if err != nil { if err != nil {
log.NewError(req.OperationID, "GetGroupMemberNumByGroupID failed ", err.Error(), groupId) log.NewError(req.OperationID, "GetGroupMemberNumByGroupID failed ", err.Error(), groupId)
resp.ErrCode = constant.ErrDB.ErrCode resp.ErrCode = constant.ErrDB.ErrCode
resp.ErrMsg = constant.ErrDB.ErrMsg resp.ErrMsg = err.Error()
return resp, nil return resp, nil
} }
if req.OwnerUserID != "" {
resp.GroupInfo.OwnerUserID = req.OwnerUserID resp.GroupInfo.OwnerUserID = req.OwnerUserID
okUserIDList = append(okUserIDList, req.OwnerUserID)
}
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()) log.NewInfo(req.OperationID, "rpc CreateGroup return ", resp.String())
chat.GroupCreatedNotification(req.OperationID, req.OpUserID, groupId, okUserIDList) chat.GroupCreatedNotification(req.OperationID, req.OpUserID, groupId, okUserIDList)
return resp, nil 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) { func (s *groupServer) GetJoinedGroupList(ctx context.Context, req *pbGroup.GetJoinedGroupListReq) (*pbGroup.GetJoinedGroupListResp, error) {
@@ -306,6 +343,24 @@ func (s *groupServer) InviteUserToGroup(ctx context.Context, req *pbGroup.Invite
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "SetConversation success", respPb.String(), v) 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) chat.MemberInvitedNotification(req.OperationID, req.GroupID, req.OpUserID, req.Reason, okUserIDList)
resp.ErrCode = 0 resp.ErrCode = 0
log.NewInfo(req.OperationID, "InviteUserToGroup rpc return ", resp.String()) log.NewInfo(req.OperationID, "InviteUserToGroup rpc return ", resp.String())
@@ -449,6 +504,24 @@ func (s *groupServer) KickGroupMember(ctx context.Context, req *pbGroup.KickGrou
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "SetConversation success", respPb.String(), v) 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) chat.MemberKickedNotification(req, okUserIDList)
log.NewInfo(req.OperationID, "GetGroupMemberList rpc return ", resp.String()) log.NewInfo(req.OperationID, "GetGroupMemberList rpc return ", resp.String())
return &resp, nil return &resp, nil
@@ -525,7 +598,7 @@ func (s *groupServer) GetGroupsInfo(ctx context.Context, req *pbGroup.GetGroupsI
} }
resp := pbGroup.GetGroupsInfoResp{GroupInfoList: groupsInfoList} 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 return &resp, nil
} }
@@ -599,6 +672,18 @@ func (s *groupServer) GroupApplicationResponse(_ context.Context, req *pbGroup.G
} else { } else {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "SetConversation success", respPb.String()) 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.GroupApplicationAcceptedNotification(req)
chat.MemberEnterNotification(req) chat.MemberEnterNotification(req)
} else if req.HandleResult == constant.GroupResponseRefuse { } else if req.HandleResult == constant.GroupResponseRefuse {
@@ -690,6 +775,24 @@ func (s *groupServer) QuitGroup(ctx context.Context, req *pbGroup.QuitGroupReq)
} else { } else {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "SetConversation success", respPb.String()) 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) chat.MemberQuitNotification(req)
log.NewInfo(req.OperationID, "rpc QuitGroup return ", pbGroup.QuitGroupResp{CommonResp: &pbGroup.CommonResp{ErrCode: 0, ErrMsg: ""}}) log.NewInfo(req.OperationID, "rpc QuitGroup return ", pbGroup.QuitGroupResp{CommonResp: &pbGroup.CommonResp{ErrCode: 0, ErrMsg: ""}})
return &pbGroup.QuitGroupResp{CommonResp: &pbGroup.CommonResp{ErrCode: 0, ErrMsg: ""}}, nil return &pbGroup.QuitGroupResp{CommonResp: &pbGroup.CommonResp{ErrCode: 0, ErrMsg: ""}}, nil
@@ -893,7 +996,8 @@ func (s *groupServer) GetGroups(_ context.Context, req *pbGroup.GetGroupsReq) (*
for _, v := range groups { for _, v := range groups {
groupMember, err := imdb.GetGroupMaster(v.GroupID) groupMember, err := imdb.GetGroupMaster(v.GroupID)
if err != nil { 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{ resp.CMSGroups = append(resp.CMSGroups, &pbGroup.CMSGroup{
GroupInfo: &open_im_sdk.GroupInfo{ GroupInfo: &open_im_sdk.GroupInfo{
@@ -909,7 +1013,7 @@ func (s *groupServer) GetGroups(_ context.Context, req *pbGroup.GetGroupsReq) (*
GroupMasterName: groupMember.Nickname, GroupMasterName: groupMember.Nickname,
}) })
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "GetGroups ", resp.String())
return resp, nil return resp, nil
} }
@@ -989,6 +1093,7 @@ func (s *groupServer) GetGroupMembersCMS(_ context.Context, req *pbGroup.GetGrou
CurrentPage: req.Pagination.PageNumber, CurrentPage: req.Pagination.PageNumber,
ShowNumber: req.Pagination.ShowNumber, ShowNumber: req.Pagination.ShowNumber,
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp:", resp.String())
return resp, nil return resp, nil
} }
@@ -1030,9 +1135,26 @@ func (s *groupServer) RemoveGroupMembersCMS(_ context.Context, req *pbGroup.Remo
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "SetConversation success", respPb.String(), v) 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) chat.MemberKickedNotification(reqKick, resp.Success)
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "success: ", resp.Success) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "failed: ", resp.Failed)
return resp, nil return resp, nil
} }
@@ -1069,6 +1191,24 @@ func (s *groupServer) AddGroupMembersCMS(_ context.Context, req *pbGroup.AddGrou
resp.Success = append(resp.Success, userId) 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) chat.MemberInvitedNotification(req.OperationId, req.GroupId, req.OpUserId, "admin add you to group", resp.Success)
return resp, nil return resp, nil
} }

View File

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

View File

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

View File

@@ -12,12 +12,13 @@ import (
func (rpc *rpcChat) DelMsgList(_ context.Context, req *commonPb.DelMsgListReq) (*commonPb.DelMsgListResp, error) { func (rpc *rpcChat) DelMsgList(_ context.Context, req *commonPb.DelMsgListReq) (*commonPb.DelMsgListResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String()) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp := &commonPb.DelMsgListResp{} 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()) log.NewError(req.OperationID, utils.GetSelfFuncName(), "DelMsg failed", err.Error())
resp.ErrMsg = constant.ErrDB.ErrMsg resp.ErrMsg = constant.ErrDB.ErrMsg
resp.ErrCode = constant.ErrDB.ErrCode resp.ErrCode = constant.ErrDB.ErrCode
return resp, nil return resp, nil
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String()) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil return resp, nil
} }

View File

@@ -11,7 +11,7 @@ import (
) )
func (rpc *rpcChat) GetMaxAndMinSeq(_ context.Context, in *pbMsg.GetMaxAndMinSeqReq) (*pbMsg.GetMaxAndMinSeqResp, error) { 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) //seq, err := model.GetBiggestSeqFromReceive(in.UserID)
maxSeq, err1 := commonDB.DB.GetUserMaxSeq(in.UserID) maxSeq, err1 := commonDB.DB.GetUserMaxSeq(in.UserID)
minSeq, err2 := commonDB.DB.GetUserMinSeq(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.GetMsgBySeqList(in.UserID, in.SeqList, in.OperationID)
msgList, err := commonDB.DB.GetMsgBySeqListMongo2(in.UserID, in.SeqList, in.OperationID) msgList, err := commonDB.DB.GetMsgBySeqListMongo2(in.UserID, in.SeqList, in.OperationID)
if err != nil { 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.ErrCode = 201
resp.ErrMsg = err.Error() resp.ErrMsg = err.Error()
return resp, nil return resp, nil

View File

@@ -19,7 +19,8 @@ type rpcChat struct {
rpcRegisterName string rpcRegisterName string
etcdSchema string etcdSchema string
etcdAddr []string etcdAddr []string
producer *kafka.Producer onlineProducer *kafka.Producer
offlineProducer *kafka.Producer
} }
func NewRpcChatServer(port int) *rpcChat { func NewRpcChatServer(port int) *rpcChat {
@@ -30,38 +31,47 @@ func NewRpcChatServer(port int) *rpcChat {
etcdSchema: config.Config.Etcd.EtcdSchema, etcdSchema: config.Config.Etcd.EtcdSchema,
etcdAddr: config.Config.Etcd.EtcdAddr, 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 return &rc
} }
func (rpc *rpcChat) Run() { func (rpc *rpcChat) Run() {
log.Info("", "", "rpc get_token init...") log.Info("", "rpcChat init...")
listenIP := ""
address := utils.ServerIP + ":" + strconv.Itoa(rpc.rpcPort) 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) listener, err := net.Listen("tcp", address)
if err != nil { if err != nil {
log.Error("", "", "listen network failed, err = %s, address = %s", err.Error(), address) panic("listening err:" + err.Error() + rpc.rpcRegisterName)
return
} }
log.Info("", "", "listen network success, address = ", address) log.Info("", "listen network success, address ", address)
//grpc server
srv := grpc.NewServer() srv := grpc.NewServer()
defer srv.GracefulStop() defer srv.GracefulStop()
//service registers with etcd rpcRegisterIP := ""
pbChat.RegisterChatServer(srv, rpc) 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 { if err != nil {
log.Error("", "", "register rpc get_token to etcd failed, err = %s", err.Error()) 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 rpcChat to etcd failed ", err.Error())
return return
} }
err = srv.Serve(listener) err = srv.Serve(listener)
if err != nil { if err != nil {
log.Info("", "", "rpc get_token fail, err = %s", err.Error()) log.Error("", "rpc rpcChat failed ", err.Error())
return 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/db"
"Open_IM/pkg/common/log" "Open_IM/pkg/common/log"
"Open_IM/pkg/grpc-etcdv3/getcdv3" "Open_IM/pkg/grpc-etcdv3/getcdv3"
cacheRpc "Open_IM/pkg/proto/cache"
pbCache "Open_IM/pkg/proto/cache"
pbChat "Open_IM/pkg/proto/chat" pbChat "Open_IM/pkg/proto/chat"
rpc "Open_IM/pkg/proto/friend" pbConversation "Open_IM/pkg/proto/conversation"
pbGroup "Open_IM/pkg/proto/group" pbRelay "Open_IM/pkg/proto/relay"
sdk_ws "Open_IM/pkg/proto/sdk_ws" sdk_ws "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils" "Open_IM/pkg/utils"
"context" "context"
"errors"
"github.com/garyburd/redigo/redis" "github.com/garyburd/redigo/redis"
"github.com/golang/protobuf/proto" "github.com/golang/protobuf/proto"
"math/rand" "math/rand"
"strconv" "strconv"
"strings" "strings"
"sync"
"time" "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 { type MsgCallBackReq struct {
SendID string `json:"sendID"` SendID string `json:"sendID"`
RecvID string `json:"recvID"` RecvID string `json:"recvID"`
@@ -47,36 +54,38 @@ func userRelationshipVerification(data *pbChat.SendMsgReq) (bool, int32, string)
return true, 0, "" return true, 0, ""
} }
log.NewDebug(data.OperationID, config.Config.MessageVerify.FriendVerify) log.NewDebug(data.OperationID, config.Config.MessageVerify.FriendVerify)
req := &rpc.IsInBlackListReq{CommID: &rpc.CommID{}} reqGetBlackIDListFromCache := &cacheRpc.GetBlackIDListFromCacheReq{UserID: data.MsgData.RecvID, OperationID: data.OperationID}
req.CommID.OperationID = data.OperationID etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImCacheName)
req.CommID.OpUserID = data.MsgData.RecvID cacheClient := cacheRpc.NewCacheClient(etcdConn)
req.CommID.FromUserID = data.MsgData.RecvID cacheResp, err := cacheClient.GetBlackIDListFromCache(context.Background(), reqGetBlackIDListFromCache)
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)
if err != nil { if err != nil {
log.NewDebug(data.OperationID, "IsInBlackListReq rpc failed, ", req.String(), err.Error()) log.NewError(data.OperationID, "GetBlackIDListFromCache rpc call failed ", err.Error())
} else if reply.Response == true { } else {
log.NewDebug(data.OperationID, "IsInBlackListReq ", req.String()) 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" return false, 600, "in black list"
} }
}
}
log.NewDebug(data.OperationID, config.Config.MessageVerify.FriendVerify) log.NewDebug(data.OperationID, config.Config.MessageVerify.FriendVerify)
if config.Config.MessageVerify.FriendVerify { if config.Config.MessageVerify.FriendVerify {
friendReq := &rpc.IsFriendReq{CommID: &rpc.CommID{}} reqGetFriendIDListFromCache := &cacheRpc.GetFriendIDListFromCacheReq{UserID: data.MsgData.RecvID, OperationID: data.OperationID}
friendReq.CommID.OperationID = data.OperationID etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImCacheName)
friendReq.CommID.OpUserID = data.MsgData.RecvID cacheClient := cacheRpc.NewCacheClient(etcdConn)
friendReq.CommID.FromUserID = data.MsgData.RecvID cacheResp, err := cacheClient.GetFriendIDListFromCache(context.Background(), reqGetFriendIDListFromCache)
friendReq.CommID.ToUserID = data.MsgData.SendID
friendReply, err := client.IsFriend(context.Background(), friendReq)
if err != nil { if err != nil {
log.NewDebug(data.OperationID, "IsFriendReq rpc failed, ", req.String(), err.Error()) log.NewError(data.OperationID, "GetFriendIDListFromCache rpc call failed ", err.Error())
return true, 0, "" } else {
} else if friendReply.Response == false { if cacheResp.CommonResp.ErrCode != 0 {
log.NewDebug(data.OperationID, "not friend ", req.String()) log.NewError(data.OperationID, "GetFriendIDListFromCache rpc logic call failed ", cacheResp.String())
return friendReply.Response, 601, "not friend" } 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, "" return true, 0, ""
} else { } else {
return true, 0, "" 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) // return returnMsg(&replay, pb, http.StatusUnauthorized, "token validate err,not authorized", "", 0)
rpc.encapsulateMsgData(pb.MsgData) rpc.encapsulateMsgData(pb.MsgData)
log.Info("", "this is a test MsgData ", 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) //options := utils.JsonStringToMap(pbData.Options)
isHistory := utils.GetSwitchFromOptions(pb.MsgData.Options, constant.IsHistory) isHistory := utils.GetSwitchFromOptions(pb.MsgData.Options, constant.IsHistory)
mReq := MsgCallBackReq{ 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) isSend := modifyMessageByUserMessageReceiveOpt(pb.MsgData.RecvID, pb.MsgData.SendID, constant.SingleChatType, pb)
if isSend { if isSend {
msgToMQ.MsgData = pb.MsgData msgToMQSingle.MsgData = pb.MsgData
log.NewInfo(msgToMQ.OperationID, msgToMQ) log.NewInfo(msgToMQSingle.OperationID, msgToMQSingle)
err1 := rpc.sendMsgToKafka(&msgToMQ, msgToMQ.MsgData.RecvID) err1 := rpc.sendMsgToKafka(&msgToMQSingle, msgToMQSingle.MsgData.RecvID, constant.OnlineStatus)
if err1 != nil { 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) return returnMsg(&replay, pb, 201, "kafka send msg err", "", 0)
} }
} }
if msgToMQ.MsgData.SendID != msgToMQ.MsgData.RecvID { //Filter messages sent to yourself if msgToMQSingle.MsgData.SendID != msgToMQSingle.MsgData.RecvID { //Filter messages sent to yourself
err2 := rpc.sendMsgToKafka(&msgToMQ, msgToMQ.MsgData.SendID) err2 := rpc.sendMsgToKafka(&msgToMQSingle, msgToMQSingle.MsgData.SendID, constant.OnlineStatus)
if err2 != nil { 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, 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 { if err := callbackAfterSendSingleMsg(pb); err != nil {
log.NewError(pb.OperationID, utils.GetSelfFuncName(), "callbackAfterSendSingleMsg failed", err.Error()) 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: case constant.GroupChatType:
// callback // callback
canSend, err := callbackBeforeSendGroupMsg(pb) 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") 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) 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) getGroupMemberIDListFromCacheReq := &pbCache.GetGroupMemberIDListFromCacheReq{OperationID: pb.OperationID, GroupID: pb.MsgData.GroupID}
client := pbGroup.NewGroupClient(etcdConn) etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImCacheName)
req := &pbGroup.GetGroupAllMemberReq{ client := pbCache.NewCacheClient(etcdConn)
GroupID: pb.MsgData.GroupID, cacheResp, err := client.GetGroupMemberIDListFromCache(context.Background(), getGroupMemberIDListFromCacheReq)
OperationID: pb.OperationID,
}
reply, err := client.GetGroupAllMember(context.Background(), req)
if err != nil { if err != nil {
log.Error(pb.Token, pb.OperationID, "rpc send_msg getGroupInfo failed, err = %s", err.Error()) log.NewError(pb.OperationID, "GetGroupMemberIDListFromCache rpc call failed ", err.Error())
return returnMsg(&replay, pb, 201, err.Error(), "", 0) return returnMsg(&replay, pb, 201, "GetGroupMemberIDListFromCache failed", "", 0)
} }
if reply.ErrCode != 0 { if cacheResp.CommonResp.ErrCode != 0 {
log.Error(pb.Token, pb.OperationID, "rpc send_msg getGroupInfo failed, err = %s", reply.ErrMsg) log.NewError(pb.OperationID, "GetGroupMemberIDListFromCache rpc logic call failed ", cacheResp.String())
return returnMsg(&replay, pb, reply.ErrCode, reply.ErrMsg, "", 0) return returnMsg(&replay, pb, 201, "GetGroupMemberIDListFromCache logic failed", "", 0)
} }
memberUserIDList := cacheResp.UserIDList
log.Debug(pb.OperationID, "GetGroupAllMember userID list", cacheResp.UserIDList)
var addUidList []string var addUidList []string
switch pb.MsgData.ContentType { switch pb.MsgData.ContentType {
case constant.MemberKickedNotification: case constant.MemberKickedNotification:
@@ -246,84 +254,134 @@ func (rpc *rpcChat) SendMsg(_ context.Context, pb *pbChat.SendMsgReq) (*pbChat.S
} }
case constant.MemberQuitNotification: case constant.MemberQuitNotification:
addUidList = append(addUidList, pb.MsgData.SendID) addUidList = append(addUidList, pb.MsgData.SendID)
case constant.AtText:
//tagMe := utils.IsContain(c.loginUserID, s.AtElem.AtUserList)
//tagAll := utils.IsContain(constant.AtAllString, pb.MsgData.AtUserIDList)
//if tagAll {
// if tagMe {
// lc.GroupAtType = constant.AtAllAtMe
// return
// }
// lc.GroupAtType = constant.AtAll
// return
//}
//if tagMe {
// lc.GroupAtType = constant.AtMe
//}
default: default:
} }
groupID := pb.MsgData.GroupID m := make(map[string][]string, 2)
for _, v := range reply.MemberList { if len(memberUserIDList) > GroupMemberNum {
pb.MsgData.RecvID = v.UserID getOnlineAndOfflineUserIDList(memberUserIDList, m, pb.OperationID)
isSend := modifyMessageByUserMessageReceiveOpt(v.UserID, groupID, constant.GroupChatType, pb) log.Debug(pb.OperationID, m[constant.OnlineStatus], m[constant.OfflineStatus])
if isSend { } else {
msgToMQ.MsgData = pb.MsgData m[constant.OnlineStatus] = memberUserIDList
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)
}
} }
//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)
} }
log.Info(msgToMQ.OperationID, "addUidList", addUidList) if remain > 0 {
for _, v := range addUidList { wg.Add(1)
pb.MsgData.RecvID = v go rpc.sendMsgToGroup(v[split*(len(v)/split):], *pb, k, &sendTag, &wg)
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)
}
} }
} }
wg.Add(1)
go rpc.sendMsgToGroup(addUidList, *pb, constant.OnlineStatus, &sendTag, &wg)
wg.Wait()
// callback // callback
if err := callbackAfterSendGroupMsg(pb); err != nil { if err := callbackAfterSendGroupMsg(pb); err != nil {
log.NewError(pb.OperationID, utils.GetSelfFuncName(), "callbackAfterSendGroupMsg failed", err.Error()) 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: case constant.NotificationChatType:
msgToMQ.MsgData = pb.MsgData msgToMQSingle.MsgData = pb.MsgData
log.NewInfo(msgToMQ.OperationID, msgToMQ) log.NewInfo(msgToMQSingle.OperationID, msgToMQSingle)
err1 := rpc.sendMsgToKafka(&msgToMQ, msgToMQ.MsgData.RecvID) err1 := rpc.sendMsgToKafka(&msgToMQSingle, msgToMQSingle.MsgData.RecvID, constant.OnlineStatus)
if err1 != nil { 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) return returnMsg(&replay, pb, 201, "kafka send msg err", "", 0)
} }
if msgToMQ.MsgData.SendID != msgToMQ.MsgData.RecvID { //Filter messages sent to yourself if msgToMQSingle.MsgData.SendID != msgToMQSingle.MsgData.RecvID { //Filter messages sent to yourself
err2 := rpc.sendMsgToKafka(&msgToMQ, msgToMQ.MsgData.SendID) err2 := rpc.sendMsgToKafka(&msgToMQSingle, msgToMQSingle.MsgData.SendID, constant.OnlineStatus)
if err2 != nil { 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, 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: default:
return returnMsg(&replay, pb, 203, "unkonwn sessionType", "", 0) return returnMsg(&replay, pb, 203, "unkonwn sessionType", "", 0)
} }
} }
func (rpc *rpcChat) sendMsgToKafka(m *pbChat.MsgDataToMQ, key string) error { func (rpc *rpcChat) sendMsgToKafka(m *pbChat.MsgDataToMQ, key string, status string) error {
pid, offset, err := rpc.producer.SendMessage(m, key) switch status {
case constant.OnlineStatus:
pid, offset, err := rpc.onlineProducer.SendMessage(m, key)
if err != nil { if err != nil {
log.ErrorByKv("kafka send failed", m.OperationID, "send data", m.String(), "pid", pid, "offset", offset, "err", err.Error(), "key", key) 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
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 errors.New("status error")
} }
func GetMsgID(sendID string) string { func GetMsgID(sendID string) string {
t := time.Now().Format("2006-01-02 15:04:05") t := time.Now().Format("2006-01-02 15:04:05")
@@ -638,3 +696,79 @@ func Notification(n *NotificationMsg) {
log.NewError(req.OperationID, "SendMsg rpc failed, ", req.String(), reply.ErrCode, reply.ErrMsg) 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

@@ -10,12 +10,9 @@ import (
"github.com/golang/protobuf/proto" "github.com/golang/protobuf/proto"
) )
func WorkMomentSendNotification(operationID, sendID, recvID string, notificationMsg *pbOffice.WorkMomentNotificationMsg) { func WorkMomentSendNotification(operationID, recvID string, notificationMsg *pbOffice.WorkMomentNotificationMsg) {
log.NewInfo(operationID, utils.GetSelfFuncName(), sendID, recvID, notificationMsg) log.NewInfo(operationID, utils.GetSelfFuncName(), recvID, notificationMsg)
//if sendID == recvID { WorkMomentNotification(operationID, recvID, recvID, notificationMsg)
// return
//}
WorkMomentNotification(operationID, sendID, recvID, notificationMsg)
} }
func WorkMomentNotification(operationID, sendID, recvID string, m proto.Message) { func WorkMomentNotification(operationID, sendID, recvID string, m proto.Message) {

View File

@@ -9,6 +9,7 @@ import (
imdb "Open_IM/pkg/common/db/mysql_model/im_mysql_model" imdb "Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log" "Open_IM/pkg/common/log"
"Open_IM/pkg/grpc-etcdv3/getcdv3" "Open_IM/pkg/grpc-etcdv3/getcdv3"
pbCache "Open_IM/pkg/proto/cache"
pbOffice "Open_IM/pkg/proto/office" pbOffice "Open_IM/pkg/proto/office"
pbCommon "Open_IM/pkg/proto/sdk_ws" pbCommon "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils" "Open_IM/pkg/utils"
@@ -17,6 +18,7 @@ import (
"net" "net"
"strconv" "strconv"
"strings" "strings"
"sync"
"time" "time"
) )
@@ -39,22 +41,34 @@ func NewOfficeServer(port int) *officeServer {
func (s *officeServer) Run() { func (s *officeServer) Run() {
log.NewInfo("0", "officeServer rpc start ") log.NewInfo("0", "officeServer rpc start ")
ip := utils.ServerIP listenIP := ""
registerAddress := ip + ":" + strconv.Itoa(s.rpcPort) if config.Config.ListenIP == "" {
//listener network listenIP = "0.0.0.0"
listener, err := net.Listen("tcp", registerAddress) } else {
if err != nil { listenIP = config.Config.ListenIP
log.NewError("0", "Listen failed ", err.Error(), registerAddress)
return
} }
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() defer listener.Close()
//grpc server //grpc server
srv := grpc.NewServer() srv := grpc.NewServer()
defer srv.GracefulStop() defer srv.GracefulStop()
//Service registers with etcd //Service registers with etcd
pbOffice.RegisterOfficeServiceServer(srv, s) 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 { if err != nil {
log.NewError("0", "RegisterEtcd failed ", err.Error()) log.NewError("0", "RegisterEtcd failed ", err.Error())
return 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) { func (s *officeServer) SetTag(_ context.Context, req *pbOffice.SetTagReq) (resp *pbOffice.SetTagResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String()) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.SetTagResp{CommonResp: &pbOffice.CommonResp{}} resp = &pbOffice.SetTagResp{CommonResp: &pbOffice.CommonResp{}}
IncreaseUserIDList := utils.RemoveRepeatedStringInList(req.IncreaseUserIDList) increaseUserIDList := utils.RemoveRepeatedStringInList(req.IncreaseUserIDList)
reduceUserIDList := utils.RemoveRepeatedStringInList(req.ReduceUserIDList) reduceUserIDList := utils.RemoveRepeatedStringInList(req.ReduceUserIDList)
if err := db.DB.SetTag(req.UserID, req.TagID, req.NewName, IncreaseUserIDList, reduceUserIDList); err != nil { 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()) log.NewError(req.OperationID, utils.GetSelfFuncName(), "SetTag failed", increaseUserIDList, reduceUserIDList, err.Error())
resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
return resp, nil return resp, nil
@@ -160,15 +174,29 @@ func (s *officeServer) SendMsg2Tag(_ context.Context, req *pbOffice.SendMsg2TagR
} }
var groupUserIDList []string var groupUserIDList []string
for _, groupID := range req.GroupList { for _, groupID := range req.GroupList {
userIDList, err := im_mysql_model.GetGroupMemberIDListByGroupID(groupID) 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,
}
getGroupMemberIDListFromCacheResp, err := cacheClient.GetGroupMemberIDListFromCache(context.Background(), &req)
if err != nil { if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetGroupMemberIDListByGroupID failed", err.Error()) log.NewError(req.OperationID, "GetGroupMemberIDListFromCache rpc call failed ", err.Error(), req.String())
continue resp.CommonResp.ErrCode = constant.ErrServer.ErrCode
resp.CommonResp.ErrMsg = err.Error()
return resp, nil
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), userIDList) if getGroupMemberIDListFromCacheResp.CommonResp.ErrCode != 0 {
groupUserIDList = append(groupUserIDList, userIDList...) 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.NewInfo(req.OperationID, utils.GetSelfFuncName(), groupUserIDList, req.GroupList) log.NewDebug(req.OperationID, utils.GetSelfFuncName(), getGroupMemberIDListFromCacheResp.UserIDList)
groupUserIDList = append(groupUserIDList, getGroupMemberIDListFromCacheResp.UserIDList...)
}
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), groupUserIDList, req.GroupList)
var userIDList []string var userIDList []string
userIDList = append(userIDList, tagUserIDList...) userIDList = append(userIDList, tagUserIDList...)
userIDList = append(userIDList, groupUserIDList...) userIDList = append(userIDList, groupUserIDList...)
@@ -179,32 +207,47 @@ func (s *officeServer) SendMsg2Tag(_ context.Context, req *pbOffice.SendMsg2TagR
userIDList = append(userIDList[:i], userIDList[i+1:]...) userIDList = append(userIDList[:i], userIDList[i+1:]...)
} }
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "total userIDList result: ", userIDList) log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "total userIDList result: ", userIDList)
us, err := imdb.GetUserByUserID(req.SendID) user, err := imdb.GetUserByUserID(req.SendID)
if err != nil { if err != nil {
log.NewError(req.OperationID, "GetUserByUserID failed ", err.Error(), req.SendID) 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 { 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 var tagSendLogs db.TagSendLog
wg.Add(len(userIDList))
for _, userID := range userIDList { for _, userID := range userIDList {
go func(userID string) {
defer wg.Done()
userName, err := im_mysql_model.GetUserNameByUserID(userID) userName, err := im_mysql_model.GetUserNameByUserID(userID)
if err != nil { if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserNameByUserID failed", err.Error()) log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserNameByUserID failed", err.Error())
continue return
} }
tagSendLogs.UserList = append(tagSendLogs.UserList, db.TagUser{ tagSendLogs.UserList = append(tagSendLogs.UserList, db.TagUser{
UserID: userID, UserID: userID,
UserName: userName, UserName: userName,
}) })
}(userID)
} }
wg.Wait()
tagSendLogs.SendID = req.SendID tagSendLogs.SendID = req.SendID
tagSendLogs.Content = req.Content tagSendLogs.Content = req.Content
tagSendLogs.SenderPlatformID = req.SenderPlatformID tagSendLogs.SenderPlatformID = req.SenderPlatformID
tagSendLogs.SendTime = time.Now().Unix() tagSendLogs.SendTime = time.Now().Unix()
if err := db.DB.SaveTagSendLog(&tagSendLogs); err != nil { 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.ErrCode = constant.ErrDB.ErrCode
resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg
return resp, nil return resp, nil
@@ -272,7 +315,8 @@ func (s *officeServer) CreateOneWorkMoment(_ context.Context, req *pbOffice.Crea
resp = &pbOffice.CreateOneWorkMomentResp{CommonResp: &pbOffice.CommonResp{}} resp = &pbOffice.CreateOneWorkMomentResp{CommonResp: &pbOffice.CommonResp{}}
workMoment := db.WorkMoment{ workMoment := db.WorkMoment{
Comments: []*db.Comment{}, Comments: []*db.Comment{},
LikeUserList: []*db.LikeUser{}, LikeUserList: []*db.WorkMomentUser{},
PermissionUserList: []*db.WorkMomentUser{},
} }
createUser, err := imdb.GetUserByUserID(req.WorkMoment.UserID) createUser, err := imdb.GetUserByUserID(req.WorkMoment.UserID)
if err != nil { if err != nil {
@@ -286,6 +330,18 @@ func (s *officeServer) CreateOneWorkMoment(_ context.Context, req *pbOffice.Crea
workMoment.UserName = createUser.Nickname workMoment.UserName = createUser.Nickname
workMoment.FaceURL = createUser.FaceURL workMoment.FaceURL = createUser.FaceURL
workMoment.PermissionUserIDList = s.getPermissionUserIDList(req.OperationID, req.WorkMoment.PermissionGroupList, req.WorkMoment.PermissionUserList) 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) log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "workMoment to create", workMoment)
err = db.DB.CreateOneWorkMoment(&workMoment) err = db.DB.CreateOneWorkMoment(&workMoment)
if err != nil { if err != nil {
@@ -303,8 +359,23 @@ func (s *officeServer) CreateOneWorkMoment(_ context.Context, req *pbOffice.Crea
UserID: workMoment.UserID, UserID: workMoment.UserID,
FaceURL: createUser.FaceURL, FaceURL: createUser.FaceURL,
UserName: createUser.Nickname, UserName: createUser.Nickname,
CreateTime: workMoment.CreateTime,
} }
msg.WorkMomentSendNotification(req.OperationID, workMoment.UserID, atUser.UserID, workMomentNotificationMsg) 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()) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil return resp, nil
@@ -314,12 +385,13 @@ func (s *officeServer) CreateOneWorkMoment(_ context.Context, req *pbOffice.Crea
func (s *officeServer) getPermissionUserIDList(operationID string, groupList []*pbOffice.PermissionGroup, userList []*pbOffice.WorkMomentUser) []string { func (s *officeServer) getPermissionUserIDList(operationID string, groupList []*pbOffice.PermissionGroup, userList []*pbOffice.WorkMomentUser) []string {
var permissionUserIDList []string var permissionUserIDList []string
for _, group := range groupList { for _, group := range groupList {
GroupMemberIDList, err := imdb.GetGroupMemberIDListByGroupID(group.GroupID) groupMemberIDList, err := imdb.GetGroupMemberIDListByGroupID(group.GroupID)
if err != nil { if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "GetGroupMemberIDListByGroupID failed", group, err.Error()) log.NewError(operationID, utils.GetSelfFuncName(), "GetGroupMemberIDListByGroupID failed", group, err.Error())
continue continue
} }
permissionUserIDList = append(permissionUserIDList, GroupMemberIDList...) log.NewDebug(operationID, utils.GetSelfFuncName(), "groupMemberIDList: ", groupMemberIDList)
permissionUserIDList = append(permissionUserIDList, groupMemberIDList...)
} }
var userIDList []string var userIDList []string
for _, user := range userList { for _, user := range userList {
@@ -375,13 +447,13 @@ func isUserCanSeeWorkMoment(userID string, workMoment db.WorkMoment) bool {
func (s *officeServer) LikeOneWorkMoment(_ context.Context, req *pbOffice.LikeOneWorkMomentReq) (resp *pbOffice.LikeOneWorkMomentResp, err error) { func (s *officeServer) LikeOneWorkMoment(_ context.Context, req *pbOffice.LikeOneWorkMomentReq) (resp *pbOffice.LikeOneWorkMomentResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String()) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.LikeOneWorkMomentResp{CommonResp: &pbOffice.CommonResp{}} resp = &pbOffice.LikeOneWorkMomentResp{CommonResp: &pbOffice.CommonResp{}}
userName, err := imdb.GetUserNameByUserID(req.UserID) user, err := imdb.GetUserByUserID(req.UserID)
if err != nil { if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserNameByUserID failed", err.Error()) log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserNameByUserID failed", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg} resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil return resp, nil
} }
workMoment, like, err := db.DB.LikeOneWorkMoment(req.UserID, userName, req.WorkMomentID) workMoment, like, err := db.DB.LikeOneWorkMoment(req.UserID, user.Nickname, req.WorkMomentID)
if err != nil { if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "LikeOneWorkMoment failed ", err.Error()) log.NewError(req.OperationID, utils.GetSelfFuncName(), "LikeOneWorkMoment failed ", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg} resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
@@ -391,13 +463,14 @@ func (s *officeServer) LikeOneWorkMoment(_ context.Context, req *pbOffice.LikeOn
NotificationMsgType: constant.WorkMomentLikeNotification, NotificationMsgType: constant.WorkMomentLikeNotification,
WorkMomentID: workMoment.WorkMomentID, WorkMomentID: workMoment.WorkMomentID,
WorkMomentContent: workMoment.Content, WorkMomentContent: workMoment.Content,
UserID: workMoment.UserID, UserID: user.UserID,
FaceURL: workMoment.FaceURL, FaceURL: user.FaceURL,
UserName: workMoment.UserName, UserName: user.Nickname,
CreateTime: int32(time.Now().Unix()),
} }
// send notification // send notification
if like { if like && workMoment.UserID != req.UserID {
msg.WorkMomentSendNotification(req.OperationID, req.UserID, workMoment.UserID, workMomentNotificationMsg) msg.WorkMomentSendNotification(req.OperationID, workMoment.UserID, workMomentNotificationMsg)
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String()) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil return resp, nil
@@ -439,23 +512,21 @@ func (s *officeServer) CommentOneWorkMoment(_ context.Context, req *pbOffice.Com
NotificationMsgType: constant.WorkMomentCommentNotification, NotificationMsgType: constant.WorkMomentCommentNotification,
WorkMomentID: workMoment.WorkMomentID, WorkMomentID: workMoment.WorkMomentID,
WorkMomentContent: workMoment.Content, WorkMomentContent: workMoment.Content,
UserID: workMoment.UserID, UserID: commentUser.UserID,
FaceURL: workMoment.FaceURL,
UserName: workMoment.UserName,
Comment: &pbOffice.Comment{
UserID: comment.UserID,
UserName: comment.UserName,
FaceURL: commentUser.FaceURL, FaceURL: commentUser.FaceURL,
UserName: commentUser.Nickname,
ReplyUserID: comment.ReplyUserID, ReplyUserID: comment.ReplyUserID,
ReplyUserName: comment.ReplyUserName, ReplyUserName: comment.ReplyUserName,
ContentID: comment.ContentID, ContentID: comment.ContentID,
Content: comment.Content, Content: comment.Content,
CreateTime: comment.CreateTime, CreateTime: comment.CreateTime,
},
} }
msg.WorkMomentSendNotification(req.OperationID, req.UserID, workMoment.UserID, workMomentNotificationMsg) log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "msg: ", *workMomentNotificationMsg)
if req.ReplyUserID != "" { if req.UserID != workMoment.UserID {
msg.WorkMomentSendNotification(req.OperationID, req.UserID, req.ReplyUserID, workMomentNotificationMsg) 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()) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil return resp, nil
@@ -470,7 +541,6 @@ func (s *officeServer) GetWorkMomentByID(_ context.Context, req *pbOffice.GetWor
workMoment, err := db.DB.GetWorkMomentByID(req.WorkMomentID) workMoment, err := db.DB.GetWorkMomentByID(req.WorkMomentID)
if err != nil { if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetWorkMomentByID failed", err.Error()) 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 return resp, nil
} }
canSee := isUserCanSeeWorkMoment(req.OpUserID, *workMoment) canSee := isUserCanSeeWorkMoment(req.OpUserID, *workMoment)
@@ -488,17 +558,21 @@ func (s *officeServer) GetWorkMomentByID(_ context.Context, req *pbOffice.GetWor
func (s *officeServer) GetUserWorkMoments(_ context.Context, req *pbOffice.GetUserWorkMomentsReq) (resp *pbOffice.GetUserWorkMomentsResp, err error) { func (s *officeServer) GetUserWorkMoments(_ context.Context, req *pbOffice.GetUserWorkMomentsReq) (resp *pbOffice.GetUserWorkMomentsResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String()) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.GetUserWorkMomentsResp{CommonResp: &pbOffice.CommonResp{}, WorkMoments: []*pbOffice.WorkMoment{}} resp = &pbOffice.GetUserWorkMomentsResp{CommonResp: &pbOffice.CommonResp{}, WorkMoments: []*pbOffice.WorkMoment{}}
//resp.WorkMoments = make([]*pbOffice.WorkMoment, 0) resp.Pagination = &pbCommon.ResponsePagination{CurrentPage: req.Pagination.PageNumber, ShowNumber: req.Pagination.ShowNumber}
workMoments, err := db.DB.GetUserWorkMoments(req.UserID, req.Pagination.ShowNumber, req.Pagination.PageNumber) 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 { if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err) log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserWorkMoments failed", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg} resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil return resp, nil
} }
if err := utils.CopyStructFields(&resp.WorkMoments, workMoments); err != nil { if err := utils.CopyStructFields(&resp.WorkMoments, workMoments); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
} }
resp.Pagination = &pbCommon.ResponsePagination{CurrentPage: req.Pagination.PageNumber, ShowNumber: req.Pagination.ShowNumber}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String()) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil return resp, nil
} }
@@ -506,15 +580,8 @@ func (s *officeServer) GetUserWorkMoments(_ context.Context, req *pbOffice.GetUs
func (s *officeServer) GetUserFriendWorkMoments(_ context.Context, req *pbOffice.GetUserFriendWorkMomentsReq) (resp *pbOffice.GetUserFriendWorkMomentsResp, err error) { func (s *officeServer) GetUserFriendWorkMoments(_ context.Context, req *pbOffice.GetUserFriendWorkMomentsReq) (resp *pbOffice.GetUserFriendWorkMomentsResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String()) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.GetUserFriendWorkMomentsResp{CommonResp: &pbOffice.CommonResp{}, WorkMoments: []*pbOffice.WorkMoment{}} resp = &pbOffice.GetUserFriendWorkMomentsResp{CommonResp: &pbOffice.CommonResp{}, WorkMoments: []*pbOffice.WorkMoment{}}
//resp.WorkMoments = make([]*pbOffice.WorkMoment, 0) resp.Pagination = &pbCommon.ResponsePagination{CurrentPage: req.Pagination.PageNumber, ShowNumber: req.Pagination.ShowNumber}
friendIDList, err := imdb.GetFriendIDListByUserID(req.UserID) workMoments, err := db.DB.GetUserFriendWorkMoments(req.Pagination.ShowNumber, req.Pagination.PageNumber, req.UserID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetFriendIDListByUserID", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "friendIDList: ", friendIDList)
workMoments, err := db.DB.GetUserFriendWorkMoments(friendIDList, req.Pagination.ShowNumber, req.Pagination.PageNumber, req.UserID)
if err != nil { if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserFriendWorkMoments", err.Error()) log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserFriendWorkMoments", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg} resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
@@ -523,7 +590,6 @@ func (s *officeServer) GetUserFriendWorkMoments(_ context.Context, req *pbOffice
if err := utils.CopyStructFields(&resp.WorkMoments, workMoments); err != nil { if err := utils.CopyStructFields(&resp.WorkMoments, workMoments); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error()) log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
} }
resp.Pagination = &pbCommon.ResponsePagination{CurrentPage: req.Pagination.PageNumber, ShowNumber: req.Pagination.ShowNumber}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String()) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil return resp, nil
} }

View File

@@ -10,6 +10,7 @@ import (
"Open_IM/pkg/common/token_verify" "Open_IM/pkg/common/token_verify"
"Open_IM/pkg/grpc-etcdv3/getcdv3" "Open_IM/pkg/grpc-etcdv3/getcdv3"
"Open_IM/pkg/proto/auth" "Open_IM/pkg/proto/auth"
groupRpc "Open_IM/pkg/proto/group"
rpc "Open_IM/pkg/proto/organization" rpc "Open_IM/pkg/proto/organization"
open_im_sdk "Open_IM/pkg/proto/sdk_ws" open_im_sdk "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils" "Open_IM/pkg/utils"
@@ -40,27 +41,38 @@ func NewServer(port int) *organizationServer {
func (s *organizationServer) Run() { func (s *organizationServer) Run() {
log.NewInfo("", "organization rpc start ") log.NewInfo("", "organization rpc start ")
ip := utils.ServerIP listenIP := ""
registerAddress := ip + ":" + strconv.Itoa(s.rpcPort) if config.Config.ListenIP == "" {
//listener network listenIP = "0.0.0.0"
listener, err := net.Listen("tcp", registerAddress) } else {
if err != nil { listenIP = config.Config.ListenIP
log.NewError("", "Listen failed ", err.Error(), registerAddress)
return
} }
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() defer listener.Close()
//grpc server //grpc server
srv := grpc.NewServer() srv := grpc.NewServer()
defer srv.GracefulStop() defer srv.GracefulStop()
//Service registers with etcd //Service registers with etcd
rpc.RegisterOrganizationServer(srv, s) rpc.RegisterOrganizationServer(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 { if err != nil {
log.NewError("", "RegisterEtcd failed ", err.Error()) log.NewError("", "RegisterEtcd failed ", err.Error())
return return
} }
log.NewInfo("", "organization rpc RegisterEtcd success", ip, s.rpcPort, s.rpcRegisterName, 10) log.NewInfo("", "organization rpc RegisterEtcd success", rpcRegisterIP, s.rpcPort, s.rpcRegisterName, 10)
err = srv.Serve(listener) err = srv.Serve(listener)
if err != nil { if err != nil {
log.NewError("", "Serve failed ", err.Error()) log.NewError("", "Serve failed ", err.Error())
@@ -99,6 +111,34 @@ func (s *organizationServer) CreateDepartment(ctx context.Context, req *rpc.Crea
utils.CopyStructFields(resp.DepartmentInfo, createdDepartment) utils.CopyStructFields(resp.DepartmentInfo, createdDepartment)
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc return ", *resp) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc return ", *resp)
chat.OrganizationNotificationToAll(req.OpUserID, req.OperationID) 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 return resp, nil
} }
@@ -296,6 +336,19 @@ func (s *organizationServer) CreateDepartmentMember(ctx context.Context, req *rp
return resp, nil 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) { func (s *organizationServer) GetUserInDepartmentByUserID(userID string, operationID string) (*open_im_sdk.UserInDepartment, error) {
err, organizationUser := imdb.GetOrganizationUser(userID) err, organizationUser := imdb.GetOrganizationUser(userID)
if err != nil { if err != nil {
@@ -427,3 +480,18 @@ func (s *organizationServer) GetDepartmentMember(ctx context.Context, req *rpc.G
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc return ", resp) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), " rpc return ", resp)
return &resp, nil 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/config"
"Open_IM/pkg/common/constant" "Open_IM/pkg/common/constant"
"context" "context"
"strconv"
"sync" "sync"
"time" "time"
@@ -21,7 +22,6 @@ import (
//"context" //"context"
errors "Open_IM/pkg/common/http" errors "Open_IM/pkg/common/http"
"net" "net"
"strconv"
"strings" "strings"
"google.golang.org/grpc" "google.golang.org/grpc"
@@ -46,22 +46,35 @@ func NewStatisticsServer(port int) *statisticsServer {
func (s *statisticsServer) Run() { func (s *statisticsServer) Run() {
log.NewInfo("0", "Statistics rpc start ") log.NewInfo("0", "Statistics rpc start ")
ip := utils.ServerIP
registerAddress := ip + ":" + strconv.Itoa(s.rpcPort) listenIP := ""
//listener network if config.Config.ListenIP == "" {
listener, err := net.Listen("tcp", registerAddress) listenIP = "0.0.0.0"
if err != nil { } else {
log.NewError("0", "Listen failed ", err.Error(), registerAddress) listenIP = config.Config.ListenIP
return
} }
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() defer listener.Close()
//grpc server //grpc server
srv := grpc.NewServer() srv := grpc.NewServer()
defer srv.GracefulStop() defer srv.GracefulStop()
//Service registers with etcd //Service registers with etcd
pbStatistics.RegisterUserServer(srv, s) 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 { if err != nil {
log.NewError("0", "RegisterEtcd failed ", err.Error()) log.NewError("0", "RegisterEtcd failed ", err.Error())
return return
@@ -75,13 +88,14 @@ func (s *statisticsServer) Run() {
} }
func (s *statisticsServer) GetActiveGroup(_ context.Context, req *pbStatistics.GetActiveGroupReq) (*pbStatistics.GetActiveGroupResp, error) { 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{} resp := &pbStatistics.GetActiveGroupResp{}
fromTime, toTime, err := ParseTimeFromTo(req.StatisticsReq.From, req.StatisticsReq.To) fromTime, toTime, err := ParseTimeFromTo(req.StatisticsReq.From, req.StatisticsReq.To)
if err != nil { if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "ParseTimeFromTo failed", err.Error()) log.NewError(req.OperationID, utils.GetSelfFuncName(), "ParseTimeFromTo failed", err.Error())
return resp, errors.WrapError(constant.ErrArgs) return resp, errors.WrapError(constant.ErrArgs)
} }
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "time: ", fromTime, toTime)
activeGroups, err := imdb.GetActiveGroups(fromTime, toTime, 12) activeGroups, err := imdb.GetActiveGroups(fromTime, toTime, 12)
if err != nil { if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetActiveGroups failed", err.Error()) 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), MessageNum: int32(activeGroup.MessageNum),
}) })
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), resp.String())
return resp, nil 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()) log.NewError(req.OperationID, utils.GetSelfFuncName(), "ParseTimeFromTo failed", err.Error())
return resp, errors.WrapError(constant.ErrDB) return resp, errors.WrapError(constant.ErrDB)
} }
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "time: ", fromTime, toTime)
activeUsers, err := imdb.GetActiveUsers(fromTime, toTime, 12) activeUsers, err := imdb.GetActiveUsers(fromTime, toTime, 12)
if err != nil { if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetActiveUsers failed", err.Error()) 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 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)) increaseGroupNum, err := imdb.GetIncreaseGroupNum(fromTime, toTime.Add(time.Hour*24))
if err != nil { 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) return resp, errors.WrapError(constant.ErrDB)
} }
totalGroupNum, err := imdb.GetTotalGroupNum() totalGroupNum, err := imdb.GetTotalGroupNum()
@@ -230,7 +247,7 @@ func (s *statisticsServer) GetGroupStatistics(_ context.Context, req *pbStatisti
resp.IncreaseGroupNum = increaseGroupNum resp.IncreaseGroupNum = increaseGroupNum
resp.TotalGroupNum = totalGroupNum resp.TotalGroupNum = totalGroupNum
times := GetRangeDate(fromTime, toTime) times := GetRangeDate(fromTime, toTime)
log.NewInfo(req.OperationID, "times:", times) log.NewDebug(req.OperationID, "times:", times)
wg := &sync.WaitGroup{} wg := &sync.WaitGroup{}
resp.IncreaseGroupNumList = make([]*pbStatistics.DateNumList, len(times), len(times)) resp.IncreaseGroupNumList = make([]*pbStatistics.DateNumList, len(times), len(times))
resp.TotalGroupNumList = 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, i, v)
} }
wg.Wait() wg.Wait()
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
return resp, nil return resp, nil
} }
@@ -264,6 +282,7 @@ func (s *statisticsServer) GetMessageStatistics(_ context.Context, req *pbStatis
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), req.String()) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), req.String())
resp := &pbStatistics.GetMessageStatisticsResp{} resp := &pbStatistics.GetMessageStatisticsResp{}
fromTime, toTime, err := ParseTimeFromTo(req.StatisticsReq.From, req.StatisticsReq.To) fromTime, toTime, err := ParseTimeFromTo(req.StatisticsReq.From, req.StatisticsReq.To)
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "times: ", fromTime, toTime)
if err != nil { if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "ParseTimeFromTo failed", err.Error()) log.NewError(req.OperationID, utils.GetSelfFuncName(), "ParseTimeFromTo failed", err.Error())
return resp, errors.WrapError(constant.ErrArgs) 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()) log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetGroupMessageNum failed", err.Error())
return resp, errors.WrapError(constant.ErrDB) return resp, errors.WrapError(constant.ErrDB)
} }
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), privateMessageNum, groupMessageNum)
resp.PrivateMessageNum = privateMessageNum resp.PrivateMessageNum = privateMessageNum
resp.GroupMessageNum = groupMessageNum resp.GroupMessageNum = groupMessageNum
times := GetRangeDate(fromTime, toTime) 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) { 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{} resp := &pbStatistics.GetUserStatisticsResp{}
fromTime, toTime, err := ParseTimeFromTo(req.StatisticsReq.From, req.StatisticsReq.To) fromTime, toTime, err := ParseTimeFromTo(req.StatisticsReq.From, req.StatisticsReq.To)
if err != nil { if err != nil {
@@ -374,5 +394,6 @@ func (s *statisticsServer) GetUserStatistics(_ context.Context, req *pbStatistic
}(wg, i, v) }(wg, i, v)
} }
wg.Wait() wg.Wait()
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
return resp, nil return resp, nil
} }

View File

@@ -16,7 +16,6 @@ import (
pbUser "Open_IM/pkg/proto/user" pbUser "Open_IM/pkg/proto/user"
"Open_IM/pkg/utils" "Open_IM/pkg/utils"
"context" "context"
"fmt"
"net" "net"
"strconv" "strconv"
"strings" "strings"
@@ -42,26 +41,38 @@ func NewUserServer(port int) *userServer {
} }
func (s *userServer) Run() { func (s *userServer) Run() {
log.NewInfo("0", "", "rpc user start...") log.NewInfo("0", "rpc user start...")
ip := utils.ServerIP listenIP := ""
registerAddress := ip + ":" + strconv.Itoa(s.rpcPort) if config.Config.ListenIP == "" {
//listener network listenIP = "0.0.0.0"
listener, err := net.Listen("tcp", registerAddress) } else {
if err != nil { listenIP = config.Config.ListenIP
log.NewError("0", "listen network failed ", err.Error(), registerAddress)
return
} }
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() defer listener.Close()
//grpc server //grpc server
srv := grpc.NewServer() srv := grpc.NewServer()
defer srv.GracefulStop() defer srv.GracefulStop()
//Service registers with etcd //Service registers with etcd
pbUser.RegisterUserServer(srv, s) 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 { if err != nil {
log.NewError("0", "RegisterEtcd failed ", err.Error(), s.etcdSchema, strings.Join(s.etcdAddr, ","), ip, s.rpcPort, s.rpcRegisterName) 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, ","), rpcRegisterIP, s.rpcPort, s.rpcRegisterName)
return return
} }
err = srv.Serve(listener) err = srv.Serve(listener)
@@ -158,6 +169,7 @@ func (s *userServer) GetAllConversations(ctx context.Context, req *pbUser.GetAll
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String()) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp := &pbUser.GetAllConversationsResp{Conversations: []*pbUser.Conversation{}} resp := &pbUser.GetAllConversationsResp{Conversations: []*pbUser.Conversation{}}
conversations, err := imdb.GetUserAllConversations(req.OwnerUserID) conversations, err := imdb.GetUserAllConversations(req.OwnerUserID)
log.NewDebug(req.OperationID, "conversations: ", conversations)
if err != nil { if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetConversations error", err.Error()) log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetConversations error", err.Error())
resp.CommonResp = &pbUser.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg} resp.CommonResp = &pbUser.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
@@ -175,6 +187,7 @@ func (s *userServer) GetConversation(ctx context.Context, req *pbUser.GetConvers
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String()) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp := &pbUser.GetConversationResp{Conversation: &pbUser.Conversation{}} resp := &pbUser.GetConversationResp{Conversation: &pbUser.Conversation{}}
conversation, err := imdb.GetConversation(req.OwnerUserID, req.ConversationID) conversation, err := imdb.GetConversation(req.OwnerUserID, req.ConversationID)
log.NewDebug("", utils.GetSelfFuncName(), "conversation", conversation)
if err != nil { if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetConversation error", err.Error()) log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetConversation error", err.Error())
resp.CommonResp = &pbUser.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg} resp.CommonResp = &pbUser.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
@@ -192,6 +205,7 @@ func (s *userServer) GetConversations(ctx context.Context, req *pbUser.GetConver
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String()) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp := &pbUser.GetConversationsResp{Conversations: []*pbUser.Conversation{}} resp := &pbUser.GetConversationsResp{Conversations: []*pbUser.Conversation{}}
conversations, err := imdb.GetConversations(req.OwnerUserID, req.ConversationIDs) conversations, err := imdb.GetConversations(req.OwnerUserID, req.ConversationIDs)
log.NewDebug("", utils.GetSelfFuncName(), "conversations", conversations)
if err != nil { if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetConversations error", err.Error()) log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetConversations error", err.Error())
resp.CommonResp = &pbUser.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg} resp.CommonResp = &pbUser.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
@@ -219,6 +233,7 @@ func (s *userServer) SetConversation(ctx context.Context, req *pbUser.SetConvers
return resp, nil return resp, nil
} }
if groupInfo.Status == constant.GroupStatusDismissed && !req.Conversation.IsNotInGroup { if groupInfo.Status == constant.GroupStatusDismissed && !req.Conversation.IsNotInGroup {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "group status is dismissed", groupInfo)
errMsg := "group status is dismissed" errMsg := "group status is dismissed"
resp.CommonResp = &pbUser.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg} resp.CommonResp = &pbUser.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: errMsg}
return resp, nil return resp, nil
@@ -389,11 +404,29 @@ func (s *userServer) UpdateUserInfo(ctx context.Context, req *pbUser.UpdateUserI
log.Info(req.OperationID, "UserInfoUpdatedNotification ", req.UserInfo.UserID, v.FriendUser.UserID) 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, v.FriendUser.UserID)
} }
chat.UserInfoUpdatedNotification(req.OperationID, req.UserInfo.UserID, req.OpUserID) chat.UserInfoUpdatedNotification(req.OperationID, req.UserInfo.UserID, req.OpUserID)
log.Info(req.OperationID, "UserInfoUpdatedNotification ", 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 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) { func (s *userServer) GetUsersByName(ctx context.Context, req *pbUser.GetUsersByNameReq) (*pbUser.GetUsersByNameResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req:", req.String()) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req:", req.String())
resp := &pbUser.GetUsersByNameResp{} resp := &pbUser.GetUsersByNameResp{}
@@ -427,6 +460,7 @@ func (s *userServer) GetUsersByName(ctx context.Context, req *pbUser.GetUsersByN
CurrentPage: req.Pagination.PageNumber, CurrentPage: req.Pagination.PageNumber,
ShowNumber: req.Pagination.ShowNumber, ShowNumber: req.Pagination.ShowNumber,
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
return resp, nil return resp, nil
} }
@@ -450,6 +484,7 @@ func (s *userServer) GetUserById(ctx context.Context, req *pbUser.GetUserByIdReq
CreateTime: user.CreateTime.String(), CreateTime: user.CreateTime.String(),
IsBlock: isBlock, IsBlock: isBlock,
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil return resp, nil
} }
@@ -458,6 +493,7 @@ func (s *userServer) GetUsers(ctx context.Context, req *pbUser.GetUsersReq) (*pb
resp := &pbUser.GetUsersResp{User: []*pbUser.User{}} resp := &pbUser.GetUsersResp{User: []*pbUser.User{}}
users, err := imdb.GetUsers(req.Pagination.ShowNumber, req.Pagination.PageNumber) users, err := imdb.GetUsers(req.Pagination.ShowNumber, req.Pagination.PageNumber)
if err != nil { if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUsers failed", err.Error())
return resp, errors.WrapError(constant.ErrDB) return resp, errors.WrapError(constant.ErrDB)
} }
for _, v := range users { for _, v := range users {
@@ -471,16 +507,19 @@ func (s *userServer) GetUsers(ctx context.Context, req *pbUser.GetUsersReq) (*pb
IsBlock: isBlock, IsBlock: isBlock,
} }
resp.User = append(resp.User, user) resp.User = append(resp.User, user)
} else {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "UserIsBlock failed", err.Error())
} }
} }
user := db.User{} user := db.User{}
nums, err := imdb.GetUsersCount(user) nums, err := imdb.GetUsersCount(user)
if err != nil { 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) return resp, errors.WrapError(constant.ErrDB)
} }
resp.UserNums = nums resp.UserNums = nums
resp.Pagination = &sdkws.ResponsePagination{ShowNumber: req.Pagination.ShowNumber, CurrentPage: req.Pagination.PageNumber} resp.Pagination = &sdkws.ResponsePagination{ShowNumber: req.Pagination.ShowNumber, CurrentPage: req.Pagination.PageNumber}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil return resp, nil
} }
@@ -490,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) { 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{} resp := &pbUser.AlterUserResp{}
user := db.User{ user := db.User{
PhoneNumber: strconv.FormatInt(req.PhoneNumber, 10), PhoneNumber: strconv.FormatInt(req.PhoneNumber, 10),
@@ -503,11 +542,12 @@ func (s *userServer) AlterUser(ctx context.Context, req *pbUser.AlterUserReq) (*
return resp, errors.WrapError(constant.ErrDB) return resp, errors.WrapError(constant.ErrDB)
} }
chat.UserInfoUpdatedNotification(req.OperationID, req.UserId, req.OpUserId) chat.UserInfoUpdatedNotification(req.OperationID, req.UserId, req.OpUserId)
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil return resp, nil
} }
func (s *userServer) AddUser(ctx context.Context, req *pbUser.AddUserReq) (*pbUser.AddUserResp, error) { 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{} resp := &pbUser.AddUserResp{}
err := imdb.AddUser(req.UserId, req.PhoneNumber, req.Name) err := imdb.AddUser(req.UserId, req.PhoneNumber, req.Name)
if err != nil { if err != nil {
@@ -518,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) { func (s *userServer) BlockUser(ctx context.Context, req *pbUser.BlockUserReq) (*pbUser.BlockUserResp, error) {
log.NewInfo(req.OperationID, "BlockUser args ", req.String()) log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
fmt.Println("BlockUser args ", req.String())
resp := &pbUser.BlockUserResp{} resp := &pbUser.BlockUserResp{}
err := imdb.BlockUser(req.UserId, req.EndDisableTime) err := imdb.BlockUser(req.UserId, req.EndDisableTime)
if err != nil { if err != nil {
@@ -530,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) { 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{} resp := &pbUser.UnBlockUserResp{}
err := imdb.UnBlockUser(req.UserId) err := imdb.UnBlockUser(req.UserId)
if err != nil { if err != nil {
@@ -541,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) { 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{} resp := &pbUser.GetBlockUsersResp{}
blockUsers, err := imdb.GetBlockUsers(req.Pagination.ShowNumber, req.Pagination.PageNumber) blockUsers, err := imdb.GetBlockUsers(req.Pagination.ShowNumber, req.Pagination.PageNumber)
if err != nil { if err != nil {
@@ -569,11 +608,12 @@ func (s *userServer) GetBlockUsers(ctx context.Context, req *pbUser.GetBlockUser
return resp, errors.WrapError(constant.ErrDB) return resp, errors.WrapError(constant.ErrDB)
} }
resp.UserNums = nums resp.UserNums = nums
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
return resp, nil return resp, nil
} }
func (s *userServer) GetBlockUserById(_ context.Context, req *pbUser.GetBlockUserByIdReq) (*pbUser.GetBlockUserByIdResp, error) { 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{} resp := &pbUser.GetBlockUserByIdResp{}
user, err := imdb.GetBlockUserById(req.UserId) user, err := imdb.GetBlockUserById(req.UserId)
if err != nil { if err != nil {
@@ -590,6 +630,7 @@ func (s *userServer) GetBlockUserById(_ context.Context, req *pbUser.GetBlockUse
BeginDisableTime: (user.BeginDisableTime).String(), BeginDisableTime: (user.BeginDisableTime).String(),
EndDisableTime: (user.EndDisableTime).String(), EndDisableTime: (user.EndDisableTime).String(),
} }
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", req.String())
return resp, nil return resp, nil
} }

View File

@@ -1,13 +1 @@
package utils 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 CommResp
UserToken UserTokenInfo `json:"data"` 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

@@ -58,6 +58,15 @@ type SetConversationReq struct {
type SetConversationResp struct { type SetConversationResp struct {
CommResp 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 { type BatchSetConversationsReq struct {
Conversations []Conversation `json:"conversations" binding:"required"` Conversations []Conversation `json:"conversations" binding:"required"`

View File

@@ -81,8 +81,8 @@ type GetGroupAllMemberResp struct {
} }
type CreateGroupReq struct { type CreateGroupReq struct {
MemberList []*GroupAddMemberInfo `json:"memberList" binding:"required"` MemberList []*GroupAddMemberInfo `json:"memberList"`
OwnerUserID string `json:"ownerUserID" binding:"required"` OwnerUserID string `json:"ownerUserID"`
GroupType int32 `json:"groupType"` GroupType int32 `json:"groupType"`
GroupName string `json:"groupName"` GroupName string `json:"groupName"`
Notification string `json:"notification"` Notification string `json:"notification"`
@@ -90,6 +90,7 @@ type CreateGroupReq struct {
FaceURL string `json:"faceURL"` FaceURL string `json:"faceURL"`
Ex string `json:"ex"` Ex string `json:"ex"`
OperationID string `json:"operationID" binding:"required"` OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID"`
} }
type CreateGroupResp struct { type CreateGroupResp struct {
CommResp CommResp

View File

@@ -1,5 +1,7 @@
package base_info package base_info
import "mime/multipart"
type MinioStorageCredentialReq struct { type MinioStorageCredentialReq struct {
OperationID string `json:"operationID"` OperationID string `json:"operationID"`
} }
@@ -23,3 +25,35 @@ type MinioUploadFileResp struct {
SnapshotURL string `json:"snapshotURL,omitempty"` SnapshotURL string `json:"snapshotURL,omitempty"`
SnapshotNewName string `json:"snapshotName,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

@@ -32,3 +32,21 @@ type GetSelfUserInfoResp struct {
UserInfo *open_im_sdk.UserInfo `json:"-"` UserInfo *open_im_sdk.UserInfo `json:"-"`
Data map[string]interface{} `json:"data"` 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

@@ -8,6 +8,7 @@ type CreateOneWorkMomentReq struct {
type CreateOneWorkMomentResp struct { type CreateOneWorkMomentResp struct {
CommResp CommResp
Data struct{} `json:"data"`
} }
type DeleteOneWorkMomentReq struct { type DeleteOneWorkMomentReq struct {
@@ -16,6 +17,7 @@ type DeleteOneWorkMomentReq struct {
type DeleteOneWorkMomentResp struct { type DeleteOneWorkMomentResp struct {
CommResp CommResp
Data struct{} `json:"data"`
} }
type LikeOneWorkMomentReq struct { type LikeOneWorkMomentReq struct {
@@ -24,6 +26,7 @@ type LikeOneWorkMomentReq struct {
type LikeOneWorkMomentResp struct { type LikeOneWorkMomentResp struct {
CommResp CommResp
Data struct{} `json:"data"`
} }
type CommentOneWorkMomentReq struct { type CommentOneWorkMomentReq struct {
@@ -32,6 +35,16 @@ type CommentOneWorkMomentReq struct {
type CommentOneWorkMomentResp struct { type CommentOneWorkMomentResp struct {
CommResp CommResp
Data struct{} `json:"data"`
}
type DeleteCommentReq struct {
office.DeleteCommentReq
}
type DeleteCommentResp struct {
CommResp
Data struct{} `json:"data"`
} }
type WorkMomentsUserCommonReq struct { type WorkMomentsUserCommonReq struct {
@@ -50,13 +63,12 @@ type WorkMoment struct {
Content string `json:"content"` Content string `json:"content"`
LikeUserList []*WorkMomentUser `json:"likeUsers"` LikeUserList []*WorkMomentUser `json:"likeUsers"`
Comments []*Comment `json:"comments"` Comments []*Comment `json:"comments"`
FaceURL string `json:"faceUrl"` FaceURL string `json:"faceURL"`
UserName string `json:"userName"` UserName string `json:"userName"`
//Permission int32 `json:"permission"`
//PermissionUserIDList []string `json:"permissionUserIDList"`
//PermissionGroupIDList []string `json:"permissionGroupIDList"`
AtUserList []*WorkMomentUser `json:"atUsers"` AtUserList []*WorkMomentUser `json:"atUsers"`
PermissionUserList []*WorkMomentUser `json:"permissionUsers"`
CreateTime int32 `json:"createTime"` CreateTime int32 `json:"createTime"`
Permission int32 `json:"permission"`
} }
type WorkMomentUser struct { type WorkMomentUser struct {
@@ -83,6 +95,7 @@ type GetWorkMomentByIDResp struct {
type GetUserWorkMomentsReq struct { type GetUserWorkMomentsReq struct {
WorkMomentsUserCommonReq WorkMomentsUserCommonReq
UserID string `json:"userID"`
} }
type GetUserWorkMomentsResp struct { type GetUserWorkMomentsResp struct {
@@ -113,4 +126,5 @@ type SetUserWorkMomentsLevelReq struct {
type SetUserWorkMomentsLevelResp struct { type SetUserWorkMomentsLevelResp struct {
CommResp CommResp
Data struct{} `json:"data"`
} }

View File

@@ -1,5 +1,9 @@
package cms_api_struct package cms_api_struct
import (
apiStruct "Open_IM/pkg/base_info"
)
type AdminLoginRequest struct { type AdminLoginRequest struct {
AdminName string `json:"admin_name" binding:"required"` AdminName string `json:"admin_name" binding:"required"`
Secret string `json:"secret" binding:"required"` Secret string `json:"secret" binding:"required"`
@@ -8,3 +12,32 @@ type AdminLoginRequest struct {
type AdminLoginResponse struct { type AdminLoginResponse struct {
Token string `json:"token"` 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" "path/filepath"
"runtime" "runtime"
"github.com/spf13/viper"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
) )
@@ -26,15 +25,22 @@ type callBackConfig struct {
type config struct { type config struct {
ServerIP string `yaml:"serverip"` ServerIP string `yaml:"serverip"`
RpcRegisterIP string `yaml:"rpcRegisterIP"`
ListenIP string `yaml:"listenIP"`
ServerVersion string `yaml:"serverversion"` ServerVersion string `yaml:"serverversion"`
Api struct { Api struct {
GinPort []int `yaml:"openImApiPort"` GinPort []int `yaml:"openImApiPort"`
ListenIP string `yaml:"listenIP"`
} }
CmsApi struct { CmsApi struct {
GinPort []int `yaml:"openImCmsApiPort"` GinPort []int `yaml:"openImCmsApiPort"`
ListenIP string `yaml:"listenIP"`
} }
Sdk struct { Sdk struct {
WsPort []int `yaml:"openImSdkWsPort"` WsPort []int `yaml:"openImSdkWsPort"`
DataDir []string `yaml:"dataDir"`
} }
Credential struct { Credential struct {
Tencent struct { Tencent struct {
@@ -57,6 +63,7 @@ type config struct {
} }
Minio struct { Minio struct {
Bucket string `yaml:"bucket"` Bucket string `yaml:"bucket"`
AppBucket string `yaml:"appBucket"`
Location string `yaml:"location"` Location string `yaml:"location"`
Endpoint string `yaml:"endpoint"` Endpoint string `yaml:"endpoint"`
AccessKeyID string `yaml:"accessKeyID"` AccessKeyID string `yaml:"accessKeyID"`
@@ -78,7 +85,7 @@ type config struct {
DBMaxLifeTime int `yaml:"dbMaxLifeTime"` DBMaxLifeTime int `yaml:"dbMaxLifeTime"`
} }
Mongo struct { Mongo struct {
DBUri string `yaml:"dbUri"` // 当dbUri值不为空则直接使用该值 DBUri string `yaml:"dbUri"`
DBAddress []string `yaml:"dbAddress"` DBAddress []string `yaml:"dbAddress"`
DBDirect bool `yaml:"dbDirect"` DBDirect bool `yaml:"dbDirect"`
DBTimeout int `yaml:"dbTimeout"` DBTimeout int `yaml:"dbTimeout"`
@@ -106,7 +113,7 @@ type config struct {
RpcGetTokenPort []int `yaml:"rpcGetTokenPort"` RpcGetTokenPort []int `yaml:"rpcGetTokenPort"`
} }
RpcRegisterName struct { RpcRegisterName struct {
OpenImStatisticsName string `yaml:"OpenImStatisticsName"` OpenImStatisticsName string `yaml:"openImStatisticsName"`
OpenImUserName string `yaml:"openImUserName"` OpenImUserName string `yaml:"openImUserName"`
OpenImFriendName string `yaml:"openImFriendName"` OpenImFriendName string `yaml:"openImFriendName"`
OpenImOfflineMessageName string `yaml:"openImOfflineMessageName"` OpenImOfflineMessageName string `yaml:"openImOfflineMessageName"`
@@ -118,6 +125,9 @@ type config struct {
OpenImAdminCMSName string `yaml:"openImAdminCMSName"` OpenImAdminCMSName string `yaml:"openImAdminCMSName"`
OpenImOfficeName string `yaml:"openImOfficeName"` OpenImOfficeName string `yaml:"openImOfficeName"`
OpenImOrganizationName string `yaml:"openImOrganizationName"` OpenImOrganizationName string `yaml:"openImOrganizationName"`
OpenImConversationName string `yaml:"openImConversationName"`
OpenImCacheName string `yaml:"openImCacheName"`
OpenImRealTimeCommName string `yaml:"openImRealTimeCommName"`
} }
Etcd struct { Etcd struct {
EtcdSchema string `yaml:"etcdSchema"` EtcdSchema string `yaml:"etcdSchema"`
@@ -182,12 +192,17 @@ type config struct {
Addr []string `yaml:"addr"` Addr []string `yaml:"addr"`
Topic string `yaml:"topic"` Topic string `yaml:"topic"`
} }
Ws2mschatOffline struct {
Addr []string `yaml:"addr"`
Topic string `yaml:"topic"`
}
Ms2pschat struct { Ms2pschat struct {
Addr []string `yaml:"addr"` Addr []string `yaml:"addr"`
Topic string `yaml:"topic"` Topic string `yaml:"topic"`
} }
ConsumerGroupID struct { ConsumerGroupID struct {
MsgToMongo string `yaml:"msgToMongo"` MsgToMongo string `yaml:"msgToMongo"`
MsgToMongoOffline string `yaml:"msgToMongoOffline"`
MsgToMySql string `yaml:"msgToMySql"` MsgToMySql string `yaml:"msgToMySql"`
MsgToPush string `yaml:"msgToPush"` MsgToPush string `yaml:"msgToPush"`
} }
@@ -387,9 +402,15 @@ type config struct {
OfflinePush POfflinePush `yaml:"offlinePush"` OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"` DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"workMomentsNotification"` } `yaml:"workMomentsNotification"`
JoinDepartmentNotification struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"joinDepartmentNotification"`
} }
Demo struct { Demo struct {
Port []int `yaml:"openImDemoPort"` Port []int `yaml:"openImDemoPort"`
ListenIP string `yaml:"listenIP"`
AliSMSVerify struct { AliSMSVerify struct {
AccessKeyID string `yaml:"accessKeyId"` AccessKeyID string `yaml:"accessKeyId"`
AccessKeySecret string `yaml:"accessKeySecret"` AccessKeySecret string `yaml:"accessKeySecret"`
@@ -405,6 +426,7 @@ type config struct {
SmtpAddr string `yaml:"smtpAddr"` SmtpAddr string `yaml:"smtpAddr"`
SmtpPort int `yaml:"smtpPort"` SmtpPort int `yaml:"smtpPort"`
} }
TestDepartMentID string `yaml:"testDepartMentID"`
} }
Rtc struct { Rtc struct {
Port int `yaml:"port"` Port int `yaml:"port"`
@@ -427,21 +449,11 @@ type PDefaultTips struct {
} }
func init() { 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") cfgName := os.Getenv("CONFIG_NAME")
if len(cfgName) == 0 { if len(cfgName) == 0 {
cfgName = Root + "/config/config.yaml" cfgName = Root + "/config/config.yaml"
} }
viper.SetConfigFile(cfgName)
err := viper.ReadInConfig()
if err != nil {
panic(err.Error())
}
bytes, err := ioutil.ReadFile(cfgName) bytes, err := ioutil.ReadFile(cfgName)
if err != nil { if err != nil {
panic(err.Error()) panic(err.Error())

View File

@@ -151,6 +151,10 @@ const (
GroupStatusDismissed = 2 GroupStatusDismissed = 2
GroupStatusMuted = 3 GroupStatusMuted = 3
//GroupType
NormalGroup = 0
DepartmentGroup = 1
GroupBaned = 3 GroupBaned = 3
GroupBanPrivateChat = 4 GroupBanPrivateChat = 4
@@ -214,6 +218,16 @@ var ContentType2PushContent = map[int64]string{
Common: "你收到一条新消息", Common: "你收到一条新消息",
} }
const (
FieldRecvMsgOpt = 1
FieldIsPinned = 2
FieldAttachedInfo = 3
FieldIsPrivateChat = 4
FieldGroupAtType = 5
FieldIsNotInGroup = 6
FieldEx = 7
)
const ( const (
AppOrdinaryUsers = 1 AppOrdinaryUsers = 1
AppAdmin = 2 AppAdmin = 2
@@ -257,3 +271,5 @@ func GroupIsBanPrivateChat(status int32) bool {
const BigVersion = "v3" const BigVersion = "v3"
const LogFileName = "OpenIM.log" const LogFileName = "OpenIM.log"
const StatisticsTimeInterval = 300

View File

@@ -2,7 +2,8 @@ package db
import ( import (
"Open_IM/pkg/common/config" "Open_IM/pkg/common/config"
"go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/x/bsonx"
"strings"
//"Open_IM/pkg/common/log" //"Open_IM/pkg/common/log"
"Open_IM/pkg/utils" "Open_IM/pkg/utils"
@@ -68,64 +69,30 @@ func init() {
} }
fmt.Println("0", utils.GetSelfFuncName(), "mongo driver client init success: ", uri) fmt.Println("0", utils.GetSelfFuncName(), "mongo driver client init success: ", uri)
// mongodb create index // mongodb create index
opts := options.CreateIndexes().SetMaxTime(10 * time.Second) if err := createMongoIndex(mongoClient, cSendLog, false, "send_id", "-send_time"); err != nil {
dataBase := mongoClient.Database(config.Config.Mongo.DBDatabase) fmt.Println("send_id", "-send_time", "index create failed", err.Error())
cCommentMsgModels := []mongo.IndexModel{
{
Keys: bson.M{"create_time": -1, "user_id": -1},
},
} }
result, err := dataBase.Collection(cCommentMsg).Indexes().CreateMany(context.Background(), cCommentMsgModels, opts) if err := createMongoIndex(mongoClient, cChat, true, "uid"); err != nil {
if err != nil { fmt.Println("uid", " index create failed", err.Error())
fmt.Println("mongodb create cCommentMsgModels failed", result, 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())
} }
cSendLogModels := []mongo.IndexModel{ if err := createMongoIndex(mongoClient, cWorkMoment, false, "user_id", "-create_time"); err != nil {
{ fmt.Println("user_id", "-create_time", "index create failed", err.Error())
Keys: bson.M{"user_id": -1, "send_time": -1},
},
}
result, err = dataBase.Collection(cSendLog).Indexes().CreateMany(context.Background(), cSendLogModels, opts)
if err != nil {
fmt.Println("mongodb create cSendLogModels failed", result, err.Error())
} }
cChatModels := []mongo.IndexModel{ if err := createMongoIndex(mongoClient, cTag, false, "user_id", "-create_time"); err != nil {
{ fmt.Println("user_id", "-create_time", "index create failed", err.Error())
Keys: bson.M{"uid": -1},
},
} }
result, err = dataBase.Collection(cChat).Indexes().CreateMany(context.Background(), cChatModels, opts) if err := createMongoIndex(mongoClient, cTag, true, "tag_id"); err != nil {
if err != nil { fmt.Println("user_id", "-create_time", "index create failed", err.Error())
fmt.Println("mongodb create cChatModels failed", result, err.Error())
}
cWorkMomentModels := []mongo.IndexModel{
{
Keys: bson.M{"work_moment_id": -1},
},
{
Keys: bson.M{"user_id": -1, "create_time": -1},
},
}
result, err = dataBase.Collection(cWorkMoment).Indexes().CreateMany(context.Background(), cWorkMomentModels, opts)
if err != nil {
fmt.Println("mongodb create cWorkMomentModels failed", result, err.Error())
}
cTagModels := []mongo.IndexModel{
{
Keys: bson.M{"tag_id": -1},
},
{
Keys: bson.M{"user_id": -1, "tag_id": -1},
},
}
result, err = dataBase.Collection(cTag).Indexes().CreateMany(context.Background(), cTagModels, opts)
if err != nil {
fmt.Println("mongodb create cTagModels failed", result, err.Error())
} }
fmt.Println("create index success")
DB.mongoClient = mongoClient DB.mongoClient = mongoClient
// redis pool init // redis pool init
@@ -146,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

@@ -232,6 +232,7 @@ type Department struct {
ParentID string `gorm:"column:parent_id;size:64" json:"parentID" binding:"required"` // "0" or Real parent id 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, ... Order int32 `gorm:"column:order" json:"order" ` // 1, 2, ...
DepartmentType int32 `gorm:"column:department_type" json:"departmentType"` //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"` CreateTime time.Time `gorm:"column:create_time" json:"createTime"`
Ex string `gorm:"column:ex;type:varchar(1024)" json:"ex"` Ex string `gorm:"column:ex;type:varchar(1024)" json:"ex"`
} }
@@ -272,3 +273,17 @@ type DepartmentMember struct {
func (DepartmentMember) TableName() string { func (DepartmentMember) TableName() string {
return "department_members" 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" "github.com/gogo/protobuf/sortkeys"
"go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/options"
"math/rand" "math/rand"
"sync"
//"github.com/garyburd/redigo/redis" //"github.com/garyburd/redigo/redis"
"github.com/golang/protobuf/proto" "github.com/golang/protobuf/proto"
"gopkg.in/mgo.v2/bson" "go.mongodb.org/mongo-driver/bson"
"strconv" "strconv"
"time" "time"
@@ -79,6 +80,53 @@ func (d *DataBases) GetMinSeqFromMongo2(uid string) (MinSeq uint32, err error) {
return 1, nil 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 // deleteMsgByLogic
func (d *DataBases) DelMsgLogic(uid string, seqList []uint32, operationID string) error { func (d *DataBases) DelMsgLogic(uid string, seqList []uint32, operationID string) error {
sortkeys.Uint32s(seqList) sortkeys.Uint32s(seqList)
@@ -96,6 +144,27 @@ func (d *DataBases) DelMsgLogic(uid string, seqList []uint32, operationID string
return nil 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 { func (d *DataBases) ReplaceMsgBySeq(uid string, msg *open_im_sdk.MsgData, operationID string) error {
log.NewInfo(operationID, utils.GetSelfFuncName(), uid, *msg) log.NewInfo(operationID, utils.GetSelfFuncName(), uid, *msg)
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second) ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
@@ -109,6 +178,7 @@ func (d *DataBases) ReplaceMsgBySeq(uid string, msg *open_im_sdk.MsgData, operat
log.NewError(operationID, utils.GetSelfFuncName(), "proto marshal", err.Error()) log.NewError(operationID, utils.GetSelfFuncName(), "proto marshal", err.Error())
return utils.Wrap(err, "") return utils.Wrap(err, "")
} }
updateResult, err := c.UpdateOne( updateResult, err := c.UpdateOne(
ctx, bson.M{"uid": uid}, ctx, bson.M{"uid": uid},
bson.M{"$set": bson.M{s: bytes}}) bson.M{"$set": bson.M{s: bytes}})
@@ -228,6 +298,36 @@ func (d *DataBases) GetMsgBySeqListMongo2(uid string, seqList []uint32, operatio
return seqMsg, nil 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) { func genExceptionMessageBySeqList(seqList []uint32) (exceptionMsg []*open_im_sdk.MsgData) {
for _, v := range seqList { for _, v := range seqList {
msg := new(open_im_sdk.MsgData) msg := new(open_im_sdk.MsgData)
@@ -571,20 +671,16 @@ type WorkMoment struct {
UserName string `bson:"user_name"` UserName string `bson:"user_name"`
FaceURL string `bson:"face_url"` FaceURL string `bson:"face_url"`
Content string `bson:"content"` Content string `bson:"content"`
LikeUserList []*LikeUser `bson:"like_user_list"` LikeUserList []*WorkMomentUser `bson:"like_user_list"`
AtUserList []*AtUser `bson:"at_user_list"` AtUserList []*WorkMomentUser `bson:"at_user_list"`
PermissionUserList []*WorkMomentUser `bson:"permission_user_list"`
Comments []*Comment `bson:"comments"` Comments []*Comment `bson:"comments"`
PermissionUserIDList []string `bson:"permission_user_id_list"` PermissionUserIDList []string `bson:"permission_user_id_list"`
Permission int32 `bson:"permission"` Permission int32 `bson:"permission"`
CreateTime int32 `bson:"create_time"` CreateTime int32 `bson:"create_time"`
} }
type AtUser struct { type WorkMomentUser struct {
UserID string `bson:"user_id"`
UserName string `bson:"user_name"`
}
type LikeUser struct {
UserID string `bson:"user_id"` UserID string `bson:"user_id"`
UserName string `bson:"user_name"` UserName string `bson:"user_name"`
} }
@@ -616,6 +712,18 @@ func (d *DataBases) DeleteOneWorkMoment(workMomentID string) error {
return err 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) { func (d *DataBases) GetWorkMomentByID(workMomentID string) (*WorkMoment, error) {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second) ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cWorkMoment) c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cWorkMoment)
@@ -637,7 +745,7 @@ func (d *DataBases) LikeOneWorkMoment(likeUserID, userName, workMomentID string)
} }
} }
if !isAlreadyLike { if !isAlreadyLike {
workMoment.LikeUserList = append(workMoment.LikeUserList, &LikeUser{UserID: likeUserID, UserName: userName}) workMoment.LikeUserList = append(workMoment.LikeUserList, &WorkMomentUser{UserID: likeUserID, UserName: userName})
} }
log.NewDebug("", utils.GetSelfFuncName(), workMoment) log.NewDebug("", utils.GetSelfFuncName(), workMoment)
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second) ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
@@ -659,7 +767,7 @@ func (d *DataBases) CommentOneWorkMoment(comment *Comment, workMomentID string)
return workMoment, err return workMoment, err
} }
func (d *DataBases) GetUserWorkMoments(userID string, showNumber, pageNumber int32) ([]WorkMoment, error) { func (d *DataBases) GetUserSelfWorkMoments(userID string, showNumber, pageNumber int32) ([]WorkMoment, error) {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second) ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cWorkMoment) c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cWorkMoment)
var workMomentList []WorkMoment var workMomentList []WorkMoment
@@ -672,14 +780,42 @@ func (d *DataBases) GetUserWorkMoments(userID string, showNumber, pageNumber int
return workMomentList, err return workMomentList, err
} }
func (d *DataBases) GetUserFriendWorkMoments(friendIDList []*string, showNumber, pageNumber int32, userID string) ([]WorkMoment, error) { 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) ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cWorkMoment) c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cWorkMoment)
var workMomentList []WorkMoment var workMomentList []WorkMoment
findOpts := options.Find().SetLimit(int64(showNumber)).SetSkip(int64(showNumber) * (int64(pageNumber) - 1)).SetSort(bson.M{"create_time": -1}) findOpts := options.Find().SetLimit(int64(showNumber)).SetSkip(int64(showNumber) * (int64(pageNumber) - 1)).SetSort(bson.M{"create_time": -1})
result, err := c.Find(ctx, result, err := c.Find(ctx, bson.D{ // 等价条件: select * from
bson.M{"user_id": friendIDList, "$or": bson.M{"who_can_see_user_id_list": bson.M{"$elemMatch": bson.M{"$eq": userID}}, {"user_id", userID},
"who_cant_see_user_id_list": bson.M{"$nin": 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) }, findOpts)
if err != nil { if err != nil {
return workMomentList, err return workMomentList, err
@@ -713,7 +849,7 @@ func getMsgIndex(seq uint32) int {
seqSuffix := seq / singleGocMsgNum seqSuffix := seq / singleGocMsgNum
var index uint32 var index uint32
if seqSuffix == 0 { if seqSuffix == 0 {
index = (seq - seqSuffix*5000) - 1 index = (seq - seqSuffix*singleGocMsgNum) - 1
} else { } else {
index = seq - seqSuffix*singleGocMsgNum index = seq - seqSuffix*singleGocMsgNum
} }

View File

@@ -59,7 +59,7 @@ func initMysqlDB() {
&GroupMember{}, &GroupMember{},
&GroupRequest{}, &GroupRequest{},
&User{}, &User{},
&Black{}, &ChatLog{}, &Register{}, &Conversation{}) &Black{}, &ChatLog{}, &Register{}, &Conversation{}, &AppVersion{}, &Department{})
db.Set("gorm:table_options", "CHARSET=utf8") db.Set("gorm:table_options", "CHARSET=utf8")
db.Set("gorm:table_options", "collation=utf8_unicode_ci") db.Set("gorm:table_options", "collation=utf8_unicode_ci")
@@ -119,7 +119,10 @@ func initMysqlDB() {
fmt.Println("CreateTable DepartmentMember") fmt.Println("CreateTable DepartmentMember")
db.CreateTable(&DepartmentMember{}) db.CreateTable(&DepartmentMember{})
} }
if !db.HasTable(&AppVersion{}) {
fmt.Println("CreateTable DepartmentMember")
db.CreateTable(&AppVersion{})
}
return return
} }

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,13 +49,13 @@ func GetFriendListByUserID(OwnerUserID string) ([]db.Friend, error) {
return friends, nil return friends, nil
} }
func GetFriendIDListByUserID(OwnerUserID string) ([]*string, error) { func GetFriendIDListByUserID(OwnerUserID string) ([]string, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB() dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil { if err != nil {
return nil, err return nil, err
} }
var friendIDList []*string var friendIDList []string
err = dbConn.Table("friends").Select("friend_user_id").Where("owner_user_id=?", OwnerUserID).Find(&friendIDList).Error err = dbConn.Table("friends").Where("owner_user_id=?", OwnerUserID).Pluck("friend_user_id", &friendIDList).Error
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@@ -72,15 +72,11 @@ func GetGroupMemberIDListByGroupID(groupID string) ([]string, error) {
return nil, err return nil, err
} }
dbConn.LogMode(false) dbConn.LogMode(false)
var groupMembers []db.GroupMember var groupMemberIDList []string
err = dbConn.Table("group_members").Select("user_id").Where("group_id=?", groupID).Find(&groupMembers).Error err = dbConn.Table("group_members").Where("group_id=?", groupID).Pluck("user_id", &groupMemberIDList).Error
if err != nil { if err != nil {
return nil, err return nil, err
} }
var groupMemberIDList []string
for _, v := range groupMembers {
groupMemberIDList = append(groupMemberIDList, v.UserID)
}
return groupMemberIDList, nil return groupMemberIDList, nil
} }

View File

@@ -223,3 +223,13 @@ func UpdateGroupInfoDefaultZero(groupID string, args map[string]interface{}) err
} }
return dbConn.Table("groups").Where("group_id = ? ", groupID).Update(args).Error return dbConn.Table("groups").Where("group_id = ? ", groupID).Update(args).Error
} }
func GetAllGroupIDList() ([]string, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var groupIDList []string
err = dbConn.Table("groups").Pluck("group_id", &groupIDList).Error
return groupIDList, err
}

View File

@@ -3,6 +3,7 @@ package im_mysql_model
import ( import (
"Open_IM/pkg/common/db" "Open_IM/pkg/common/db"
"Open_IM/pkg/utils" "Open_IM/pkg/utils"
"github.com/jinzhu/gorm"
"time" "time"
) )
@@ -234,5 +235,48 @@ func GetSubDepartmentNum(departmentID string) (error, uint32) {
return utils.Wrap(err, ""), 0 return utils.Wrap(err, ""), 0
} }
return nil, number return nil, number
}
func GetDepartmentRelatedGroupIDList(departmentIDList []string) ([]string, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, utils.Wrap(err, "DefaultGormDB failed")
}
var groupIDList []string
err = dbConn.Table("departments").Where("department_id IN (?) ", departmentIDList).Pluck("related_group_id", &groupIDList).Error
return groupIDList, err
}
func getDepartmentParent(departmentID string, dbConn *gorm.DB) (*db.Department, error) {
var department db.Department
var parentID string
dbConn.LogMode(true)
// select * from departments where department_id = (select parent_id from departments where department_id= zx234fd);
err := dbConn.Table("departments").Where("department_id=?", dbConn.Table("departments").Where("department_id=?", departmentID).Pluck("parent_id", parentID)).Find(&department).Error
return &department, err
}
func GetDepartmentParent(departmentID string, dbConn *gorm.DB, parentIDList []string) (*db.Department, error) {
department, err := getDepartmentParent(departmentID, dbConn)
if err != nil {
return nil, err
}
if department.ParentID != "" {
parentIDList = append(parentIDList, department.ParentID)
_, err = GetDepartmentParent(departmentID, dbConn, parentIDList)
if err != nil {
return nil, nil
}
}
return nil, nil
}
func GetDepartmentParentIDList(departmentID string) ([]string, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var parentIDList []string
_, err = GetDepartmentParent(departmentID, dbConn, parentIDList)
return parentIDList, err
} }

View File

@@ -56,3 +56,16 @@ func GetBlackListByUserID(ownerUserID string) ([]db.Black, error) {
} }
return blackListUsersInfo, nil return blackListUsersInfo, nil
} }
func GetBlackIDListByUserID(ownerUserID string) ([]string, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var blackIDList []string
err = dbConn.Table("blacks").Where("owner_user_id=?", ownerUserID).Pluck("block_user_id", &blackIDList).Error
if err != nil {
return nil, err
}
return blackIDList, nil
}

View File

@@ -4,7 +4,6 @@ import (
"Open_IM/pkg/common/config" "Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant" "Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db" "Open_IM/pkg/common/db"
"Open_IM/pkg/common/log"
"Open_IM/pkg/utils" "Open_IM/pkg/utils"
"fmt" "fmt"
"time" "time"
@@ -61,6 +60,16 @@ func DeleteUser(userID string) (i int64) {
return i return i
} }
func GetAllUser() ([]db.User, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var userList []db.User
err = dbConn.Table("users").Find(&userList).Error
return userList, err
}
func GetUserByUserID(userID string) (*db.User, error) { func GetUserByUserID(userID string) (*db.User, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB() dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil { if err != nil {
@@ -305,101 +314,3 @@ func GetBlockUsersNumCount() (int32, error) {
} }
return count, nil return count, nil
} }
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 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 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
}

View File

@@ -3,18 +3,24 @@ package db
import ( import (
"Open_IM/pkg/common/constant" "Open_IM/pkg/common/constant"
log2 "Open_IM/pkg/common/log" log2 "Open_IM/pkg/common/log"
pbCommon "Open_IM/pkg/proto/sdk_ws"
"encoding/json"
"github.com/garyburd/redigo/redis" "github.com/garyburd/redigo/redis"
) )
const ( const (
AccountTempCode = "ACCOUNT_TEMP_CODE" accountTempCode = "ACCOUNT_TEMP_CODE"
resetPwdTempCode = "RESET_PWD_TEMP_CODE" resetPwdTempCode = "RESET_PWD_TEMP_CODE"
userIncrSeq = "REDIS_USER_INCR_SEQ:" // user incr seq userIncrSeq = "REDIS_USER_INCR_SEQ:" // user incr seq
appleDeviceToken = "DEVICE_TOKEN" appleDeviceToken = "DEVICE_TOKEN"
userMinSeq = "REDIS_USER_MIN_SEQ:" userMinSeq = "REDIS_USER_MIN_SEQ:"
uidPidToken = "UID_PID_TOKEN_STATUS:" uidPidToken = "UID_PID_TOKEN_STATUS:"
conversationReceiveMessageOpt = "CON_RECV_MSG_OPT:" conversationReceiveMessageOpt = "CON_RECV_MSG_OPT:"
GetuiToken = "GETUI" getuiToken = "GETUI"
userInfoCache = "USER_INFO_CACHE:"
friendRelationCache = "FRIEND_RELATION_CACHE:"
blackListCache = "BLACK_LIST_CACHE:"
groupCache = "GROUP_CACHE:"
) )
func (d *DataBases) Exec(cmd string, key interface{}, args ...interface{}) (interface{}, error) { func (d *DataBases) Exec(cmd string, key interface{}, args ...interface{}) (interface{}, error) {
@@ -37,16 +43,16 @@ func (d *DataBases) Exec(cmd string, key interface{}, args ...interface{}) (inte
return con.Do(cmd, params...) return con.Do(cmd, params...)
} }
func (d *DataBases) JudgeAccountEXISTS(account string) (bool, error) { func (d *DataBases) JudgeAccountEXISTS(account string) (bool, error) {
key := AccountTempCode + account key := accountTempCode + account
return redis.Bool(d.Exec("EXISTS", key)) return redis.Bool(d.Exec("EXISTS", key))
} }
func (d *DataBases) SetAccountCode(account string, code, ttl int) (err error) { func (d *DataBases) SetAccountCode(account string, code, ttl int) (err error) {
key := AccountTempCode + account key := accountTempCode + account
_, err = d.Exec("SET", key, code, "ex", ttl) _, err = d.Exec("SET", key, code, "ex", ttl)
return err return err
} }
func (d *DataBases) GetAccountCode(account string) (string, error) { func (d *DataBases) GetAccountCode(account string) (string, error) {
key := AccountTempCode + account key := accountTempCode + account
return redis.String(d.Exec("GET", key)) return redis.String(d.Exec("GET", key))
} }
@@ -147,11 +153,100 @@ func (d *DataBases) GetMultiConversationMsgOpt(userID string, conversationIDs []
} }
func (d *DataBases) SetGetuiToken(token string, expireTime int64) error { func (d *DataBases) SetGetuiToken(token string, expireTime int64) error {
_, err := d.Exec("SET", GetuiToken, token, "ex", expireTime) _, err := d.Exec("SET", getuiToken, token, "ex", expireTime)
return err return err
} }
func (d *DataBases) GetGetuiToken() (string, error) { func (d *DataBases) GetGetuiToken() (string, error) {
result, err := redis.String(d.Exec("GET", GetuiToken)) result, err := redis.String(d.Exec("GET", getuiToken))
return result, err
}
func (d *DataBases) SearchContentType() {
}
func (d *DataBases) SetUserInfoToCache(userID string, m map[string]interface{}) error {
_, err := d.Exec("hmset", userInfoCache+userID, redis.Args{}.Add().AddFlat(m)...)
return err
}
func (d *DataBases) GetUserInfoFromCache(userID string) (*pbCommon.UserInfo, error) {
result, err := redis.String(d.Exec("hgetall", userInfoCache+userID))
log2.NewInfo("", result)
if err != nil {
return nil, err
}
userInfo := &pbCommon.UserInfo{}
err = json.Unmarshal([]byte(result), userInfo)
return userInfo, err
}
func (d *DataBases) AddFriendToCache(userID string, friendIDList ...string) error {
var IDList []interface{}
for _, id := range friendIDList {
IDList = append(IDList, id)
}
_, err := d.Exec("SADD", friendRelationCache+userID, IDList...)
return err
}
func (d *DataBases) ReduceFriendToCache(userID string, friendIDList ...string) error {
var IDList []interface{}
for _, id := range friendIDList {
IDList = append(IDList, id)
}
_, err := d.Exec("SREM", friendRelationCache+userID, IDList...)
return err
}
func (d *DataBases) GetFriendIDListFromCache(userID string) ([]string, error) {
result, err := redis.Strings(d.Exec("SMEMBERS", friendRelationCache+userID))
return result, err
}
func (d *DataBases) AddBlackUserToCache(userID string, blackList ...string) error {
var IDList []interface{}
for _, id := range blackList {
IDList = append(IDList, id)
}
_, err := d.Exec("SADD", blackListCache+userID, IDList...)
return err
}
func (d *DataBases) ReduceBlackUserFromCache(userID string, blackList ...string) error {
var IDList []interface{}
for _, id := range blackList {
IDList = append(IDList, id)
}
_, err := d.Exec("SREM", blackListCache+userID, IDList...)
return err
}
func (d *DataBases) GetBlackListFromCache(userID string) ([]string, error) {
result, err := redis.Strings(d.Exec("SMEMBERS", blackListCache+userID))
return result, err
}
func (d *DataBases) AddGroupMemberToCache(groupID string, userIDList ...string) error {
var IDList []interface{}
for _, id := range userIDList {
IDList = append(IDList, id)
}
_, err := d.Exec("SADD", groupCache+groupID, IDList...)
return err
}
func (d *DataBases) ReduceGroupMemberFromCache(groupID string, userIDList ...string) error {
var IDList []interface{}
for _, id := range userIDList {
IDList = append(IDList, id)
}
_, err := d.Exec("SREM", groupCache+groupID, IDList...)
return err
}
func (d *DataBases) GetGroupMemberIDListFromCache(groupID string) ([]string, error) {
result, err := redis.Strings(d.Exec("SMEMBERS", groupCache+groupID))
return result, err return result, err
} }

View File

@@ -129,13 +129,23 @@ func CheckAccess(OpUserID string, OwnerUserID string) bool {
return false return false
} }
func GetUserIDFromToken(token string, operationID string) (bool, string) { func GetUserIDFromToken(token string, operationID string) (bool, string, string) {
claims, err := ParseToken(token, operationID) claims, err := ParseToken(token, operationID)
if err != nil { if err != nil {
log.Error(operationID, "ParseToken failed, ", err.Error(), token) log.Error(operationID, "ParseToken failed, ", err.Error(), token)
return false, "" return false, "", err.Error()
} }
return true, claims.UID log.Debug(operationID, "token claims.ExpiresAt.Second() ", claims.ExpiresAt.Unix())
return true, claims.UID, ""
}
func GetUserIDFromTokenExpireTime(token string, operationID string) (bool, string, string, int64) {
claims, err := ParseToken(token, operationID)
if err != nil {
log.Error(operationID, "ParseToken failed, ", err.Error(), token)
return false, "", err.Error(), 0
}
return true, claims.UID, "", claims.ExpiresAt.Unix()
} }
func ParseTokenGetUserID(token string, operationID string) (error, string) { func ParseTokenGetUserID(token string, operationID string) (error, string) {
@@ -206,7 +216,7 @@ func ParseRedisInterfaceToken(redisToken interface{}) (*Claims, error) {
func VerifyToken(token, uid string) (bool, error) { func VerifyToken(token, uid string) (bool, error) {
claims, err := ParseToken(token, "") claims, err := ParseToken(token, "")
if err != nil { if err != nil {
return false, err return false, utils.Wrap(err, "ParseToken failed")
} }
if claims.UID != uid { if claims.UID != uid {
return false, &constant.ErrTokenUnknown return false, &constant.ErrTokenUnknown
@@ -215,8 +225,8 @@ func VerifyToken(token, uid string) (bool, error) {
log.NewDebug("", claims.UID, claims.Platform) log.NewDebug("", claims.UID, claims.Platform)
return true, nil return true, nil
} }
func WsVerifyToken(token, uid string, platformID string) (bool, error, string) { func WsVerifyToken(token, uid string, platformID string, operationID string) (bool, error, string) {
claims, err := ParseToken(token, "") claims, err := ParseToken(token, operationID)
if err != nil { if err != nil {
return false, utils.Wrap(err, "parse token err"), "parse token err" return false, utils.Wrap(err, "parse token err"), "parse token err"
} }
@@ -226,6 +236,6 @@ func WsVerifyToken(token, uid string, platformID string) (bool, error, string) {
if claims.Platform != constant.PlatformIDToName(utils.StringToInt32(platformID)) { if claims.Platform != constant.PlatformIDToName(utils.StringToInt32(platformID)) {
return false, utils.Wrap(&constant.ErrTokenUnknown, "platform is not same to token platform"), "platform is not same to token platform" return false, utils.Wrap(&constant.ErrTokenUnknown, "platform is not same to token platform"), "platform is not same to token platform"
} }
log.NewDebug("", claims.UID, claims.Platform) log.NewDebug(operationID, utils.GetSelfFuncName(), " check ok ", claims.UID, uid, claims.Platform)
return true, nil, "" return true, nil, ""
} }

View File

@@ -154,8 +154,3 @@ func UserDBCopyOpenIM(dst *open_im_sdk.UserInfo, src *db.User) {
func UserDBCopyOpenIMPublicUser(dst *open_im_sdk.PublicUserInfo, src *db.User) { func UserDBCopyOpenIMPublicUser(dst *open_im_sdk.PublicUserInfo, src *db.User) {
utils.CopyStructFields(dst, src) utils.CopyStructFields(dst, src)
} }
//
//func PublicUserDBCopyOpenIM(dst *open_im_sdk.PublicUserInfo, src *db.User){
//
//}

View File

@@ -4,7 +4,7 @@ import (
"Open_IM/pkg/common/log" "Open_IM/pkg/common/log"
"context" "context"
"fmt" "fmt"
"go.etcd.io/etcd/clientv3" clientv3 "go.etcd.io/etcd/client/v3"
"net" "net"
"strconv" "strconv"
"strings" "strings"

View File

@@ -1,10 +1,13 @@
package getcdv3 package getcdv3
import ( import (
"Open_IM/pkg/common/log"
"context" "context"
"fmt" "fmt"
"go.etcd.io/etcd/clientv3" "go.etcd.io/etcd/api/v3/mvccpb"
"go.etcd.io/etcd/mvcc/mvccpb" clientv3 "go.etcd.io/etcd/client/v3"
//"go.etcd.io/etcd/mvcc/mvccpb"
//"google.golang.org/genproto/googleapis/ads/googleads/v1/services" //"google.golang.org/genproto/googleapis/ads/googleads/v1/services"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/balancer/roundrobin" "google.golang.org/grpc/balancer/roundrobin"
@@ -43,13 +46,19 @@ func NewResolver(schema, etcdAddr, serviceName string) (*Resolver, error) {
r.schema = schema r.schema = schema
r.etcdAddr = etcdAddr r.etcdAddr = etcdAddr
resolver.Register(&r) resolver.Register(&r)
//
conn, err := grpc.Dial( ctx, _ := context.WithTimeout(context.Background(), time.Second*5)
GetPrefix(schema, serviceName), conn, err := grpc.DialContext(ctx, GetPrefix(schema, serviceName),
grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"LoadBalancingPolicy": "%s"}`, roundrobin.Name)), grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"LoadBalancingPolicy": "%s"}`, roundrobin.Name)),
grpc.WithInsecure(), grpc.WithInsecure())
grpc.WithTimeout(time.Duration(5)*time.Second), log.Debug("", "etcd key ", GetPrefix(schema, serviceName))
)
//conn, err := grpc.Dial(
// GetPrefix(schema, serviceName),
// grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"LoadBalancingPolicy": "%s"}`, roundrobin.Name)),
// grpc.WithInsecure(),
// grpc.WithTimeout(time.Duration(5)*time.Second),
//)
if err == nil { if err == nil {
r.grpcClientConn = conn r.grpcClientConn = conn
} }
@@ -67,6 +76,7 @@ func GetConn(schema, etcdaddr, serviceName string) *grpc.ClientConn {
r, ok := nameResolver[schema+serviceName] r, ok := nameResolver[schema+serviceName]
rwNameResolverMutex.RUnlock() rwNameResolverMutex.RUnlock()
if ok { if ok {
log.Debug("", "etcd key ", schema+serviceName, "value ", *r.grpcClientConn, *r)
return r.grpcClientConn return r.grpcClientConn
} }
@@ -74,15 +84,18 @@ func GetConn(schema, etcdaddr, serviceName string) *grpc.ClientConn {
r, ok = nameResolver[schema+serviceName] r, ok = nameResolver[schema+serviceName]
if ok { if ok {
rwNameResolverMutex.Unlock() rwNameResolverMutex.Unlock()
log.Debug("", "etcd key ", schema+serviceName, "value ", *r.grpcClientConn, *r)
return r.grpcClientConn return r.grpcClientConn
} }
r, err := NewResolver(schema, etcdaddr, serviceName) r, err := NewResolver(schema, etcdaddr, serviceName)
if err != nil { if err != nil {
log.Error("", "etcd failed ", schema, etcdaddr, serviceName)
rwNameResolverMutex.Unlock() rwNameResolverMutex.Unlock()
return nil return nil
} }
log.Debug("", "etcd key ", schema+serviceName, "value ", *r.grpcClientConn, *r)
nameResolver[schema+serviceName] = r nameResolver[schema+serviceName] = r
rwNameResolverMutex.Unlock() rwNameResolverMutex.Unlock()
return r.grpcClientConn return r.grpcClientConn
@@ -93,7 +106,7 @@ func (r *Resolver) Build(target resolver.Target, cc resolver.ClientConn, opts re
return nil, fmt.Errorf("etcd clientv3 client failed, etcd:%s", target) return nil, fmt.Errorf("etcd clientv3 client failed, etcd:%s", target)
} }
r.cc = cc r.cc = cc
log.Debug("", "Build..")
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second) ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
// "%s:///%s" // "%s:///%s"
prefix := GetPrefix(r.schema, r.serviceName) prefix := GetPrefix(r.schema, r.serviceName)
@@ -102,7 +115,7 @@ func (r *Resolver) Build(target resolver.Target, cc resolver.ClientConn, opts re
if err == nil { if err == nil {
var addrList []resolver.Address var addrList []resolver.Address
for i := range resp.Kvs { for i := range resp.Kvs {
//log.Debug("", "init addr: ", string(resp.Kvs[i].Value)) log.Debug("", "etcd init addr: ", string(resp.Kvs[i].Value))
addrList = append(addrList, resolver.Address{Addr: string(resp.Kvs[i].Value)}) addrList = append(addrList, resolver.Address{Addr: string(resp.Kvs[i].Value)})
} }
r.cc.UpdateState(resolver.State{Addresses: addrList}) r.cc.UpdateState(resolver.State{Addresses: addrList})
@@ -148,27 +161,27 @@ func (r *Resolver) watch(prefix string, addrList []resolver.Address) {
if !exists(addrList, string(ev.Kv.Value)) { if !exists(addrList, string(ev.Kv.Value)) {
flag = 1 flag = 1
addrList = append(addrList, resolver.Address{Addr: string(ev.Kv.Value)}) addrList = append(addrList, resolver.Address{Addr: string(ev.Kv.Value)})
//log.Debug("", "after add, new list: ", addrList) log.Debug("", "after add, new list: ", addrList)
} }
case mvccpb.DELETE: case mvccpb.DELETE:
//log.Debug("remove addr key: ", string(ev.Kv.Key), "value:", string(ev.Kv.Value)) log.Debug("remove addr key: ", string(ev.Kv.Key), "value:", string(ev.Kv.Value))
i := strings.LastIndexAny(string(ev.Kv.Key), "/") i := strings.LastIndexAny(string(ev.Kv.Key), "/")
if i < 0 { if i < 0 {
return return
} }
t := string(ev.Kv.Key)[i+1:] t := string(ev.Kv.Key)[i+1:]
//log.Debug("remove addr key: ", string(ev.Kv.Key), "value:", string(ev.Kv.Value), "addr:", t) log.Debug("remove addr key: ", string(ev.Kv.Key), "value:", string(ev.Kv.Value), "addr:", t)
if s, ok := remove(addrList, t); ok { if s, ok := remove(addrList, t); ok {
flag = 1 flag = 1
addrList = s addrList = s
//log.Debug("after remove, new list: ", addrList) log.Debug("after remove, new list: ", addrList)
} }
} }
} }
if flag == 1 { if flag == 1 {
r.cc.UpdateState(resolver.State{Addresses: addrList}) r.cc.UpdateState(resolver.State{Addresses: addrList})
//log.Debug("update: ", addrList) log.Debug("update: ", addrList)
} }
} }
} }
@@ -176,7 +189,7 @@ func (r *Resolver) watch(prefix string, addrList []resolver.Address) {
func GetConn4Unique(schema, etcdaddr, servicename string) []*grpc.ClientConn { func GetConn4Unique(schema, etcdaddr, servicename string) []*grpc.ClientConn {
gEtcdCli, err := clientv3.New(clientv3.Config{Endpoints: strings.Split(etcdaddr, ",")}) gEtcdCli, err := clientv3.New(clientv3.Config{Endpoints: strings.Split(etcdaddr, ",")})
if err != nil { if err != nil {
//log.Error("clientv3.New failed", err.Error()) log.Error("clientv3.New failed", err.Error())
return nil return nil
} }

1564
pkg/proto/cache/cache.pb.go vendored Normal file

File diff suppressed because it is too large Load Diff

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