复制项目

This commit is contained in:
kim.dev.6789
2026-01-14 22:16:44 +08:00
parent e2577b8cee
commit e50142a3b9
691 changed files with 97009 additions and 1 deletions

77
docs/.generated_docs Normal file
View File

@@ -0,0 +1,77 @@
docs/.generated_docs
docs/guide/en-US/cmd/openim/openim.md
docs/guide/en-US/cmd/openim/openim_color.md
docs/guide/en-US/cmd/openim/openim_completion.md
docs/guide/en-US/cmd/openim/openim_info.md
docs/guide/en-US/cmd/openim/openim_jwt.md
docs/guide/en-US/cmd/openim/openim_jwt_show.md
docs/guide/en-US/cmd/openim/openim_jwt_sign.md
docs/guide/en-US/cmd/openim/openim_jwt_verify.md
docs/guide/en-US/cmd/openim/openim_new.md
docs/guide/en-US/cmd/openim/openim_options.md
docs/guide/en-US/cmd/openim/openim_policy.md
docs/guide/en-US/cmd/openim/openim_policy_create.md
docs/guide/en-US/cmd/openim/openim_policy_delete.md
docs/guide/en-US/cmd/openim/openim_policy_get.md
docs/guide/en-US/cmd/openim/openim_policy_list.md
docs/guide/en-US/cmd/openim/openim_policy_update.md
docs/guide/en-US/cmd/openim/openim_secret.md
docs/guide/en-US/cmd/openim/openim_secret_create.md
docs/guide/en-US/cmd/openim/openim_secret_delete.md
docs/guide/en-US/cmd/openim/openim_secret_get.md
docs/guide/en-US/cmd/openim/openim_secret_list.md
docs/guide/en-US/cmd/openim/openim_secret_update.md
docs/guide/en-US/cmd/openim/openim_set.md
docs/guide/en-US/cmd/openim/openim-rpc-user.md
docs/guide/en-US/cmd/openim/openim-rpc-user_create.md
docs/guide/en-US/cmd/openim/openim-rpc-user_delete.md
docs/guide/en-US/cmd/openim/openim-rpc-user_get.md
docs/guide/en-US/cmd/openim/openim-rpc-user_list.md
docs/guide/en-US/cmd/openim/openim-rpc-user_update.md
docs/guide/en-US/cmd/openim/openim_validate.md
docs/guide/en-US/cmd/openim/openim_version.md
docs/guide/en-US/yaml/openim/config.yaml
docs/guide/en-US/yaml/openim/openim_color.yaml
docs/guide/en-US/yaml/openim/openim_completion.yaml
docs/guide/en-US/yaml/openim/openim_info.yaml
docs/guide/en-US/yaml/openim/openim_jwt.yaml
docs/guide/en-US/yaml/openim/openim_new.yaml
docs/guide/en-US/yaml/openim/openim_options.yaml
docs/guide/en-US/yaml/openim/openim_policy.yaml
docs/guide/en-US/yaml/openim/openim_secret.yaml
docs/guide/en-US/yaml/openim/openim_set.yaml
docs/guide/en-US/yaml/openim/openim-rpc-user.yaml
docs/guide/en-US/yaml/openim/openim_validate.yaml
docs/guide/en-US/yaml/openim/openim_version.yaml
docs/man/man1/openim-color.1
docs/man/man1/openim-completion.1
docs/man/man1/openim-info.1
docs/man/man1/openim-jwt-show.1
docs/man/man1/openim-jwt-sign.1
docs/man/man1/openim-jwt-verify.1
docs/man/man1/openim-jwt.1
docs/man/man1/openim-new.1
docs/man/man1/openim-options.1
docs/man/man1/openim-policy-create.1
docs/man/man1/openim-policy-delete.1
docs/man/man1/openim-policy-get.1
docs/man/man1/openim-policy-list.1
docs/man/man1/openim-policy-update.1
docs/man/man1/openim-policy.1
docs/man/man1/openim-secret-create.1
docs/man/man1/openim-secret-delete.1
docs/man/man1/openim-secret-get.1
docs/man/man1/openim-secret-list.1
docs/man/man1/openim-secret-update.1
docs/man/man1/openim-secret.1
docs/man/man1/openim-set.1
docs/man/man1/openim-user-create.1
docs/man/man1/openim-user-delete.1
docs/man/man1/openim-user-get.1
docs/man/man1/openim-user-list.1
docs/man/man1/openim-user-update.1
docs/man/man1/openim-user.1
docs/man/man1/openim-validate.1
docs/man/man1/openim-version.1
docs/man/man1/openim.1

4
docs/CODEOWNERS Normal file
View File

@@ -0,0 +1,4 @@
# CODEOWNERS file
# This file is used to specify the individuals who are required to review changes in this repository.
* @Bloomingg @FGadvancer @skiffer-git @withchao

View File

@@ -0,0 +1,925 @@
# K8s 服务发现 Bug 最终修复方案(含调试日志)
## 目录
- [1. 修复方案概述](#1-修复方案概述)
- [2. 完整修复代码](#2-完整修复代码)
- [3. 调试日志说明](#3-调试日志说明)
- [4. 测试验证](#4-测试验证)
- [5. 问题排查指南](#5-问题排查指南)
---
## 1. 修复方案概述
### 1.1 修复内容
基于历史修复尝试的教训,本次修复包含以下内容:
1.**修复监听资源类型**:从 Pod 改为 Endpoints
2.**GetConn 使用 DNS**:避免连接被强制关闭(关键!)
3.**GetConns 使用 Endpoints**:支持负载均衡和自动更新
4.**延迟关闭旧连接**:避免正在进行的请求失败
5.**添加健康检查**:确保连接有效性
6.**添加 KeepAlive**:支持自动重连
7.**添加详细调试日志**:方便问题排查
### 1.2 核心原则
- **GetConn → DNS**:避免连接被强制关闭,导致消息同步和推送失败
- **GetConns → Endpoints**:支持负载均衡和自动更新
- **延迟关闭**:给正在进行的请求时间完成
- **详细日志**:记录关键操作,方便调试
---
## 2. 完整修复代码
### 2.1 修复后的完整文件
```go
package kubernetes
import (
"context"
"fmt"
"log"
"os"
"sync"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/keepalive"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
)
type KubernetesConnManager struct {
clientset *kubernetes.Clientset
namespace string
dialOptions []grpc.DialOption
rpcTargets map[string]string
selfTarget string
mu sync.RWMutex
connMap map[string][]*grpc.ClientConn
}
// NewKubernetesConnManager creates a new connection manager that uses Kubernetes services for service discovery.
func NewKubernetesConnManager(namespace string, options ...grpc.DialOption) (*KubernetesConnManager, error) {
log.Printf("[K8s Discovery] Initializing Kubernetes connection manager, namespace: %s", namespace)
// 获取集群内配置
config, err := rest.InClusterConfig()
if err != nil {
log.Printf("[K8s Discovery] ERROR: Failed to create in-cluster config: %v", err)
return nil, fmt.Errorf("failed to create in-cluster config: %v", err)
}
log.Printf("[K8s Discovery] Successfully created in-cluster config")
// 创建 K8s API 客户端
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Printf("[K8s Discovery] ERROR: Failed to create clientset: %v", err)
return nil, fmt.Errorf("failed to create clientset: %v", err)
}
log.Printf("[K8s Discovery] Successfully created clientset")
// 初始化连接管理器
k := &KubernetesConnManager{
clientset: clientset,
namespace: namespace,
dialOptions: options,
connMap: make(map[string][]*grpc.ClientConn),
rpcTargets: make(map[string]string),
}
// 启动后台 goroutine 监听 Endpoints 变化
log.Printf("[K8s Discovery] Starting Endpoints watcher")
go k.watchEndpoints()
log.Printf("[K8s Discovery] Kubernetes connection manager initialized successfully")
return k, nil
}
// initializeConns 初始化指定服务的所有 gRPC 连接
func (k *KubernetesConnManager) initializeConns(serviceName string) error {
log.Printf("[K8s Discovery] [%s] Starting to initialize connections", serviceName)
// 步骤 1: 获取 Service 的端口
port, err := k.getServicePort(serviceName)
if err != nil {
log.Printf("[K8s Discovery] [%s] ERROR: Failed to get service port: %v", serviceName, err)
return fmt.Errorf("failed to get service port: %w", err)
}
log.Printf("[K8s Discovery] [%s] Service port: %d", serviceName, port)
// 步骤 2: 获取 Service 对应的 Endpoints
endpoints, err := k.clientset.CoreV1().Endpoints(k.namespace).Get(
context.Background(),
serviceName,
metav1.GetOptions{},
)
if err != nil {
log.Printf("[K8s Discovery] [%s] ERROR: Failed to get endpoints: %v", serviceName, err)
return fmt.Errorf("failed to get endpoints for service %s: %w", serviceName, err)
}
// 统计 Endpoints 数量
var totalAddresses int
for _, subset := range endpoints.Subsets {
totalAddresses += len(subset.Addresses)
}
log.Printf("[K8s Discovery] [%s] Found %d endpoint addresses", serviceName, totalAddresses)
// 步骤 3: 为每个 Pod IP 创建 gRPC 连接
var newConns []*grpc.ClientConn
var newTargets []string
var failedTargets []string
for _, subset := range endpoints.Subsets {
for _, address := range subset.Addresses {
target := fmt.Sprintf("%s:%d", address.IP, port)
log.Printf("[K8s Discovery] [%s] Creating connection to %s", serviceName, target)
// 创建 gRPC 连接,配置 KeepAlive
conn, err := grpc.Dial(
target,
append(k.dialOptions,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: 10 * time.Second,
Timeout: 3 * time.Second,
PermitWithoutStream: true,
}),
)...,
)
if err != nil {
log.Printf("[K8s Discovery] [%s] ERROR: Failed to dial %s: %v", serviceName, target, err)
failedTargets = append(failedTargets, target)
// 如果连接失败,关闭已创建的连接并返回错误
for _, c := range newConns {
_ = c.Close()
}
return fmt.Errorf("failed to dial endpoint %s: %w", target, err)
}
// 检查连接状态
state := conn.GetState()
log.Printf("[K8s Discovery] [%s] Connection to %s created, state: %v", serviceName, target, state)
newConns = append(newConns, conn)
newTargets = append(newTargets, target)
}
}
if len(failedTargets) > 0 {
log.Printf("[K8s Discovery] [%s] WARNING: Failed to connect to %d targets: %v", serviceName, len(failedTargets), failedTargets)
}
log.Printf("[K8s Discovery] [%s] Successfully created %d connections", serviceName, len(newConns))
// 步骤 4: 获取旧连接并延迟关闭
k.mu.Lock()
oldConns, exists := k.connMap[serviceName]
var oldConnCount int
if exists {
oldConnCount = len(oldConns)
log.Printf("[K8s Discovery] [%s] Found %d old connections to close", serviceName, oldConnCount)
}
// 步骤 5: 立即替换为新连接,让新请求使用新连接
k.connMap[serviceName] = newConns
k.mu.Unlock()
log.Printf("[K8s Discovery] [%s] Connection map updated: %d old -> %d new", serviceName, oldConnCount, len(newConns))
// 步骤 6: 延迟关闭旧连接,给正在进行的请求时间完成
if exists && len(oldConns) > 0 {
log.Printf("[K8s Discovery] [%s] Scheduling delayed close for %d old connections (5 seconds delay)", serviceName, len(oldConns))
go func() {
// 等待 5 秒,让正在进行的请求完成
time.Sleep(5 * time.Second)
log.Printf("[K8s Discovery] [%s] Closing %d old connections", serviceName, len(oldConns))
closedCount := 0
for _, oldConn := range oldConns {
if err := oldConn.Close(); err != nil {
log.Printf("[K8s Discovery] [%s] ERROR: Failed to close old connection: %v", serviceName, err)
} else {
closedCount++
}
}
log.Printf("[K8s Discovery] [%s] Closed %d/%d old connections", serviceName, closedCount, len(oldConns))
}()
}
log.Printf("[K8s Discovery] [%s] Connection initialization completed successfully", serviceName)
return nil
}
// GetConns returns gRPC client connections for a given Kubernetes service name.
func (k *KubernetesConnManager) GetConns(ctx context.Context, serviceName string, opts ...grpc.DialOption) ([]*grpc.ClientConn, error) {
log.Printf("[K8s Discovery] [%s] GetConns called", serviceName)
// 步骤 1: 第一次检查缓存(读锁)
k.mu.RLock()
conns, exists := k.connMap[serviceName]
k.mu.RUnlock()
// 步骤 2: 如果缓存中有连接,检查健康状态
if exists {
log.Printf("[K8s Discovery] [%s] Found %d connections in cache, checking health", serviceName, len(conns))
// 检查连接健康状态
validConns := k.filterValidConns(serviceName, conns)
// 如果还有有效连接,更新缓存并返回
if len(validConns) > 0 {
// 如果有效连接数量减少,更新缓存
if len(validConns) < len(conns) {
log.Printf("[K8s Discovery] [%s] Removed %d invalid connections, %d valid connections remaining",
serviceName, len(conns)-len(validConns), len(validConns))
k.mu.Lock()
k.connMap[serviceName] = validConns
k.mu.Unlock()
} else {
log.Printf("[K8s Discovery] [%s] All %d connections are healthy", serviceName, len(validConns))
}
return validConns, nil
}
// 如果所有连接都失效,清除缓存并重新初始化
log.Printf("[K8s Discovery] [%s] All connections are invalid, clearing cache and reinitializing", serviceName)
k.mu.Lock()
delete(k.connMap, serviceName)
k.mu.Unlock()
} else {
log.Printf("[K8s Discovery] [%s] No connections in cache, initializing", serviceName)
}
// 步骤 3: 缓存中没有连接或所有连接都失效,重新初始化
k.mu.Lock()
// 双重检查:在获取写锁后再次检查,避免重复初始化
conns, exists = k.connMap[serviceName]
if exists {
log.Printf("[K8s Discovery] [%s] Connections were initialized by another goroutine", serviceName)
k.mu.Unlock()
return conns, nil
}
k.mu.Unlock()
// 初始化新连接
log.Printf("[K8s Discovery] [%s] Initializing new connections", serviceName)
if err := k.initializeConns(serviceName); err != nil {
log.Printf("[K8s Discovery] [%s] ERROR: Failed to initialize connections: %v", serviceName, err)
return nil, fmt.Errorf("failed to initialize connections for service %s: %w", serviceName, err)
}
// 返回新初始化的连接
k.mu.RLock()
conns = k.connMap[serviceName]
k.mu.RUnlock()
log.Printf("[K8s Discovery] [%s] Returning %d connections", serviceName, len(conns))
return conns, nil
}
// filterValidConns 过滤出有效的连接
func (k *KubernetesConnManager) filterValidConns(serviceName string, conns []*grpc.ClientConn) []*grpc.ClientConn {
validConns := make([]*grpc.ClientConn, 0, len(conns))
invalidStates := make(map[connectivity.State]int)
for i, conn := range conns {
state := conn.GetState()
// 只保留 Ready 和 Idle 状态的连接
if state == connectivity.Ready || state == connectivity.Idle {
validConns = append(validConns, conn)
} else {
invalidStates[state]++
log.Printf("[K8s Discovery] [%s] Connection #%d is invalid, state: %v, closing", serviceName, i, state)
// 连接失效,关闭它
if err := conn.Close(); err != nil {
log.Printf("[K8s Discovery] [%s] ERROR: Failed to close invalid connection #%d: %v", serviceName, i, err)
}
}
}
if len(invalidStates) > 0 {
log.Printf("[K8s Discovery] [%s] Invalid connection states: %v", serviceName, invalidStates)
}
return validConns
}
// GetConn returns a single gRPC client connection for a given Kubernetes service name.
// 重要GetConn 使用 DNS避免连接被强制关闭
// 原因:
// 1. GetConn 返回的连接可能被长期复用
// 2. 如果使用 Endpoints 直连,连接会在 Endpoints 刷新时被关闭
// 3. 这会导致正在进行的请求失败grpc: the client connection is closing
// 4. DNS 方式由 gRPC 客户端管理连接,不会受到 Endpoints 刷新的影响
func (k *KubernetesConnManager) GetConn(ctx context.Context, serviceName string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
log.Printf("[K8s Discovery] [%s] GetConn called (using DNS)", serviceName)
var target string
// 检查是否有自定义目标
if k.rpcTargets[serviceName] == "" {
// 获取 Service 端口
svcPort, err := k.getServicePort(serviceName)
if err != nil {
log.Printf("[K8s Discovery] [%s] ERROR: Failed to get service port: %v", serviceName, err)
return nil, err
}
// 构建 K8s DNS 名称
// 格式:<service>.<namespace>.svc.cluster.local:<port>
// K8s DNS 会自动解析到所有后端 Pod并实现负载均衡
target = fmt.Sprintf("%s.%s.svc.cluster.local:%d", serviceName, k.namespace, svcPort)
log.Printf("[K8s Discovery] [%s] Using DNS target: %s", serviceName, target)
} else {
// 使用自定义目标(如果有)
target = k.rpcTargets[serviceName]
log.Printf("[K8s Discovery] [%s] Using custom target: %s", serviceName, target)
}
// 创建 gRPC 连接
log.Printf("[K8s Discovery] [%s] Dialing DNS target: %s", serviceName, target)
conn, err := grpc.DialContext(
ctx,
target,
append([]grpc.DialOption{
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithDefaultCallOptions(
grpc.MaxCallRecvMsgSize(1024*1024*10), // 最大接收消息大小10MB
grpc.MaxCallSendMsgSize(1024*1024*20), // 最大发送消息大小20MB
),
// 配置 KeepAlive
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: 10 * time.Second,
Timeout: 3 * time.Second,
PermitWithoutStream: true,
}),
}, k.dialOptions...)...,
)
if err != nil {
log.Printf("[K8s Discovery] [%s] ERROR: Failed to dial DNS target %s: %v", serviceName, target, err)
return nil, err
}
// 检查连接状态
state := conn.GetState()
log.Printf("[K8s Discovery] [%s] Connection created, state: %v", serviceName, state)
// 如果连接不是 Ready 状态,等待一下
if state != connectivity.Ready {
log.Printf("[K8s Discovery] [%s] Connection not ready, waiting for state change", serviceName)
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if conn.WaitForStateChange(ctx, state) {
newState := conn.GetState()
log.Printf("[K8s Discovery] [%s] Connection state changed: %v -> %v", serviceName, state, newState)
} else {
log.Printf("[K8s Discovery] [%s] WARNING: Connection state change timeout", serviceName)
}
}
log.Printf("[K8s Discovery] [%s] GetConn completed successfully", serviceName)
return conn, nil
}
// watchEndpoints 监听 Endpoints 资源变化
func (k *KubernetesConnManager) watchEndpoints() {
log.Printf("[K8s Discovery] Starting Endpoints watcher")
// 创建 Informer 工厂
// resyncPeriod: 10 分钟,定期重新同步资源
informerFactory := informers.NewSharedInformerFactory(k.clientset, time.Minute*10)
// 创建 Endpoints Informer
// 注意:这里修复了原来的 bug
// 原来监听的是 Pod现在改为 Endpoints
informer := informerFactory.Core().V1().Endpoints().Informer()
log.Printf("[K8s Discovery] Endpoints Informer created")
// 注册事件处理器
informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
// AddFunc: 当新的 Endpoints 资源被创建时触发
AddFunc: func(obj interface{}) {
endpoint := obj.(*v1.Endpoints)
log.Printf("[K8s Discovery] [Watcher] Endpoints ADDED: %s", endpoint.Name)
k.handleEndpointChange(obj)
},
// UpdateFunc: 当 Endpoints 资源被更新时触发
UpdateFunc: func(oldObj, newObj interface{}) {
oldEndpoint := oldObj.(*v1.Endpoints)
newEndpoint := newObj.(*v1.Endpoints)
// 检查是否有实际变化
if k.endpointsChanged(oldEndpoint, newEndpoint) {
log.Printf("[K8s Discovery] [Watcher] Endpoints UPDATED: %s", newEndpoint.Name)
k.handleEndpointChange(newObj)
} else {
log.Printf("[K8s Discovery] [Watcher] Endpoints %s updated but no meaningful change", newEndpoint.Name)
}
},
// DeleteFunc: 当 Endpoints 资源被删除时触发
DeleteFunc: func(obj interface{}) {
endpoint := obj.(*v1.Endpoints)
log.Printf("[K8s Discovery] [Watcher] Endpoints DELETED: %s", endpoint.Name)
k.handleEndpointChange(obj)
},
})
// 启动 Informer
log.Printf("[K8s Discovery] Starting Informer factory")
informerFactory.Start(context.Background().Done())
// 等待 Informer 同步完成
log.Printf("[K8s Discovery] Waiting for Informer cache to sync")
if !cache.WaitForCacheSync(context.Background().Done(), informer.HasSynced) {
log.Printf("[K8s Discovery] ERROR: Failed to sync Informer cache")
return
}
log.Printf("[K8s Discovery] Informer cache synced successfully")
// 阻塞等待,直到程序退出
log.Printf("[K8s Discovery] Endpoints watcher is running")
<-context.Background().Done()
log.Printf("[K8s Discovery] Endpoints watcher stopped")
}
// endpointsChanged 检查 Endpoints 是否有实际变化
func (k *KubernetesConnManager) endpointsChanged(old, new *v1.Endpoints) bool {
// 比较地址列表
oldAddresses := make(map[string]bool)
for _, subset := range old.Subsets {
for _, address := range subset.Addresses {
oldAddresses[address.IP] = true
}
}
newAddresses := make(map[string]bool)
for _, subset := range new.Subsets {
for _, address := range subset.Addresses {
newAddresses[address.IP] = true
}
}
// 比较数量
if len(oldAddresses) != len(newAddresses) {
return true
}
// 比较内容
for ip := range oldAddresses {
if !newAddresses[ip] {
return true
}
}
return false
}
// handleEndpointChange 处理 Endpoints 资源变化
func (k *KubernetesConnManager) handleEndpointChange(obj interface{}) {
// 类型断言
endpoint, ok := obj.(*v1.Endpoints)
if !ok {
// 类型断言失败,记录日志但不中断程序
log.Printf("[K8s Discovery] [Watcher] ERROR: Expected *v1.Endpoints, got %T", obj)
return
}
serviceName := endpoint.Name
log.Printf("[K8s Discovery] [Watcher] Handling Endpoints change for service: %s", serviceName)
// 统计 Endpoints 信息
var totalAddresses int
for _, subset := range endpoint.Subsets {
totalAddresses += len(subset.Addresses)
}
log.Printf("[K8s Discovery] [Watcher] Service %s has %d endpoint addresses", serviceName, totalAddresses)
// 重新初始化连接
if err := k.initializeConns(serviceName); err != nil {
// 初始化失败,记录错误但不中断程序
log.Printf("[K8s Discovery] [Watcher] ERROR: Failed to initialize connections for %s: %v", serviceName, err)
} else {
log.Printf("[K8s Discovery] [Watcher] Successfully updated connections for %s", serviceName)
}
}
// getServicePort 获取 Service 的 RPC 端口
func (k *KubernetesConnManager) getServicePort(serviceName string) (int32, error) {
log.Printf("[K8s Discovery] [%s] Getting service port", serviceName)
svc, err := k.clientset.CoreV1().Services(k.namespace).Get(
context.Background(),
serviceName,
metav1.GetOptions{},
)
if err != nil {
log.Printf("[K8s Discovery] [%s] ERROR: Failed to get service: %v", serviceName, err)
return 0, fmt.Errorf("failed to get service %s: %w", serviceName, err)
}
if len(svc.Spec.Ports) == 0 {
log.Printf("[K8s Discovery] [%s] ERROR: Service has no ports defined", serviceName)
return 0, fmt.Errorf("service %s has no ports defined", serviceName)
}
// 找到 RPC 端口(非 10001
var svcPort int32
for _, port := range svc.Spec.Ports {
if port.Port != 10001 {
svcPort = port.Port
break
}
}
if svcPort == 0 {
log.Printf("[K8s Discovery] [%s] ERROR: Service has no RPC port (all ports are 10001)", serviceName)
return 0, fmt.Errorf("service %s has no RPC port (all ports are 10001)", serviceName)
}
log.Printf("[K8s Discovery] [%s] Service port: %d", serviceName, svcPort)
return svcPort, nil
}
// Close 关闭所有连接
func (k *KubernetesConnManager) Close() {
log.Printf("[K8s Discovery] Closing all connections")
k.mu.Lock()
defer k.mu.Unlock()
totalConns := 0
for serviceName, conns := range k.connMap {
log.Printf("[K8s Discovery] Closing %d connections for service %s", len(conns), serviceName)
for i, conn := range conns {
if err := conn.Close(); err != nil {
log.Printf("[K8s Discovery] ERROR: Failed to close connection #%d for service %s: %v", i, serviceName, err)
}
}
totalConns += len(conns)
}
log.Printf("[K8s Discovery] Closed %d total connections", totalConns)
k.connMap = make(map[string][]*grpc.ClientConn)
}
// GetSelfConnTarget returns the connection target for the current service.
func (k *KubernetesConnManager) GetSelfConnTarget() string {
if k.selfTarget == "" {
hostName := os.Getenv("HOSTNAME")
log.Printf("[K8s Discovery] Getting self connection target, HOSTNAME: %s", hostName)
pod, err := k.clientset.CoreV1().Pods(k.namespace).Get(context.Background(), hostName, metav1.GetOptions{})
if err != nil {
log.Printf("[K8s Discovery] ERROR: Failed to get pod %s: %v", hostName, err)
}
for pod.Status.PodIP == "" {
log.Printf("[K8s Discovery] Waiting for pod %s IP to be assigned", hostName)
pod, err = k.clientset.CoreV1().Pods(k.namespace).Get(context.TODO(), hostName, metav1.GetOptions{})
if err != nil {
log.Printf("[K8s Discovery] ERROR: Failed to get pod: %v", err)
}
time.Sleep(3 * time.Second)
}
var selfPort int32
for _, port := range pod.Spec.Containers[0].Ports {
if port.ContainerPort != 10001 {
selfPort = port.ContainerPort
break
}
}
k.selfTarget = fmt.Sprintf("%s:%d", pod.Status.PodIP, selfPort)
log.Printf("[K8s Discovery] Self connection target: %s", k.selfTarget)
}
return k.selfTarget
}
// AddOption appends gRPC dial options to the existing options.
func (k *KubernetesConnManager) AddOption(opts ...grpc.DialOption) {
k.mu.Lock()
defer k.mu.Unlock()
k.dialOptions = append(k.dialOptions, opts...)
log.Printf("[K8s Discovery] Added %d dial options", len(opts))
}
// CloseConn closes a given gRPC client connection.
func (k *KubernetesConnManager) CloseConn(conn *grpc.ClientConn) {
log.Printf("[K8s Discovery] Closing single connection")
conn.Close()
}
func (k *KubernetesConnManager) Register(serviceName, host string, port int, opts ...grpc.DialOption) error {
// K8s 环境下不需要注册,返回 nil
return nil
}
func (k *KubernetesConnManager) UnRegister() error {
// K8s 环境下不需要注销,返回 nil
return nil
}
func (k *KubernetesConnManager) GetUserIdHashGatewayHost(ctx context.Context, userId string) (string, error) {
// K8s 环境下不支持,返回空
return "", nil
}
```
---
## 3. 调试日志说明
### 3.1 日志格式
所有日志都使用统一的前缀:`[K8s Discovery]`,方便过滤和查找。
### 3.2 日志级别
- **INFO**:正常操作流程
- **WARNING**:需要注意但不影响功能
- **ERROR**:错误信息,需要关注
### 3.3 关键日志点
#### 3.3.1 初始化日志
```
[K8s Discovery] Initializing Kubernetes connection manager, namespace: default
[K8s Discovery] Successfully created in-cluster config
[K8s Discovery] Successfully created clientset
[K8s Discovery] Starting Endpoints watcher
[K8s Discovery] Kubernetes connection manager initialized successfully
```
#### 3.3.2 连接初始化日志
```
[K8s Discovery] [user-rpc-service] Starting to initialize connections
[K8s Discovery] [user-rpc-service] Service port: 10320
[K8s Discovery] [user-rpc-service] Found 3 endpoint addresses
[K8s Discovery] [user-rpc-service] Creating connection to 10.244.1.5:10320
[K8s Discovery] [user-rpc-service] Connection to 10.244.1.5:10320 created, state: Connecting
[K8s Discovery] [user-rpc-service] Successfully created 3 connections
[K8s Discovery] [user-rpc-service] Found 2 old connections to close
[K8s Discovery] [user-rpc-service] Connection map updated: 2 old -> 3 new
[K8s Discovery] [user-rpc-service] Scheduling delayed close for 2 old connections (5 seconds delay)
[K8s Discovery] [user-rpc-service] Connection initialization completed successfully
```
#### 3.3.3 Endpoints 监听日志
```
[K8s Discovery] [Watcher] Endpoints UPDATED: user-rpc-service
[K8s Discovery] [Watcher] Service user-rpc-service has 3 endpoint addresses
[K8s Discovery] [Watcher] Handling Endpoints change for service: user-rpc-service
[K8s Discovery] [Watcher] Successfully updated connections for user-rpc-service
```
#### 3.3.4 连接健康检查日志
```
[K8s Discovery] [user-rpc-service] GetConns called
[K8s Discovery] [user-rpc-service] Found 3 connections in cache, checking health
[K8s Discovery] [user-rpc-service] Connection #1 is invalid, state: Shutdown, closing
[K8s Discovery] [user-rpc-service] Removed 1 invalid connections, 2 valid connections remaining
[K8s Discovery] [user-rpc-service] Returning 2 connections
```
#### 3.3.5 GetConn 日志
```
[K8s Discovery] [msg-rpc-service] GetConn called (using DNS)
[K8s Discovery] [msg-rpc-service] Using DNS target: msg-rpc-service.default.svc.cluster.local:10280
[K8s Discovery] [msg-rpc-service] Dialing DNS target: msg-rpc-service.default.svc.cluster.local:10280
[K8s Discovery] [msg-rpc-service] Connection created, state: Ready
[K8s Discovery] [msg-rpc-service] GetConn completed successfully
```
---
## 4. 测试验证
### 4.1 测试场景 1Pod 重建
**步骤**
```bash
# 1. 查看日志
kubectl logs -f <pod-name> | grep "K8s Discovery"
# 2. 触发 Pod 重建
kubectl delete pod <target-pod-name>
# 3. 观察日志输出
# 应该看到:
# - Endpoints UPDATED 事件
# - 连接重新初始化
# - 旧连接延迟关闭
```
**预期日志**
```
[K8s Discovery] [Watcher] Endpoints UPDATED: user-rpc-service
[K8s Discovery] [user-rpc-service] Starting to initialize connections
[K8s Discovery] [user-rpc-service] Found 2 old connections to close
[K8s Discovery] [user-rpc-service] Scheduling delayed close for 2 old connections (5 seconds delay)
[K8s Discovery] [user-rpc-service] Connection initialization completed successfully
[K8s Discovery] [user-rpc-service] Closing 2 old connections
[K8s Discovery] [user-rpc-service] Closed 2/2 old connections
```
### 4.2 测试场景 2消息同步和推送
**步骤**
```bash
# 1. 发送消息
# 2. 触发 Pod 重建
kubectl delete pod <msg-service-pod>
# 3. 验证消息同步和推送不失败
# 4. 查看日志确认连接正常
```
**预期结果**
- ✅ 消息同步不失败GetConn 使用 DNS不受影响
- ✅ 消息推送不失败GetConns 自动更新连接)
- ✅ 日志显示连接自动恢复
### 4.3 测试场景 3连接健康检查
**步骤**
```bash
# 1. 查看当前连接状态
kubectl logs <pod-name> | grep "checking health"
# 2. 模拟连接失效(停止目标服务)
kubectl scale deployment <target-service> --replicas=0
# 3. 等待一段时间后查看日志
# 应该看到连接被标记为无效并移除
```
**预期日志**
```
[K8s Discovery] [user-rpc-service] GetConns called
[K8s Discovery] [user-rpc-service] Found 3 connections in cache, checking health
[K8s Discovery] [user-rpc-service] Connection #0 is invalid, state: TransientFailure, closing
[K8s Discovery] [user-rpc-service] Connection #1 is invalid, state: TransientFailure, closing
[K8s Discovery] [user-rpc-service] Connection #2 is invalid, state: TransientFailure, closing
[K8s Discovery] [user-rpc-service] All connections are invalid, clearing cache and reinitializing
```
---
## 5. 问题排查指南
### 5.1 常见问题
#### 问题 1连接初始化失败
**症状**
```
[K8s Discovery] [user-rpc-service] ERROR: Failed to dial endpoint 10.244.1.5:10320: connection refused
```
**可能原因**
- Pod 还未就绪
- 网络问题
- 端口配置错误
**排查步骤**
1. 检查 Pod 状态:`kubectl get pods`
2. 检查 Service 配置:`kubectl get svc user-rpc-service -o yaml`
3. 检查 Endpoints`kubectl get endpoints user-rpc-service`
#### 问题 2Endpoints 监听不工作
**症状**
- Pod 重建后连接不更新
- 没有看到 `[Watcher] Endpoints UPDATED` 日志
**可能原因**
- Informer 未启动
- 权限问题
- 网络问题
**排查步骤**
1. 检查日志中是否有 `[K8s Discovery] Starting Endpoints watcher`
2. 检查 ServiceAccount 权限
3. 手动检查 Endpoints`kubectl get endpoints -w`
#### 问题 3连接被强制关闭
**症状**
```
grpc: the client connection is closing
```
**可能原因**
- GetConn 使用了 Endpoints 直连(错误)
- 旧连接被立即关闭
**排查步骤**
1. 检查日志中是否有 `[K8s Discovery] [xxx] GetConn called (using DNS)`
2. 确认 GetConn 使用的是 DNS 而不是 Endpoints
3. 检查延迟关闭是否生效
#### 问题 4连接泄漏
**症状**
- 连接数量持续增长
- 内存使用持续增长
**可能原因**
- 旧连接未正确关闭
- 延迟关闭的 goroutine 未执行
**排查步骤**
1. 查看日志中是否有 `[K8s Discovery] [xxx] Closing X old connections`
2. 检查延迟关闭的日志
3. 监控连接数量变化
### 5.2 日志过滤命令
**查看所有 K8s Discovery 日志**
```bash
kubectl logs <pod-name> | grep "K8s Discovery"
```
**查看特定服务的日志**
```bash
kubectl logs <pod-name> | grep "K8s Discovery.*user-rpc-service"
```
**查看错误日志**
```bash
kubectl logs <pod-name> | grep "K8s Discovery.*ERROR"
```
**查看 Watcher 日志**
```bash
kubectl logs <pod-name> | grep "K8s Discovery.*Watcher"
```
**实时监控日志**
```bash
kubectl logs -f <pod-name> | grep "K8s Discovery"
```
### 5.3 调试技巧
1. **启用详细日志**:如果默认日志不够,可以增加日志级别
2. **监控连接状态**:定期检查连接数量和状态
3. **对比 Endpoints**:手动检查 Endpoints 是否与连接列表一致
4. **测试 Pod 重建**:主动触发 Pod 重建,观察连接更新过程
---
## 6. 总结
### 6.1 修复要点
1.**修复监听资源类型**:从 Pod 改为 Endpoints
2.**GetConn 使用 DNS**:避免连接被强制关闭
3.**GetConns 使用 Endpoints**:支持负载均衡和自动更新
4.**延迟关闭旧连接**:避免正在进行的请求失败
5.**添加健康检查**:确保连接有效性
6.**添加 KeepAlive**:支持自动重连
7.**添加详细日志**:方便问题排查
### 6.2 关键改进
- **解决了历史修复尝试中的问题**GetConn 使用 DNS避免连接被强制关闭
- **添加了完整的调试日志**:每个关键操作都有日志记录
- **改进了错误处理**:更好的错误信息和恢复机制
### 6.3 使用建议
1. **部署前**:充分测试 Pod 重建场景
2. **部署后**:监控日志,观察连接更新过程
3. **问题排查**:使用日志过滤命令快速定位问题
4. **持续优化**:根据实际使用情况调整延迟关闭时间
---
## 7. 相关文件
- 修复文件:`pkg/common/discovery/kubernetes/kubernetes.go`
- 测试脚本:可以编写自动化测试脚本验证修复效果
- 监控指标:可以添加 Prometheus 指标监控连接状态

66
docs/README.md Normal file
View File

@@ -0,0 +1,66 @@
# OpenIM Server Docs
Welcome to the OpenIM Documentation hub! This center provides a comprehensive range of guides and manuals designed to help you get the most out of your OpenIM experience.
## Table of Contents
1. [Contrib](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib) - Guidance on contributing and configurations for developers
2. [Conversions](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib) - Coding conventions, logging policies, and other transformation tools
## Contrib
This section offers developers a detailed guide on how to contribute code, set up their environment, and follow the associated processes.
- [Code Conventions](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/code-conventions.md) - Rules and conventions for writing code in OpenIM.
- [Development Guide](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/development.md) - A guide on how to carry out development within OpenIM.
- [Git Cherry Pick](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/gitcherry-pick.md) - Guidelines on cherry-picking operations.
- [Git Workflow](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/git-workflow.md) - The git workflow in OpenIM.
- [Initialization Configurations](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/init-config.md) - Guidance on setting up and initializing OpenIM.
- [Docker Installation](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/install-docker.md) - How to install Docker on your machine.
- [Linux Development Environment](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/linux-development.md) - Guide to set up the development environment on Linux.
- [Local Actions](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/local-actions.md) - Guidelines on how to carry out certain common actions locally.
- [Offline Deployment](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/offline-deployment.md) - Methods of deploying OpenIM offline.
- [Protoc Tools](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/protoc-tools.md) - Guide on using protoc tools.
- [Go Tools](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/util-go.md) - Tools and libraries in OpenIM for Go.
- [Makefile Tools](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/util-makefile.md) - Best practices and tools for Makefile.
- [Script Tools](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/util-scripts.md) - Best practices and tools for scripts.
## Conversions
This section introduces various conventions and policies within OpenIM, encompassing code, logs, versions, and more.
- [API Conversions](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/api.md) - Guidelines and methods for API conversions.
- [Logging Policy](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/bash-log.md) - Logging policies and conventions in OpenIM.
- [CI/CD Actions](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/cicd-actions.md) - Procedures and conventions for CI/CD.
- [Commit Conventions](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/commit.md) - Conventions for code commits in OpenIM.
- [Directory Conventions](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/directory.md) - Directory structure and conventions within OpenIM.
- [Error Codes](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/error-code.md) - List and descriptions of error codes.
- [Go Code Conversions](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/go-code.md) - Conventions and conversions for Go code.
- [Docker Image Strategy](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/images.md) - Management strategies for OpenIM Docker images, spanning multiple architectures and image repositories.
- [Logging Conventions](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/logging.md) - Further detailed conventions on logging.
- [Version Conventions](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/version.md) - Naming and management strategies for OpenIM versions.
## For Developers, Contributors, and Community Maintainers
### Developers & Contributors
If you're a developer or someone keen on contributing:
- Familiarize yourself with our [Code Conventions](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/code-conventions.md) and [Git Workflow](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/git-workflow.md) to ensure smooth contributions.
- Dive into the [Development Guide](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/development.md) to get a hang of the development practices in OpenIM.
### Community Maintainers
As a community maintainer:
- Ensure that contributions align with the standards outlined in our documentation.
- Regularly review the [Logging Policy](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/bash-log.md) and [Error Codes](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/error-code.md) to stay updated.
## For Users
Users should pay particular attention to:
- [Docker Installation](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/install-docker.md) - Necessary if you're planning to use Docker images of OpenIM.
- [Docker Image Strategy](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/images.md) - To understand the different images available and how to choose the right one for your architecture.

View File

@@ -0,0 +1,183 @@
# SuperGroup (GroupType=1) 使用限制分析
## 一、核心问题
如果绕过创建限制,创建了 `GroupType=1` (SuperGroup) 的群组,在使用上会有以下**关键差异和潜在问题**
## 二、关键差异点
### 2.1 消息验证逻辑差异 ⚠️ **重要**
**位置**: `internal/rpc/msg/verify.go:187-220`
**SuperGroup (GroupType=1) 的特殊处理**
```go
if groupInfo.GroupType == constant.SuperGroup {
// SuperGroup 跳过大部分检查,但仍需检查文件权限
if data.MsgData.ContentType == constant.File {
// 只检查文件发送权限
}
return nil // 直接返回,跳过后续所有检查
}
```
**WorkingGroup (GroupType=2) 的完整验证**
- ✅ 检查用户是否在群内
- ✅ 检查文件发送权限(群主/管理员/userType=1
- ✅ 检查链接发送权限userType=1/群主/管理员可发送链接)
- ✅ 检查二维码图片userType=0 普通成员不能发送包含二维码的图片)
- ✅ 检查禁言状态MuteEndTime
- ✅ 检查群组是否被禁言GroupStatusMuted
**差异总结**
| 检查项 | SuperGroup | WorkingGroup |
|--------|-----------|--------------|
| 文件发送权限 | ✅ 检查 | ✅ 检查 |
| 链接检测 | ❌ **跳过** | ✅ 检查 |
| 二维码检测 | ❌ **跳过** | ✅ 检查 |
| 禁言检查 | ❌ **跳过** | ✅ 检查 |
| 群组禁言检查 | ❌ **跳过** | ✅ 检查 |
**⚠️ 风险**
- SuperGroup 可以发送包含链接的消息,即使 userType=0
- SuperGroup 可以发送包含二维码的图片,即使 userType=0
- SuperGroup 成员即使被禁言也可以发送消息
- SuperGroup 即使群组被禁言,成员仍可发送消息
### 2.2 消息推送机制
**位置**: `internal/push/push_handler.go:104-116`
**推送逻辑**
```go
switch msgFromMQ.MsgData.SessionType {
case constant.ReadGroupChatType:
err = c.Push2Group(ctx, msgFromMQ.MsgData.GroupID, msgFromMQ.MsgData)
default:
err = c.Push2User(ctx, pushUserIDList, msgFromMQ.MsgData)
}
```
**关键发现**
- 推送逻辑**不依赖 GroupType**,而是依赖 **SessionType**
- `SessionType` 是客户端发送消息时指定的,**不是根据 GroupType 自动确定的**
- 如果客户端发送消息时 `SessionType != ReadGroupChatType`,会走 `Push2User` 而不是 `Push2Group`
**⚠️ 潜在问题**
- 如果创建了 `GroupType=1` 的群组,但客户端发送消息时使用 `SessionType=WriteGroupChatType`值为2消息会按单聊方式推送可能导致推送逻辑异常
- `Push2Group``Push2User` 的推送机制不同,可能影响消息分发
### 2.3 会话ID生成差异
**位置**: `pkg/msgprocessor/conversation.go:68-97`
**会话ID生成规则**
```go
case constant.WriteGroupChatType:
return "g_" + msg.GroupID // 普通群聊
case constant.ReadGroupChatType:
return "sg_" + msg.GroupID // 超级群聊
```
**差异**
- `WriteGroupChatType` (值为2): 会话ID前缀为 `g_`
- `ReadGroupChatType` (值为3): 会话ID前缀为 `sg_`
**⚠️ 潜在问题**
- 如果 `GroupType=1` 但使用 `SessionType=WriteGroupChatType`会话ID会是 `g_xxx` 而不是 `sg_xxx`
- 这可能导致会话管理不一致
### 2.4 在线推送方法
**位置**: `internal/push/onlinepusher.go:99`
**推送方法**
- 所有群聊消息(无论 GroupType都使用 `SuperGroupOnlineBatchPushOneMsg` 方法
- 方法名虽然叫 "SuperGroup",但实际上所有群聊都使用这个方法
**结论**:推送方法本身**不受 GroupType 影响**,但推送逻辑受 `SessionType` 影响
## 三、使用限制和潜在错误
### 3.1 必须使用正确的 SessionType ⚠️ **关键**
**问题**:如果创建了 `GroupType=1` 的群组,但发送消息时:
- ❌ 使用 `SessionType=WriteGroupChatType` (值为2) → 会走 `Push2User`,推送逻辑可能异常
- ✅ 必须使用 `SessionType=ReadGroupChatType` (值为3) → 会走 `Push2Group`,推送正常
**建议**:客户端发送消息时,需要根据群组的 `GroupType` 自动设置正确的 `SessionType`
- `GroupType=1` (SuperGroup) → `SessionType=ReadGroupChatType` (值为3)
- `GroupType=2` (WorkingGroup) → `SessionType=WriteGroupChatType` (值为2) 或 `ReadGroupChatType` (值为3)
### 3.2 权限检查缺失 ⚠️ **安全风险**
**SuperGroup 跳过的检查**
1. **链接检测**:普通成员可以发送包含链接的消息
2. **二维码检测**:普通成员可以发送包含二维码的图片
3. **禁言检查**:被禁言的成员仍可发送消息
4. **群组禁言检查**:群组被禁言时,成员仍可发送消息
**安全影响**
- 可能被用于发送恶意链接
- 可能被用于发送包含二维码的垃圾信息
- 禁言功能失效
### 3.3 会话管理不一致
**问题**
- 如果 `GroupType=1` 但使用 `SessionType=WriteGroupChatType`会话ID会是 `g_xxx`
- 如果使用 `SessionType=ReadGroupChatType`会话ID会是 `sg_xxx`
- 这可能导致同一个群组产生不同的会话ID造成会话管理混乱
## 四、总结
### 4.1 主要差异
| 方面 | SuperGroup (GroupType=1) | WorkingGroup (GroupType=2) |
|------|-------------------------|---------------------------|
| **消息验证** | 跳过大部分检查(链接、二维码、禁言) | 完整验证 |
| **文件权限** | 检查(群主/管理员/userType=1 | 检查(群主/管理员/userType=1 |
| **推送机制** | 依赖 SessionType需使用 ReadGroupChatType | 依赖 SessionType |
| **会话ID** | 需使用 ReadGroupChatType 生成 sg_ 前缀 | 可使用 WriteGroupChatType 或 ReadGroupChatType |
### 4.2 使用建议
如果允许创建 `SuperGroup` 类型的群组,需要:
1. **客户端适配**
- 发送消息时,根据群组的 `GroupType` 自动设置正确的 `SessionType`
- `GroupType=1``SessionType=ReadGroupChatType` (值为3)
2. **安全考虑**
- 明确 SuperGroup 跳过权限检查的设计意图
- 如果需要安全控制,考虑在业务层或回调中实现
3. **一致性**
- 确保所有使用 SuperGroup 的地方都使用 `ReadGroupChatType`
- 统一会话ID生成规则
### 4.3 潜在错误场景
1. **推送错误**:如果使用错误的 SessionType消息可能无法正确推送给所有群成员
2. **会话混乱**同一个群组可能产生不同的会话ID
3. **权限绕过**SuperGroup 会跳过禁言等权限检查
4. **安全风险**:可以发送链接和二维码,可能被滥用
## 五、代码修改建议
如果要支持 SuperGroup建议
1. **创建群组时**:允许 `GroupType=1``GroupType=2`
2. **消息发送时**:根据 `GroupType` 自动设置 `SessionType`
3. **消息验证时**:明确 SuperGroup 的特殊逻辑,考虑是否需要保留部分安全检查
4. **文档说明**:明确 SuperGroup 和 WorkingGroup 的差异和使用场景

1455
docs/client-api.md Normal file

File diff suppressed because it is too large Load Diff

42
docs/contrib/README.md Normal file
View File

@@ -0,0 +1,42 @@
# Contrib Documentation Index
## 📚 General Information
- [📄 README](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/README.md) - General introduction to the contribution documentation.
- [📑 Development Guide](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/development.md) - Guidelines for setting up a development environment.
## 🛠 Setup and Installation
- [🌍 Environment Setup](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/environment.md) - Instructions on setting up the development environment.
- [🐳 Docker Installation Guide](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-docker.md) - Steps to install Docker for container management.
- [🔧 OpenIM Linux System Installation](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-openim-linux-system.md) - Guide for installing OpenIM on a Linux system.
## 💻 Development Practices
- [👨‍💻 Code Conventions](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/code-conventions.md) - Coding standards to follow for consistency.
- [📐 Directory Structure](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/directory.md) - Explanation of the repository's directory layout.
- [🔀 Git Workflow](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/git-workflow.md) - The workflow for using Git in this project (note the file extension error).
- [💾 GitHub Workflow](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/github-workflow.md) - Workflow guidelines for GitHub.
## 🧪 Testing and Deployment
- [⚙️ CI/CD Actions](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/cicd-actions.md) - Continuous integration and deployment configurations.
- [🚀 Offline Deployment](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/offline-deployment.md) - How to deploy the application offline.
## 🔧 Utilities and Tools
- [📦 Protoc Tools](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/protoc-tools.md) - Protobuf compiler-related utilities.
- [🔨 Utility Go](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-go.md) - Go utilities and helper functions.
- [🛠 Makefile Utilities](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-makefile.md) - Makefile scripts for automation.
- [📜 Script Utilities](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-scripts.md) - Utility scripts for development.
## 📋 Standards and Conventions
- [🚦 Commit Guidelines](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/commit.md) - Standards for writing commit messages.
- [✅ Testing Guide](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/test.md) - Guidelines and conventions for writing tests.
- [📈 Versioning](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/version.md) - Version management for the project.
## 🖼 Additional Resources
- [🌐 API Reference](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/api.md) - Detailed API documentation.
- [📚 Go Code Standards](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/go-code.md) - Go programming language standards.
- [🖼 Image Guidelines](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/images.md) - Guidelines for image assets.
## 🐛 Troubleshooting
- [🔍 Error Code Reference](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/error-code.md) - List of error codes and their meanings.
- [🐚 Bash Logging](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/bash-log.md) - Logging standards for bash scripts.
- [📈 Logging Conventions](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/logging.md) - Conventions for application logging.
- [🛠 Local Actions Guide](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/local-actions.md) - How to perform local actions for troubleshooting.

5
docs/contrib/api.md Normal file
View File

@@ -0,0 +1,5 @@
## Interface Standards
Our project, OpenIM, adheres to the [OpenAPI 3.0](https://spec.openapis.org/oas/latest.html) interface standards.
> Chinese translation: [OpenAPI Specification Chinese Translation](https://fishead.gitbook.io/openapi-specification-zhcn-translation/3.0.0.zhcn)

49
docs/contrib/bash-log.md Normal file
View File

@@ -0,0 +1,49 @@
## OpenIM Logging System: Design and Usage
**PATH:** `scripts/lib/logging.sh`
### Introduction
OpenIM, an intricate project, requires a robust logging mechanism to diagnose issues, maintain system health, and provide insights. A custom-built logging system embedded within OpenIM ensures consistent and structured logs. Let's delve into the design of this logging system and understand its various functions and their usage scenarios.
### Design Overview
1. **Initialization**: The system begins by determining the verbosity level through the `OPENIM_VERBOSE` variable. If it's not set, a default value of 5 is assigned. This verbosity level dictates the depth of the log details.
2. **Log File Setup**: Logs are stored in the directory specified by `OPENIM_OUTPUT`. If this variable isn't explicitly set, it defaults to the `_output` directory relative to the script location. Each log file is named based on the date to facilitate easy identification.
3. **Logging Function**: The `echo_log()` function plays a pivotal role by writing messages to both the console (stdout) and the log file.
4. **Logging to a file**: The `echo_log()` function writes to the log file by appending the message to the file. It also adds a timestamp to the message. path: `_output/logs/*`, Enable logging by default. Set to false to disable. If you wish to turn off output to log files set `export ENABLE_LOGGING=flase`.
### Key Functions & Their Usages
1. **Error Handling**:
- `openim::log::errexit()`: Activated when a command exits with an error. It prints a call tree showing the sequence of functions leading to the error and then calls `openim::log::error_exit()` with relevant information.
- `openim::log::install_errexit()`: Sets up the trap for catching errors and ensures that the error handler (`errexit`) gets propagated to various script constructs like functions, expansions, and subshells.
2. **Logging Levels**:
- `openim::log::error()`: Logs error messages with a timestamp. The log message starts with '!!!' to indicate its severity.
- `openim::log::info()`: Provides informational messages. The display of these messages is governed by the verbosity level (`OPENIM_VERBOSE`).
- `openim::log::progress()`: Designed for logging progress messages or creating progress bars.
- `openim::log::status()`: Logs status messages with a timestamp, prefixing each entry with '+++' for easy identification.
- `openim::log::success()`: Highlights successful operations with a bright green prefix. It's ideal for visually signifying operations that completed successfully.
3. **Exit and Stack Trace**:
- `openim::log::error_exit()`: Logs an error message, dumps the call stack, and exits the script with a specified exit code.
- `openim::log::stack()`: Prints out a stack trace, showing the call hierarchy leading to the point where this function was invoked.
4. **Usage Information**:
- `openim::log::usage() & openim::log::usage_from_stdin()`: Both functions provide a mechanism to display usage instructions. The former accepts arguments directly, while the latter reads them from stdin.
5. **Test Function**:
- `openim::log::test_log()`: This function is a test suite to verify that all logging functions are operating as expected.
### Usage Scenario
Imagine a situation where an OpenIM operation fails, and you need to ascertain the cause. With the logging system in place, you can:
- Check the log file for the specific day to find error messages with the '!!!' prefix.
- View the call tree and stack trace to trace back the sequence of operations leading to the failure.
- Use the verbosity level to filter out unnecessary details and focus on the crux of the issue.
This systematic and structured approach greatly simplifies the debugging process, making system maintenance more efficient.
### Conclusion
OpenIM's logging system is a testament to the importance of structured and detailed logging in complex projects. By using this logging mechanism, developers and system administrators can streamline troubleshooting and ensure the seamless operation of the OpenIM project.

View File

@@ -0,0 +1,129 @@
# Continuous Integration and Automation
Every change on the OpenIM repository, either made through a pull request or direct push, triggers the continuous integration pipelines defined within the same repository. Needless to say, all the OpenIM contributions can be merged until all the checks pass (AKA having green builds).
- [Continuous Integration and Automation](#continuous-integration-and-automation)
- [CI Platforms](#ci-platforms)
- [GitHub Actions](#github-actions)
- [Running locally](#running-locally)
## CI Platforms
Currently, there are two different platforms involved in running the CI processes:
- GitHub actions
- Drone pipelines on CNCF infrastructure
### GitHub Actions
All the existing GitHub Actions are defined as YAML files under the `.github/workflows` directory. These can be grouped into:
- **PR Checks**. These actions run all the required validations upon PR creation and update. Covering the DCO compliance check, `x86_64` test batteries (unit, integration, smoke), and code coverage.
- **Repository automation**. Currently, it only covers issues and epic grooming.
Everything runs on GitHub's provided runners; thus, the tests are limited to run in `x86_64` architectures.
## Running locally
A contributor should verify their changes locally to speed up the pull request process. Fortunately, all the CI steps can be on local environments, except for the publishing ones, through either of the following methods:
**User Makefile:**
```bash
root@PS2023EVRHNCXG:~/workspaces/openim/Open-IM-Server# make help 😊
Usage: make <TARGETS> <OPTIONS> ...
Targets:
all Run tidy, gen, add-copyright, format, lint, cover, build 🚀
build Build binaries by default 🛠️
multiarch Build binaries for multiple platforms. See option PLATFORMS. 🌍
tidy tidy go.mod ✨
vendor vendor go.mod 📦
style code style -> fmt,vet,lint 💅
fmt Run go fmt against code. ✨
vet Run go vet against code. ✅
lint Check syntax and styling of go sources. ✔️
format Gofmt (reformat) package sources (exclude vendor dir if existed). 🔄
test Run unit test. 🧪
cover Run unit test and get test coverage. 📊
updates Check for updates to go.mod dependencies 🆕
imports task to automatically handle import packages in Go files using goimports tool 📥
clean Remove all files that are created by building. 🗑️
image Build docker images for host arch. 🐳
image.multiarch Build docker images for multiple platforms. See option PLATFORMS. 🌍🐳
push Build docker images for host arch and push images to registry. 📤🐳
push.multiarch Build docker images for multiple platforms and push images to registry. 🌍📤🐳
tools Install dependent tools. 🧰
gen Generate all necessary files. 🧩
swagger Generate swagger document. 📖
serve-swagger Serve swagger spec and docs. 🚀📚
verify-copyright Verify the license headers for all files. ✅
add-copyright Add copyright ensure source code files have license headers. 📄
release release the project 🎉
help Show this help info.
help-all Show all help details info. ℹ️📚
Options:
DEBUG Whether or not to generate debug symbols. Default is 0. ❓
BINS Binaries to build. Default is all binaries under cmd. 🛠️
This option is available when using: make {build}(.multiarch) 🧰
Example: make build BINS="openim-api openim_cms_api".
PLATFORMS Platform to build for. Default is linux_arm64 and linux_amd64. 🌍
This option is available when using: make {build}.multiarch 🌍
Example: make multiarch PLATFORMS="linux_s390x linux_mips64
linux_mips64le darwin_amd64 windows_amd64 linux_amd64 linux_arm64".
V Set to 1 enable verbose build. Default is 0. 📝
```
How to Use Makefile to Help Contributors Build Projects Quickly 😊
The `make help` command is a handy tool that provides useful information on how to utilize the Makefile effectively. By running this command, contributors will gain insights into various targets and options available for building projects swiftly.
Here's a breakdown of the targets and options provided by the Makefile:
**Targets 😃**
1. `all`: This target runs multiple tasks like `tidy`, `gen`, `add-copyright`, `format`, `lint`, `cover`, and `build`. It ensures comprehensive project building.
2. `build`: The primary target that compiles binaries by default. It is particularly useful for creating the necessary executable files.
3. `multiarch`: A target that builds binaries for multiple platforms. Contributors can specify the desired platforms using the `PLATFORMS` option.
4. `tidy`: This target cleans up the `go.mod` file, ensuring its consistency.
5. `vendor`: A target that updates the project dependencies based on the `go.mod` file.
6. `style`: Checks the code style using tools like `fmt`, `vet`, and `lint`. It ensures a consistent coding style throughout the project.
7. `fmt`: Formats the code using the `go fmt` command, ensuring proper indentation and formatting.
8. `vet`: Runs the `go vet` command to identify common errors in the code.
9. `lint`: Validates the syntax and styling of Go source files using a linter.
10. `format`: Reformats the package sources using `gofmt`. It excludes the vendor directory if it exists.
11. `test`: Executes unit tests to ensure the functionality and stability of the code.
12. `cover`: Performs unit tests and calculates the test coverage of the code.
13. `updates`: Checks for updates to the project's dependencies specified in the `go.mod` file.
14. `imports`: Automatically handles import packages in Go files using the `goimports` tool.
15. `clean`: Removes all files generated during the build process, effectively cleaning up the project directory.
16. `image`: Builds Docker images for the host architecture.
17. `image.multiarch`: Similar to the `image` target, but it builds Docker images for multiple platforms. Contributors can specify the desired platforms using the `PLATFORMS` option.
18. `push`: Builds Docker images for the host architecture and pushes them to a registry.
19. `push.multiarch`: Builds Docker images for multiple platforms and pushes them to a registry. Contributors can specify the desired platforms using the `PLATFORMS` option.
20. `tools`: Installs the necessary tools or dependencies required by the project.
21. `gen`: Generates all the required files automatically.
22. `swagger`: Generates the swagger document for the project.
23. `serve-swagger`: Serves the swagger specification and documentation.
24. `verify-copyright`: Verifies the license headers for all project files.
25. `add-copyright`: Adds copyright headers to the source code files.
26. `release`: Releases the project, presumably for distribution.
27. `help`: Displays information about available targets and options.
28. `help-all`: Shows detailed information about all available targets and options.
**Options 😄**
1. `DEBUG`: A boolean option that determines whether or not to generate debug symbols. The default value is 0 (false).
2. `BINS`: Specifies the binaries to build. By default, it builds all binaries under the `cmd` directory. Contributors can provide a list of specific binaries using this option.
3. `PLATFORMS`: Specifies the platforms to build for. The default platforms are `linux_arm64` and `linux_amd64`. Contributors can specify multiple platforms by providing a space-separated list of platform names.
4. `V`: A boolean option that enables verbose build output when set to 1 (true). The default value is 0 (false).
With these targets and options in place, contributors can efficiently build projects using the Makefile. Happy coding! 🚀😊

View File

@@ -0,0 +1,88 @@
# Code conventions
- [Code conventions](#code-conventions)
- [POSIX shell](#posix-shell)
- [Go](#go)
- [OpenIM Naming Conventions Guide](#openim-naming-conventions-guide)
- [1. General File Naming](#1-general-file-naming)
- [2. Special File Types](#2-special-file-types)
- [a. Script and Markdown Files](#a-script-and-markdown-files)
- [b. Uppercase Markdown Documentation](#b-uppercase-markdown-documentation)
- [3. Directory Naming](#3-directory-naming)
- [4. Configuration Files](#4-configuration-files)
- [Best Practices](#best-practices)
- [Directory and File Conventions](#directory-and-file-conventions)
- [Testing conventions](#testing-conventions)
## POSIX shell
- [Style guide](https://google.github.io/styleguide/shell.xml)
## Go
- [Go Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments)
- [Effective Go](https://golang.org/doc/effective_go.html)
- Know and avoid [Go landmines](https://gist.github.com/lavalamp/4bd23295a9f32706a48f)
- Comment your code.
- [Go's commenting conventions](http://blog.golang.org/godoc-documenting-go-code)
- If reviewers ask questions about why the code is the way it is, that's a sign that comments might be helpful.
- Command-line flags should use dashes, not underscores
- Naming
- Please consider package name when selecting an interface name, and avoid redundancy. For example, `storage.Interface` is better than `storage.StorageInterface`.
- Do not use uppercase characters, underscores, or dashes in package names.
- Please consider parent directory name when choosing a package name. For example, `pkg/controllers/autoscaler/foo.go` should say `package autoscaler` not `package autoscalercontroller`.
- Unless there's a good reason, the `package foo` line should match the name of the directory in which the `.go` file exists.
- Importers can use a different name if they need to disambiguate.Ⓜ️
## OpenIM Naming Conventions Guide
Welcome to the OpenIM Naming Conventions Guide. This document outlines the best practices and standardized naming conventions that our project follows to maintain clarity, consistency, and alignment with industry standards, specifically taking cues from the Google Naming Conventions.
### 1. General File Naming
Files within the OpenIM project should adhere to the following rules:
+ Both hyphens (`-`) and underscores (`_`) are acceptable in file names.
+ Underscores (`_`) are preferred for general files to enhance readability and compatibility.
+ For example: `data_processor.py`, `user_profile_generator.go`
### 2. Special File Types
#### a. Script and Markdown Files
+ Bash scripts and Markdown files should use hyphens (`-`) to facilitate better searchability and compatibility in web browsers.
+ For example: `deploy-script.sh`, `project-overview.md`
#### b. Uppercase Markdown Documentation
+ Markdown files with uppercase names, such as `README`, may include underscores (`_`) to separate words if necessary.
+ For example: `README_SETUP.md`, `CONTRIBUTING_GUIDELINES.md`
### 3. Directory Naming
+ Directories must use hyphens (`-`) exclusively to maintain a clean and organized file structure.
+ For example: `image-assets`, `user-data`
### 4. Configuration Files
+ Configuration files, including but not limited to `.yaml` files, should use hyphens (`-`).
+ For example: `app-config.yaml`, `logging-config.yaml`
### Best Practices
+ Keep names concise but descriptive enough to convey the file's purpose or contents at a glance.
+ Avoid using spaces in names; use hyphens or underscores instead to improve compatibility across different operating systems and environments.
+ Stick to lowercase naming where possible for consistency and to prevent issues with case-sensitive systems.
+ Include version numbers or dates in file names if the file is subject to updates, following the format: `project-plan-v1.2.md` or `backup-2023-03-15.sql`.
## Directory and File Conventions
- Avoid generic utility packages. Instead of naming a package "util", choose a name that clearly describes its purpose. For instance, functions related to waiting operations are contained within the `wait` package, which includes methods like `Poll`, fully named as `wait.Poll`.
- All filenames, script files, configuration files, and directories should be in lowercase and use dashes (`-`) as separators.
- For Go language files, filenames should be in lowercase and use underscores (`_`).
- Package names should match their directory names to ensure consistency. For example, within the `openim-api` directory, the Go file should be named `openim-api.go`, following the convention of using dashes for directory names and aligning package names with directory names.
## Testing conventions
Please refer to [TESTING.md](https://github.com/openimsdk/open-im-server-deploy/tree/main/test/readme) document.

9
docs/contrib/commit.md Normal file
View File

@@ -0,0 +1,9 @@
## Commit Standards
Our project, OpenIM, follows the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0) standards.
> Chinese translation: [Conventional Commits: A Specification Making Commit Logs More Human and Machine-friendly](https://tool.lu/en_US/article/2ac/preview)
In addition to adhering to these standards, we encourage all contributors to the OpenIM project to ensure that their commit messages are clear and descriptive. This helps in maintaining a clean and meaningful project history. Each commit message should succinctly describe the changes made and, where necessary, the reasoning behind those changes.
To facilitate a streamlined process, we also recommend using appropriate commit type based on Conventional Commits guidelines such as `fix:` for bug fixes, `feat:` for new features, and so forth. Understanding and using these conventions helps in generating automatic release notes, making versioning easier, and improving overall readability of commit history.

View File

@@ -0,0 +1,72 @@
# Development Guide
Since OpenIM is written in Go, it is fair to assume that the Go tools are all one needs to contribute to this project. Unfortunately, there is a point where this no longer holds true when required to test or build local changes. This document elaborates on the required tooling for OpenIM development.
- [Development Guide](#development-guide)
- [Non-Linux environment prerequisites](#non-linux-environment-prerequisites)
- [Windows Setup](#windows-setup)
- [macOS Setup](#macos-setup)
- [Installing Required Software](#installing-required-software)
- [Go](#go)
- [Docker](#docker)
- [Vagrant](#vagrant)
- [Dependency management](#dependency-management)
## Non-Linux environment prerequisites
All the test and build scripts within this repository were created to be run on GNU Linux development environments. Due to this, it is suggested to use the virtual machine defined on this repository's [Vagrantfile](https://developer.hashicorp.com/vagrant/docs/vagrantfile) to use them.
Either way, if one still wants to build and test OpenIM on non-Linux environments, specific setups are to be followed.
### Windows Setup
To build OpenIM on Windows is only possible for versions that support Windows Subsystem for Linux (WSL). If the development environment in question has Windows 10, Version 2004, Build 19041 or higher, [follow these instructions to install WSL2](https://docs.microsoft.com/en-us/windows/wsl/install-win10); otherwise, use a Linux Virtual machine instead.
### macOS Setup
The shell scripts in charge of the build and test processes rely on GNU utils (i.e. `sed`), [which slightly differ on macOS](https://unix.stackexchange.com/a/79357), meaning that one must make some adjustments before using them.
First, install the GNU utils:
```sh
brew install coreutils findutils gawk gnu-sed gnu-tar grep make
```
Then update the shell init script (i.e. `.bashrc`) to prepend the GNU Utils to the `$PATH` variable
```sh
GNUBINS="$(find /usr/local/opt -type d -follow -name gnubin -print)"
for bindir in ${GNUBINS[@]}; do
PATH=$bindir:$PATH
done
export PATH
```
## Installing Required Software
### Go
It is well known that OpenIM is written in [Go](http://golang.org). Please follow the [Go Getting Started guide](https://golang.org/doc/install) to install and set up the Go tools used to compile and run the test batteries.
| OpenIM | requires Go |
|----------------|-------------|
| 2.24 - 3.00 | 1.15 + |
| 3.30 + | 1.18 + |
### Docker
OpenIM build and test processes development require Docker to run certain steps. [Follow the Docker website instructions to install Docker](https://docs.docker.com/get-docker/) in the development environment.
### Vagrant
As described in the [Testing documentation](https://github.com/openimsdk/open-im-server-deploy/tree/main/test/readme), all the smoke tests are run in virtual machines managed by Vagrant. To install Vagrant in the development environment, [follow the instructions from the Hashicorp website](https://www.vagrantup.com/downloads), alongside any of the following hypervisors:
- [VirtualBox](https://www.virtualbox.org/)
- [libvirt](https://libvirt.org/) and the [vagrant-libvirt plugin](https://github.com/vagrant-libvirt/vagrant-libvirt#installation)
## Dependency management
OpenIM uses [go modules](https://github.com/golang/go/wiki/Modules) to manage dependencies.

View File

@@ -0,0 +1,3 @@
## Catalog Service Interface Specification
+ [https://github.com/kubecub/go-project-layout](https://github.com/kubecub/go-project-layout)

537
docs/contrib/environment.md Normal file
View File

@@ -0,0 +1,537 @@
# OpenIM ENVIRONMENT CONFIGURATION
<!-- vscode-markdown-toc -->
* 1. [OpenIM Deployment Guide](#OpenIMDeploymentGuide)
* 1.1. [Deployment Strategies](#DeploymentStrategies)
* 1.2. [Source Code Deployment](#SourceCodeDeployment)
* 1.3. [Docker Compose Deployment](#DockerComposeDeployment)
* 1.4. [Environment Variable Configuration](#EnvironmentVariableConfiguration)
* 1.4.1. [Recommended using environment variables](#Recommendedusingenvironmentvariables)
* 1.4.2. [Additional Configuration](#AdditionalConfiguration)
* 1.4.3. [Security Considerations](#SecurityConsiderations)
* 1.4.4. [Data Management](#DataManagement)
* 1.4.5. [Monitoring and Logging](#MonitoringandLogging)
* 1.4.6. [Troubleshooting](#Troubleshooting)
* 1.4.7. [Conclusion](#Conclusion)
* 1.4.8. [Additional Resources](#AdditionalResources)
* 2. [Further Configuration](#FurtherConfiguration)
* 2.1. [Image Registry Configuration](#ImageRegistryConfiguration)
* 2.2. [OpenIM Docker Network Configuration](#OpenIMDockerNetworkConfiguration)
* 2.3. [OpenIM Configuration](#OpenIMConfiguration)
* 2.4. [OpenIM Chat Configuration](#OpenIMChatConfiguration)
* 2.5. [Zookeeper Configuration](#ZookeeperConfiguration)
* 2.6. [MySQL Configuration](#MySQLConfiguration)
* 2.7. [MongoDB Configuration](#MongoDBConfiguration)
* 2.8. [Tencent Cloud COS Configuration](#TencentCloudCOSConfiguration)
* 2.9. [Alibaba Cloud OSS Configuration](#AlibabaCloudOSSConfiguration)
* 2.10. [Redis Configuration](#RedisConfiguration)
* 2.11. [Kafka Configuration](#KafkaConfiguration)
* 2.12. [OpenIM Web Configuration](#OpenIMWebConfiguration)
* 2.13. [RPC Configuration](#RPCConfiguration)
* 2.14. [Prometheus Configuration](#PrometheusConfiguration)
* 2.15. [Grafana Configuration](#GrafanaConfiguration)
* 2.16. [RPC Port Configuration Variables](#RPCPortConfigurationVariables)
* 2.17. [RPC Register Name Configuration](#RPCRegisterNameConfiguration)
* 2.18. [Log Configuration](#LogConfiguration)
* 2.19. [Additional Configuration Variables](#AdditionalConfigurationVariables)
* 2.20. [Prometheus Configuration](#PrometheusConfiguration-1)
* 2.20.1. [General Configuration](#GeneralConfiguration)
* 2.20.2. [Service-Specific Prometheus Ports](#Service-SpecificPrometheusPorts)
* 2.21. [Qiniu Cloud Kodo Configuration](#QiniuCloudKODOConfiguration)
## 0. <a name='TableofContents'></a>OpenIM Config File
Ensuring that OpenIM operates smoothly requires clear direction on the configuration file's location. Here's a detailed step-by-step guide on how to provide this essential path to OpenIM:
1. **Using the Command-line Argument**:
+ **For Configuration Path**: When initializing OpenIM, you can specify the path to the configuration file directly using the `-c` or `--config_folder_path` option.
```bash
_output/bin/platforms/linux/amd64/openim-api --config_folder_path="/your/config/folder/path"
```
+ **For Port Specification**: Similarly, if you wish to designate a particular port, utilize the `-p` option followed by the desired port number.
```bash
_output/bin/platforms/linux/amd64/openim-api -p 1234
```
Note: If the port is not specified here, OpenIM will fetch it from the configuration file. Setting the port via environment variables isn't supported. We recommend consolidating settings in the configuration file for a more consistent and streamlined setup.
2. **Leveraging the Environment Variable**:
You have the flexibility to determine OpenIM's configuration path by setting an `OPENIMCONFIG` environment variable. This method provides a seamless way to instruct OpenIM without command-line parameters every time.
```bash
export OPENIMCONFIG="/path/to/your/config"
```
3. **Relying on the Default Path**:
In scenarios where neither command-line arguments nor environment variables are provided, OpenIM will intuitively revert to the `config/` directory to locate its configuration.
## 1. <a name='OpenIMDeploymentGuide'></a>OpenIM Deployment Guide
Welcome to the OpenIM Deployment Guide! OpenIM offers a versatile and robust instant messaging server, and deploying it can be achieved through various methods. This guide will walk you through the primary deployment strategies, ensuring you can set up OpenIM in a way that best suits your needs.
### 1.1. <a name='DeploymentStrategies'></a>Deployment Strategies
OpenIM provides multiple deployment methods, each tailored to different use cases and technical preferences:
1. **[Source Code Deployment Guide](https://doc.rentsoft.cn/guides/gettingStarted/imSourceCodeDeployment)**
2. **[Docker Deployment Guide](https://doc.rentsoft.cn/guides/gettingStarted/dockerCompose)**
3. **[Kubernetes Deployment Guide](https://github.com/openimsdk/open-im-server-deploy/tree/main/deployments)**
While the first two methods will be our main focus, it's worth noting that the third method, Kubernetes deployment, is also viable and can be rendered via the `environment.sh` script variables.
### 1.2. <a name='SourceCodeDeployment'></a>Source Code Deployment
In the source code deployment method, the configuration generation process involves executing `make init`, which fundamentally runs the script `./scripts/init-config.sh`. This script utilizes variables defined in the [`environment.sh`](https://github.com/openimsdk/open-im-server-deploy/blob/main/scripts/install/environment.sh) script to render the [`config.yaml`](https://github.com/openimsdk/open-im-server-deploy/blob/main/deployments/templates/config.yaml) template file, subsequently generating the [`config.yaml`](https://github.com/openimsdk/open-im-server-deploy/blob/main/config/config.yaml) configuration file.
### 1.3. <a name='DockerComposeDeployment'></a>Docker Compose Deployment
Docker deployment offers a slightly more intricate template. Within the [openim-server](https://github.com/openimsdk/openim-docker/tree/main/openim-server) directory, multiple subdirectories correspond to various versions, each aligning with `openim-chat` as illustrated below:
| openim-server | openim-chat |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| [main](https://github.com/openimsdk/openim-docker/tree/main/openim-server/main) | [main](https://github.com/openimsdk/openim-docker/tree/main/openim-chat/main) |
| [release-v3.2](https://github.com/openimsdk/openim-docker/tree/main/openim-server/release-v3.3) | [release-v3.2](https://github.com/openimsdk/openim-docker/tree/main/openim-chat/release-v1.3) |
| [release-v3.2](https://github.com/openimsdk/openim-docker/tree/main/openim-server/release-v3.2) | [release-v3.2](https://github.com/openimsdk/openim-docker/tree/main/openim-chat/release-v1.2) |
Configuration file modifications can be made by specifying corresponding environment variables, for instance:
```bash
export CHAT_IMAGE_VERSION="main"
export SERVER_IMAGE_VERSION="main"
```
These variables are stored within the [`environment.sh`](https://github.com/OpenIMSDK/open-im-server-deploy/blob/main/scripts/install/environment.sh) configuration:
```bash
readonly CHAT_IMAGE_VERSION=${CHAT_IMAGE_VERSION:-'main'}
readonly SERVER_IMAGE_VERSION=${SERVER_IMAGE_VERSION:-'main'}
```
> [!IMPORTANT]
> Can learn to read our mirror version strategy: https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/images.md
Setting a variable, e.g., `export CHAT_IMAGE_VERSION="release-v1.3"`, will prioritize `CHAT_IMAGE_VERSION="release-v1.3"` as the variable value. Ultimately, the chosen image version is determined, and rendering is achieved through `make init` (or `./scripts/init-config.sh`).
> Note: Direct modifications to the `config.yaml` file are also permissible without utilizing `make init`.
### 1.4. <a name='EnvironmentVariableConfiguration'></a>Environment Variable Configuration
For convenience, configuration through modifying environment variables is recommended:
#### 1.4.1. <a name='Recommendedusingenvironmentvariables'></a>Recommended using environment variables
+ PASSWORD
+ **Description**: Password for mongodb, redis, and minio.
+ **Default**: `openIM123`
+ Notes:
+ Minimum password length: 8 characters.
+ Special characters are not allowed.
```bash
export PASSWORD="openIM123"
```
+ OPENIM_USER
+ **Description**: Username for redis, and minio.
+ **Default**: `root`
```bash
export OPENIM_USER="root"
```
> mongo is `openIM`, use `export MONGO_OPENIM_USERNAME="openIM"` to modify
+ OPENIM_IP
+ **Description**: API address.
+ **Note**: If the server has an external IP, it will be automatically obtained. For internal networks, set this variable to the IP serving internally.
```bash
export OPENIM_IP="ip"
```
+ DATA_DIR
+ **Description**: Data mount directory for components.
+ **Default**: `/data/openim`
```bash
export DATA_DIR="/data/openim"
```
#### 1.4.2. <a name='AdditionalConfiguration'></a>Additional Configuration
##### MinIO Access and Secret Key
To secure your MinIO server, you should set up an access key and secret key. These credentials are used to authenticate requests to your MinIO server.
```bash
export MINIO_ACCESS_KEY="YourAccessKey"
export MINIO_SECRET_KEY="YourSecretKey"
```
##### MinIO Browser
MinIO comes with an embedded web-based object browser. You can control the availability of the MinIO browser by setting the `MINIO_BROWSER` environment variable.
```bash
export MINIO_BROWSER="on"
```
#### 1.4.3. <a name='SecurityConsiderations'></a>Security Considerations
##### TLS/SSL Configuration
For secure communication, it's recommended to enable TLS/SSL for your MinIO server. You can do this by providing the path to the SSL certificate and key files.
```bash
export MINIO_CERTS_DIR="/path/to/certs/directory"
```
#### 1.4.4. <a name='DataManagement'></a>Data Management
##### Data Retention Policy
You may want to set up a data retention policy to automatically delete objects after a specified period.
```bash
export MINIO_RETENTION_DAYS="30"
```
#### 1.4.5. <a name='MonitoringandLogging'></a>Monitoring and Logging
##### [Audit Logging](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/environment.md#audit-logging)
Enable audit logging to keep track of access and changes to your data.
```bash
export MINIO_AUDIT="on"
```
#### 1.4.6. <a name='Troubleshooting'></a>Troubleshooting
##### Debug Mode
In case of issues, you may enable debug mode to get more detailed logs to assist in troubleshooting.
```bash
export MINIO_DEBUG="on"
```
#### 1.4.7. <a name='Conclusion'></a>Conclusion
With the environment variables configured as per your requirements, your MinIO server should be ready to securely store and manage your object data. Ensure to verify the setup and monitor the logs for any unusual activities or errors. Regularly update the MinIO server and review your configuration to adapt to any changes or improvements in the MinIO system.
#### 1.4.8. <a name='AdditionalResources'></a>Additional Resources
+ [MinIO Client Quickstart Guide](https://docs.min.io/docs/minio-client-quickstart-guide)
+ [MinIO Admin Complete Guide](https://docs.min.io/docs/minio-admin-complete-guide)
+ [MinIO Docker Quickstart Guide](https://docs.min.io/docs/minio-docker-quickstart-guide)
Feel free to explore the MinIO documentation for more advanced configurations and usage scenarios.
## 2. <a name='FurtherConfiguration'></a>Further Configuration
### 2.1. <a name='ImageRegistryConfiguration'></a>Image Registry Configuration
**Description**: The image registry configuration allows users to select an image address for use. The default is set to use GITHUB images, but users can opt for Docker Hub or Ali Cloud, especially beneficial for Chinese users due to its local proximity.
| Parameter | Default Value | Description |
| ---------------- | --------------------- | ------------------------------------------------------------ |
| `IMAGE_REGISTRY` | `"ghcr.io/openimsdk"` | The registry from which Docker images will be pulled. Other options include `"openim"` and `"registry.cn-hangzhou.aliyuncs.com/openimsdk"`. |
### 2.2. <a name='OpenIMDockerNetworkConfiguration'></a>OpenIM Docker Network Configuration
**Description**: This section configures the Docker network subnet and generates IP addresses for various services within the defined subnet.
| Parameter | Example Value | Description |
| --------------------------- | ----------------- | ------------------------------------------------------------ |
| `DOCKER_BRIDGE_SUBNET` | `'172.28.0.0/16'` | The subnet for the Docker network. |
| `DOCKER_BRIDGE_GATEWAY` | Generated IP | The gateway IP address within the Docker subnet. |
| `[SERVICE]_NETWORK_ADDRESS` | Generated IP | The network IP address for a specific service (e.g., MYSQL, MONGO, REDIS, etc.) within the Docker subnet. |
### 2.3. <a name='OpenIMConfiguration'></a>OpenIM Configuration
**Description**: OpenIM configuration involves setting up directories for data, installation, configuration, and logs. It also involves configuring the OpenIM server address and ports for WebSocket and API.
| Parameter | Default Value | Description |
| ----------------------- | ------------------------ | ----------------------------------------- |
| `OPENIM_DATA_DIR` | `"/data/openim"` | Directory for OpenIM data. |
| `OPENIM_INSTALL_DIR` | `"/opt/openim"` | Directory where OpenIM is installed. |
| `OPENIM_CONFIG_DIR` | `"/etc/openim"` | Directory for OpenIM configuration files. |
| `OPENIM_LOG_DIR` | `"/var/log/openim"` | Directory for OpenIM logs. |
| `OPENIM_SERVER_ADDRESS` | Docker Bridge Gateway IP | OpenIM server address. |
| `OPENIM_WS_PORT` | `'10001'` | Port for OpenIM WebSocket. |
| `API_OPENIM_PORT` | `'10002'` | Port for OpenIM API. |
### 2.4. <a name='OpenIMChatConfiguration'></a>OpenIM Chat Configuration
**Description**: Configuration for OpenIM chat, including data directory, server address, and ports for API and chat functionalities.
| Parameter | Example Value | Description |
| ----------------------- | -------------------------- | ------------------------------- |
| `OPENIM_CHAT_DATA_DIR` | `"./openim-chat/[BRANCH]"` | Directory for OpenIM chat data. |
| `OPENIM_CHAT_ADDRESS` | Docker Bridge Gateway IP | OpenIM chat service address. |
| `OPENIM_CHAT_API_PORT` | `"10008"` | Port for OpenIM chat API. |
| `OPENIM_ADMIN_API_PORT` | `"10009"` | Port for OpenIM Admin API. |
| `OPENIM_ADMIN_PORT` | `"30200"` | Port for OpenIM chat Admin. |
| `OPENIM_CHAT_PORT` | `"30300"` | Port for OpenIM chat. |
### 2.5. <a name='ZookeeperConfiguration'></a>Zookeeper Configuration
**Description**: Configuration for Zookeeper, including schema, port, address, and credentials.
| Parameter | Example Value | Description |
| -------------------- | ------------------------ | ----------------------- |
| `ZOOKEEPER_SCHEMA` | `"openim"` | Schema for Zookeeper. |
| `ZOOKEEPER_PORT` | `"12181"` | Port for Zookeeper. |
| `ZOOKEEPER_ADDRESS` | Docker Bridge Gateway IP | Address for Zookeeper. |
| `ZOOKEEPER_USERNAME` | `""` | Username for Zookeeper. |
| `ZOOKEEPER_PASSWORD` | `""` | Password for Zookeeper. |
### 2.7. <a name='MongoDBConfiguration'></a>MongoDB Configuration
This section involves setting up MongoDB, including its port, address, and credentials.
| Parameter | Example Value | Description |
| -------------- | -------------- | ----------------------- |
| MONGO_PORT | "27017" | Port used by MongoDB. |
| MONGO_ADDRESS | [Generated IP] | IP address for MongoDB. |
| MONGO_USERNAME | [User Defined] | Admin Username for MongoDB. |
| MONGO_PASSWORD | [User Defined] | Admin Password for MongoDB. |
| MONGO_OPENIM_USERNAME | [User Defined] | OpenIM Username for MongoDB. |
| MONGO_OPENIM_PASSWORD | [User Defined] | OpenIM Password for MongoDB. |
### 2.8. <a name='TencentCloudCOSConfiguration'></a>Tencent Cloud COS Configuration
This section involves setting up Tencent Cloud COS, including its bucket URL and credentials.
| Parameter | Example Value | Description |
| ----------------- | ------------------------------------------------------------ | ------------------------------------ |
| COS_BUCKET_URL | "[https://temp-1252357374.cos.ap-chengdu.myqcloud.com](https://temp-1252357374.cos.ap-chengdu.myqcloud.com/)" | Tencent Cloud COS bucket URL. |
| COS_SECRET_ID | [User Defined] | Secret ID for Tencent Cloud COS. |
| COS_SECRET_KEY | [User Defined] | Secret key for Tencent Cloud COS. |
| COS_SESSION_TOKEN | [User Defined] | Session token for Tencent Cloud COS. |
| COS_PUBLIC_READ | "false" | Public read access. |
### 2.9. <a name='AlibabaCloudOSSConfiguration'></a>Alibaba Cloud OSS Configuration
This section involves setting up Alibaba Cloud OSS, including its endpoint, bucket name, and credentials.
| Parameter | Example Value | Description |
| --------------------- | ------------------------------------------------------------ | ---------------------------------------- |
| OSS_ENDPOINT | "[https://oss-cn-chengdu.aliyuncs.com](https://oss-cn-chengdu.aliyuncs.com/)" | Endpoint URL for Alibaba Cloud OSS. |
| OSS_BUCKET | "demo-9999999" | Bucket name for Alibaba Cloud OSS. |
| OSS_BUCKET_URL | "[https://demo-9999999.oss-cn-chengdu.aliyuncs.com](https://demo-9999999.oss-cn-chengdu.aliyuncs.com/)" | Bucket URL for Alibaba Cloud OSS. |
| OSS_ACCESS_KEY_ID | [User Defined] | Access key ID for Alibaba Cloud OSS. |
| OSS_ACCESS_KEY_SECRET | [User Defined] | Access key secret for Alibaba Cloud OSS. |
| OSS_SESSION_TOKEN | [User Defined] | Session token for Alibaba Cloud OSS. |
| OSS_PUBLIC_READ | "false" | Public read access. |
### 2.10. <a name='RedisConfiguration'></a>Redis Configuration
This section involves setting up Redis, including its port, address, and credentials.
| Parameter | Example Value | Description |
| -------------- | -------------------------- | --------------------- |
| REDIS_PORT | "16379" | Port used by Redis. |
| REDIS_ADDRESS | "${DOCKER_BRIDGE_GATEWAY}" | IP address for Redis. |
| REDIS_USERNAME | [User Defined] | Username for Redis. |
| REDIS_PASSWORD | "${PASSWORD}" | Password for Redis. |
### 2.11. <a name='KafkaConfiguration'></a>Kafka Configuration
This section involves setting up Kafka, including its port, address, credentials, and topics.
| Parameter | Example Value | Description |
| ---------------------------- | -------------------------- | ----------------------------------- |
| KAFKA_USERNAME | [User Defined] | Username for Kafka. |
| KAFKA_PASSWORD | [User Defined] | Password for Kafka. |
| KAFKA_PORT | "19094" | Port used by Kafka. |
| KAFKA_ADDRESS | "${DOCKER_BRIDGE_GATEWAY}" | IP address for Kafka. |
| KAFKA_LATESTMSG_REDIS_TOPIC | "latestMsgToRedis" | Topic for latest message to Redis. |
| KAFKA_OFFLINEMSG_MONGO_TOPIC | "offlineMsgToMongoMysql" | Topic for offline message to Mongo. |
| KAFKA_MSG_PUSH_TOPIC | "msgToPush" | Topic for message to push. |
| KAFKA_CONSUMERGROUPID_REDIS | "redis" | Consumer group ID to Redis. |
| KAFKA_CONSUMERGROUPID_MONGO | "mongo" | Consumer group ID to Mongo. |
| KAFKA_CONSUMERGROUPID_MYSQL | "mysql" | Consumer group ID to MySQL. |
| KAFKA_CONSUMERGROUPID_PUSH | "push" | Consumer group ID to push. |
Note: Ensure to replace placeholder values (like [User Defined], `${DOCKER_BRIDGE_GATEWAY}`, and `${PASSWORD}`) with actual values before deploying the configuration.
### 2.12. <a name='OpenIMWebConfiguration'></a>OpenIM Web Configuration
This section involves setting up OpenIM Web, including its port, address, and dist path.
| Parameter | Example Value | Description |
| -------------------- | -------------------------- | ------------------------- |
| OPENIM_WEB_PORT | "11001" | Port used by OpenIM Web. |
| OPENIM_WEB_ADDRESS | "${DOCKER_BRIDGE_GATEWAY}" | Address for OpenIM Web. |
| OPENIM_WEB_DIST_PATH | "/app/dist" | Dist path for OpenIM Web. |
### 2.13. <a name='RPCConfiguration'></a>RPC Configuration
Configuration for RPC, including the register and listen IP.
| Parameter | Example Value | Description |
| --------------- | -------------- | -------------------- |
| RPC_REGISTER_IP | [User Defined] | Register IP for RPC. |
| RPC_LISTEN_IP | "0.0.0.0" | Listen IP for RPC. |
### 2.14. <a name='PrometheusConfiguration'></a>Prometheus Configuration
Setting up Prometheus, including its port and address.
| Parameter | Example Value | Description |
| ------------------ | -------------------------- | ------------------------ |
| PROMETHEUS_PORT | "19090" | Port used by Prometheus. |
| PROMETHEUS_ADDRESS | "${DOCKER_BRIDGE_GATEWAY}" | Address for Prometheus. |
### 2.15. <a name='GrafanaConfiguration'></a>Grafana Configuration
Configuration for Grafana, including its port and address.
| Parameter | Example Value | Description |
| --------------- | -------------------------- | --------------------- |
| GRAFANA_PORT | "13000" | Port used by Grafana. |
| GRAFANA_ADDRESS | "${DOCKER_BRIDGE_GATEWAY}" | Address for Grafana. |
### 2.16. <a name='RPCPortConfigurationVariables'></a>RPC Port Configuration Variables
Configuration for various RPC ports. Note: For launching multiple programs, just fill in multiple ports separated by commas. Try not to have spaces.
| Parameter | Example Value | Description |
| --------------------------- | ------------- | ----------------------------------- |
| OPENIM_USER_PORT | '10110' | OpenIM User Service Port. |
| OPENIM_FRIEND_PORT | '10120' | OpenIM Friend Service Port. |
| OPENIM_MESSAGE_PORT | '10130' | OpenIM Message Service Port. |
| OPENIM_MESSAGE_GATEWAY_PORT | '10140' | OpenIM Message Gateway Service Port |
| OPENIM_GROUP_PORT | '10150' | OpenIM Group Service Port. |
| OPENIM_AUTH_PORT | '10160' | OpenIM Authorization Service Port. |
| OPENIM_PUSH_PORT | '10170' | OpenIM Push Service Port. |
| OPENIM_CONVERSATION_PORT | '10180' | OpenIM Conversation Service Port. |
| OPENIM_THIRD_PORT | '10190' | OpenIM Third-Party Service Port. |
### 2.17. <a name='RPCRegisterNameConfiguration'></a>RPC Register Name Configuration
This section involves setting up the RPC Register Names for various OpenIM services.
| Parameter | Example Value | Description |
| --------------------------- | ---------------- | ----------------------------------- |
| OPENIM_USER_NAME | "User" | OpenIM User Service Name |
| OPENIM_FRIEND_NAME | "Friend" | OpenIM Friend Service Name |
| OPENIM_MSG_NAME | "Msg" | OpenIM Message Service Name |
| OPENIM_PUSH_NAME | "Push" | OpenIM Push Service Name |
| OPENIM_MESSAGE_GATEWAY_NAME | "MessageGateway" | OpenIM Message Gateway Service Name |
| OPENIM_GROUP_NAME | "Group" | OpenIM Group Service Name |
| OPENIM_AUTH_NAME | "Auth" | OpenIM Authorization Service Name |
| OPENIM_CONVERSATION_NAME | "Conversation" | OpenIM Conversation Service Name |
| OPENIM_THIRD_NAME | "Third" | OpenIM Third-Party Service Name |
### 2.18. <a name='LogConfiguration'></a>Log Configuration
This section involves configuring the log settings, including storage location, rotation time, and log level.
| Parameter | Example Value | Description |
| ------------------------- | ------------------------ | --------------------------------- |
| LOG_STORAGE_LOCATION | "${OPENIM_ROOT}/_output/logs/" | Location for storing logs |
| LOG_ROTATION_TIME | "24" | Log rotation time (in hours) |
| LOG_REMAIN_ROTATION_COUNT | "2" | Number of log rotations to retain |
| LOG_REMAIN_LOG_LEVEL | "6" | Log level to retain |
| LOG_IS_STDOUT | "false" | Output log to standard output |
| LOG_IS_JSON | "false" | Log in JSON format |
| LOG_WITH_STACK | "false" | Include stack info in logs |
### 2.19. <a name='AdditionalConfigurationVariables'></a>Additional Configuration Variables
This section involves setting up additional configuration variables for Websocket, Push Notifications, and Chat.
| Parameter | Example Value | Description |
|-------------------------|-------------------|----------------------------------|
| WEBSOCKET_MAX_CONN_NUM | "100000" | Maximum Websocket connections |
| WEBSOCKET_MAX_MSG_LEN | "4096" | Maximum Websocket message length |
| WEBSOCKET_TIMEOUT | "10" | Websocket timeout |
| PUSH_ENABLE | "getui" | Push notification enable status |
| GETUI_PUSH_URL | [Generated URL] | GeTui Push Notification URL |
| GETUI_MASTER_SECRET | [User Defined] | GeTui Master Secret |
| GETUI_APP_KEY | [User Defined] | GeTui Application Key |
| GETUI_INTENT | [User Defined] | GeTui Push Intent |
| GETUI_CHANNEL_ID | [User Defined] | GeTui Channel ID |
| GETUI_CHANNEL_NAME | [User Defined] | GeTui Channel Name |
| FCM_SERVICE_ACCOUNT | "x.json" | FCM Service Account |
| JPUSH_APP_KEY | [User Defined] | JPUSH Application Key |
| JPUSH_MASTER_SECRET | [User Defined] | JPUSH Master Secret |
| JPUSH_PUSH_URL | [User Defined] | JPUSH Push Notification URL |
| JPUSH_PUSH_INTENT | [User Defined] | JPUSH Push Intent |
| IM_ADMIN_USERID | "imAdmin" | IM Administrator ID |
| IM_ADMIN_NAME | "imAdmin" | IM Administrator Nickname |
| MULTILOGIN_POLICY | "1" | Multi-login Policy |
| CHAT_PERSISTENCE_MYSQL | "true" | Chat Persistence in MySQL |
| MSG_CACHE_TIMEOUT | "86400" | Message Cache Timeout |
| GROUP_MSG_READ_RECEIPT | "true" | Group Message Read Receipt Enable |
| SINGLE_MSG_READ_RECEIPT | "true" | Single Message Read Receipt Enable |
| RETAIN_CHAT_RECORDS | "365" | Retain Chat Records (in days) |
| CHAT_RECORDS_CLEAR_TIME | [Cron Expression] | Chat Records Clear Time |
| MSG_DESTRUCT_TIME | [Cron Expression] | Message Destruct Time |
| SECRET | "${PASSWORD}" | Secret Key |
| TOKEN_EXPIRE | "90" | Token Expiry Time |
| FRIEND_VERIFY | "false" | Friend Verification Enable |
| IOS_PUSH_SOUND | "xxx" | iOS |
| CALLBACK_ENABLE | "false" | Enable callback |
| CALLBACK_TIMEOUT | "5" | Maximum timeout for callback call |
| CALLBACK_FAILED_CONTINUE| "true" | fails to continue to the next step |
### 2.20. <a name='PrometheusConfiguration-1'></a>Prometheus Configuration
This section involves configuring Prometheus, including enabling/disabling it and setting up ports for various services.
#### 2.20.1. <a name='GeneralConfiguration'></a>General Configuration
| Parameter | Example Value | Description |
| ------------------- | ------------- | ----------------------------- |
| `PROMETHEUS_ENABLE` | "false" | Whether to enable Prometheus. |
#### 2.20.2. <a name='Service-SpecificPrometheusPorts'></a>Service-Specific Prometheus Ports
| Service | Parameter | Default Port Value | Description |
| ------------------------ | ------------------------ | ---------------------------- | -------------------------------------------------- |
| User Service | `USER_PROM_PORT` | '20110' | Prometheus port for the User service. |
| Friend Service | `FRIEND_PROM_PORT` | '20120' | Prometheus port for the Friend service. |
| Message Service | `MESSAGE_PROM_PORT` | '20130' | Prometheus port for the Message service. |
| Message Gateway | `MSG_GATEWAY_PROM_PORT` | '20140' | Prometheus port for the Message Gateway. |
| Group Service | `GROUP_PROM_PORT` | '20150' | Prometheus port for the Group service. |
| Auth Service | `AUTH_PROM_PORT` | '20160' | Prometheus port for the Auth service. |
| Push Service | `PUSH_PROM_PORT` | '20170' | Prometheus port for the Push service. |
| Conversation Service | `CONVERSATION_PROM_PORT` | '20230' | Prometheus port for the Conversation service. |
| RTC Service | `RTC_PROM_PORT` | '21300' | Prometheus port for the RTC service. |
| Third Service | `THIRD_PROM_PORT` | '21301' | Prometheus port for the Third service. |
| Message Transfer Service | `MSG_TRANSFER_PROM_PORT` | '21400, 21401, 21402, 21403' | Prometheus ports for the Message Transfer service. |
### 2.21. <a name='QiniuCloudKODOConfiguration'></a>Qiniu Cloud Kodo Configuration
This section involves setting up Qiniu Cloud Kodo, including its endpoint, bucket name, and credentials.
| Parameter | Example Value | Description |
| --------------------- | ------------------------------------------------------------ | ---------------------------------------- |
| KODO_ENDPOINT | "[http://s3.cn-east-1.qiniucs.com](http://s3.cn-east-1.qiniucs.com)" | Endpoint URL for Qiniu Cloud Kodo. |
| KODO_BUCKET | "demo-9999999" | Bucket name for Qiniu Cloud Kodo. |
| KODO_BUCKET_URL | "[http://your.domain.com](http://your.domain.com)" | Bucket URL for Qiniu Cloud Kodo. |
| KODO_ACCESS_KEY_ID | [User Defined] | Access key ID for Qiniu Cloud Kodo. |
| KODO_ACCESS_KEY_SECRET | [User Defined] | Access key secret for Qiniu Cloud Kodo. |
| KODO_SESSION_TOKEN | [User Defined] | Session token for Qiniu Cloud Kodo. |
| KODO_PUBLIC_READ | "false" | Public read access. |

View File

@@ -0,0 +1,22 @@
## Error Code Standards
Error codes are one of the important means for users to locate and solve problems. When an application encounters an exception, users can quickly locate and resolve the problem based on the error code and the description and solution of the error code in the documentation.
### Error Code Naming Standards
- Follow CamelCase notation;
- Error codes are divided into two levels. For example, `InvalidParameter.BindError`, separated by a `.`. The first-level error code is platform-level, and the second-level error code is resource-level, which can be customized according to the scenario;
- The second-level error code can only use English letters or numbers ([a-zA-Z0-9]), and should use standard English word spelling, standard abbreviations, RFC term abbreviations, etc.;
- The error code should avoid multiple definitions of the same semantics, for example: `InvalidParameter.ErrorBind`, `InvalidParameter.BindError`.
### First-Level Common Error Codes
| Error Code | Error Description | Error Type |
| ---------------- | ------------------------------------------------------------ | ---------- |
| InternalError | Internal error | 1 |
| InvalidParameter | Parameter error (including errors in parameter type, format, value, etc.) | 0 |
| AuthFailure | Authentication / Authorization error | 0 |
| ResourceNotFound | Resource does not exist | 0 |
| FailedOperation | Operation failed | 2 |
> Error Type: 0 represents the client, 1 represents the server, 2 represents both the client / server.

View File

@@ -0,0 +1,102 @@
# Git workflows
This document is an overview of OpenIM git workflow. It includes conventions, tips, and how to maintain good repository hygiene.
- [Git workflows](#git-workflows)
- [Branching model](#branching-model)
- [Branch naming conventions](#branch-naming-conventions)
- [Backport policy](#backport-policy)
- [Git operations](#git-operations)
- [Setting up](#setting-up)
- [Branching out](#branching-out)
- [Keeping local branches in sync](#keeping-local-branches-in-sync)
- [Pushing changes](#pushing-changes)
## Branching model
OpenIM project uses the [GitHub flow](https://docs.github.com/en/get-started/quickstart/github-flow) as its branching model, where most of the changes come from repositories forks instead of branches within the same one.
### Branch naming conventions
Every forked repository works independently, meaning that any contributor can create branches with the name they see fit. However, it is worth noting that OpenIM mirrors [OpenIM version skew policy](https://github.com/openimsdk/open-im-server-deploy/releases) by maintaining release branches for the most recent three minor releases. The only exception is that the main branch mirrors the latest OpenIM release (3.10) instead of using a `release-` prefixed one.
```text
main -------------------------------------------. (OpenIM 3.10)
release-3.0.0 \---------------|---------------. (OpenIM 3.00)
release-2.4.0 \---------------. (OpenIM 2.40)
```
### Backport policy
All new work happens on the main branch, which means that for most cases, one should branch out from there and create the pull request against it. If the change involves adding a feature or patching OpenIM, the maintainers will backport it into the supported release branches.
## Git operations
There are everyday tasks related to git that every contributor needs to perform, and this section elaborates on them.
### Setting up
Creating a OpenIM fork, cloning it, and setting its upstream remote can be summarized on:
1. Visit <https://github.com/openimsdk/open-im-server-deploy>
2. Click the `Fork` button (top right) to establish a cloud-based fork
3. Clone fork to local storage
4. Add to your fork OpenIM remote as upstream
Once cloned, in code it would look this way:
```sh
## Clone fork to local storage
export user="your github profile name"
git clone https://github.com/$user/OpenIM.git
# or: git clone git@github.com:$user/OpenIM.git
## Add OpenIM as upstream to your fork
cd OpenIM
git remote add upstream https://github.com/openimsdk/open-im-server-deploy.git
# or: git remote add upstream git@github.com:openimsdk/open-im-server-deploy.git
## Ensure to never push to upstream directly
git remote set-url --push upstream no_push
## Confirm that your remotes make sense:
git remote -v
```
### Branching out
Every time one wants to work on a new OpenIM feature, we do:
1. Get local main branch up to date
2. Create a new branch from the main one (i.e.: myfeature branch )
In code it would look this way:
```sh
## Get local main up to date
# Assuming the OpenIM clone is the current working directory
git fetch upstream
git checkout main
git rebase upstream/main
## Create a new branch from main
git checkout -b myfeature
```
### Keeping local branches in sync
Either when branching out from main or a release one, keep in mind it is worth checking if any change has been pushed upstream by doing:
```sh
git fetch upstream
git rebase upstream/main
```
It is suggested to `fetch` then `rebase` instead of `pull` since the latter does a merge, which leaves merge commits. For this, one can consider changing the local repository configuration by doing `git config branch.autoSetupRebase always` to change the behavior of `git pull`, or another non-merge option such as `git pull --rebase`.
### Pushing changes
For commit messages and signatures please refer to the [CONTRIBUTING.md](../../CONTRIBUTING.md) document.
Nobody should push directly to upstream, even if one has such contributor access; instead, prefer [Github's pull request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests) mechanism to contribute back into OpenIM. For expectations and guidelines about pull requests, consult the [CONTRIBUTING.md](../../CONTRIBUTING.md) document.

View File

@@ -0,0 +1,176 @@
# Git Cherry-Pick Guide
- Git Cherry-Pick Guide
- [Introduction](#introduction)
- [What is git cherry-pick?](#what-is-git-cherry-pick)
- [Using git cherry-pick](#using-git-cherry-pick)
- [Applying Multiple Commits](#applying-multiple-commits)
- [Configurations](#configurations)
- [Handling Conflicts](#handling-conflicts)
- [Applying Commits from Another Repository](#applying-commits-from-another-repository)
## Introduction
Author: @cubxxw
As OpenIM has progressively embarked on a standardized path, I've had the honor of initiating a significant project, `git cherry-pick`. While some may see it as merely a naming convention in the Go language, it represents more. It's a thoughtful design within the OpenIM project, my very first conscious design, and a first in laying out an extensive collaboration process and copyright management with goals of establishing a top-tier community standard.
## What is git cherry-pick?
In multi-branch repositories, transferring commits from one branch to another is common. You can either merge all changes from one branch (using `git merge`) or selectively apply certain commits. This selective application of commits is where `git cherry-pick` comes into play.
Our collaboration strategy with GitHub necessitates maintenance of multiple `release-v*` branches alongside the `main` branch. To manage this, we mainly develop on the `main` branch and selectively merge into `release-v*` branches. This ensures the `main` branch stays current while the `release-v*` branches remain stable.
Ensuring this strategy's success extends beyond just documentation; it hinges on well-engineered solutions and automation tools, like Makefile, powerful CI/CD processes, and even Prow.
## Prerequisites
- [Contributor License Agreement](https://github.com/openim-sigs/cla) is considered implicit for all code within cherry pick pull requests, **unless there is a large conflict**.
- A pull request merged against the `main` branch.
- The release branch exists (example: [`release-1.18`](https://github.com/openimsdk/open-im-server-deploy/tree/release-v3.1))
- The normal git and GitHub configured shell environment for pushing to your openim-server `origin` fork on GitHub and making a pull request against a configured remote `upstream` that tracks `https://github.com/openimsdk/open-im-server-deploy.git`, including `GITHUB_USER`.
- Have GitHub CLI (`gh`) installed following [installation instructions](https://github.com/cli/cli#installation).
- A github personal access token which has permissions "repo" and "read:org". Permissions are required for [gh auth login](https://cli.github.com/manual/gh_auth_login) and not used for anything unrelated to cherry-pick creation process (creating a branch and initiating PR).
## What Kind of PRs are Good for Cherry Picks
Compared to the normal main branch's merge volume across time, the release branches see one or two orders of magnitude less PRs. This is because there is an order or two of magnitude higher scrutiny. Again, the emphasis is on critical bug fixes, e.g.,
- Loss of data
- Memory corruption
- Panic, crash, hang
- Security
A bugfix for a functional issue (not a data loss or security issue) that only affects an alpha feature does not qualify as a critical bug fix.
If you are proposing a cherry pick and it is not a clear and obvious critical bug fix, please reconsider. If upon reflection you wish to continue, bolster your case by supplementing your PR with e.g.,
- A GitHub issue detailing the problem
- Scope of the change
- Risks of adding a change
- Risks of associated regression
- Testing performed, test cases added
- Key stakeholder SIG reviewers/approvers attesting to their confidence in the change being a required backport
If the change is in cloud provider-specific platform code (which is in the process of being moved out of core openim-server), describe the customer impact, how the issue escaped initial testing, remediation taken to prevent similar future escapes, and why the change cannot be carried in your downstream fork of the openim-server project branches.
It is critical that our full community is actively engaged on enhancements in the project. If a released feature was not enabled on a particular provider's platform, this is a community miss that needs to be resolved in the `main` branch for subsequent releases. Such enabling will not be backported to the patch release branches.
## Initiate a Cherry Pick
### Before you begin
- Plan to initiate a cherry-pick against *every* supported release branch. If you decide to skip some release branch, explain your decision in a comment to the PR being cherry-picked.
- Initiate cherry-picks in order, from newest to oldest supported release branches. For example, if 3.1 is the newest supported release branch, then, before cherry-picking to 2.25, make sure the cherry-pick PR already exists for in 2.26 and 3.1. This helps to prevent regressions as a result of an upgrade to the next release.
### Steps
- Run the [cherry pick script](https://github.com/openimsdk/open-im-server-deploy/tree/main/scripts/cherry-pick.sh)
This example applies a main branch PR #98765 to the remote branch `upstream/release-v3.1`:
```
scripts/cherry-pick.sh upstream/release-v3.1 98765
```
- Be aware the cherry pick script assumes you have a git remote called `upstream` that points at the openim-server github org.
Please see our [recommended Git workflow](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/github-workflow.md#workflow).
- You will need to run the cherry pick script separately for each patch release you want to cherry pick to. Cherry picks should be applied to all [active](https://github.com/openimsdk/open-im-server-deploy/releases) release branches where the fix is applicable.
- If `GITHUB_TOKEN` is not set you will be asked for your github password: provide the github [personal access token](https://github.com/settings/tokens) rather than your actual github password. If you can securely set the environment variable `GITHUB_TOKEN` to your personal access token then you can avoid an interactive prompt. Refer [mislav/hub#2655 (comment)](https://github.com/mislav/hub/issues/2655#issuecomment-735836048)
- Your cherry pick PR will immediately get the `do-not-merge/cherry-pick-not-approved` label.
## Cherry Pick Review
As with any other PR, code OWNERS review (`/lgtm`) and approve (`/approve`) on cherry pick PRs as they deem appropriate.
The same release note requirements apply as normal pull requests, except the release note stanza will auto-populate from the main branch pull request from which the cherry pick originated.
## Using git cherry-pick
`git cherry-pick` applies specified commits from one branch to another.
```bash
$ git cherry-pick <commitHash>
```
As an example, consider a repository with `main` and `release-v3.1` branches. To apply commit `f` from the `release-v3.1` branch to the `main` branch:
```
# Switch to main branch
$ git checkout main
# Perform cherry-pick
$ git cherry-pick f
```
You can also use a branch name instead of a commit hash to cherry-pick the latest commit from that branch.
```bash
$ git cherry-pick release-v3.1
```
## Applying Multiple Commits
To apply multiple commits simultaneously:
```bash
$ git cherry-pick <HashA> <HashB>
```
To apply a range of consecutive commits:
```bash
$ git cherry-pick <HashA>..<HashB>
```
## Configurations
Here are some commonly used configurations for `git cherry-pick`:
- **`-e`, `--edit`**: Open an external editor to modify the commit message.
- **`-n`, `--no-commit`**: Update the working directory and staging area without creating a new commit.
- **`-x`**: Append a reference in the commit message for tracking the source of the cherry-picked commit.
- **`-s`, `--signoff`**: Add a sign-off message at the end of the commit indicating who performed the cherry-pick.
- **`-m parent-number`, `--mainline parent-number`**: When the original commit is a merge of two branches, specify which parent branch's changes should be used.
## Handling Conflicts
If conflicts arise during the cherry-pick:
- **`--continue`**: After resolving conflicts, stage the changes with `git add .` and then continue the cherry-pick process.
- **`--abort`**: Abandon the cherry-pick and revert to the previous state.
- **`--quit`**: Exit the cherry-pick without reverting to the previous state.
## Applying Commits from Another Repository
You can also cherry-pick commits from another repository:
1. Add the external repository as a remote:
```
$ git remote add target git://gitUrl
```
2. Fetch the commits from the remote:
```
$ git fetch target
```
3. Identify the commit hash you wish to cherry-pick:
```
$ git log target/main
```
4. Perform the cherry-pick:
```
$ git cherry-pick <commitHash>
```

View File

@@ -0,0 +1,283 @@
---
title: "GitHub Workflow"
weight: 6
description: |
This document is an overview of the GitHub workflow used by the
open-im-server-deploy project. It includes tips and suggestions on keeping your
local environment in sync with upstream and how to maintain good
commit hygiene.
---
## 1. Fork in the cloud
1. Visit https://github.com/openimsdk/open-im-server-deploy
2. Click `Fork` button (top right) to establish a cloud-based fork.
## 2. Clone fork to local storage
Per Go's [workspace instructions][go-workspace], place open-im-server-deploy' code on your
`GOPATH` using the following cloning procedure.
[go-workspace]: https://golang.org/doc/code.html#Workspaces
In your shell, define a local working directory as `working_dir`. If your `GOPATH` has multiple paths, pick
just one and use it instead of `$GOPATH`. You must follow exactly this pattern,
neither `$GOPATH/src/github.com/${your github profile name}/`
nor any other pattern will work.
```sh
export working_dir="$(go env GOPATH)/src/github.com/openimsdk"
```
If you already do Go development on github, the `github.com/openimsdk` directory
will be a sibling to your existing `github.com` directory.
Set `user` to match your github profile name:
```sh
export user=<your github profile name>
```
Both `$working_dir` and `$user` are mentioned in the figure above.
Create your clone:
```sh
mkdir -p $working_dir
cd $working_dir
git clone https://github.com/$user/open-im-server-deploy.git
# or: git clone git@github.com:$user/open-im-server-deploy.git
cd $working_dir/open-im-server-deploy
git remote add upstream https://github.com/openimsdk/open-im-server-deploy.git
# or: git remote add upstream git@github.com:openimsdk/open-im-server-deploy.git
# Never push to upstream master
git remote set-url --push upstream no_push
# Confirm that your remotes make sense:
git remote -v
```
## 3. Create a Working Branch
Get your local master up to date. Note that depending on which repository you are working from,
the default branch may be called "main" instead of "master".
```sh
cd $working_dir/open-im-server-deploy
git fetch upstream
git checkout master
git rebase upstream/master
```
Create your new branch.
```sh
git checkout -b myfeature
```
You may now edit files on the `myfeature` branch.
### Building open-im-server-deploy
This workflow is process-specific. For quick-start build instructions for [openimsdk/open-im-server-deploy](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/util-makefile.md)
## 4. Keep your branch in sync
You will need to periodically fetch changes from the `upstream`
repository to keep your working branch in sync. Note that depending on which repository you are working from,
the default branch may be called 'main' instead of 'master'.
Make sure your local repository is on your working branch and run the
following commands to keep it in sync:
```sh
git fetch upstream
git rebase upstream/master
```
Please don't use `git pull` instead of the above `fetch` and
`rebase`. Since `git pull` executes a merge, it creates merge commits. These make the commit history messy
and violate the principle that commits ought to be individually understandable
and useful (see below).
You might also consider changing your `.git/config` file via
`git config branch.autoSetupRebase always` to change the behavior of `git pull`, or another non-merge option such as `git pull --rebase`.
## 5. Commit Your Changes
You will probably want to regularly commit your changes. It is likely that you will go back and edit,
build, and test multiple times. After a few cycles of this, you might
[amend your previous commit](https://www.w3schools.com/git/git_amend.asp).
```sh
git commit
```
## 6. Push to GitHub
When your changes are ready for review, push your working branch to
your fork on GitHub.
```sh
git push -f <your_remote_name> myfeature
```
## 7. Create a Pull Request
1. Visit your fork at `https://github.com/<user>/open-im-server-deploy`
2. Click the **Compare & Pull Request** button next to your `myfeature` branch.
3. Check out the pull request process for more details and
advice.
_If you have upstream write access_, please refrain from using the GitHub UI for
creating PRs, because GitHub will create the PR branch inside the main
repository rather than inside your fork.
### Get a code review
Once your pull request has been opened it will be assigned to one or more
reviewers. Those reviewers will do a thorough code review, looking for
correctness, bugs, opportunities for improvement, documentation and comments,
and style.
Commit changes made in response to review comments to the same branch on your
fork.
Very small PRs are easy to review. Very large PRs are very difficult to review.
### Squash commits
After a review, prepare your PR for merging by squashing your commits.
All commits left on your branch after a review should represent meaningful milestones or units of work. Use commits to add clarity to the development and review process.
Before merging a PR, squash the following kinds of commits:
- Fixes/review feedback
- Typos
- Merges and rebases
- Work in progress
Aim to have every commit in a PR compile and pass tests independently if you can, but it's not a requirement. In particular, `merge` commits must be removed, as they will not pass tests.
To squash your commits, perform an [interactive rebase](https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History):
1. Check your git branch:
```
git status
```
The output should be similar to this:
```
On branch your-contribution
Your branch is up to date with 'origin/your-contribution'.
```
2. Start an interactive rebase using a specific commit hash, or count backwards from your last commit using `HEAD~<n>`, where `<n>` represents the number of commits to include in the rebase.
```
git rebase -i HEAD~3
```
The output should be similar to this:
```
pick 2ebe926 Original commit
pick 31f33e9 Address feedback
pick b0315fe Second unit of work
# Rebase 7c34fc9..b0315ff onto 7c34fc9 (3 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup <commit> = like "squash", but discard this commit's log message
...
```
3. Use a command line text editor to change the word `pick` to `squash` for the commits you want to squash, then save your changes and continue the rebase:
```
pick 2ebe926 Original commit
squash 31f33e9 Address feedback
pick b0315fe Second unit of work
...
```
The output after saving changes should look similar to this:
```
[detached HEAD 61fdded] Second unit of work
Date: Thu Mar 5 19:01:32 2020 +0100
2 files changed, 15 insertions(+), 1 deletion(-)
...
Successfully rebased and updated refs/heads/master.
```
4. Force push your changes to your remote branch:
```
git push --force
```
For mass automated fixups such as automated doc formatting, use one or more
commits for the changes to tooling and a final commit to apply the fixup en
masse. This makes reviews easier.
An alternative to this manual squashing process is to use the Prow and Tide based automation that is configured in GitHub: adding a comment to your PR with `/label tide/merge-method-squash` will trigger the automation so that GitHub squash your commits onto the target branch once the PR is approved. Using this approach simplifies things for those less familiar with Git, but there are situations in where it's better to squash locally; reviewers will have this in mind and can ask for manual squashing to be done.
By squashing locally, you control the commit message(s) for your work, and can separate a large PR into logically separate changes.
For example: you have a pull request that is code complete and has 24 commits. You rebase this against the same merge base, simplifying the change to two commits. Each of those two commits represents a single logical change and each commit message summarizes what changes. Reviewers see that the set of changes are now understandable, and approve your PR.
## Merging a commit
Once you've received review and approval, your commits are squashed, your PR is ready for merging.
Merging happens automatically after both a Reviewer and Approver have approved the PR. If you haven't squashed your commits, they may ask you to do so before approving a PR.
## Reverting a commit
In case you wish to revert a commit, use the following instructions.
_If you have upstream write access_, please refrain from using the
`Revert` button in the GitHub UI for creating the PR, because GitHub
will create the PR branch inside the main repository rather than inside your fork.
- Create a branch and sync it with upstream. Note that depending on which repository you are working from, the default branch may be called 'main' instead of 'master'.
```sh
# create a branch
git checkout -b myrevert
# sync the branch with upstream
git fetch upstream
git rebase upstream/master
```
- If the commit you wish to revert is a *merge commit*, use this command:
```sh
# SHA is the hash of the merge commit you wish to revert
git revert -m 1 <SHA>
```
If it is a *single commit*, use this command:
```sh
# SHA is the hash of the single commit you wish to revert
git revert <SHA>
```
- This will create a new commit reverting the changes. Push this new commit to your remote.
```sh
git push <your_remote_name> myrevert
```
- Finally, [create a Pull Request](#7-create-a-pull-request) using this branch.

1478
docs/contrib/go-code.md Normal file

File diff suppressed because it is too large Load Diff

1554
docs/contrib/go-code1.md Normal file

File diff suppressed because it is too large Load Diff

50
docs/contrib/go-doc.md Normal file
View File

@@ -0,0 +1,50 @@
# Go Language Documentation for OpenIM
In the realm of software development, especially within Go language projects, documentation plays a crucial role in ensuring code maintainability and ease of use. Properly written and accurate documentation is not only essential for understanding and utilizing software effectively but also needs to be easy to write and maintain. This principle is at the heart of OpenIM's approach to supporting commands and generating documentation.
## Supported Commands in OpenIM
OpenIM leverages Go language's documentation standards to facilitate clear and maintainable code documentation. Below are some of the key commands used in OpenIM for documentation purposes:
### `go doc` Command
The `go doc` command is used to print documentation for Go language entities such as variables, constants, functions, structures, and interfaces. This command allows specifying the identifier of the program entity to tailor the output. Examples of `go doc` command usage include:
- `go doc sync.WaitGroup.Add` prints the documentation for a specific method of a type in a package.
- `go doc -u -all sync.WaitGroup` displays all program entities, including unexported ones, for a specified type.
- `go doc -u sync` outputs all program entities for a specified package, focusing on exported ones without detailed comments.
### `godoc` Command
For environments lacking internet access, the `godoc` command serves to view the Go language standard library and project dependency library documentation in a web format. Notably, post-Go 1.12 versions, `godoc` is not part of the Go compiler suite. It can be installed using:
```shell
go get -u -v golang.org/x/tools/cmd/godoc
```
The `godoc` command, once running, hosts a local web server (by default on port 6060) to facilitate documentation browsing at http://127.0.0.1:6060. It generates documentation based on the GOROOT and GOPATH directories, showcasing both the project's own documentation and that of third-party packages installed via `go get`.
### Custom Documentation Generation Commands in OpenIM
OpenIM includes a suite of commands aimed at initializing, generating, and maintaining project documentation and associated files. Some notable commands are:
- `gen.init`: Initializes the OpenIM server project.
- `gen.docgo`: Generates missing `doc.go` files for Go packages, crucial for package-level documentation.
- `gen.errcode.doc`: Generates markdown documentation for OpenIM error codes.
- `gen.ca`: Generates CA files for all certificates, enhancing security documentation.
These commands underscore the project's commitment to thorough and accessible documentation, supporting both developers and users alike.
## Writing Your Own Documentation
When creating documentation for Go projects, including OpenIM, it's important to follow certain practices:
1. **Commenting**: Use single-line (`//`) and block (`/* */`) comments to provide detailed documentation within the code. Block comments are especially useful for package documentation, which should immediately precede the package statement without any intervening blank lines.
2. **Overview Section**: To create an overview section in the documentation, place a block comment directly before the package statement. This section should succinctly describe the package's purpose and functionality.
3. **Detailed Descriptions**: Comments placed before functions, structures, or variables will be used to generate detailed descriptions in the documentation. Follow the same commenting rules as for the overview section.
4. **Examples**: Include example functions prefixed with `Example` to demonstrate usage. Output from these examples can be documented at the end of the function, starting with `// Output:` followed by the expected result.
Through adherence to these documentation practices, OpenIM ensures that its codebase remains accessible, maintainable, and easy to use for developers and users alike.

116
docs/contrib/images.md Normal file
View File

@@ -0,0 +1,116 @@
# OpenIM Image Management Strategy and Pulling Guide
OpenIM is an efficient, stable, and scalable instant messaging framework that provides convenient deployment methods through Docker images. OpenIM manages multiple image sources, hosted respectively on GitHub (ghcr), Alibaba Cloud, and Docker Hub. This document is aimed at detailing the image management strategy of OpenIM and providing the steps for pulling these images.
## Image Management Strategy
OpenIM's versions correspond to GitHub's tag versions. Each time we release a new version and tag it on GitHub, an automated process is triggered that pushes the new Docker image version to the following three platforms:
1. **GitHub (ghcr.io):** We use GitHub Container Registry (ghcr.io) to host OpenIM's Docker images. This allows us to better integrate with the GitHub source code repository, providing better version control and continuous integration/deployment (CI/CD) features. You can view all GitHub images [here](https://github.com/orgs/OpenIMSDK/packages).
2. **Alibaba Cloud (registry.cn-hangzhou.aliyuncs.com):** For users in Mainland China, we also host OpenIM's Docker images on Alibaba Cloud to provide faster pull speeds. You can view all Alibaba Cloud images on this [page](https://cr.console.aliyun.com/cn-hangzhou/instances/repositories) of Alibaba Cloud Image Service (note that you need to log in to your Alibaba Cloud account first).
3. **Docker Hub (docker.io):** Docker Hub is the most commonly used Docker image hosting platform, and we also host OpenIM's images there to facilitate developers worldwide. You can view all Docker Hub images on the [OpenIM's Docker Hub page](https://hub.docker.com/r/openim).
## Base images design
+ [https://github.com/openim-sigs/openim-base-image](https://github.com/openim-sigs/openim-base-image)
## OpenIM Image Design and Usage Guide
OpenIM offers a comprehensive and flexible system of Docker images, available across multiple repositories. We actively maintain these images across different platforms, namely GitHub's ghcr.io, Alibaba Cloud, and Docker Hub. However, we highly recommend ghcr.io for deployment.
### Available Versions
We provide multiple versions of our images to meet different project requirements. Here's a quick overview of what you can expect:
1. `main`: This image corresponds to the latest version of the main branch in OpenIM. It is updated frequently, making it perfect for users who want to stay at the cutting edge of our features.
2. `release-v3.*`: This is the image that corresponds to the latest version of OpenIM's stable release branch. It's ideal for users who prefer a balance between new features and stability.
3. `v3.*.*`: These images are specific to each tag in OpenIM. They are preserved in their original state and are never overwritten. These are the go-to images for users who need a specific, unchanging version of OpenIM.
4. The image versions adhere to Semantic Versioning 2.0.0 strategy. Taking the `openim-server` image as an example, available at [openim-server container package](https://github.com/openimsdk/open-im-server-deploy/pkgs/container/openim-server): upon tagging with v3.5.0, the CI automatically releases the following tags - `openim-server:3`, `openim-server:3.5`, `openim-server:3.5.0`, `openim-server:v3.5.0`, `openim-server:latest`, and `sha-e0244d9`. It's important to note that only `sha-e0244d9` is absolutely unique, whereas `openim-server:v3.5.0` and `openim-server:3.5.0` maintain a degree of uniqueness.
### Multi-Architecture Images
In order to cater to a wider range of needs, some of our images are provided with multiple architectures under `OS / Arch`. These images offer greater compatibility across different operating systems and hardware architectures, ensuring that OpenIM can be deployed virtually anywhere.
**Example:**
+ [https://github.com/OpenIMSDK/chat/pkgs/container/openim-chat/113925695?tag=v1.1.0](https://github.com/OpenIMSDK/chat/pkgs/container/openim-chat/113925695?tag=v1.1.0)
## Methods and Steps for Pulling Images
When pulling OpenIM's Docker images, you can choose the most suitable source based on your geographic location and network conditions. Here are the steps to pull OpenIM images from each source:
### Select image
1. Choose the image repository platform you prefer. As previously mentioned, we recommend [OpenIM ghcr.io](https://github.com/orgs/OpenIMSDK/packages).
2. Choose the image name and image version that suits your needs. Refer to the description above for more details.
### Install image
1. First, make sure Docker is installed on your machine. If not, you can refer to the [Docker official documentation](https://docs.docker.com/get-docker/) for installation.
2. Open the terminal and run the following commands to pull the images:
For OpenIM Server:
- Pull from GitHub:
```bash
docker pull ghcr.io/openimsdk/openim-server:latest
```
- Pull from Alibaba Cloud:
```bash
docker pull registry.cn-hangzhou.aliyuncs.com/openimsdk/openim-server:latest
```
- Pull from Docker Hub:
```bash
docker pull docker.io/openim/openim-server:latest
```
For OpenIM Chat:
- Pull from GitHub:
```bash
docker pull ghcr.io/openimsdk/openim-chat:latest
```
- Pull from Alibaba Cloud:
```bash
docker pull registry.cn-hangzhou.aliyuncs.com/openimsdk/openim-chat:latest
```
- Pull from Docker Hub:
```bash
docker pull docker.io/openim/openim-chat:latest
```
3. Run the `docker images` command to confirm that the image has been successfully pulled.
### Accelerating Deployment for Users in China with Aliyun Mirror or Alternative Image Addresses
For users in China looking to speed up the deployment process of OpenIM, leveraging a mirror image address is a highly recommended practice. After executing the `make init` command, a `.env` file is generated, which you'll need to edit to configure the image registry source. This configuration is crucial for optimizing download speeds and ensuring a smoother setup process.
Within the generated `.env` file, you'll find a section dedicated to choosing the image address. It includes options for GitHub (`ghcr.io/openimsdk`), Docker Hub (`openim`), and Ali Cloud (`registry.cn-hangzhou.aliyuncs.com/openimsdk`). To achieve the best performance within China, it is advised to use the Aliyun image address.
To do this, you need to comment out the current `IMAGE_REGISTRY` setting and uncomment the Aliyun option. Here is how you can adjust it for Aliyun:
```bash
# Choose the image address: GitHub (ghcr.io/openimsdk), Docker Hub (openim),
# or Ali Cloud (registry.cn-hangzhou.aliyuncs.com/openimsdk).
# Uncomment one of the following three options. Aliyun is recommended for users in China.
# IMAGE_REGISTRY="ghcr.io/openimsdk"
# IMAGE_REGISTRY="openim"
IMAGE_REGISTRY="registry.cn-hangzhou.aliyuncs.com/openimsdk"
```
This change directs the deployment process to fetch the required images from the Aliyun registry, significantly improving download and installation speeds due to the geographical and network advantages within China. If, for any reason, you prefer not to use Aliyun or encounter issues, consider switching to another mirror address listed in the `.env` file by following the same uncommenting process. This flexibility ensures that users can select the most suitable image source for their specific situation, leading to a more efficient deployment of OpenIM.

View File

@@ -0,0 +1,74 @@
# Init OpenIM Config
- [Init OpenIM Config](#init-openim-config)
- [Start](#start)
- [Define Automated Configuration](#define-automated-configuration)
- [Define Configuration Variables](#define-configuration-variables)
- [Bash Parsing Features](#bash-parsing-features)
- [Reasons and Advantages of the Design](#reasons-and-advantages-of-the-design)
## Start
With the increasing complexity of software engineering, effective configuration management has become more and more important. Yaml and other configuration files provide the necessary parameters and guidance for systems, but they also impose additional management overhead for developers. This article explores how to automate and optimize configuration management, thereby improving efficiency and reducing the chances of errors.
First, obtain the OpenIM code through the contributor documentation and initialize it following the steps below.
## Define Automated Configuration
We no longer strongly recommend modifying the same configuration file. If you have a new configuration file related to your business, we suggest generating and managing it through automation.
In the `scripts/init_config.sh` file, we defined some template files. These templates will be automatically generated to the corresponding directories when executing `make init`.
```
# Defines an associative array where the keys are the template files and the values are the corresponding output files.
declare -A TEMPLATES=(
["${OPENIM_ROOT}/scripts/template/config-tmpl/env.template"]="${OPENIM_OUTPUT_SUBPATH}/bin/.env"
["${OPENIM_ROOT}/scripts/template/config-tmpl/config.yaml"]="${OPENIM_OUTPUT_SUBPATH}/bin/config.yaml"
)
```
If you have your new mapping files, you can implement them by appending them to the array.
Lastly, run:
```
./scripts/init_config.sh
```
## Define Configuration Variables
In the `scripts/install/environment.sh` file, we defined many reusable variables for automation convenience.
In the provided example, the def function is a core element. This function not only provides a concise way to define variables but also offers default value options for each variable. This way, even if a specific variable is not explicitly set in an environment or scenario, it can still have an expected value.
```
function def() {
local var_name="$1"
local default_value="$2"
eval "readonly $var_name=\${$var_name:-$default_value}"
}
```
### Bash Parsing Features
Since bash is a parsing script language, it executes commands in the order they appear in the script. This characteristic means we can define commonly used or core variables at the beginning of the script and then reuse or modify them later on.
For instance, we can initially set a universal password and reuse this password in subsequent variable definitions.
```
# Set a consistent password for easy memory
def "PASSWORD" "openIM123"
# Linux system user for openim
def "LINUX_USERNAME" "openim"
def "LINUX_PASSWORD" "${PASSWORD}"
```
## Reasons and Advantages of the Design
1. **Simplify Configuration Management**: Through automation scripts, we can avoid manual operations and configurations, thus reducing tedious repetitive tasks.
2. **Reduce Errors**: Manually editing yaml or other configuration files can lead to formatting mistakes or typographical errors. Automating with scripts can lower the risk of such errors.
3. **Enhanced Readability**: Using the `def` function and other bash scripting techniques, we can establish a clear, easy-to-read, and maintainable configuration system.
4. **Improved Reusability**: As demonstrated above, we can reuse variables and functions in different parts of the script, reducing redundant code and increasing overall consistency.
5. **Flexible Default Value Mechanism**: By providing default values for variables, we can ensure configurations are complete and consistent across various scenarios, while also offering customization options for advanced users.

View File

@@ -0,0 +1,53 @@
<!-- vscode-markdown-toc -->
<!-- vscode-markdown-toc-config
numbering=true
autoSave=true
/vscode-markdown-toc-config -->
<!-- /vscode-markdown-toc -->
# Install Docker
The installation command is as follows:
```bash
$ curl -fsSL https://get.docker.com | bash -s docker --mirror aliyun
``
## 2.2 Start Docker
```bash
$ systemctl start docker
```
## 2.3 Test Docker
```bash
$ docker run hello-world
```
## 2.4 Configure Docker Acceleration
```bash
$ mkdir -p /etc/docker
$ tee /etc/docker/daemon.json <<-'EOF'
{
"registry-mirrors": ["https://registry.docker-cn.com"]
}
EOF
$ systemctl daemon-reload
$ systemctl restart docker
```
## 2.5 Install Docker Compose
```bash
$ sudo curl -L "https://github.com/docker/compose/releases/download/latest/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
$ sudo chmod +x /usr/local/bin/docker-compose
```
## 2.6 Test Docker Compose
```bash
$ docker-compose --version
```

View File

@@ -0,0 +1,353 @@
# OpenIM System: Setup and Usage Guide
<!-- vscode-markdown-toc -->
* 1. [1. Introduction](#Introduction)
* 2. [2. Prerequisites (Requires root permissions)](#PrerequisitesRequiresrootpermissions)
* 3. [3. Create `openim-api` systemd unit template file](#Createopenim-apisystemdunittemplatefile)
* 4. [4. Copy systemd unit template file to systemd config directory (Requires root permissions)](#CopysystemdunittemplatefiletosystemdconfigdirectoryRequiresrootpermissions)
* 5. [5. Start systemd service](#Startsystemdservice)
## 0. <a name='Introduction'></a>0. Introduction
Systemd is the default service management form for the latest Linux distributions, replacing the original init.
The OpenIM system is a comprehensive suite of services tailored to address a wide variety of messaging needs. This guide will walk you through the steps of setting up the OpenIM system services and provide insights into its usage.
**Prerequisites:**
+ A Linux server with necessary privileges.
+ Ensure you have `systemctl` installed and running.
## 1. <a name='Deployment'></a>1. Deployment
1. **Retrieve the Installation Script**:
Begin by obtaining the OpenIM installation script which will be utilized to deploy the entire OpenIM system.
2. **Install OpenIM**:
To install all the components of OpenIM, run:
```bash
./scripts/install/install.sh -i
```
or
```bash
./scripts/install/install.sh --install
```
This will initiate the installation process for all OpenIM components.
3. **Check the Status**:
Post installation, it is good practice to verify if all the services are running as expected:
```bash
systemctl status openim.target
```
This will list the status of all related services of OpenIM.
**Maintenance & Management:**
1. **Checking Individual Service Status**:
You can monitor the status of individual services with the following command:
```bash
systemctl status <service-name>
```
For instance:
```bash
systemctl status openim-api.service
``
2. **Starting and Stopping Services**:
If you wish to start or stop any specific service, you can do so with `systemctl start` or `systemctl stop` followed by the service name:
```bash
systemctl start openim-api.service
systemctl stop openim-api.service
```
3. **Uninstalling OpenIM**:
In case you wish to remove the OpenIM components from your server, utilize:
```bash
./scripts/install/install.sh -u
```
or
```bash
./scripts/install/install.sh --uninstall
```
Ensure you take a backup of any important data before executing the uninstall command.
4. **Logs & Troubleshooting**:
Logs play a pivotal role in understanding the system's operation and troubleshooting any issues. OpenIM logs can typically be found in the directory specified during installation, usually `${OPENIM_LOG_DIR}`.
Always refer to the logs when troubleshooting. Look for any error messages or warnings that might give insights into the issue at hand.
**Note:**
+ `openim-api.service`: Manages the main API gateways for OpenIM communication.
+ `openim-crontask.service`: Manages scheduled tasks and jobs.
+ `openim-msggateway.service`: Takes care of message gateway operations.
+ `openim-msgtransfer.service`: Handles message transfer functionalities.
+ `openim-push.service`: Responsible for push notification services.
+ `openim-rpc-auth.service`: Manages RPC (Remote Procedure Call) for authentication.
+ `openim-rpc-conversation.service`: Manages RPC for conversations.
+ `openim-rpc-friend.service`: Handles RPC for friend-related operations.
+ `openim-rpc-group.service`: Manages group-related RPC operations.
+ `openim-rpc-msg.service`: Takes care of message RPCs.
+ `openim-rpc-third.service`: Deals with third-party integrations using RPC.
+ `openim-rpc-user.service`: Manages user-related RPC operations.
+ `openim.target`: A target that bundles all the above services for collective operations.
**Viewing Logs with `journalctl`:**
`systemctl` services usually log their output to the systemd journal, which you can access using the `journalctl` command.
1. **View Logs for a Specific Service**:
To view the logs for a particular service, you can use:
```bash
journalctl -u <service-name>
```
For example, to see the logs for the `openim-api.service`, you would use:
```bash
journalctl -u openim-api.service
```
2. **Filtering Logs**:
+ By Time
: If you wish to see logs since a specific time:
```bash
journalctl -u openim-api.service --since "2023-10-28 12:00:00"
```
+ Most Recent Logs
: To view the most recent logs, you can combine
`tail` functionality with `journalctl`:
```bash
journalctl -u openim-api.service -n 100
```
3. **Continuous Monitoring of Logs**:
To see new log messages in real-time, you can use the `-f` flag, which mimics the behavior of `tail -f`:
```bash
journalctl -u openim-api.service -f
```
### Continued Maintenance:
1. **Regularly Check Service Status**:
It's good practice to routinely verify that all services are active and running. This can be done with:
```bash
systemctl status openim-api.service openim-push.service openim-rpc-group.service openim-crontask.service openim-rpc-auth.service openim-rpc-msg.service openim-msggateway.service openim-rpc-conversation.service openim-rpc-third.service openim-msgtransfer.service openim-rpc-friend.service openim-rpc-user.service
```
2. **Update Services**:
Periodically, there might be updates or patches to the OpenIM system or its components. Make sure you keep the system updated. After updating any service, always reload the daemon and restart the service:
```bash
systemctl daemon-reload
systemctl restart openim-api.service
```
3. **Backup Important Data**:
Regularly backup any configuration files, user data, and other essential data. This ensures that you can restore the system to a working state in case of failures.
### Important `systemctl` and Logging Commands to Learn:
1. **Start/Stop/Restart Services**:
```bash
systemctl start <service-name>
systemctl stop <service-name>
systemctl restart <service-name>
```
2. **Enable/Disable Services**:
If you want a service to start automatically at boot:
```bash
systemctl enable <service-name>
```
To prevent it from starting at boot:
```bash
systemctl disable <service-name>
```
3. **Check Failed Services**:
To quickly check if any service has failed:
```bash
systemctl --failed
```
4. **Log Rotation**:
`journalctl` logs can grow large. To clear all archived journal entries, use:
```bash
journalctl --vacuum-time=1d
```
**Advanced requirements:**
- Convenient service runtime log recording for problem analysis
- Service management logs
- Option to restart upon abnormal exit
The daemon does not meet these advanced requirements.
`nohup` only logs the service's runtime outputs and errors.
Only systemd can fulfill all of the above requirements.
> The default logs are enhanced with timestamps, usernames, service names, PIDs, etc., making them user-friendly. You can view logs of abnormal service exits. Advanced customization is possible through the configuration files in `/lib/systemd/system/`.
In short, systemd is the current mainstream way to manage backend services on Linux, so I've abandoned `nohup` in my new versions of bash scripts, opting instead for systemd.
## 2. <a name='PrerequisitesRequiresrootpermissions'></a>Prerequisites (Requires root permissions)
1. Configure `environment.sh` based on the comments.
2. Create a data directory:
```bash
mkdir -p ${OPENIM_DATA_DIR}/{openim-api,openim-crontask}
```
3. Create a bin directory and copy `openim-api` and `openim-crontask` executable files:
```bash
source ./environment.sh
mkdir -p ${OPENIM_INSTALL_DIR}/bin
cp openim-api openim-crontask ${OPENIM_INSTALL_DIR}/bin
```
4. Copy the configuration files of `openim-api` and `openim-crontask` to the `${OPENIM_CONFIG_DIR}` directory:
```bash
mkdir -p ${OPENIM_CONFIG_DIR}
cp openim-api.yaml openim-crontask.yaml ${OPENIM_CONFIG_DIR}
```
## 3. <a name='Createopenim-apisystemdunittemplatefile'></a> Create `openim-api` systemd unit template file
For each OpenIM service, we will create a systemd unit template. Follow the steps below for each service:
Run the following shell script to generate the `openim-api.service.template`:
```bash
source ./environment.sh
cat > openim-api.service.template <<EOF
[Unit]
Description=OpenIM Server API
Documentation=https://github.com/oepnimsdk/open-im-server-deploy/blob/master/init/README.md
[Service]
WorkingDirectory=${OPENIM_DATA_DIR}/openim-api
ExecStart=${OPENIM_INSTALL_DIR}/bin/openim-api --config=${OPENIM_CONFIG_DIR}/openim-api.yaml
Restart=always
RestartSec=5
StartLimitInterval=0
[Install]
WantedBy=multi-user.target
EOF
```
Following the above style, create the respective template files or generate them in bulk:
First, make sure you've sourced the environment variables:
```bash
source ./environment.sh
```
Use the shell script to generate the systemd unit template for each service:
```bash
declare -a services=(
"openim-api"
... [other services]
)
for service in "${services[@]}"
do
cat > $service.service.template <<EOF
[Unit]
Description=OpenIM Server - $service
Documentation=https://github.com/oepnimsdk/open-im-server-deploy/blob/master/init/README.md
[Service]
WorkingDirectory=${OPENIM_DATA_DIR}/$service
ExecStart=${OPENIM_INSTALL_DIR}/bin/$service --config=${OPENIM_CONFIG_DIR}/$service.yaml
Restart=always
RestartSec=5
StartLimitInterval=0
[Install]
WantedBy=multi-user.target
EOF
done
```
## 4. <a name='CopysystemdunittemplatefiletosystemdconfigdirectoryRequiresrootpermissions'></a>Copy systemd unit template file to systemd config directory (Requires root permissions)
Ensure you have root permissions to perform this operation:
```bash
for service in "${services[@]}"
do
sudo cp $service.service.template /etc/systemd/system/$service.service
done
...
```
## 5. <a name='Startsystemdservice'></a>Start systemd service
To start the OpenIM services:
```bash
for service in "${services[@]}"
do
sudo systemctl daemon-reload
sudo systemctl enable $service
sudo systemctl restart $service
done
```

162
docs/contrib/kafka.md Normal file
View File

@@ -0,0 +1,162 @@
# OpenIM Kafka Guide
This document aims to provide a set of concise guidelines to help you quickly install and use Kafka through Docker Compose.
## Installing Kafka
With the Docker Compose script provided by OpenIM, you can easily install Kafka. Use the following command to start Kafka:
```bash
docker compose up -d
```
After executing this command, Kafka will be installed and started. You can confirm the Kafka container is running with the following command:
```bash
docker ps | grep kafka
```
The output of this command, as shown below, displays the status information of the Kafka container:
```
be416b5a0851 bitnami/kafka:3.5.1 "/opt/bitnami/script…" 3 days ago Up 2 days 9092/tcp, 0.0.0.0:19094->9094/tcp, :::19094->9094/tcp kafka
```
### References
- Official Docker installation documentation: [Click here](http://events.jianshu.io/p/b60afa35303a)
- Detailed installation guide: [Tutorial on Towards Data Science](https://towardsdatascience.com/how-to-install-apache-kafka-using-docker-the-easy-way-4ceb00817d8b)
## Using Kafka
### Entering the Kafka Container
To execute Kafka commands, you first need to enter the Kafka container. Use the following command:
```bash
docker exec -it kafka bash
```
### Kafka Command Tools
Inside the Kafka container, you can use various command-line tools to manage Kafka. These tools include but are not limited to:
- `kafka-topics.sh`: For creating, deleting, listing, or altering topics.
- `kafka-console-producer.sh`: Allows sending messages to a specified topic from the command line.
- `kafka-console-consumer.sh`: Allows reading messages from the command line, with the ability to specify topics.
- `kafka-consumer-groups.sh`: For managing consumer group information.
### Kafka Client Tool Installation
For easier Kafka management, you can install Kafka client tools. If you installed Kafka through OpenIM's Docker Compose, you can install the Kafka client tools with the following command:
```bash
make install.kafkactl
```
### Automatic Topic Creation
When installing Kafka through OpenIM's Docker Compose method, OpenIM automatically creates the following topics:
- `latestMsgToRedis`
- `msgToPush`
- `offlineMsgToMongoMysql`
These topics are created using the `scripts/create-topic.sh` script. The script waits for Kafka to be ready before executing the commands to create topics:
```bash
# Wait for Kafka to be ready
until /opt/bitnami/kafka/bin/kafka-topics.sh --list --bootstrap-server localhost:9092; do
echo "Waiting for Kafka to be ready..."
sleep 2
done
# Create topics
/opt/bitnami/kafka/bin/kafka-topics.sh --create --bootstrap-server localhost:9092 --replication-factor 1 --partitions 8 --topic latestMsgToRedis
/opt/bitnami/kafka/bin/kafka-topics.sh --create --bootstrap-server localhost:9092 --replication-factor 1 --partitions 8 --topic msgToPush
/opt/bitnami/kafka/bin/kafka-topics.sh --create --bootstrap-server localhost:9092 --replication-factor 1 --partitions 8 --topic offlineMsgToMongoMysql
echo "Topics created."
```
The optimized and expanded documentation further details some basic commands for operations inside the Kafka container, as well as basic commands for managing Kafka using `kafkactl`. Here is a more detailed guide.
## Basic Commands in the Kafka Container
### Listing Topics
To list all existing topics, you can use the following command:
```bash
kafka-topics.sh --list --bootstrap-server localhost:9092
```
### Creating a New Topic
When creating a new topic, you can specify the number of partitions and the replication factor. Here is the command to create a new topic:
```bash
kafka-topics.sh --create --bootstrap-server localhost:9092 --replication-factor 1 --partitions 1 --topic your_topic_name
```
### Producing Messages
To send messages to a specific topic, you can use the producer command. The following command prompts you to enter messages, which are sent to the specified topic with each press of the Enter key:
```bash
kafka-console-producer.sh --broker-list localhost:9092 --topic your_topic_name
```
### Consuming Messages
To read messages from a specific topic, you can use the consumer command. The following command reads new messages from the specified topic and outputs them on the console:
```bash
kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic your_topic_name --from-beginning
```
The `
--from-beginning` parameter reads messages from the beginning of the topic. If this parameter is omitted, only new messages will be read.
## Basic Commands Using `kafkactl`
`kafkactl` is a command-line tool for managing and operating Kafka clusters. It offers a more modern way to interact with Kafka.
### Listing Topics
To list all topics, you can use:
```bash
kafkactl get topics
```
### Creating a New Topic
To create a new topic with `kafkactl`, use:
```bash
kafkactl create topic your_topic_name --partitions 1 --replication-factor 1
```
### Producing Messages
To send messages to a topic, you can use:
```bash
kafkactl produce your_topic_name --value "your message"
```
Here, `"your message"` is the content of the message you want to send.
### Consuming Messages
To consume messages from a topic, use:
```bash
kafkactl consume your_topic_name --from-beginning
```
Again, the `--from-beginning` parameter will start consuming messages from the beginning of the topic. If you do not wish to start from the beginning, you can omit this parameter.

View File

@@ -0,0 +1,137 @@
# Ubuntu 22.04 OpenIM Project Development Guide
## TOC
- [Ubuntu 22.04 OpenIM Project Development Guide](#ubuntu-2204-openim-project-development-guide)
- [TOC](#toc)
- [1. Setting Up Ubuntu Server](#1-setting-up-ubuntu-server)
- [1.1 Create `openim` Standard User](#11-create-openim-standard-user)
- [1.2 Setting up the `openim` User's Shell Environment](#12-setting-up-the-openim-users-shell-environment)
- [1.3 Installing Dependencies](#13-installing-dependencies)
## 1. Setting Up Ubuntu Server
You can use tools like PuTTY or other SSH clients to log in to your Ubuntu server. Once logged in, a few fundamental configurations are required, such as creating a standard user, adding to sudoers, and setting up the `$HOME/.bashrc` file. The steps are as follows:
## 1.1 Create `openim` Standard User
1. Log in to the Ubuntu system as the `root` user and create a standard user.
Generally, a project will involve multiple developers. Instead of provisioning a server for every developer, many organizations share a single development machine among developers. To simulate this real-world scenario, we'll use a standard user for development. To create the `openim` user:
```
# adduser openim # Create the openim user, which developers will use for login and development.
# passwd openim # Set the login password for openim.
```
Working with a non-root user ensures the system's safety and is a good practice. It's recommended to avoid using the root user as much as possible during everyday development.
1. Add to sudoers.
Often, even standard users need root privileges. Instead of frequently asking the system administrator for the root password, you can add the standard user to the sudoers. This allows them to temporarily gain root access using the sudo command. To add the `openim` user to sudoers:
```
# sed -i '/^root.*ALL=(ALL:ALL).*ALL/a\openim\tALL=(ALL) \tALL' /etc/sudoers
```
## 1.2 Setting up the `openim` User's Shell Environment
1. Log into the Ubuntu system.
Assuming we're using the **openim** user, log in using PuTTY or other SSH clients.
1. Configure the `$HOME/.bashrc` file.
The first step after logging into a new server is to configure the `$HOME/.bashrc` file. It makes the Linux shell more user-friendly by setting environment variables like `LANG` and `PS1`. Here's how the configuration would look:
```
# .bashrc
# User specific aliases and functions
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
# Source global definitions
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi
if [ ! -d $HOME/workspace ]; then
mkdir -p $HOME/workspace
fi
# User specific environment
export LANG="en_US.UTF-8"
export PS1='[\u@dev \W]\$ '
export WORKSPACE="$HOME/workspace"
export PATH=$HOME/bin:$PATH
cd $WORKSPACE
```
After updating `$HOME/.bashrc`, run the `bash` command to reload the configurations into the current shell.
## 1.3 Installing Dependencies
The OpenIM project on Ubuntu may have various dependencies. Some are direct, and others are indirect. Installing these in advance prevents issues like missing packages or compile-time errors later on.
1. Install dependencies.
You can use the `apt` command to install the required tools on Ubuntu:
```
$ sudo apt-get update
$ sudo apt-get install build-essential autoconf automake cmake perl libcurl4-gnutls-dev libtool gcc g++ glibc-doc-reference zlib1g-dev git-lfs telnet lrzsz jq libexpat1-dev libssl-dev
$ sudo apt install libcurl4-openssl-dev
```
1. Install Git.
A higher version of Git ensures compatibility with certain commands like `git fetch --unshallow`. To install a recent version:
```
$ cd /tmp
$ wget --no-check-certificate https://mirrors.edge.kernel.org/pub/software/scm/git/git-2.36.1.tar.gz
$ tar -xvzf git-2.36.1.tar.gz
$ cd git-2.36.1/
$ ./configure
$ make
$ sudo make install
$ git --version
```
Then, add Git's binary directory to the `PATH`:
```
$ echo 'export PATH=/usr/local/libexec/git-core:$PATH' >> $HOME/.bashrc
```
1. Configure Git.
To set up Git:
```
$ git config --global user.name "Your Name"
$ git config --global user.email "your_email@example.com"
$ git config --global credential.helper store
$ git config --global core.longpaths true
```
Other Git configurations include:
```
$ git config --global core.quotepath off
```
And for handling larger files:
```
$ git lfs install --skip-repo
```
By following the steps in this guide, your Ubuntu 22.04 server should now be set up and ready for OpenIM project development.

View File

@@ -0,0 +1,14 @@
# act
Run your [GitHub Actions](https://developer.github.com/actions/) locally! Why would you want to do this? Two reasons:
- **Fast Feedback** - Rather than having to commit/push every time you want to test out the changes you are making to your `.github/workflows/` files (or for any changes to embedded GitHub actions), you can use `act` to run the actions locally. The [environment variables](https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables) and [filesystem](https://help.github.com/en/actions/reference/virtual-environments-for-github-hosted-runners#filesystems-on-github-hosted-runners) are all configured to match what GitHub provides.
- **Local Task Runner** - I love [make](https://en.wikipedia.org/wiki/Make_(software)). However, I also hate repeating myself. With `act`, you can use the GitHub Actions defined in your `.github/workflows/` to replace your `Makefile`!
## install act
+ [https://github.com/nektos/act](https://github.com/nektos/act)
```bash
curl -s https://raw.githubusercontent.com/nektos/act/master/install.sh | sudo bash
···

507
docs/contrib/logging.md Normal file
View File

@@ -0,0 +1,507 @@
# OpenIM Logging and Error Handling Documentation
## Script Logging Documentation Link
If you wish to view the script's logging documentation, you can click on this link: [Logging Documentation](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/bash-log.md).
Below is the documentation for logging and error handling in the OpenIM Go project.
To create a standard set of documentation that is quick to read and easy to understand, we will highlight key information about the `Logger` interface and the `CodeError` interface. This includes the purpose of each interface, key methods, and their use cases. This will help developers quickly grasp how to effectively use logging and error handling within the project.
## Logging (`Logger` Interface)
### Purpose
The `Logger` interface aims to provide the OpenIM project with a unified and flexible logging mechanism, supporting structured logging formats for efficient log management and analysis.
### Key Methods
- **Debug, Info, Warn, Error**
Log messages of different levels to suit various logging needs and scenarios. These methods accept a context (`context.Context`), a message (`string`), and key-value pairs (`...interface{}`), allowing the log to carry rich context information.
- **WithValues**
Append key-value pair information to log messages, returning a new `Logger` instance. This helps in adding consistent context information.
- **WithName**
Set the name of the logger, which helps in identifying the source of the logs.
- **WithCallDepth**
Adjust the call stack depth to accurately identify the source of the log message.
### Use Cases
- Developers should choose the appropriate logging level (such as `Debug`, `Info`, `Warn`, `Error`) based on the importance of the information when logging.
- Use `WithValues` and `WithName` to add richer context information to logs, facilitating subsequent tracking and analysis.
## Error Handling (`CodeError` Interface)
### Purpose
The `CodeError` interface is designed to provide a unified mechanism for error handling and wrapping, making error information more detailed and manageable.
### Key Methods
- **Code**
Return the error code to distinguish between different types of errors.
- **Msg**
Return the error message description to display to the user.
- **Detail**
Return detailed information about the error for further debugging by developers.
- **WithDetail**
Add detailed information to the error, returning a new `CodeError` instance.
- **Is**
Determine whether the current error matches a specified error, supporting a flexible error comparison mechanism.
- **Wrap**
Wrap another error with additional message description, facilitating the tracing of the error's cause.
### Use Cases
- When defining errors with specific codes and messages, use error types that implement the `CodeError` interface.
- Use `WithDetail` to add additional context information to errors for more accurate problem localization.
- Use the `Is` method to judge the type of error for conditional branching.
- Use the `Wrap` method to wrap underlying errors while adding more contextual descriptions.
## Logging Standards and Code Examples
In the OpenIM project, we use the unified logging package `github.com/openimsdk/tools/log` for logging to achieve efficient log management and analysis. This logging package supports structured logging formats, making it easier for developers to handle log information.
### Logger Interface and Implementation
The logger interface is defined as follows:
```go
type Logger interface {
Debug(ctx context.Context, msg string, keysAndValues ...interface{})
Info(ctx context.Context, msg string, keysAndValues ...interface{})
Warn(ctx context.Context, msg string, err error, keysAndValues ...interface{})
Error(ctx context.Context, msg string, err error, keysAndValues ...interface{})
WithValues(keysAndValues ...interface{}) Logger
WithName(name string) Logger
WithCallDepth(depth int) Logger
}
```
Example code: Using the `Logger` interface to log at the info level.
```go
func main() {
logger := log.NewLogger().WithName("MyService")
ctx := context.Background()
logger.Info(ctx, "Service started", "port", "8080")
}
```
## Error Handling and Code Examples
We use the `github.com/openimsdk/tools/errs` package for unified error handling and wrapping.
### CodeError Interface and Implementation
The error interface is defined as follows:
```go
type CodeError interface {
Code() int
Msg() string
Detail() string
WithDetail(detail string) CodeError
Is(err error, loose ...bool) bool
Wrap(msg ...string) error
error
}
```
Example code: Creating and using the `CodeError` interface to handle errors.
```go
package main
import (
"fmt"
"github.com/openimsdk/tools/errs"
)
func main() {
err := errs.New(404, "Resource not found")
err = err.WithDetail("
More details")
if e, ok := err.(errs.CodeError); ok {
fmt.Println(e.Code(), e.Msg(), e.Detail())
}
}
```
### Detailed Logging Standards and Code Examples
1. **Print key information at startup**
It is crucial to print entry parameters and key process information at program startup. This helps understand the startup state and configuration of the program.
**Code Example**:
```go
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("Program startup, version: 1.0.0")
fmt.Printf("Connecting to database: %s\n", os.Getenv("DATABASE_URL"))
}
```
2. **Use `tools/log` and `fmt` for logging**
Logging should be done using a specialized logging library for unified management and formatted log output.
**Code Example**: Logging an info level message with `tools/log`.
```go
package main
import (
"context"
"github.com/openimsdk/tools/log"
)
func main() {
ctx := context.Background()
log.Info(ctx, "Application started successfully")
}
```
3. **Use standard error output for startup failures or critical information**
Critical error messages or program startup failures should be indicated to the user through standard error output.
**Code Example**:
```go
package main
import (
"fmt"
"os"
)
func checkEnvironment() bool {
return os.Getenv("REQUIRED_ENV") != ""
}
func main() {
if !checkEnvironment() {
fmt.Fprintln(os.Stderr, "Missing required environment variable")
os.Exit(1)
}
}
```
We encapsulate it into separate tools, which can output error information through the `tools/log` package.
```go
package main
import (
util "git.imall.cloud/openim/open-im-server-deploy/pkg/util/genutil"
)
func main() {
if err := apiCmd.Execute(); err != nil {
util.ExitWithError(err)
}
}
```
4. **Use `tools/log` package for runtime logging**
This ensures consistency and control over logging.
**Code Example**: Same as the above example using `tools/log`. When `tools/log` is not initialized, consider using `fmt` for standard output.
5. **Error logs should be printed by the top-level caller**
This is to avoid duplicate logging of errors, typically errors are caught and logged at the application's outermost level.
**Code Example**:
```go
package main
import (
"github.com/openimsdk/tools/log"
"context"
)
func doSomething() error {
// An error occurs here
return errs.Wrap(errors.New("An error occurred"))
}
func controller() error {
err := doSomething()
if err != nil {
return err
}
return nil
}
func main() {
err := controller()
if err != nil {
log.Error(context.Background(), "Operation failed", err)
}
}
```
6. **Handling logs for API RPC calls and non-RPC applications**
For API RPC calls using gRPC, logs at the information level are printed by middleware on the gRPC server side, reducing the need to manually log in each RPC method. For non-RPC applications, it's recommended to manually log key execution paths to track the application's execution flow.
**gRPC Server-Side Logging Middleware:**
In gRPC, `UnaryInterceptor` and `StreamInterceptor` can intercept Unary and Stream type RPC calls, respectively. Here's an example of how to implement a simple Unary RPC logging middleware:
```go
package main
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"log"
"time"
)
// unaryServerInterceptor returns a new unary server interceptor that logs each request.
func unaryServerInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
// Record the start time of the request
start := time.Now()
// Call the actual RPC method
resp, err = handler(ctx, req)
// After the request ends, log the duration and other information
log.Printf("Request method: %s, duration: %s, error status: %v", info.FullMethod, time.Since(start), status.Code(err))
return resp, err
}
}
func main() {
// Create a gRPC server and add the middleware
s := grpc.NewServer
(grpc.UnaryInterceptor(unaryServerInterceptor()))
// Register your service
// Start the gRPC server
log.Println("Starting gRPC server...")
// ...
}
```
**Logging for Non-RPC Applications:**
For non-RPC applications, the key is to log at appropriate places in the code to maintain an execution trace. Here's a simple example showing how to log when handling a task:
```go
package main
import (
"log"
)
func processTask(taskID string) {
// Log the start of task processing
log.Printf("Starting task processing: %s", taskID)
// Suppose this is where the task is processed
// Log after the task is completed
log.Printf("Task processing completed: %s", taskID)
}
func main() {
// Example task ID
taskID := "task123"
processTask(taskID)
}
```
In both scenarios, appropriate logging can help developers and operators monitor the health of the system, trace the source of issues, and quickly locate and resolve problems. For gRPC logging, using middleware can effectively centralize log management and control. For non-RPC applications, ensuring logs are placed at critical execution points can help understand the program's operational flow and state changes.
### When to Wrap Errors?
1. **Wrap errors generated within the function**
When an error occurs within a function, use `errs.Wrap` to add context information to the original error.
**Code Example**:
```go
func doSomething() error {
// Suppose an error occurs here
err, _ := someFunc()
if err != nil {
return errs.WrapMsg(err, "doSomething failed")
}
}
```
It just works if the package is wrong:
```go
func doSomething() error {
// Suppose an error occurs here
err, _ := someFunc()
if err != nil {
return errs.Wrap(err)
}
}
```
2. **Wrap errors from system calls or other packages**
When calling external libraries or system functions that return errors, also add context information to wrap the error.
**Code Example**:
```go
func readConfig(file string) error {
_, err := os.ReadFile(file)
if err != nil {
return errs.Wrap(err, "Failed to read config file")
}
return nil
}
```
3. **No need to re-wrap errors for internal module calls**
If an error has been appropriately wrapped with sufficient context information in an internal module call, there's no need to wrap it again.
**Code Example**:
```go
func doSomething() error {
err := doAnotherThing()
if err != nil {
return err
}
return nil
}
```
4. **Ensure comprehensive wrapping of errors with detailed messages**
When wrapping errors, ensure to provide ample context information to make the error more understandable and easier to debug.
**Code Example**:
```go
func connectDatabase() error {
err := db.Connect(config.DatabaseURL)
if err != nil {
return errs.Wrap(err, fmt.Sprintf("Failed to connect to database, URL: %s", config.DatabaseURL))
}
return nil
}
```
### About WrapMsg Use
```go
// "github.com/openimsdk/tools/errs"
func WrapMsg(err error, msg string, kv ...any) error {
if len(kv) == 0 {
if len(msg) == 0 {
return errors.WithStack(err)
} else {
return errors.WithMessage(err, msg)
}
}
var buf bytes.Buffer
if len(msg) > 0 {
buf.WriteString(msg)
buf.WriteString(" ")
}
for i := 0; i < len(kv); i += 2 {
if i > 0 {
buf.WriteString(", ")
}
buf.WriteString(toString(kv[i]))
buf.WriteString("=")
buf.WriteString(toString(kv[i+1]))
}
return errors.WithMessage(err, buf.String())
}
```
1. **Function Signature**:
- `err error`: The original error object.
- `msg string`: The message text to append to the error.
- `kv ...any`: A variable number of parameters used to pass key-value pairs. `any` was introduced in Go 1.18 and is equivalent to `interface{}`, meaning any type.
2. **Logic**:
- If there are no key-value pairs (`kv` is empty):
- If `msg` is also empty, use `errors.WithStack(err)` to return the original error with the call stack appended.
- If `msg` is not empty, use `errors.WithMessage(err, msg)` to append the message text to the original error.
- If there are key-value pairs, the function constructs a string containing the message text and all key-value pairs. The key-value pairs are added in the format `"key=value"`, separated by commas. If a message text is provided, it is added first, followed by a space.
3. **Key-Value Pair Formatting**:
- A loop iterates over all the key-value pairs, processing one pair at a time.
- The `toString` function (although not provided in the code, we can assume it converts any type to a string) is used to convert both keys and values to strings, and they are added to a `bytes.Buffer` in the format `"key=value"`.
4. **Result**:
- Use `errors.WithMessage(err, buf.String())` to append the constructed message text to the original error, and return this new error object.
Next, let's demonstrate several ways to use the `WrapMsg` function:
**Example 1: No Additional Information**
```go
// "github.com/openimsdk/tools/errs"
err := errors.New("original error")
wrappedErr := errs.WrapMsg(err, "")
// wrappedErr will contain the original error and its call stack
```
**Example 2: Message Text Only**
```go
// "github.com/openimsdk/tools/errs"
err := errors.New("original error")
wrappedErr := errs.WrapMsg(err, "additional error information")
// wrappedErr will contain the original error, call stack, and "additional error information"
```
**Example 3: Message Text and Key-Value Pairs**
```go
// "github.com/openimsdk/tools/errs"
err := errors.New("original error")
wrappedErr := errs.WrapMsg(err, "problem occurred", "code", 404, "url", "webhook://example.com")
// wrappedErr will contain the original error, call stack, and "problem occurred code=404, url=http://example.com"
```
**Example 4: Key-Value Pairs Only**
```go
// "github.com/openimsdk/tools/errs"
err := errors.New("original error")
wrappedErr := errs.WrapMsg(err, "", "user", "john_doe", "action", "login")
// wrappedErr will contain the original error, call stack, and "user=john_doe, action=login"
```
> [!TIP] WThese examples demonstrate how the `errs.WrapMsg` function can flexibly handle error messages and context data, helping developers to more effectively track and debug their programs.
### Example 5: Dynamic Key-Value Pairs from Context
Suppose we have some runtime context variables, such as a user ID and the type of operation being performed, and we want to include these variables in the error message. This can help with later debugging and identifying the specific environment of the issue.
```go
// Define some context variables
userID := "user123"
operation := "update profile"
errorCode := 500
requestURL := "webhook://example.com/updateProfile"
// Create a new error
err := errors.New("original error")
// Wrap the error, including dynamic key-value pairs from the context
wrappedErr := errs.WrapMsg(err, "operation failed", "user", userID, "action", operation, "code", errorCode, "url", requestURL)
// wrappedErr will contain the original error, call stack, and "operation failed user=user123, action=update profile, code=500, url=http://example.com/updateProfile"
```
> [!TIP]In this example, the `WrapMsg` function accepts not just a static error message and additional information, but also dynamic key-value pairs generated from the code's execution context, such as the user ID, operation type, error code, and the URL of the request. Including this contextual information in the error message makes it easier for developers to understand and resolve the issue.

View File

@@ -0,0 +1,258 @@
# Mac Developer Deployment Guide for OpenIM
## Introduction
This guide aims to assist Mac-based developers in contributing effectively to OpenIM. It covers the setup of a development environment tailored for Mac, including the use of GitHub for development workflow and `devcontainer` for a consistent development experience.
Before contributing to OpenIM through issues and pull requests, make sure you are familiar with GitHub and the [pull request workflow](https://docs.github.com/en/get-started/quickstart/github-flow).
## Prerequisites
### System Requirements
- macOS (latest stable version recommended)
- Internet connection
- Administrator access
### Knowledge Requirements
- Basic understanding of Git and GitHub
- Familiarity with Docker and containerization
- Experience with Go programming language
## Setting up the Development Environment
### Installing Homebrew
Homebrew is an essential package manager for macOS. Install it using:
```sh
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```
### Installing and Configuring Git
1. Install Git:
```sh
brew install git
```
2. Configure Git with your user details:
```sh
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
```
### Setting Up the Devcontainer
`Devcontainers` provide a Docker-based isolated development environment.
Read [README.md](https://github.com/openimsdk/open-im-server-deploy/tree/main/.devcontainer) in the `.devcontainer` directory of the project to learn more about the devcontainer.
To set it up:
1. Install Docker Desktop for Mac from [Docker Hub](https://docs.docker.com/desktop/install/mac-install/).
2. Install Visual Studio Code and the Remote - Containers extension.
3. Open the cloned OpenIM repository in VS Code.
4. VS Code will prompt to reopen the project in a container. Accept this to set up the environment automatically.
### Installing Go and Dependencies
Use Homebrew to install Go:
```sh
brew install go
```
Ensure the version of Go is compatible with the version required by OpenIM (refer to the main documentation for version requirements).
### Additional Tools
Install other required tools like Docker, Vagrant, and necessary GNU utils as described in the main documentation.
## Mac Deployment openim-chat and openim-server
To integrate the Chinese document into an English document for Linux deployment, we will first translate the content and then adapt it to suit the Linux environment. Here's how the translated and adapted content might look:
### Ensure a Clean Environment
- It's recommended to execute in a new directory.
- Run `ps -ef | grep openim` to ensure no OpenIM processes are running.
- Run `ps -ef | grep chat` to check for absence of chat-related processes.
- Execute `docker ps` to verify there are no related containers running.
### Source Code Deployment
#### Deploying openim-server
Source code deployment is slightly more complex because Docker's networking on Linux differs from Mac.
```bash
git clone https://github.com/openimsdk/open-im-server-deploy
cd open-im-server-deploy
export OPENIM_IP="Your IP" # If it's a cloud server, setting might not be needed
make init # Generates configuration files
```
Before deploying openim-server, modify the Kafka logic in the docker-compose.yml file. Replace:
```yaml
- KAFKA_CFG_ADVERTISED_LISTENERS=PLAINTEXT://kafka:9092,EXTERNAL://${DOCKER_BRIDGE_GATEWAY:-172.28.0.1}:${KAFKA_PORT:-19094}
```
With:
```yaml
- KAFKA_CFG_ADVERTISED_LISTENERS=PLAINTEXT://kafka:9092,EXTERNAL://127.0.0.1:${KAFKA_PORT:-19094}
```
Then start the service:
```bash
docker compose up -d
```
Before starting the openim-server source, set `config/config.yaml` by replacing all instances of `172.28.0.1` with `127.0.0.1`:
```bash
vim config/config.yaml -c "%s/172\.28\.0\.1/127.0.0.1/g" -c "wq"
```
Then start openim-server:
```bash
make start
```
To check the startup:
```bash
make check
```
<aside>
🚧 To avoid mishaps, it's best to wait five minutes before running `make check` again.
</aside>
#### Deploying openim-chat
There are several ways to deploy openim-chat, either by source code or using Docker.
Navigate back to the parent directory:
```bash
cd ..
```
First, let's look at deploying chat from source:
```bash
git clone https://github.com/openimsdk/chat
cd chat
make init # Generates configuration files
```
If openim-chat has not deployed MySQL, you will need to deploy it. Note that the official Docker Hub for MySQL does not support architectures like ARM, so you can use the newer version of the open-source edition:
```bash
docker run -d \
--name mysql \
-p 13306:3306 \
-p 3306:33060 \
-v "$(pwd)/components/mysql/data:/var/lib/mysql" \
-v "/etc/localtime:/etc/localtime" \
-e MYSQL_ROOT_PASSWORD="openIM123" \
--restart always \
mariadb:10.6
```
Before starting the source code of openim-chat, set `config/config.yaml` by replacing all instances of `172.28.0.1` with `127.0.0.1`:
```bash
vim config/config.yaml -c "%s/172\.28\.0\.1/127.0.0.1/g" -c "wq"
```
Then start openim-chat from source:
```bash
make start
```
To check, ensure the following four processes start successfully:
```bash
make check
```
### Docker Deployment
Refer to https://github.com/openimsdk/openim-docker for Docker deployment instructions, which can be followed similarly on Linux.
```bash
git clone https://github.com/openimsdk/openim-docker
cd openim-docker
export OPENIM_IP="Your IP"
make init
docker compose up -d
docker compose logs -f openim-server
docker compose logs -f openim-chat
```
## GitHub Development Workflow
### Creating a New Branch
For new features or fixes, create a new branch:
```sh
git checkout -b feat/your-feature-name
```
### Making Changes and Committing
1. Make your changes in the code.
2. Stage your changes:
```sh
git add .
```
3. Commit with a meaningful message:
```sh
git commit -m "Add a brief description of your changes"
```
### Pushing Changes and Creating Pull Requests
1. Push your branch to GitHub:
```sh
git push origin feat/your-feature-name
```
2. Go to your fork on GitHub and create a pull request to the main OpenIM repository.
### Keeping Your Fork Updated
Regularly sync your fork with the main repository:
```sh
git fetch upstream
git checkout main
git rebase upstream/main
```
More read: [https://github.com/openimsdk/open-im-server-deploy/blob/main/CONTRIBUTING.md](https://github.com/openimsdk/open-im-server-deploy/blob/main/CONTRIBUTING.md)
## Testing and Quality Assurance
Run tests as described in the OpenIM documentation to ensure your changes do not break existing functionality.
## Conclusion
This guide provides a comprehensive overview for Mac developers to set up and contribute to OpenIM. By following these steps, you can ensure a smooth and efficient development experience. Happy coding!

View File

@@ -0,0 +1,178 @@
# OpenIM Offline Deployment Design
## 1. Base Images
Below are the base images and their versions you'll need:
- [ ] bitnami/kafka:3.5.1
- [ ] redis:7.0.0
- [ ] mongo:6.0.2
- [ ] bitnami/zookeeper:3.8
- [ ] minio/minio:RELEASE.2024-01-11T07-46-16Z
> [!IMPORTANT]
> It is important to note that OpenIM removed mysql components from versions v3.5.0 (release-v3.5) and above, so mysql can be deployed without this requirement or above
**If you need to install more IM components or monitoring products**
OpenIM:
> [!TIP]
> If you need to install more IM components or monitoring products [images.md](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/images.md)
- [ ] ghcr.io/openimsdk/openim-web:<version-name>
- [ ] ghcr.io/openimsdk/openim-admin:<version-name>
- [ ] ghcr.io/openimsdk/openim-chat:<version-name>
- [ ] ghcr.io/openimsdk/openim-server:<version-name>
Monitoring:
- [ ] prom/prometheusv2.48.1
- [ ] prom/alertmanagerv0.23.0
- [ ] grafana/grafana10.2.2
- [ ] bitnami/node-exporter1.7.0
Use the following commands to pull these base images:
```bash
docker pull bitnami/kafka:3.5.1
docker pull redis:7.0.0
docker pull mongo:6.0.2
docker pull mariadb:10.6
docker pull bitnami/zookeeper:3.8
docker pull minio/minio:2024-01-11T07-46-16Z
```
If you need to install more IM components or monitoring products:
```bash
docker pull prom/prometheus:v2.48.1
docker pull prom/alertmanager:v0.23.0
docker pull grafana/grafana:10.2.2
docker pull bitnami/node-exporter:1.7.0
```
## 2. OpenIM Images
**For detailed understanding of version management and storage of OpenIM and Chat**: [version.md](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/version.md)
### OpenIM Image
- Get image version info: [images.md](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/images.md)
- Depending on the required version, execute the following command:
```bash
docker pull ghcr.io/openimsdk/openim-server:<version-name>
```
### Chat Image
- Execute the following command to pull the image:
```bash
docker pull ghcr.io/openimsdk/openim-chat:<version-name>
```
### Web Image
- Execute the following command to pull the image:
```bash
docker pull ghcr.io/openimsdk/openim-web:<version-name>
```
### Admin Image
- Execute the following command to pull the image:
```bash
docker pull ghcr.io/openimsdk/openim-admin:<version-name>
```
## 3. Image Storage Selection
**Repositories**:
- Alibaba Cloud: `registry.cn-hangzhou.aliyuncs.com/openimsdk/openim-server`
- Docker Hub: `openim/openim-server`
**Version Selection**:
- Stable: e.g. release-v3.2 (or 3.1, 3.3)
- Latest: latest
- Latest of main: main
## 4. Version Selection
You can select from the following versions:
- Stable: e.g. release-v3.2
- Latest: latest
- Latest from main branch: main
## 5. Offline Deployment Steps
1. **Pull images**: Execute the above `docker pull` commands to pull all required images locally.
2. **Save images**:
```bash
docker save -o <tar-file-name>.tar <image-name>
```
If you want to save all the images, use the following command:
```bash
docker save -o <tar-file-name>.tar $(docker images -q)
```
3. **Fetch code**: Clone the repository:
```bash
git clone https://github.com/openimsdk/openim-docker.git
```
Or download the code from [Releases](https://github.com/openimsdk/openim-docker/releases/).
> Because of the difference between win and linux newlines, please do not clone the repository with win and then synchronize scp to linux.
4. **Transfer files**: Use `scp` to transfer all images and code to the intranet server.
```bash
scp <tar-file-name>.tar user@remote-ip:/path/on/remote/server
```
Or choose other transfer methods such as a hard drive.
5. **Import images**: On the intranet server:
```bash
docker load -i <tar-file-name>.tar
```
Import directly with shortcut commands:
```bash
for i in `ls ./`;do docker load -i $i;done
```
6. **Deploy**: Navigate to the `openim-docker` repository directory and follow the [README guide](https://github.com/openimsdk/openim-docker) for deployment.
7. **Deploy using docker compose**:
```bash
export OPENIM_IP="your ip" # Set Ip
make init # Init config
docker compose up -d # Deployment
docker compose ps # Verify
```
> **Note**: If you're using a version of Docker prior to 20, make sure you've installed `docker-compose`.
## 6. Reference Links
- [openimsdk Issue #432](https://github.com/openimsdk/open-im-server-deploy/issues/432)
- [Notion Link](https://nsddd.notion.site/435ee747c0bc44048da9300a2d745ad3?pvs=25)
- [openimsdk Issue #474](https://github.com/openimsdk/open-im-server-deploy/issues/474)

View File

@@ -0,0 +1,326 @@
# Deployment and Design of OpenIM's Management Backend and Monitoring
<!-- vscode-markdown-toc -->
* 1. [Source Code & Docker](#SourceCodeDocker)
* 1.1. [Deployment](#Deployment)
* 1.2. [Configuration](#Configuration)
* 1.3. [Monitoring Running in Docker Guide](#MonitoringRunninginDockerGuide)
* 1.3.1. [Introduction](#Introduction)
* 1.3.2. [Prerequisites](#Prerequisites)
* 1.3.3. [Step 1: Clone the Repository](#Step1:ClonetheRepository)
* 1.3.4. [Step 2: Start Docker Compose](#Step2:StartDockerCompose)
* 1.3.5. [Step 3: Use the OpenIM Web Interface](#Step3:UsetheOpenIMWebInterface)
* 1.3.6. [Running Effect](#RunningEffect)
* 1.3.7. [Step 4: Access the Admin Panel](#Step4:AccesstheAdminPanel)
* 1.3.8. [Step 5: Access the Monitoring Interface](#Step5:AccesstheMonitoringInterface)
* 1.3.9. [Next Steps](#NextSteps)
* 1.3.10. [Troubleshooting](#Troubleshooting)
* 2. [Kubernetes](#Kubernetes)
* 2.1. [Middleware Monitoring](#MiddlewareMonitoring)
* 2.2. [Custom OpenIM Metrics](#CustomOpenIMMetrics)
* 2.3. [Node Exporter](#NodeExporter)
* 3. [Setting Up and Configuring AlertManager Using Environment Variables and `make init`](#SettingUpandConfiguringAlertManagerUsingEnvironmentVariablesandmakeinit)
* 3.1. [Introduction](#Introduction-1)
* 3.2. [Prerequisites](#Prerequisites-1)
* 3.3. [Configuration Steps](#ConfigurationSteps)
* 3.3.1. [Exporting Environment Variables](#ExportingEnvironmentVariables)
* 3.3.2. [Initializing AlertManager](#InitializingAlertManager)
* 3.3.3. [Key Configuration Fields](#KeyConfigurationFields)
* 3.3.4. [Configuring SMTP Authentication Password](#ConfiguringSMTPAuthenticationPassword)
* 3.3.5. [Useful Links for Common Email Servers](#UsefulLinksforCommonEmailServers)
* 3.4. [Conclusion](#Conclusion)
<!-- vscode-markdown-toc-config
numbering=true
autoSave=true
/vscode-markdown-toc-config -->
<!-- /vscode-markdown-toc -->
OpenIM offers various flexible deployment options to suit different environments and requirements. Here is a simplified and optimized description of these deployment options:
1. Source Code Deployment:
+ **Regular Source Code Deployment**: Deployment using the `nohup` method. This is a basic deployment method suitable for development and testing environments. For details, refer to the [Regular Source Code Deployment Guide](https://docs.openim.io/).
+ **Production-Level Deployment**: Deployment using the `system` method, more suitable for production environments. This method provides higher stability and reliability. For details, refer to the [Production-Level Deployment Guide](https://docs.openim.io/guides/gettingStarted/install-openim-linux-system).
2. Cluster Deployment:
+ **Kubernetes Deployment**: Provides two deployment methods, including deployment through Helm and sealos. This is suitable for environments that require high availability and scalability. Specific methods can be found in the [Kubernetes Deployment Guide](https://docs.openim.io/guides/gettingStarted/k8s-deployment).
3. Docker Deployment:
+ **Regular Docker Deployment**: Suitable for quick deployments and small projects. For detailed information, refer to the [Docker Deployment Guide](https://docs.openim.io/guides/gettingStarted/dockerCompose).
+ **Docker Compose Deployment**: Provides more convenient service management and configuration, suitable for complex multi-container applications.
Next, we will introduce the specific steps, monitoring, and management backend configuration for each of these deployment methods, as well as usage tips to help you choose the most suitable deployment option according to your needs.
## 1. <a name='SourceCodeDocker'></a>Source Code & Docker
### 1.1. <a name='Deployment'></a>Deployment
OpenIM deploys openim-server and openim-chat from source code, while other components are deployed via Docker.
For Docker deployment, you can deploy all components with a single command using the [openimsdk/openim-docker](https://github.com/openimsdk/openim-docker) repository. The deployment configuration can be found in the [environment.sh](https://github.com/openimsdk/open-im-server-deploy/blob/main/scripts/install/environment.sh) document, which provides information on how to learn and familiarize yourself with various environment variables.
For Prometheus, it is not enabled by default. To enable it, set the environment variable before executing `make init`:
```bash
export PROMETHEUS_ENABLE=true # Default is false
```
Then, execute:
```bash
make init
docker compose up -d
```
### 1.2. <a name='Configuration'></a>Configuration
To configure Prometheus data sources in Grafana, follow these steps:
1. **Log in to Grafana**: First, open your web browser and access the Grafana URL. If you haven't changed the port, the address is typically [http://localhost:13000](http://localhost:13000/).
2. **Log in with default credentials**: Grafana's default username and password are both `admin`. You will be prompted to change the password on your first login.
3. **Access Data Sources Settings**:
+ In the left menu of Grafana, look for and click the "gear" icon representing "Configuration."
+ In the configuration menu, select "Data Sources."
4. **Add a New Data Source**:
+ On the Data Sources page, click the "Add data source" button.
+ In the list, find and select "Prometheus."
![image-20231114175117374](http://sm.nsddd.top/sm202311141751692.png)
Click `Add New connection` to add more data sources, such as Loki (responsible for log storage and query processing).
5. **Configure the Prometheus Data Source**:
+ On the configuration page, fill in the details of the Prometheus server. This typically includes the URL of the Prometheus service (e.g., if Prometheus is running on the same machine as OpenIM, the URL might be `http://172.28.0.1:19090`, with the address matching the `DOCKER_BRIDGE_GATEWAY` variable address). OpenIM and the components are linked via a gateway. The default port used by OpenIM is `19090`.
+ Adjust other settings as needed, such as authentication and TLS settings.
![image-20231114180351923](http://sm.nsddd.top/sm202311141803076.png)
6. **Save and Test**:
+ After completing the configuration, click the "Save & Test" button to ensure that Grafana can successfully connect to Prometheus.
**Importing Dashboards in Grafana**
Importing Grafana Dashboards is a straightforward process and is applicable to OpenIM Server application services and Node Exporter. Here are detailed steps and necessary considerations:
**Key Metrics Overview and Deployment Steps**
To monitor OpenIM in Grafana, you need to focus on three categories of key metrics, each with its specific deployment and configuration steps:
**OpenIM Metrics (`prometheus-dashboard.yaml`)**:
- **Configuration File Path**: Find this at `config/prometheus-dashboard.yaml`.
- **Enabling Monitoring**: Activate Prometheus monitoring by setting the environment variable: `export PROMETHEUS_ENABLE=true`.
- **More Information**: For detailed instructions, see the [OpenIM Configuration Guide](https://docs.openim.io/configurations/prometheus-integration).
**Node Exporter**:
- **Container Deployment**: Use the container `quay.io/prometheus/node-exporter` for effective node monitoring.
- **Access Dashboard**: Visit the [Node Exporter Full Feature Dashboard](https://grafana.com/grafana/dashboards/1860-node-exporter-full/) for dashboard integration either through YAML file download or ID.
- **Deployment Guide**: For deployment steps, consult the [Node Exporter Deployment Documentation](https://prometheus.io/docs/guides/node-exporter/).
**Middleware Metrics**: Different middlewares require unique steps and configurations for monitoring:
- MySQL:
- **Configuration**: Make sure MySQL is set up for performance monitoring.
- **Guide**: See the [MySQL Monitoring Configuration Guide](https://grafana.com/docs/grafana/latest/datasources/mysql/).
- Redis:
- **Configuration**: Adjust Redis settings to enable monitoring data export.
- **Guide**: Consult the [Redis Monitoring Guide](https://grafana.com/docs/grafana/latest/datasources/redis/).
- MongoDB:
- **Configuration**: Configure MongoDB for monitoring metrics.
- **Guide**: Visit the [MongoDB Monitoring Guide](https://grafana.com/grafana/plugins/grafana-mongodb-datasource/).
- Kafka:
- **Configuration**: Set up Kafka for Prometheus monitoring integration.
- **Guide**: Refer to the [Kafka Monitoring Guide](https://grafana.com/grafana/plugins/grafana-kafka-datasource/).
- Zookeeper:
- **Configuration**: Ensure Prometheus can monitor Zookeeper.
- **Guide**: Check out the [Zookeeper Monitoring Configuration](https://grafana.com/docs/grafana/latest/datasources/zookeeper/).
**Importing Steps**:
1. Access the Dashboard Import Interface:
+ Click the `+` icon on the left menu or in the top right corner of Grafana, then select "Create."
+ Choose "Import" to access the dashboard import interface.
2. **Perform Dashboard Import**:
+ **Upload via File**: Directly upload your YAML file.
+ **Paste Content**: Open the YAML file, copy its content, and paste it into the import interface.
+ **Import via Grafana.com Dashboard**: Visit [Grafana Dashboards](https://grafana.com/grafana/dashboards/), search for the desired dashboard, and import it using its ID.
3. **Configure the Dashboard**:
+ Select the appropriate data source, such as the previously configured Prometheus.
+ Adjust other settings, such as the dashboard name or folder.
4. **Save and View the Dashboard**:
+ After configuring, click "Import" to complete the process.
+ Immediately view the new dashboard after successful import.
**Graph Examples:**
![image-20231114194451673](http://sm.nsddd.top/sm202311141944953.png)
### 1.3. <a name='MonitoringRunninginDockerGuide'></a>Monitoring Running in Docker Guide
#### 1.3.1. <a name='Introduction'></a>Introduction
This guide provides the steps to run OpenIM using Docker. OpenIM is an open-source instant messaging solution that can be quickly deployed using Docker. For more information, please refer to the [OpenIM Docker GitHub](https://github.com/openimsdk/openim-docker).
#### 1.3.2. <a name='Prerequisites'></a>Prerequisites
+ Ensure that Docker and Docker Compose are installed.
+ Basic understanding of Docker and containerization technology.
#### 1.3.3. <a name='Step1:ClonetheRepository'></a>Step 1: Clone the Repository
First, clone the OpenIM Docker repository:
```bash
git clone https://github.com/openimsdk/openim-docker.git
```
Navigate to the repository directory and check the `README` file for more information and configuration options.
#### 1.3.4. <a name='Step2:StartDockerCompose'></a>Step 2: Start Docker Compose
In the repository directory, run the following command to start the service:
```bash
docker-compose up -d
```
This will download the required Docker images and start the OpenIM service.
#### 1.3.5. <a name='Step3:UsetheOpenIMWebInterface'></a>Step 3: Use the OpenIM Web Interface
+ Open a browser in private mode and access [OpenIM Web](http://localhost:11001/).
+ Register two users and try adding friends.
+ Test sending messages and pictures.
#### 1.3.6. <a name='RunningEffect'></a>Running Effect
![image-20231115100811208](http://sm.nsddd.top/sm202311151008639.png)
#### 1.3.7. <a name='Step4:AccesstheAdminPanel'></a>Step 4: Access the Admin Panel
+ Access the [OpenIM Admin Panel](http://localhost:11002/).
+ Log in using the default username and password (`admin1:admin1`).
Running Effect Image:
![image-20231115101039837](http://sm.nsddd.top/sm202311151010116.png)
#### 1.3.8. <a name='Step5:AccesstheMonitoringInterface'></a>Step 5: Access the Monitoring Interface
+ Log in to the [Monitoring Interface](http://localhost:3000/login) using the credentials (`admin:admin`).
#### 1.3.9. <a name='NextSteps'></a>Next Steps
+ Configure and manage the services following the steps provided in the OpenIM source code.
+ Refer to the `README` file for advanced configuration and management.
#### 1.3.10. <a name='Troubleshooting'></a>Troubleshooting
+ If you encounter any issues, please check the documentation on [OpenIM Docker GitHub](https://github.com/openimsdk/openim-docker) or search for related issues in the Issues section.
+ If the problem persists, you can create an issue on the [openim-docker](https://github.com/openimsdk/openim-docker/issues/new/choose) repository or the [openim-server](https://github.com/openimsdk/open-im-server-deploy/issues/new/choose) repository.
## 2. <a name='Kubernetes'></a>Kubernetes
Refer to [openimsdk/helm-charts](https://github.com/openimsdk/helm-charts).
When deploying and monitoring OpenIM in a Kubernetes environment, you will focus on three main metrics: middleware, custom OpenIM metrics, and Node Exporter. Here are detailed steps and guidelines:
### 2.1. <a name='MiddlewareMonitoring'></a>Middleware Monitoring
Middleware monitoring is crucial to ensure the overall system's stability. Typically, this includes monitoring the following components:
+ **MySQL**: Monitor database performance, query latency, and more.
+ **Redis**: Track operation latency, memory usage, and more.
+ **MongoDB**: Observe database operations, resource usage, and more.
+ **Kafka**: Monitor message throughput, latency, and more.
+ **Zookeeper**: Keep an eye on cluster status, performance metrics, and more.
For Kubernetes environments, you can use the corresponding Prometheus Exporters to collect monitoring data for these middleware components.
### 2.2. <a name='CustomOpenIMMetrics'></a>Custom OpenIM Metrics
Custom OpenIM metrics provide essential information about the OpenIM application itself, such as user activity, message traffic, system performance, and more. To monitor these metrics in Kubernetes:
+ Ensure OpenIM application configurations expose Prometheus metrics.
+ When deploying using Helm charts (refer to [OpenIM Helm Charts](https://github.com/openimsdk/helm-charts)), pay attention to configuring relevant monitoring settings.
### 2.3. <a name='NodeExporter'></a>Node Exporter
Node Exporter is used to collect hardware and operating system-level metrics for Kubernetes nodes, such as CPU, memory, disk usage, and more. To integrate Node Exporter in Kubernetes:
+ Deploy Node Exporter using the appropriate Helm chart. You can find information and guides on [Prometheus Community](https://prometheus.io/docs/guides/node-exporter/).
+ Ensure Node Exporter's data is collected by Prometheus instances within your cluster.
## 3. <a name='SettingUpandConfiguringAlertManagerUsingEnvironmentVariablesandmakeinit'></a>Setting Up and Configuring AlertManager Using Environment Variables and `make init`
### 3.1. <a name='Introduction-1'></a>Introduction
AlertManager, a component of the Prometheus monitoring system, handles alerts sent by client applications such as the Prometheus server. It takes care of deduplicating, grouping, and routing them to the correct receiver. This document outlines how to set up and configure AlertManager using environment variables and the `make init` command. We will focus on configuring key fields like the sender's email, SMTP settings, and SMTP authentication password.
### 3.2. <a name='Prerequisites-1'></a>Prerequisites
+ Basic knowledge of terminal and command-line operations.
+ AlertManager installed on your system.
+ Access to an SMTP server for sending emails.
### 3.3. <a name='ConfigurationSteps'></a>Configuration Steps
#### 3.3.1. <a name='ExportingEnvironmentVariables'></a>Exporting Environment Variables
Before initializing AlertManager, you need to set environment variables. These variables are used to configure the AlertManager settings without altering the code. Use the `export` command in your terminal. Here are some key variables you might set:
+ `export ALERTMANAGER_RESOLVE_TIMEOUT='5m'`
+ `export ALERTMANAGER_SMTP_FROM='alert@example.com'`
+ `export ALERTMANAGER_SMTP_SMARTHOST='smtp.example.com:465'`
+ `export ALERTMANAGER_SMTP_AUTH_USERNAME='alert@example.com'`
+ `export ALERTMANAGER_SMTP_AUTH_PASSWORD='your_password'`
+ `export ALERTMANAGER_SMTP_REQUIRE_TLS='false'`
#### 3.3.2. <a name='InitializingAlertManager'></a>Initializing AlertManager
After setting the necessary environment variables, you can initialize AlertManager by running the `make init` command. This command typically runs a script that prepares AlertManager with the provided configuration.
#### 3.3.3. <a name='KeyConfigurationFields'></a>Key Configuration Fields
##### a. Sender's Email (`ALERTMANAGER_SMTP_FROM`)
This variable sets the email address that will appear as the sender in the notifications sent by AlertManager.
##### b. SMTP Configuration
+ **SMTP Server (`ALERTMANAGER_SMTP_SMARTHOST`):** Specifies the address and port of the SMTP server used for sending emails.
+ **SMTP Authentication Username (`ALERTMANAGER_SMTP_AUTH_USERNAME`):** The username for authenticating with the SMTP server.
+ **SMTP Authentication Password (`ALERTMANAGER_SMTP_AUTH_PASSWORD`):** The password for SMTP server authentication. It's crucial to keep this value secure.
#### 3.3.4. <a name='ConfiguringSMTPAuthenticationPassword'></a>Configuring SMTP Authentication Password
The SMTP authentication password can be set using the `ALERTMANAGER_SMTP_AUTH_PASSWORD` environment variable. It's recommended to use a secure method to set this variable to avoid exposing sensitive information. For instance, you might read the password from a secure file or a secret management tool.
#### 3.3.5. <a name='UsefulLinksforCommonEmailServers'></a>Useful Links for Common Email Servers
For specific configurations related to common email servers, you may refer to their respective documentation:
+ Gmail SMTP Settings:
+ [Gmail SMTP Configuration](https://support.google.com/mail/answer/7126229?hl=en)
+ Microsoft Outlook SMTP Settings:
+ [Outlook Email Settings](https://support.microsoft.com/en-us/office/pop-imap-and-smtp-settings-8361e398-8af4-4e97-b147-6c6c4ac95353)
+ Yahoo Mail SMTP Settings:
+ [Yahoo SMTP Configuration](https://help.yahoo.com/kb/SLN4724.html)
### 3.4. <a name='Conclusion'></a>Conclusion
Setting up and configuring AlertManager with environment variables provides a flexible and secure way to manage alert settings. By following the above steps, you can easily configure AlertManager for your monitoring needs. Always ensure to secure sensitive information, especially when dealing with SMTP authentication credentials.

View File

@@ -0,0 +1,60 @@
# OpenIM Protoc Tool
## Introduction
OpenIM is passionate about ensuring that its suite of tools is custom-tailored to cater to the unique needs of its users. That commitment led us to develop and release our custom Protoc tool, version v1.0.0.
### Why a Custom Version?
There are several reasons to choose our custom Protoc tool over generic open-source versions:
- **Specialized Features**: OpenIM's Protoc tool has been enriched with features and plugins that are optimized for the OpenIM ecosystem. This makes it more aligned with the needs of OpenIM users.
- **Optimized Performance**: Built from the ground up with OpenIM's infrastructure in mind, our tool guarantees faster and more efficient operations.
- **Enhanced Compatibility**: Our Protoc tool ensures full compatibility with OpenIM's offerings, minimizing potential conflicts and integration challenges.
- **Rich Output Support**: Unlike generic tools, our custom tool provides a wide array of output options including C++, C#, Java, Kotlin, Objective-C, PHP, Python, Ruby, and more. This allows developers to generate code for their preferred platform with ease.
## Download
+ https://github.com/OpenIMSDK/Open-IM-Protoc
Access the official release of the Protoc tool on the OpenIM repository here: [OpenIM Protoc Tool v1.0.0 Release](https://github.com/OpenIMSDK/Open-IM-Protoc/releases/tag/v1.0.0)
### Direct Download Links:
- **Windows**: [Download for Windows](https://github.com/OpenIMSDK/Open-IM-Protoc/releases/download/v1.0.0/windows.zip)
- **Linux**: [Download for Linux](https://github.com/OpenIMSDK/Open-IM-Protoc/releases/download/v1.0.0/linux.zip)
## Installation
For Windows:
1. Navigate to the Windows download link provided above and download the version suitable for your system.
2. Extract the contents of the zip file.
3. Add the path of the extracted tool to your `PATH` environment variable to run the Protoc tool directly from the command line.
For Linux:
1. Navigate to the Linux download link provided above and download the version suitable for your system.
2. Extract the contents of the zip file.
3. Use `chmod +x ./*` to make the extracted files executable.
4. Add the path of the extracted tool to your `PATH` environment variable to run the Protoc tool directly from the command line.
## Usage
The OpenIM Protoc tool provides a multitude of options for parsing `.proto` files and generating output:
```
./protoc [OPTION] PROTO_FILES
```
Some of the key options include:
- `--proto_path=PATH`: Specify the directory to search for imports.
- `--version`: Show version info.
- `--encode=MESSAGE_TYPE`: Convert a text-format message of a given type from standard input to binary on standard output.
- `--decode=MESSAGE_TYPE`: Convert a binary message of a given type from standard input to text format on standard output.
- `--cpp_out=OUT_DIR`: Generate C++ header and source.
- `--java_out=OUT_DIR`: Generate Java source file.
... and many more. For a full list of options, run `./protoc --help` or refer to the official documentation.

251
docs/contrib/release.md Normal file
View File

@@ -0,0 +1,251 @@
# OpenIM Release Automation Design Document
This document outlines the automation process for releasing OpenIM. You can use the `make release` command for automated publishing. We will discuss how to use the `make release` command and Github Actions CICD separately, while also providing insight into the design principles involved.
## Github Actions Automation
In our CICD pipeline, we have implemented logic for automating the release process using the goreleaser tool. To achieve this, follow these steps on your local machine or server:
```bash
git clone https://github.com/openimsdk/open-im-server-deploy
cd open-im-server-deploy
git tag -a v3.6.0 -s -m "release: xxx"
# For pre-release versions: git tag -a v3.6.0-rc.0 -s -m "pre-release: xxx"
git push origin v3.6.0
```
The remaining tasks are handled by automated processes:
+ Automatically complete the release publication on Github
+ Automatically build the `v3.6.0` version image and push it to aliyun, dockerhub, and github
Through these automated steps, we achieve rapid and efficient OpenIM version releases, simplifying the release process and enhancing productivity.
Certainly, here is the continuation of the document in English:
## Local Make Release Design
There are two primary scenarios for local usage:
+ Advanced compilation and release, manually executed locally
+ Quick compilation verification and version release, manually executed locally
**These two scenarios can also be combined, for example, by tagging locally and then releasing:**
```bash
git add .
git commit -a -s -m "release(v3.6.0): ......"
git tag v3.6.0
git release
git push origin main
```
In a local environment, you can use the `make release` command to complete the release process. The main implementation logic can be found in the `/data/workspaces/open-im-server-deploy/scripts/lib/release.sh` file. First, let's explore its usage through the help information.
### Help Information
To view the help information, execute the following command:
```bash
$ ./scripts/release.sh --help
Usage: release.sh [options]
Options:
-h, --help Display this help message
-se, --setup-env Execute environment setup
-vp, --verify-prereqs Execute prerequisite verification
-bc, --build-command Execute build command
-bi, --build-image Execute build image (default is not executed)
-pt, --package-tarballs Execute tarball packaging
-ut, --upload-tarballs Execute tarball upload
-gr, --github-release Execute GitHub release
-gc, --generate-changelog Execute changelog generation
```
### Default Behavior
If no options are provided, all operations are executed by default:
```bash
# If no options are provided, enable all operations by default
if [ "$#" -eq 0 ]; then
perform_setup_env=true
perform_verify_prereqs=true
perform_build_command=true
perform_package_tarballs=true
perform_upload_tarballs=true
perform_github_release=true
perform_generate_changelog=true
# TODO: Defaultly not enable build_image
# perform_build_image=true
fi
```
### Environment Variable Setup
Before starting, you need to set environment variables:
```bash
export TENCENT_SECRET_KEY=OZZ****************************
export TENCENT_SECRET_ID=AKI****************************
```
### Modifying COS Account and Password
If you need to change the COS account, password, and bucket information, please modify the following section in the `/data/workspaces/open-im-server-deploy/scripts/lib/release.sh` file:
```bash
readonly BUCKET="openim-1306374445"
readonly REGION="ap-guangzhou"
readonly COS_RELEASE_DIR="openim-release"
```
### GitHub Release Configuration
If you intend to use the GitHub Release feature, you also need to set the environment variable:
```bash
export GITHUB_TOKEN="your_github_token"
```
### Modifying GitHub Release Basic Information
If you need to modify the basic information of GitHub Release, please edit the following section in the `/data/workspaces/open-im-server-deploy/scripts/lib/release.sh` file:
```bash
# OpenIM GitHub account information
readonly OPENIM_GITHUB_ORG=openimsdk
readonly OPENIM_GITHUB_REPO=open-im-server-deploy
```
This setup allows you to configure and execute the local release process according to your specific needs.
### GitHub Release Versioning Rules
Firstly, it's important to note that GitHub Releases should primarily be for pre-release versions. However, goreleaser might provide a `prerelease: auto` option, which automatically marks versions with pre-release indicators like `-rc1`, `-beta`, etc., as pre-releases.
So, if your most recent tag does not have pre-release indicators such as `-rc1` or `-beta`, even if you use `make release` for pre-release versions, goreleaser might still consider them as formal releases.
To avoid this issue, I have added the `--draft` flag to github-release. This way, all releases are created as drafts.
## CICD Release Documentation Design
The release records still require manual composition for GitHub Release. This is different from github-release.
This approach ensures that all releases are initially created as drafts, allowing you to manually review and edit the release documentation on GitHub. This manual step provides more control and allows you to curate release notes and other information before making them public.
## Makefile Section
This document aims to elaborate and explain key sections of the OpenIM Release automation design, including the Makefile section and functions within the code. Below, we will provide a detailed explanation of the logic and functions of each section.
In the project's root directory, the Makefile imports a subdirectory:
```makefile
include scripts/make-rules/release.mk
```
And defines the `release` target as follows:
```makefile
## release: release the project ✨
.PHONY: release release: release.verify release.ensure-tag
@scripts/release.sh
```
### Importing Subdirectory
At the beginning of the Makefile, the `include scripts/make-rules/release.mk` statement imports the `release.mk` file from the subdirectory. This file contains rules and configurations related to releases to be used in subsequent operations.
### The `release` Target
The Makefile defines a target named `release`, which is used to execute the project's release operation. This target is marked as a phony target (`.PHONY`), meaning it doesn't represent an actual file or directory but serves as an identifier for executing a series of actions.
In the `release` target, two dependency targets are executed first: `release.verify` and `release.ensure-tag`. Afterward, the `scripts/release.sh` script is called to perform the actual release operation.
## Logic of `release.verify` and `release.ensure-tag`
```makefile
## release.verify: Check if a tool is installed and install it
.PHONY: release.verify
release.verify: tools.verify.git-chglog tools.verify.github-release tools.verify.coscmd tools.verify.coscli
## release.ensure-tag: ensure tag
.PHONY: release.ensure-tag
release.ensure-tag: tools.verify.gsemver
@scripts/ensure-tag.sh
```
### `release.verify` Target
The `release.verify` target is used to check and install tools. It depends on four sub-targets: `tools.verify.git-chglog`, `tools.verify.github-release`, `tools.verify.coscmd`, and `tools.verify.coscli`. These sub-targets aim to check if specific tools are installed and attempt to install them if they are not.
The purpose of this target is to ensure that the necessary tools required for the release process are available so that subsequent operations can be executed smoothly.
### `release.ensure-tag` Target
The `release.ensure-tag` target is used to ensure that the project has a version tag. It depends on the sub-target `tools.verify.gsemver`, indicating that it should check if the `gsemver` tool is installed before executing.
When the `release.ensure-tag` target is executed, it calls the `scripts/ensure-tag.sh` script to ensure that the project has a version tag. Version tags are typically used to identify specific versions of the project for management and release in version control systems.
## Logic of `release.sh` Script
```bash
openim::golang::setup_env
openim::build::verify_prereqs
openim::release::verify_prereqs
#openim::build::build_image
openim::build::build_command
openim::release::package_tarballs
openim::release::upload_tarballs
git push origin ${VERSION}
#openim::release::github_release
#openim::release::generate_changelog
```
The `release.sh` script is responsible for executing the actual release operations. Below is the logic of this script:
1. `openim::golang::setup_env`: This function sets up some configurations for the Golang development environment.
2. `openim::build::verify_prereqs`: This function is used to verify whether the prerequisites for building are met. This includes checking dependencies, environment variables, and more.
3. `openim::release::verify_prereqs`: Similar to the previous function, this one is used to verify whether the prerequisites for the release are met. It focuses on conditions relevant to the release.
4. `openim::build::build_command`: This function is responsible for building the project's command, which typically involves compiling the project or performing other build operations.
5. `openim::release::package_tarballs`: This function is used to package tarball files required for the release. These tarballs are usually used for distribution packages during the release.
6. `openim::release::upload_tarballs`: This function is used to upload the packaged tarball files, typically to a distribution platform or repository.
7. `git push origin ${VERSION}`: This line of command pushes the version tag to the remote Git repository's `origin` branch, marking this release in the version control system.
In the comments, you can see that there are some operations that are commented out, such as `openim::build::build_image`, `openim::release::github_release`, and `openim::release::generate_changelog`. These operations are related to building images, releasing to GitHub, and generating changelogs, and they can be enabled in the release process as needed.
Let's take a closer look at the function responsible for packaging the tarball files:
```bash
function openim::release::package_tarballs() {
# Clean out any old releases
rm -rf "${RELEASE_STAGE}" "${RELEASE_TARS}" "${RELEASE_IMAGES}"
mkdir -p "${RELEASE_TARS}"
openim::release::package_src_tarball &
openim::release::package_client_tarballs &
openim::release::package_openim_manifests_tarball &
openim::release::package_server_tarballs &
openim::util::wait-for-jobs || { openim::log::error "previous tarball phase failed"; return 1; }
openim::release::package_final_tarball & # _final depends on some of the previous phases
openim::util::wait-for-jobs || { openim::log::error "previous tarball phase failed"; return 1; }
}
```
The `openim::release::package_tarballs()` function is responsible for packaging the tarball files required for the release. Here is the specific logic of this function:
1. `rm -rf "${RELEASE_STAGE}" "${RELEASE_TARS}" "${RELEASE_IMAGES}"`: First, the function removes any old release directories and files to ensure a clean starting state.
2. `mkdir -p "${RELEASE_TARS}"`: Next, it creates a directory `${RELEASE_TARS}` to store the packaged tarball files. If the directory doesn't exist, it will be created.
3. `openim::release::package_final_tarball &`: This is an asynchronous operation that depends on some of the previous phases. It is likely used to package the final tarball file, which includes the contents of all previous asynchronous operations.
4. `openim::util::wait-for-jobs`: It waits for all asynchronous operations to complete. If any of the previous asynchronous operations fail, an error will be returned.

263
docs/contrib/test.md Normal file
View File

@@ -0,0 +1,263 @@
# OpenIM RPC Service Test Control Script Documentation
This document serves as a comprehensive guide to understanding and utilizing the `test.sh` script for testing OpenIM RPC services. The `test.sh` script is a collection of bash functions designed to test various aspects of the OpenIM RPC services, ensuring that each part of the API is functioning as expected.
+ Scriptshttps://github.com/openimsdk/open-im-server-deploy/tree/main/scripts/install/test.sh
For some complex, bulky functional tests, performance tests, and various e2e tests, We are all in the current warehouse to https://github.com/openimsdk/open-im-server-deploy/tree/main/test or https://github.com/openim-sigs/test-infra directory In the.
+ About OpenIM Feature [Test Docs](https://docs.google.com/spreadsheets/d/1zELWkwxgOOZ7u5pmYCqqaFnvZy2SVajv/edit?usp=sharing&ouid=103266350914914783293&rtpof=true&sd=true)
## Util Test
Let's restructure and enhance the document under a unified second-level heading, adding clarity and details for better comprehension and visual appeal.
---
## Development Guide
### Comprehensive Testing Instructions
#### Running Unit Tests
- **Command**: To execute unit tests, input the following in your terminal:
```
make test
```
#### Evaluating Test Coverage
- **Overview**: It's crucial to assess how much of your code is covered by tests.
- **Command**:
```bash
make cover
```
This command generates a report detailing the percentage of your code tested, ensuring adherence to quality standards.
#### Conducting API Tests
- **Purpose**: API tests validate the interaction and functionality of your application's interfaces.
- **How to Run**:
```
make test-api
```
Use this to check the integrity and reliability of your API endpoints.
#### End-to-End (E2E) Testing
- **Scope**: E2E tests simulate real-user scenarios from start to finish.
- **Execution**:
```
make test-e2e
```
This comprehensive testing ensures your application performs as expected in real-world situations.
### Crafting Unit Test Cases
#### Setup for Test Case Generation
- **Installation**: Install the `gotests` tool to generate test cases automatically.
```bash
make install.gotests
```
This command installs the `gotests` tool for test case generation.
- **Environment Preparation**: Define your test template environment variable and generate test cases as shown below:
```bash
export GOTESTS_TEMPLATE=testify
gotests -i -w -only keyFunc .
```
This prepares your environment for test case generation using the `testify` template.
#### Isolating Function Tests
- **Single Function Testing**: When you need to focus on testing a single function for detailed examination.
- **Method**:
```bash
go test -v -run TestKeyFunc
```
This command specifically runs tests for `TestKeyFunc`, allowing targeted debugging and validation.
### Important Note
- **Quality Assurance**: Throughout your development process, it is imperative to ensure that the unit test coverage meets or surpasses the standards set by OpenIM.
- **Maintaining Standards**: Regularly running your tests with
```make test```
supports maintaining high code quality and adherence to OpenIM's rigorous testing benchmarks.
## E2E Test
TODO
## Api Test
The `test.sh` script is located within the `./scripts/install/` directory of the OpenIM service's codebase. To use the script, navigate to this directory from your terminal:
```bash
cd ./scripts/install/
chmod +x test.sh
```
### Running the Entire Test Suite
To execute all available tests, you can either call the script directly or use the `make` command:
```
./test.sh openim::test::test
```
Or, if you have a `Makefile` that defines the `test-api` target:
```bash
make test-api
```
Alternatively, you can invoke specific test functions by passing them as arguments:
```
./test.sh openim::test::<function_name>
```
This `make` command should be equivalent to running `./test.sh openim::test::test`, provided that the `Makefile` is configured accordingly.
### Executing Individual Test Functions
If you wish to run a specific set of tests, you can call the relevant function by passing it as an argument to the script. Here are some examples:
**Message Tests:**
```bash
./test.sh openim::test::msg
```
**Authentication Tests:**
```bash
./test.sh openim::test::auth
```
**User Tests:**
```bash
./test.sh openim::test::user
```
**Friend Tests:**
```bash
./test.sh openim::test::friend
```
**Group Tests:**
```bash
./test.sh openim::test::group
```
Each of these commands will run the test suite associated with the specific functionality of the OpenIM service.
### Detailed Function Test Examples
T**esting Message Sending and Receiving:**
To test message functionality, the `openim::test::msg` function is called. It will register a user, send a message, and clear messages to ensure that the messaging service is operational.
```bash
./test.sh openim::test::msg
```
**Testing User Registration and Account Checks:**
The `openim::test::user` function will create new user accounts and perform a series of checks on these accounts to verify that user registration and account queries are functioning properly.
```bash
./test.sh openim::test::user
```
**Testing Friend Management:**
By invoking `openim::test::friend`, the script will test adding friends, checking friendship status, managing friend requests, and handling blacklisting.
```bash
./test.sh openim::test::friend
```
**Testing Group Operations:**
The `openim::test::group` function tests group creation, member addition, information retrieval, and member management within groups.
```bash
./test.sh openim::test::group
```
### Log Output
Each test function will output logs to the terminal to confirm the success or failure of the tests. These logs are crucial for identifying issues and verifying that each part of the service is tested thoroughly.
Each function logs its success upon completion, which aids in debugging and understanding the test flow. The success message is standardized across functions:
```
openim::log::success "<Test suite name> completed successfully."
```
By following the guidelines and instructions outlined in this document, you can effectively utilize the `test.sh` script to test and verify the OpenIM RPC services' functionality.
## Function feature
| Function Name | Corresponding API/Action | Function Purpose |
| ---------------------------------------------------- | --------------------------------------------- | ------------------------------------------------------------ |
| `openim::test::msg` | Messaging Operations | Tests all aspects of messaging, including sending, receiving, and managing messages. |
| `openim::test::auth` | Authentication Operations | Validates the authentication process and session management, including token handling and forced logout. |
| `openim::test::user` | User Account Operations | Covers testing for user account creation, retrieval, updating, and overall management. |
| `openim::test::friend` | Friend Relationship Operations | Ensures friend management functions correctly, including requests, listing, and blacklisting. |
| `openim::test::group` | Group Management Operations | Checks group-related functionalities like creation, invitation, information retrieval, and member management. |
| `openim::test::send_msg` | Send Message API | Simulates sending a message from one user to another or within a group. |
| `openim::test::revoke_msg` | Revoke Message API (TODO) | (Planned) Will test the revocation of a previously sent message. |
| `openim::test::user_register` | User Registration API | Registers a new user in the system to validate the registration process. |
| `openim::test::check_account` | Account Check API | Checks if an account exists for a given user ID. |
| `openim::test::user_clear_all_msg` | Clear All Messages API | Clears all messages for a given user to validate message history management. |
| `openim::test::get_token` | Token Retrieval API | Retrieves an authentication token to validate token management. |
| `openim::test::force_logout` | Force Logout API | Forces a logout for a test user to validate session control. |
| `openim::test::check_user_account` | User Account Existence Check API | Confirms the existence of a test user's account. |
| `openim::test::get_users` | Get Users API | Retrieves a list of users to validate user query functionality. |
| `openim::test::get_users_info` | Get User Information API | Obtains detailed information for a given user. |
| `openim::test::get_users_online_status` | Get User Online Status API | Checks the online status of a user to validate presence functionality. |
| `openim::test::update_user_info` | Update User Information API | Updates a user's information to validate account update capabilities. |
| `openim::test::get_subscribe_users_status` | Get Subscribed Users' Status API | Retrieves the status of users that a test user has subscribed to. |
| `openim::test::subscribe_users_status` | Subscribe to Users' Status API | Subscribes a test user to a set of user statuses. |
| `openim::test::set_global_msg_recv_opt` | Set Global Message Receiving Option API | Sets the message receiving option for a test user. |
| `openim::test::is_friend` | Check Friendship Status API | Verifies if two users are friends within the system. |
| `openim::test::add_friend` | Send Friend Request API | Sends a friend request from one user to another. |
| `openim::test::get_friend_list` | Get Friend List API | Retrieves the friend list of a test user. |
| `openim::test::get_friend_apply_list` | Get Friend Application List API | Retrieves friend applications for a test user. |
| `openim::test::get_self_friend_apply_list` | Get Self-Friend Application List API | Retrieves the friend applications that the user has applied for. |
| `openim::test::add_black` | Add User to Blacklist API | Adds a user to the test user's blacklist to validate blacklist functionality. |
| `openim::test::remove_black` | Remove User from Blacklist API | Removes a user from the test user's blacklist. |
| `openim::test::get_black_list` | Get Blacklist API | Retrieves the blacklist for a test user. |
| `openim::test::create_group` | Group Creation API | Creates a new group with test users to validate group creation. |
| `openim::test::invite_user_to_group` | Invite User to Group API | Invites a user to join a group to test invitation functionality. |
| `openim::test::transfer_group` | Group Ownership Transfer API | Tests the transfer of group ownership from one member to another. |
| `openim::test::get_groups_info` | Get Group Information API | Retrieves information for specified groups to validate group query functionality. |
| `openim::test::kick_group` | Kick User from Group API | Simulates kicking a user from a group to test group membership management. |
| `openim::test::get_group_members_info` | Get Group Members Information API | Obtains detailed information for members of a specified group. |
| `openim::test::get_group_member_list` | Get Group Member List API | Retrieves a list of members for a given group to ensure member listing is functional. |
| `openim::test::get_joined_group_list` | Get Joined Group List API | Retrieves a list of groups that a user has joined to validate user's group memberships. |
| `openim::test::set_group_member_info` | Set Group Member Information API | Updates the information for a group member to test the update functionality. |
| `openim::test::mute_group` | Mute Group API | Tests the ability to mute a group, disabling message notifications for its members. |
| `openim::test::cancel_mute_group` | Cancel Mute Group API | Tests the ability to cancel the mute status of a group, re-enabling message notifications. |
| `openim::test::dismiss_group` | Dismiss Group API | Tests the ability to dismiss and delete a group from the system. |
| `openim::test::cancel_mute_group_member` | Cancel Mute Group Member API | Tests the ability to cancel mute status for a specific group member. |
| `openim::test::join_group` | Join Group API (TODO) | (Planned) Will test the functionality for a user to join a specified group. |
| `openim::test::set_group_info` | Set Group Information API | Tests the ability to update the group information, such as the name or description. |
| `openim::test::quit_group` | Quit Group API | Tests the functionality for a user to leave a specified group. |
| `openim::test::get_recv_group_applicationList` | Get Received Group Application List API | Retrieves the list of group applications received by a user to validate application management. |
| `openim::test::group_application_response` | Group Application Response API (TODO) | (Planned) Will test the functionality to respond to a group join request. |
| `openim::test::get_user_req_group_applicationList` | Get User Requested Group Application List API | Retrieves the list of group applications requested by a user to validate tracking of user's applications. |
| `openim::test::mute_group_member` | Mute Group Member API | Tests the ability to mute a specific member within a group, disabling their ability to send messages. |
| `openim::test::get_group_users_req_application_list` | Get Group Users Request Application List API | Retrieves a list of user requests for group applications to validate group request management. |

8
docs/contrib/util-go.md Normal file
View File

@@ -0,0 +1,8 @@
# utils go
+ [toold readme](https://github.com/openimsdk/open-im-server-deploy/tree/main/tools)
about scripts fix:
```
"${OPENIM-ROOT}/_output/bin/tools/${platform}/${lookfor}"
```

View File

@@ -0,0 +1,90 @@
# Open-IM-Server Development Tools Guide
- [Open-IM-Server Development Tools Guide](#open-im-server-deploy-development-tools-guide)
- [Introduction](#introduction)
- [Getting Started](#getting-started)
- [Toolset Categories](#toolset-categories)
- [Installation Commands](#installation-commands)
- [Basic Installation](#basic-installation)
- [Individual Tool Installation](#individual-tool-installation)
- [Tool Verification](#tool-verification)
- [Detailed Tool Descriptions](#detailed-tool-descriptions)
- [Best Practices](#best-practices)
- [Conclusion](#conclusion)
## Introduction
Open-IM-Server boasts a robust set of tools encapsulated within its Makefile system, designed to ease development, code formatting, and tool management. This guide aims to familiarize developers with the features and usage of the Makefile toolset provided within the Open-IM-Server project.
## Getting Started
Executing `make tools` ensures verification and installation of the default tools:
- golangci-lint
- goimports
- addlicense
- deepcopy-gen
- conversion-gen
- ginkgo
- go-junit-report
- go-gitlint
The installation path is situated at `./_output/tools/`.
## Toolset Categories
The Makefile logically groups tools into different categories for better management:
- **Development Tools**: `BUILD_TOOLS`
- **Code Analysis Tools**: `ANALYSIS_TOOLS`
- **Code Generation Tools**: `GENERATION_TOOLS`
- **Testing Tools**: `TEST_TOOLS`
- **Version Control Tools**: `VERSION_CONTROL_TOOLS`
- **Utility Tools**: `UTILITY_TOOLS`
- **Tencent Cloud Object Storage Tools**: `COS_TOOLS`
## Installation Commands
1. **golangci-lint**: high performance Go code linter with integration of multiple inspection tools.
2. **goimports**: Used to format Go source files and automatically add or remove imports.
3. **addlicense**: Adds a license header to the source file.
4. **deepcopy-gen and conversions-gen **: Generate deepcopy and conversion functionality.
5. **ginkgo**: Testing framework for Go.
6. **go-junit-report**: Converts Go test output to junit xml format.
7. **go-gitlint**: For checking git commit information. ... (And so on, list all the tools according to the `make tools.help` output above)...
### Basic Installation
- `tools.install`: Installs tools mentioned in the `BUILD_TOOLS` list.
- `tools.install-all`: Installs all tools from the `ALL_TOOLS` list.
### Individual Tool Installation
- `tools.install.%`: Installs a single tool in the `$GOBIN/` directory.
- `tools.install-all.%`: Parallelly installs an individual tool located in `./tools/*`.
### Tool Verification
- `tools.verify.%`: Checks if a specific tool is installed, and if not, installs it.
## Detailed Tool Descriptions
The following commands serve the purpose of installing particular development tools:
- `install.golangci-lint`: Installs `golangci-lint`.
- `install.addlicense`: Installs `addlicense`. ... (and so on for every tool as mentioned in the provided Makefile source)...
The commands primarily leverage Go's `install` operation, fetching and installing tools from their respective repositories. This method is especially convenient as it auto-handles dependencies and installation paths. For tools not written directly with Go (like `install.coscli`), other installation methods like wget or pip are employed.
## Best Practices
1. **Regular Updates**: To ensure tools are up-to-date, periodically run the `make tools` command.
2. **Individual Tools**: If only specific tools are required, employ the `make install.<tool-name>` command for individual installations.
3. **Verification**: Before code submissions, use the `make tools.verify.%` command to guarantee that all necessary tools are present and up-to-date.
## Conclusion
The Makefile provided by Open-IM-Server presents a centralized approach to manage and install all necessary tools during the development process. It ensures that all developers employ consistent tool versions, reducing potential issues due to version disparities. Whether you're a maintainer or a contributor to the Open-IM-Server project, understanding the workings of this Makefile will significantly enhance your developmental efficiency.

View File

@@ -0,0 +1,248 @@
# OpenIM Bash Utility Script
This script offers a variety of utilities and helpers to enhance and simplify operations related to the OpenIM project.
## Table of Contents
- [OpenIM Bash Utility Script](#openim-bash-utility-script)
- [Table of Contents](#table-of-contents)
- [brief descriptions of each function](#brief-descriptions-of-each-function)
- [Introduction](#introduction)
- [Usage](#usage)
- [SSH Key Setup](#ssh-key-setup)
- [openim::util::ensure-gnu-sed](#openimutilensure-gnu-sed)
- [openim::util::ensure-gnu-date](#openimutilensure-gnu-date)
- [openim::util::check-file-in-alphabetical-order](#openimutilcheck-file-in-alphabetical-order)
- [openim::util::require-jq](#openimutilrequire-jq)
- [openim::util::md5](#openimutilmd5)
- [openim::util::read-array](#openimutilread-array)
- [Color Definitions](#color-definitions)
- [openim::util::desc and related functions](#openimutildesc-and-related-functions)
- [openim::util::onCtrlC](#openimutilonctrlc)
- [openim::util::list-to-string](#openimutillist-to-string)
- [openim::util::remove-space](#openimutilremove-space)
- [openim::util::gencpu](#openimutilgencpu)
- [openim::util::gen-os-arch](#openimutilgen-os-arch)
- [openim::util::download-file](#openimutildownload-file)
- [openim::util::get-public-ip](#openimutilget-public-ip)
- [openim::util::extract-tarball](#openimutilextract-tarball)
- [openim::util::check-port-open](#openimutilcheck-port-open)
- [openim::util::file-lines-count](#openimutilfile-lines-count)
## brief descriptions of each function
**English:**
1. `openim::util::ensure-gnu-sed` - Determines if GNU version of `sed` exists on the system and sets its name.
2. `openim::util::ensure-gnu-date` - Determines if GNU version of `date` exists on the system and sets its name.
3. `openim::util::check-file-in-alphabetical-order` - Checks if a file is sorted in alphabetical order.
4. `openim::util::require-jq` - Checks if `jq` is installed.
5. `openim::util::md5` - Outputs the MD5 hash of a file.
6. `openim::util::read-array` - Reads content from standard input into an array.
7. `openim::util::desc` - Displays descriptive information.
8. `openim::util::run::prompt` - Displays a prompt.
9. `openim::util::run::maybe-first-prompt` - Possibly displays the first prompt based on whether it's started or not.
10. `openim::util::run` - Executes a command and captures its output.
11. `openim::util::run::relative` - Returns paths relative to the current script.
12. `openim::util::onCtrlC` - Performs an action when Ctrl+C is pressed.
13. `openim::util::list-to-string` - Converts a list into a string.
14. `openim::util::remove-space` - Removes spaces from a string.
15. `openim::util::gencpu` - Retrieves CPU information.
16. `openim::util::gen-os-arch` - Generates a repository directory based on the operating system and architecture.
17. `openim::util::download-file` - Downloads a file from a URL.
18. `openim::util::get-public-ip` - Retrieves the public IP address of the machine.
19. `openim::util::extract-tarball` - Extracts a tarball to a specified directory.
20. `openim::util::check-port-open` - Checks if a given port is open on the machine.
21. `openim::util::file-lines-count` - Counts the number of lines in a file.
## Introduction
This script is mainly used to validate whether the code is correctly formatted by `gofmt`. Apart from that, it offers utilities like setting up SSH keys, various wait conditions, host and platform detection, documentation generation, etc.
## Usage
### SSH Key Setup
To set up an SSH key:
```bash
#1. Write IPs in a file, one IP per line. Let's name it hosts-file.
#2. Modify the default username and password in the script.
hosts-file-path="path/to/your/hosts/file"
openim:util::setup_ssh_key_copy "$hosts-file-path" "root" "123"
```
## openim::util::ensure-gnu-sed
Ensures the presence of the GNU version of the `sed` command. Different operating systems may have variations of the `sed` command, and this utility function is used to make sure the script uses the GNU version. If it finds the GNU `sed`, it sets the `SED` variable accordingly. If not found, it checks for `gsed`, which is usually the name of GNU `sed` on macOS. If neither is found, an error message is displayed.
## openim::util::ensure-gnu-date
Similar to the function for `sed`, this function ensures the script uses the GNU version of the `date` command. If it identifies the GNU `date`, it sets the `DATE` variable. On macOS, it looks for `gdate` as an alternative. In the absence of both, an error message is recommended.
## openim::util::check-file-in-alphabetical-order
This function checks if the contents of a given file are sorted in alphabetical order. If not, it provides a command suggestion for the user to sort the file correctly.
## openim::util::require-jq
Verifies the installation of `jq`, a popular command-line JSON parser. If it's not present, a prompt to install it is displayed.
## openim::util::md5
A cross-platform function that computes the MD5 hash of its input. This function takes into account the differences in the `md5` command between macOS and Linux.
## openim::util::read-array
A function designed to read from stdin and populate an array, line by line. It's provided as an alternative to `mapfile -t` and is compatible with bash 3.
## Color Definitions
The script also defines a set of colors to enhance its console output. These include colors like red, yellow, green, blue, cyan, etc., which can be used for better user experience and clear logs.
## openim::util::desc and related functions
These functions seem to aid in building interactive demonstrations or tutorials in the terminal. They use the `pv` utility to control the display rate of the output, emulating typing. There's also functionality to handle user prompts and execute commands while capturing their output.
## openim::util::onCtrlC
Handles the `CTRL+C` command. It terminates background processes of the script when the user interrupts it using `CTRL+C`.
## openim::util::list-to-string
Transforms a list format (like `[10023, 2323, 3434]`) to a space-separated string (`10023 2323 3434`). Also removes unnecessary spaces and characters.
## openim::util::remove-space
Removes spaces from a given string.
## openim::util::gencpu
Fetches the number of CPUs using the `lscpu` command.
## openim::util::gen-os-arch
Identifies the operating system and architecture of the system running the script. This is useful to determine directories or binaries specific to that OS and architecture.
## openim::util::download-file
This function can be used to download a file from a URL. If `curl` is available, it uses `curl`. If not, it falls back to `wget`.
```bash
function openim::util::download-file() {
local url="$1"
local dest="$2"
if command -v curl &>/dev/null; then
curl -L "${url}" -o "${dest}"
elif command -v wget &>/dev/null; then
wget "${url}" -O "${dest}"
else
openim::log::error "Neither curl nor wget available. Cannot download file."
return 1
fi
}
```
## openim::util::get-public-ip
Fetches the public IP address of the machine.
```bash
function openim::util::get-public-ip() {
if command -v curl &>/dev/null; then
curl -s https://ipinfo.io/ip
elif command -v wget &>/dev/null; then
wget -qO- https://ipinfo.io/ip
else
openim::log::error "Neither curl nor wget available. Cannot fetch public IP."
return 1
fi
}
```
## openim::util::extract-tarball
This function extracts a tarball to a specified directory.
```bash
function openim::util::extract-tarball() {
local tarball="$1"
local dest="$2"
mkdir -p "${dest}"
tar -xzf "${tarball}" -C "${dest}"
}
```
## openim::util::check-port-open
Checks if a given port is open on the local machine.
```bash
function openim::util::check-port-open() {
local port="$1"
if command -v nc &>/dev/null; then
echo -n > /dev/tcp/127.0.0.1/"${port}" 2>&1
return $?
elif command -v telnet &>/dev/null; then
telnet 127.0.0.1 "${port}" 2>&1 | grep -q "Connected"
return $?
else
openim::log::error "Neither nc nor telnet available. Cannot check port."
return 1
fi
}
```
## openim::util::file-lines-count
Counts the number of lines in a file.
```bash
function openim::util::file-lines-count() {
local file="$1"
if [[ -f "${file}" ]]; then
wc -l < "${file}"
else
openim::log::error "File does not exist: ${file}"
return 1
fi
}
```

238
docs/contrib/version.md Normal file
View File

@@ -0,0 +1,238 @@
# OpenIM Branch Management and Versioning: A Blueprint for High-Grade Software Development
[📚 **OpenIM TOC**](#openim-branch-management-and-versioning-a-blueprint-for-high-grade-software-development)
- [OpenIM Branch Management and Versioning: A Blueprint for High-Grade Software Development](#openim-branch-management-and-versioning-a-blueprint-for-high-grade-software-development)
- [Unfolding the Mechanism of OpenIM Version Maintenance](#unfolding-the-mechanism-of-openim-version-maintenance)
- [Main Branch: The Heart of OpenIM Development](#main-branch-the-heart-of-openim-development)
- [Release Branch: The Beacon of Stability](#release-branch-the-beacon-of-stability)
- [Tag Management: The Cornerstone of Version Control](#tag-management-the-cornerstone-of-version-control)
- [Release Management: A Guided Tour](#release-management-a-guided-tour)
- [Milestones, Branching, and Addressing Major Bugs](#milestones-branching-and-addressing-major-bugs)
- [Version Skew Policy](#version-skew-policy)
- [Supported version skew](#supported-version-skew)
- [OpenIM Versioning, Branching, and Tag Strategy](#openim-versioning-branching-and-tag-strategy)
- [Supported Version Skew](#supported-version-skew-1)
- [openim-api](#openim-api)
- [openim-rpc-\* Components](#openim-rpc--components)
- [Other OpenIM Services](#other-openim-services)
- [Supported Component Upgrade Order](#supported-component-upgrade-order)
- [openim-api](#openim-api-1)
- [openim-rpc-\* Components](#openim-rpc--components-1)
- [Other OpenIM Services](#other-openim-services-1)
- [Conclusion](#conclusion)
- [Applying Principles: A Git Workflow Example](#applying-principles-a-git-workflow-example)
- [Release Process](#release-process)
- [Docker Images Version Management](#docker-images-version-management)
- [More](#more)
At OpenIM, we acknowledge the profound impact of implementing a robust and efficient version management system, hence we abide by the established standards of [Semantic Versioning 2.0.0](https://semver.org/lang/zh-CN/).
Our software blueprint orchestrates a tripartite version management system that integrates the `main` branch, the `release` branch, and `tag` management. These constituents operate in synchrony to preserve the reliability and traceability of our software across various stages of development.
## Unfolding the Mechanism of OpenIM Version Maintenance
Our version maintenance protocol revolves around two primary branches, namely: `main` and `release`. We resort to Semantic Versioning 2.0.0 for marking distinctive versions of our software, representing substantial milestones in its evolution.
In the OpenIM repository, version identification strictly complies with the `MAJOR.MINOR.PATCH` protocol. Herein:
- The `MAJOR` version indicates a shift arising from incompatible changes to the API.
- The `MINOR` version suggests the addition of features in a backward-compatible manner.
- The `PATCH` version flags backward-compatible bug fixes.
## Main Branch: The Heart of OpenIM Development
The `main` branch is the operational heart of our development process. Housing the most recent and advanced features, this branch serves as the nerve center for all enhancements and updates. It encapsulates the freshest, though possibly unstable, facets of the software. Visit our `main` branch [here](https://github.com/openimsdk/open-im-server-deploy/tree/main).
## Release Branch: The Beacon of Stability
For every major release, we curate a corresponding `release` branch, e.g., `release-v3.1`. This branch symbolizes an embodiment of stability and ensures an updated version of the software, providing a dependable option for users favoring stability over nascent, yet possibly unstable, features. Visit the `release-v3.1` branch [here](https://github.com/openimsdk/open-im-server-deploy/tree/release-v3.1).
## Tag Management: The Cornerstone of Version Control
In OpenIM's version control system, the role of `tags` stands paramount. Owing to their immutable nature, tags can be effectively utilized to retrieve a specific version of the software. Explore our library of tags [here](https://github.com/openimsdk/open-im-server-deploy/tags).
Our Docker image versions are intimately entwined with these tripartite components. For instance, a Docker image tag may correspond to `ghcr.io/openimsdk/openim-server:v3.1.0`, a release to `ghcr.io/openimsdk/openim-server:release-v3.0`, and the main branch to `ghcr.io/openimsdk/openim-server:main` or `ghcr.io/openimsdk/openim-server:latest`.
To further clarify, the semantics of our version numbers are as follows:
- **Revision version number**: This represents bug fixes or code optimizations. Typically, it entails no new feature additions and ensures backward compatibility.
- **Build version number**: Auto-generated by the system, each code submission prompts an automatic increment by 1.
- **Version modifiers**: These hint at the software's development stage and stability. Some commonly used modifiers are `alpha`, `beta`, `rc`, `ga`, `r/release/or nothing`, and `lts`.
- `alpha`: An internal testing version with numerous bugs, typically used for communication among developers.
- `beta`: A test version with numerous bugs, generally used for testing by eager community members, who provide feedback to the developers.
- `rc`: Release candidate, which is to be released as the official version. It's the last test version before the official version.
- `ga`: General Availability, the first stable release.
- `r/release/or nothing`: The final release version, intended for general users.
- `lts`: Long Term Support, the official will specify the maintenance year for this version and will fix all bugs discovered in this version.
Whenever a project undergoes a partial functional addition, the minor version number increments by 1, resetting the revision version number to 0. In contrast, any major project overhaul results in an increment by 1 in the major version number. The build number, typically auto-generated during the compilation process, only requires format definition, thereby eliminating manual control.
## Release Management: A Guided Tour
Our GitHub repository at https://github.com/openimsdk/open-im-server-deploy/releases associates a release with each tag, with a distinction between Pre-release and Latest, determined by the branch source. Every significant feature launch prompts the issue of a `release` branch, such as `release-v3.2`, as a beacon of stability and Latest release.
Pre-releases correspond to releases from the `main` branch, denoting tags with Version modifiers such as `v3.2.1-beta.0`, `v3.2.1-rc.1`, etc. If you are seeking the most recent, albeit possibly unstable, release with new features, these tags, originating from the latest `main` branch code, are your go-to.
Conversely, if stability is your primary concern, you should opt for the release tagged Latest, denoted by tags without Version modifiers, such as `v3.2.1`, `v3.2.2` etc. These tags are linked to the latest stable maintenance branch, like `release-v3.2`.
## Milestones, Branching, and Addressing Major Bugs
**About:**
+ [OpenIM Milestones](https://github.com/openimsdk/open-im-server-deploy/milestones)
+ [OpenIM Tags](https://github.com/openimsdk/open-im-server-deploy/tags)
+ [OpenIM Branches](https://github.com/openimsdk/open-im-server-deploy/branches)
We create a new branch, such as `release-v3.1`, for each significant milestone (e.g., v3.1.0), housing all relevant code for that release. All enhancements and bug fixes targeting the subsequent version (e.g., v3.2.0) are integrated into this branch.
`PATCH` versions (represented by Z in `X.Y.Z`) are primarily propelled by bug fixes, and their release may be either priority-driven or scheduled. In contrast, `MINOR` versions (represented by Y in `X.Y.Z`) are contingent upon the project's roadmap, milestone completion, or a pre-established timeline, always maintaining backward-compatible APIs.
When dealing with major bugs, we selectively merge the fix into the affected version (e.g., v3.1 or the `release-v3.1` branch), as well as the `main` branch. This dual pronged strategy ensures that users on older versions receive crucial bug fixes, while also keeping the `main` branch updated.
We reinforce our approach to branch management and versioning with stringent testing protocols. Automated tests and code review sessions form vital components of maintaining a robust and reliable codebase.
## Version Skew Policy
This document describes the maximum version skew supported between various openim components. Specific cluster deployment tools may place additional restrictions on version skew.
### Supported version skew
In highly-available (HA) clusters, the newest and oldest `openim-api` instances must be within one minor version.
### OpenIM Versioning, Branching, and Tag Strategy
Similar to Kubernetes, OpenIM has a strict versioning, branching, and tag strategy to ensure compatibility among its various services and components. This document outlines the policies, especially focusing on the version skew supported between OpenIM's components. Given that the current version is v3.3, the policy references will be centered around this version.
#### Supported Version Skew
##### openim-api
In highly-available (HA) clusters, the newest and oldest `openim-api` instances must be within one minor version.
Example:
+ Newest `openim-api` is at v3.3
+ Other `openim-api` instances are supported at v3.3 and v3.2
##### openim-rpc-* Components
All `openim-rpc-*` components (e.g., `openim-rpc-auth`, `openim-rpc-conversation`, etc.) should adhere to the following rules:
1. They must not be newer than `openim-api`.
2. They may be up to one minor version older than `openim-api`.
Example:
+ `openim-api` is at v3.3
+ All `openim-rpc-*` components are supported at v3.3 and v3.2
Note: If version skew exists between `openim-api` instances in an HA cluster, this narrows the allowed `openim-rpc-*` components versions.
##### Other OpenIM Services
Other OpenIM services such as `openim-cmdutils`, `openim-crontask`, `openim-msggateway`, etc. should adhere to the following rules:
1. These services must not be newer than `openim-api`.
2. They are expected to match the `openim-api` minor version but may be up to one minor version older (to allow live upgrades).
Example:
+ `openim-api` is at v3.3
+ `openim-msggateway`, `openim-cmdutils`, and other services are supported at v3.3 and v3.2
#### Supported Component Upgrade Order
The version skew policy has implications on the order in which components should be upgraded. Below is the recommended order to transition an existing cluster from version v3.2 to v3.3:
##### openim-api
Pre-requisites:
1. In a single-instance cluster, the existing `openim-api` instance is v3.2.
2. In an HA cluster, all `openim-api` instances are at v3.2 or v3.3.
3. All `openim-rpc-*` and other OpenIM services communicating with this server are at version v3.2.
Upgrade Procedure:
1. Upgrade `openim-api` to v3.3.
##### openim-rpc-* Components
Pre-requisites:
1. The `openim-api` instances these components communicate with are at v3.3.
Upgrade Procedure:
2. Upgrade all `openim-rpc-*` components to v3.3.
##### Other OpenIM Services
Pre-requisites:
1. The `openim-api` instances these services communicate with are at v3.3.
Upgrade Procedure:
2. Upgrade other OpenIM services such as `openim-msggateway`, `openim-cmdutils`, etc., to v3.3.
#### Conclusion
Just like Kubernetes, it's essential for OpenIM to have a strict versioning and upgrade policy to ensure seamless operation and compatibility among its various services. Adhering to the policies outlined above will help in achieving this goal.
## Applying Principles: A Git Workflow Example
The workflow to address a bug fix might follow these steps:
```bash
# Checkout the branch for the version that needs the bug fix
git checkout release-v3.1
# Create a new branch for the bug fix
git checkout -b bug/bug-name
# ... Make changes, commit your work ...
# Push the branch to your remote repository
git push origin bug/bug-name
# After the pull request is merged into the release-v3.1 branch,
# checkout and update your main branch
git checkout main
git pull origin main
# Merge or rebase the changes from release-v3.1 into main
git merge release-v3.1
# Push the updates to the main branch
git push origin main
```
## Release Process
```
Publishing v3.2.0: A Step-by-Step Guide
(1) Create the tag v3.2.0-alpha.0 from the main branch.
(2) Bugs are fixed on the main branch. Once the bugs are resolved, tag the main branch as v3.2.0-rc.0.
(3) After further testing, if v3.2.0-rc.0 is deemed stable, create a branch named release-v3.2 from the tag v3.2.0-rc.0.
(4) From the release-v3.2 branch, create the tag v3.2.0. At this point, the official release of v3.2.0 is complete.
After the release of v3.2.0, if urgent bugs are discovered, fix them on the release-v3.2 branch. Then, submit two pull requests (PRs) to both the main and release-v3.2 branches. Tag the release-v3.2 branch as v3.2.1.
```
Throughout this process, active communication within the team is pivotal to maintaining transparency and consensus on changes.
## Docker Images Version Management
For more details on managing Docker image versions, visit [OpenIM Docker Images Administration](https://github.com/openimsdk/open-im-server-deploy/blob/main/docs/contrib/images.md).
## More
More on multi-branch version management design and version management design at helm charts
About Helm's version management strategy for Multiple Apps and multiple Services:
+ [中文版本管理文档](https://github.com/openimsdk/helm-charts/blob/main/docs/contrib/version-zh.md)
+ [English version management documents](https://github.com/openimsdk/helm-charts/blob/main/docs/contrib/version.md)

View File

@@ -0,0 +1,33 @@
# How do I contribute code to OpenIM
<p align="center">
<a href="./CONTRIBUTING.md">English</a> ·
<a href="./CONTRIBUTING-zh_CN.md">中文</a> ·
<a href="docs/contributing/CONTRIBUTING-UA.md">Українська</a> ·
<a href="docs/contributing/CONTRIBUTING-CS.md">Česky</a> ·
<a href="docs/contributing/CONTRIBUTING-HU.md">Magyar</a> ·
<a href="docs/contributing/CONTRIBUTING-ES.md">Español</a> ·
<a href="docs/contributing/CONTRIBUTING-FA.md">فارسی</a> ·
<a href="docs/contributing/CONTRIBUTING-FR.md">Français</a> ·
<a href="docs/contributing/CONTRIBUTING-DE.md">Deutsch</a> ·
<a href="docs/contributing/CONTRIBUTING-PL.md">Polski</a> ·
<a href="docs/contributing/CONTRIBUTING-ID.md">Indonesian</a> ·
<a href="docs/contributing/CONTRIBUTING-FI.md">Suomi</a> ·
<a href="docs/contributing/CONTRIBUTING-ML.md">മലയാളം</a> ·
<a href="docs/contributing/CONTRIBUTING-JP.md">日本語</a> ·
<a href="docs/contributing/CONTRIBUTING-NL.md">Nederlands</a> ·
<a href="docs/contributing/CONTRIBUTING-IT.md">Italiano</a> ·
<a href="docs/contributing/CONTRIBUTING-RU.md">Русский</a> ·
<a href="docs/contributing/CONTRIBUTING-PTBR.md">Português (Brasil)</a> ·
<a href="docs/contributing/CONTRIBUTING-EO.md">Esperanto</a> ·
<a href="docs/contributing/CONTRIBUTING-KR.md">한국어</a> ·
<a href="docs/contributing/CONTRIBUTING-AR.md">العربي</a> ·
<a href="docs/contributing/CONTRIBUTING-VN.md">Tiếng Việt</a> ·
<a href="docs/contributing/CONTRIBUTING-DA.md">Dansk</a> ·
<a href="docs/contributing/CONTRIBUTING-GR.md">Ελληνικά</a> ·
<a href="docs/contributing/CONTRIBUTING-TR.md">Türkçe</a>
</p>
</div>
</p>

View File

@@ -0,0 +1,33 @@
# How do I contribute code to OpenIM
<p align="center">
<a href="./CONTRIBUTING.md">English</a> ·
<a href="./CONTRIBUTING-zh_CN.md">中文</a> ·
<a href="docs/contributing/CONTRIBUTING-UA.md">Українська</a> ·
<a href="docs/contributing/CONTRIBUTING-CS.md">Česky</a> ·
<a href="docs/contributing/CONTRIBUTING-HU.md">Magyar</a> ·
<a href="docs/contributing/CONTRIBUTING-ES.md">Español</a> ·
<a href="docs/contributing/CONTRIBUTING-FA.md">فارسی</a> ·
<a href="docs/contributing/CONTRIBUTING-FR.md">Français</a> ·
<a href="docs/contributing/CONTRIBUTING-DE.md">Deutsch</a> ·
<a href="docs/contributing/CONTRIBUTING-PL.md">Polski</a> ·
<a href="docs/contributing/CONTRIBUTING-ID.md">Indonesian</a> ·
<a href="docs/contributing/CONTRIBUTING-FI.md">Suomi</a> ·
<a href="docs/contributing/CONTRIBUTING-ML.md">മലയാളം</a> ·
<a href="docs/contributing/CONTRIBUTING-JP.md">日本語</a> ·
<a href="docs/contributing/CONTRIBUTING-NL.md">Nederlands</a> ·
<a href="docs/contributing/CONTRIBUTING-IT.md">Italiano</a> ·
<a href="docs/contributing/CONTRIBUTING-RU.md">Русский</a> ·
<a href="docs/contributing/CONTRIBUTING-PTBR.md">Português (Brasil)</a> ·
<a href="docs/contributing/CONTRIBUTING-EO.md">Esperanto</a> ·
<a href="docs/contributing/CONTRIBUTING-KR.md">한국어</a> ·
<a href="docs/contributing/CONTRIBUTING-AR.md">العربي</a> ·
<a href="docs/contributing/CONTRIBUTING-VN.md">Tiếng Việt</a> ·
<a href="docs/contributing/CONTRIBUTING-DA.md">Dansk</a> ·
<a href="docs/contributing/CONTRIBUTING-GR.md">Ελληνικά</a> ·
<a href="docs/contributing/CONTRIBUTING-TR.md">Türkçe</a>
</p>
</div>
</p>

Binary file not shown.

After

Width:  |  Height:  |  Size: 286 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 207 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 240 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 107 KiB

BIN
docs/images/wechat.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

415
docs/meeting-api.md Normal file
View File

@@ -0,0 +1,415 @@
# 会议管理接口文档
## 接口列表
### 1. 创建会议
**接口地址:** `POST /meeting/create_meeting`
**请求参数:**
```json
{
"meetingID": "string", // 会议ID选填不填则自动生成
"subject": "string", // 会议主题(必填)
"coverURL": "string", // 封面URL选填
"scheduledTime": 1234567890000, // 预约时间戳(毫秒,必填)
"description": "string", // 会议描述(选填)
"duration": 60, // 会议时长(分钟,选填)
"estimatedCount": 100, // 会议预估人数(选填)
"enableMic": true, // 是否开启连麦选填默认false
"enableComment": true, // 是否开启评论选填默认false
"anchorUserIDs": ["user1", "user2"], // 主播用户ID列表多选选填
"ex": "string" // 扩展字段(选填)
}
```
**响应参数:**
```json
{
"errCode": 0,
"errMsg": "",
"errDlt": "",
"data": {
"meetingInfo": {
"meetingID": "string", // 会议ID
"subject": "string", // 会议主题
"coverURL": "string", // 封面URL
"scheduledTime": 1234567890000, // 预约时间戳(毫秒)
"status": 1, // 会议状态1-已预约2-进行中3-已结束4-已取消
"creatorUserID": "string", // 创建者用户ID
"description": "string", // 会议描述
"duration": 60, // 会议时长(分钟)
"estimatedCount": 100, // 会议预估人数
"enableMic": true, // 是否开启连麦
"enableComment": true, // 是否开启评论
"anchorUserIDs": ["user1", "user2"], // 主播用户ID列表多选
"anchorUsers": [ // 主播用户信息列表
{
"userID": "user1",
"nickname": "主播1",
"faceURL": "https://example.com/avatar1.jpg"
},
{
"userID": "user2",
"nickname": "主播2",
"faceURL": "https://example.com/avatar2.jpg"
}
],
"createTime": 1234567890000, // 创建时间戳(毫秒)
"updateTime": 1234567890000, // 更新时间戳(毫秒)
"ex": "string", // 扩展字段
"groupID": "string" // 关联的群聊ID
},
"groupID": "string" // 创建的群聊ID
}
}
```
**说明:**
- 创建会议时会自动创建一个群聊,群聊名称为"群聊-[会议主题]"
- 会议封面会作为群聊头像
- 如果有主播列表,第一个主播自动成为群主,其他主播成为管理员
- 如果没有主播列表,创建者自动成为群主
---
### 2. 更新会议
**接口地址:** `POST /meeting/update_meeting`
**请求参数:**
```json
{
"meetingID": "string", // 会议ID必填
"subject": "string", // 会议主题(选填)
"coverURL": "string", // 封面URL选填
"scheduledTime": 1234567890000, // 预约时间戳(毫秒,选填)
"status": 2, // 会议状态1-已预约2-进行中3-已结束4-已取消(选填)
"description": "string", // 会议描述(选填)
"duration": 60, // 会议时长(分钟,选填)
"estimatedCount": 100, // 会议预估人数(选填)
"enableMic": true, // 是否开启连麦(选填,使用指针以区分是否设置)
"enableComment": true, // 是否开启评论(选填,使用指针以区分是否设置)
"anchorUserIDs": ["user1", "user2"], // 主播用户ID列表多选选填
"ex": "string" // 扩展字段(选填)
}
```
**响应参数:**
```json
{
"errCode": 0,
"errMsg": "",
"errDlt": "",
"data": {
"meetingInfo": {
"meetingID": "string", // 会议ID
"subject": "string", // 会议主题
"coverURL": "string", // 封面URL
"scheduledTime": 1234567890000, // 预约时间戳(毫秒)
"status": 2, // 会议状态1-已预约2-进行中3-已结束4-已取消
"creatorUserID": "string", // 创建者用户ID
"description": "string", // 会议描述
"duration": 60, // 会议时长(分钟)
"estimatedCount": 100, // 会议预估人数
"enableMic": true, // 是否开启连麦
"enableComment": true, // 是否开启评论
"anchorUserIDs": ["user1", "user2"], // 主播用户ID列表多选
"anchorUsers": [ // 主播用户信息列表
{
"userID": "user1",
"nickname": "主播1",
"faceURL": "https://example.com/avatar1.jpg"
},
{
"userID": "user2",
"nickname": "主播2",
"faceURL": "https://example.com/avatar2.jpg"
}
],
"createTime": 1234567890000, // 创建时间戳(毫秒)
"updateTime": 1234567890000, // 更新时间戳(毫秒)
"ex": "string", // 扩展字段
"groupID": "string" // 关联的群聊ID
}
}
}
```
**说明:**
- 可以单独更新任意字段,只传需要更新的字段即可
- 更新主题时会同步更新群聊名称
- 更新封面时会同步更新群聊头像
- 更新主播列表时,第一个主播会成为群主,其他主播会成为管理员
- 只有创建者可以更新会议
---
### 3. 获取会议列表
**接口地址:** `POST /meeting/get_meetings`
**请求参数:**
```json
{
"creatorUserID": "string", // 创建者用户ID选填
"status": 1, // 会议状态选填1-已预约2-进行中3-已结束4-已取消
"keyword": "string", // 搜索关键词(选填,搜索主题和描述)
"startTime": 1234567890000, // 开始时间戳(毫秒,选填)
"endTime": 1234567890000, // 结束时间戳(毫秒,选填)
"pagination": {
"pageNumber": 1, // 页码从1开始选填默认1
"showNumber": 20 // 每页数量选填默认20
}
}
```
**响应参数:**
```json
{
"errCode": 0,
"errMsg": "",
"errDlt": "",
"data": {
"total": 100, // 总数
"meetings": [
{
"meetingID": "string", // 会议ID
"subject": "string", // 会议主题
"coverURL": "string", // 封面URL
"scheduledTime": 1234567890000, // 预约时间戳(毫秒)
"status": 1, // 会议状态1-已预约2-进行中3-已结束4-已取消
"creatorUserID": "string", // 创建者用户ID
"description": "string", // 会议描述
"duration": 60, // 会议时长(分钟)
"estimatedCount": 100, // 会议预估人数
"enableMic": true, // 是否开启连麦
"enableComment": true, // 是否开启评论
"anchorUserIDs": ["user1", "user2"], // 主播用户ID列表多选
"anchorUsers": [ // 主播用户信息列表
{
"userID": "user1",
"nickname": "主播1",
"faceURL": "https://example.com/avatar1.jpg"
},
{
"userID": "user2",
"nickname": "主播2",
"faceURL": "https://example.com/avatar2.jpg"
}
],
"createTime": 1234567890000, // 创建时间戳(毫秒)
"updateTime": 1234567890000, // 更新时间戳(毫秒)
"ex": "string", // 扩展字段
"groupID": "string" // 关联的群聊ID
}
]
}
}
```
**说明:**
- 支持多种查询条件,可以组合使用
- 查询优先级creatorUserID > status > keyword > startTime/endTime > 全部
- 支持分页查询
- 返回的会议信息中包含主播的完整用户信息用户ID、昵称、头像等
---
### 4. 删除会议
**接口地址:** `POST /meeting/delete_meeting`
**请求参数:**
```json
{
"meetingID": "string" // 会议ID必填
}
```
**响应参数:**
```json
{
"errCode": 0,
"errMsg": "",
"errDlt": "",
"data": {}
}
```
**说明:**
- 只有创建者可以删除会议
- 删除会议不会删除关联的群聊
---
## 会议状态说明
- `1` - 已预约:会议已创建,等待开始
- `2` - 进行中:会议正在进行
- `3` - 已结束:会议已结束(用户端不可见)
- `4` - 已取消:会议已取消(用户端不可见)
**注意:** 用户端接口只能查看状态1已预约和2进行中的会议状态3已结束和4已取消的会议对用户端不可见。
---
## 通用响应格式
所有接口都遵循统一的响应格式:
```json
{
"errCode": 0, // 错误码0表示成功
"errMsg": "", // 错误消息
"errDlt": "", // 错误详情
"data": {} // 响应数据
}
```
---
## 用户端接口
### 5. 获取会议信息(用户端)
**接口地址:** `POST /meeting/get_meeting`
**请求参数:**
```json
{
"meetingID": "string" // 会议ID必填
}
```
**响应参数:**
```json
{
"errCode": 0,
"errMsg": "",
"errDlt": "",
"data": {
"meetingInfo": {
"meetingID": "string", // 会议ID
"subject": "string", // 会议主题
"coverURL": "string", // 封面URL
"scheduledTime": 1234567890000, // 预约时间戳(毫秒)
"status": 1, // 会议状态1-已预约2-进行中
"description": "string", // 会议描述
"duration": 60, // 会议时长(分钟)
"enableMic": true, // 是否开启连麦
"enableComment": true, // 是否开启评论
"anchorUsers": [ // 主播用户信息列表
{
"userID": "user1",
"nickname": "主播1",
"faceURL": "https://example.com/avatar1.jpg"
},
{
"userID": "user2",
"nickname": "主播2",
"faceURL": "https://example.com/avatar2.jpg"
}
],
"groupID": "string" // 关联的群聊ID
}
}
}
```
**说明:**
- 用户端接口只显示状态为1已预约和2进行中的会议
- 如果会议状态为3已结束或4已取消将返回错误
- 用户端接口不返回管理字段创建者ID、扩展字段、创建时间、更新时间等
- 返回的主播信息包含用户ID、昵称、头像等完整用户信息
---
### 6. 获取会议列表(用户端)
**接口地址:** `POST /meeting/get_meetings_public`
**请求参数:**
```json
{
"status": 1, // 会议状态选填1-已预约2-进行中(只能查询这两个状态)
"keyword": "string", // 搜索关键词(选填,搜索主题和描述)
"startTime": 1234567890000, // 开始时间戳(毫秒,选填)
"endTime": 1234567890000, // 结束时间戳(毫秒,选填)
"pagination": {
"pageNumber": 1, // 页码从1开始选填默认1
"showNumber": 20 // 每页数量选填默认20
}
}
```
**响应参数:**
```json
{
"errCode": 0,
"errMsg": "",
"errDlt": "",
"data": {
"total": 100, // 总数只包含状态1和2的会议
"meetings": [
{
"meetingID": "string", // 会议ID
"subject": "string", // 会议主题
"coverURL": "string", // 封面URL
"scheduledTime": 1234567890000, // 预约时间戳(毫秒)
"status": 1, // 会议状态1-已预约2-进行中
"description": "string", // 会议描述
"duration": 60, // 会议时长(分钟)
"enableMic": true, // 是否开启连麦
"enableComment": true, // 是否开启评论
"anchorUsers": [ // 主播用户信息列表
{
"userID": "user1",
"nickname": "主播1",
"faceURL": "https://example.com/avatar1.jpg"
},
{
"userID": "user2",
"nickname": "主播2",
"faceURL": "https://example.com/avatar2.jpg"
}
],
"groupID": "string" // 关联的群聊ID
}
]
}
}
```
**说明:**
- 用户端接口只显示状态为1已预约和2进行中的会议
- 如果指定status参数只能传入1或2传入其他值将返回错误
- 如果不指定status查询结果会自动过滤只返回状态1和2的会议
- 用户端接口不支持按创建者查询
- 用户端接口不返回管理字段创建者ID、扩展字段、创建时间、更新时间等
- 返回的主播信息包含用户ID、昵称、头像等完整用户信息
---
## 注意事项
1. 所有接口都需要在请求头中携带 `token` 进行身份验证
2. 创建和更新会议时,预约时间不能早于当前时间
3. 创建会议时会自动创建关联的群聊,群聊名称为"群聊-[会议主题]"
4. 更新会议主题或封面时,会同步更新关联群聊的名称或头像
5. 只有会议创建者可以更新和删除会议
6. 用户端接口只提供查看功能,不包含创建、更新、删除等管理功能
7. 用户端接口返回的数据已过滤管理字段创建者ID、扩展字段、创建时间、更新时间等
8. 用户端接口只显示状态为1已预约和2进行中的会议状态3已结束和4已取消的会议对用户端不可见

619
docs/meeting-client-api.md Normal file
View File

@@ -0,0 +1,619 @@
# OpenIM 会议接口文档(用户端 - 前端对接版)
本文档专门用于前端开发人员对接 OpenIM 会议相关 API 接口(用户端)。
## 目录
- [基础说明](#基础说明)
- [会议状态说明](#会议状态说明)
- [用户端接口](#用户端接口)
- [业务规则](#业务规则)
- [错误码说明](#错误码说明)
- [注意事项](#注意事项)
---
## 基础说明
### 请求格式
- **请求方法**: 所有接口均使用 `POST` 方法
- **Content-Type**: `application/json`
- **请求头**: 需要在请求头中携带 `token` 进行身份验证
```http
POST /meeting/get_meeting
Content-Type: application/json
token: your_token_here
```
### 响应格式
所有接口统一返回以下格式:
```json
{
"errCode": 0, // 错误码0表示成功
"errMsg": "", // 错误消息
"errDlt": "", // 错误详情
"data": {} // 响应数据,具体结构见各接口说明
}
```
### 基础URL
根据部署环境配置,例如:
- 开发环境: `http://localhost:10002`
- 生产环境: `https://your-domain.com`
---
## 会议状态说明
| 状态值 | 状态名称 | 说明 | 用户端可见 |
|--------|---------|------|-----------|
| 1 | 已预约 | 会议已创建,等待开始 | ✅ 可见 |
| 2 | 进行中 | 会议正在进行 | ✅ 可见 |
| 3 | 已结束 | 会议已结束 | ❌ 不可见 |
| 4 | 已取消 | 会议已取消 | ❌ 不可见 |
**重要提示**
- 用户端接口只能查看状态为 **1已预约****2进行中** 的会议
- 状态为 **3已结束****4已取消** 的会议对用户端不可见
---
## 用户端接口
### 1. 获取会议信息
**接口地址**: `POST /meeting/get_meeting`
**接口描述**: 获取单个会议信息,只能查看已预约和进行中的会议
**请求参数**:
```json
{
"meetingID": "string" // 会议ID必填
}
```
**响应参数**:
```json
{
"errCode": 0,
"errMsg": "",
"errDlt": "",
"data": {
"meetingInfo": {
"meetingID": "string", // 会议ID
"subject": "string", // 会议主题
"coverURL": "string", // 封面URL
"scheduledTime": 1234567890000, // 预约时间戳(毫秒)
"status": 1, // 会议状态1-已预约2-进行中
"description": "string", // 会议描述
"duration": 60, // 会议时长(分钟)
"enableMic": true, // 是否开启连麦
"enableComment": true, // 是否开启评论
"anchorUsers": [ // 主播用户信息列表
{
"userID": "user1",
"nickname": "主播1",
"faceURL": "https://example.com/avatar1.jpg"
},
{
"userID": "user2",
"nickname": "主播2",
"faceURL": "https://example.com/avatar2.jpg"
}
],
"groupID": "string", // 关联的群聊ID
"checkInCount": 50 // 签到人数统计
}
}
}
```
**业务规则**:
1. 用户端接口只显示状态为 **1已预约****2进行中** 的会议
2. 如果会议状态为 **3已结束****4已取消**,将返回错误
3. 用户端接口不返回管理字段:
- `creatorUserID`创建者ID
- `ex`(扩展字段)
- `createTime`(创建时间)
- `updateTime`(更新时间)
- `estimatedCount`(预估人数)
- `anchorUserIDs`主播ID列表只返回 `anchorUsers`
4. 返回的主播信息包含用户ID、昵称、头像等完整用户信息
5. 返回签到人数统计(`checkInCount`),用于显示会议签到情况
**错误码**:
- `0`: 成功
- `1001`: 参数错误或会议不可用(会议已结束或已取消)
- `1004`: 会议不存在
- `500`: 服务器内部错误
---
### 2. 获取会议列表
**接口地址**: `POST /meeting/get_meetings_public`
**接口描述**: 获取会议列表,只能查看已预约和进行中的会议
**请求参数**:
```json
{
"status": 1, // 会议状态选填1-已预约2-进行中(只能查询这两个状态)
"keyword": "string", // 搜索关键词(选填,搜索主题和描述)
"startTime": 1234567890000, // 开始时间戳(毫秒,选填)
"endTime": 1234567890000, // 结束时间戳(毫秒,选填)
"pagination": {
"pageNumber": 1, // 页码从1开始选填默认1
"showNumber": 20 // 每页数量选填默认20
}
}
```
**参数说明**:
- `status`: 如果指定,只能传入 `1``2`,传入其他值将返回错误
- 如果不指定 `status`查询结果会自动过滤只返回状态1和2的会议
- 用户端接口不支持按创建者查询(没有 `creatorUserID` 参数)
**响应参数**:
```json
{
"errCode": 0,
"errMsg": "",
"errDlt": "",
"data": {
"total": 100, // 总数只包含状态1和2的会议
"meetings": [
{
"meetingID": "string",
"subject": "string",
"coverURL": "string",
"scheduledTime": 1234567890000,
"status": 1,
"description": "string",
"duration": 60,
"enableMic": true,
"enableComment": true,
"anchorUsers": [
{
"userID": "user1",
"nickname": "主播1",
"faceURL": "https://example.com/avatar1.jpg"
}
],
"groupID": "string", // 关联的群聊ID
"checkInCount": 50 // 签到人数统计
}
]
}
}
```
**业务规则**:
1. 用户端接口只显示状态为 **1已预约****2进行中** 的会议
2. 如果指定 `status` 参数,只能传入 `1``2`,传入其他值将返回错误
3. 如果不指定 `status`查询结果会自动过滤只返回状态1和2的会议
4. 用户端接口不支持按创建者查询
5. 用户端接口不返回管理字段创建者ID、扩展字段、创建时间、更新时间、预估人数等
6. 返回的主播信息包含用户ID、昵称、头像等完整用户信息
**错误码**:
- `0`: 成功
- `1001`: 参数错误如状态值不是1或2
- `500`: 服务器内部错误
---
## 签到接口
### 1. 会议签到
**接口地址**: `POST /meeting/check_in`
**接口描述**: 用户对会议进行签到,一个用户在一个会议中只能签到一次
**请求参数**:
```json
{
"meetingID": "string" // 会议ID必填
}
```
**响应参数**:
```json
{
"errCode": 0,
"errMsg": "",
"errDlt": "",
"data": {
"checkInID": "string", // 签到ID
"checkInTime": 1234567890000 // 签到时间戳(毫秒)
}
}
```
**业务规则**:
1. 一个用户在一个会议中只能签到一次
2. 只能对状态为 **1已预约****2进行中** 的会议签到
3. 签到成功后会自动更新会议的签到统计(`checkInCount`
4. 如果用户已经签到过,会返回错误
**错误码**:
- `0`: 成功
- `1001`: 参数错误或会议不可用(会议已结束或已取消)
- `1001`: 用户已签到
- `1004`: 会议不存在
- `500`: 服务器内部错误
---
### 2. 检查用户是否已签到
**接口地址**: `POST /meeting/check_user_check_in`
**接口描述**: 检查当前用户是否已对指定会议签到
**请求参数**:
```json
{
"meetingID": "string" // 会议ID必填
}
```
**响应参数**:
```json
{
"errCode": 0,
"errMsg": "",
"errDlt": "",
"data": {
"isCheckedIn": true, // 是否已签到
"checkInInfo": { // 签到信息(如果已签到)
"checkInID": "string",
"meetingID": "string",
"userID": "string",
"checkInTime": 1234567890000,
"userInfo": {
"userID": "string",
"nickname": "string",
"faceURL": "string"
}
}
}
}
```
**业务规则**:
1. 如果用户已签到,返回 `isCheckedIn: true` 和签到详细信息
2. 如果用户未签到,返回 `isCheckedIn: false``checkInInfo``null`
3. 已签到时会返回用户的基本信息用户ID、昵称、头像等
**错误码**:
- `0`: 成功
- `1001`: 参数错误
- `500`: 服务器内部错误
---
### 3. 获取会议签到列表
**接口地址**: `POST /meeting/get_check_ins`
**接口描述**: 获取指定会议的所有签到记录列表
**请求参数**:
```json
{
"meetingID": "string", // 会议ID必填
"pagination": {
"pageNumber": 1, // 页码从1开始选填默认1
"showNumber": 20 // 每页数量选填默认20
}
}
```
**响应参数**:
```json
{
"errCode": 0,
"errMsg": "",
"errDlt": "",
"data": {
"total": 100, // 总数
"checkIns": [
{
"checkInID": "string", // 签到ID
"meetingID": "string", // 会议ID
"userID": "string", // 用户ID
"checkInTime": 1234567890000, // 签到时间戳(毫秒)
"userInfo": { // 用户信息
"userID": "string",
"nickname": "string",
"faceURL": "string"
}
}
]
}
}
```
**业务规则**:
1. 支持分页查询
2. 签到列表按签到时间倒序排列(最新签到的在前)
3. 每个签到记录包含用户的完整信息用户ID、昵称、头像等
**错误码**:
- `0`: 成功
- `1001`: 参数错误
- `500`: 服务器内部错误
---
### 4. 获取会议签到统计
**接口地址**: `POST /meeting/get_check_in_stats`
**接口描述**: 获取指定会议的签到人数统计
**请求参数**:
```json
{
"meetingID": "string" // 会议ID必填
}
```
**响应参数**:
```json
{
"errCode": 0,
"errMsg": "",
"errDlt": "",
"data": {
"meetingID": "string", // 会议ID
"checkInCount": 50 // 签到人数
}
}
```
**业务规则**:
1. 返回会议的签到总人数
2. 这个统计也会在会议信息中的 `checkInCount` 字段中返回
**错误码**:
- `0`: 成功
- `1001`: 参数错误
- `500`: 服务器内部错误
---
## 业务规则
### 1. 会议与群聊的关联
- 创建会议时会自动创建一个群聊
- 群聊名称为:`"会议群-{会议主题}"`
- 会议封面会作为群聊头像
- 群聊的 `ex` 字段中会包含会议标识:
```json
{
"isMeetingGroup": true,
"meetingID": "会议ID"
}
```
### 2. 主播与群角色的关系
- **有主播列表时**
- 第一个主播 → 群主
- 其他主播 → 管理员
- 创建者(如果不在主播列表中)→ 普通成员
- **没有主播列表时**
- 创建者 → 群主
### 3. 评论开关与群禁言
- **开启评论** (`enableComment: true`)
- 自动取消群禁言
- 群成员可以发送消息
- **关闭评论** (`enableComment: false`)
- 自动禁言群
- 群成员无法发送消息
### 4. 权限控制
- **查看会议**:用户端只能查看已预约和进行中的会议
### 5. 时间验证
- 创建会议时,预约时间不能早于当前时间
- 更新会议时,如果更新预约时间,也不能早于当前时间
---
## 错误码说明
### 通用错误码
| 错误码 | 说明 |
|--------|------|
| 0 | 成功 |
| 500 | 服务器内部错误 |
| 1001 | 参数错误 |
| 1002 | 权限不足 |
| 1004 | 记录不存在 |
### 会议相关错误场景
| 错误码 | 场景 |
|--------|------|
| 1001 | 查询状态不是1或2 |
| 1004 | 会议不存在 |
| 1004 | 查询已结束或已取消的会议 |
---
## 注意事项
### 1. 认证
- 所有接口都需要在请求头中携带 `token` 进行身份验证
- Token通过 `/auth/get_user_token` 接口获取
### 2. 请求格式
- 所有接口使用 `POST` 方法
- Content-Type: `application/json`
- 请求体为JSON格式
### 3. 响应格式
- 所有接口统一返回格式:`{errCode, errMsg, errDlt, data}`
- `errCode` 为 0 表示成功非0表示失败
- 失败时查看 `errMsg` 和 `errDlt` 获取错误详情
### 4. 时间戳
- 所有时间戳均为毫秒级Unix时间戳
- 例如:`1234567890000` 表示 2009-02-13 23:31:30
### 5. 分页参数
- 分页参数统一格式:
```json
{
"pagination": {
"pageNumber": 1, // 页码从1开始
"showNumber": 20 // 每页数量
}
}
```
### 6. 用户端接口特点
- 只能查看状态为 **1已预约** 和 **2进行中** 的会议
- 不返回管理字段:
- `creatorUserID`创建者ID
- `ex`(扩展字段)
- `createTime`(创建时间)
- `updateTime`(更新时间)
- `estimatedCount`(预估人数)
- `anchorUserIDs`主播ID列表只返回 `anchorUsers`
- 不支持按创建者查询(没有 `creatorUserID` 参数)
### 7. 主播信息
- 用户端接口只返回 `anchorUsers`(主播详细信息)
- 主播信息包含:`userID`、`nickname`、`faceURL` 等
### 8. 群聊关联
- 每个会议都会关联一个群聊
- 通过 `groupID` 字段可以获取关联的群聊ID
- 可以使用群聊相关接口(`/group/*`)操作关联的群聊
### 9. 会议状态流转
```
1已预约 → 2进行中 → 3已结束
4已取消
```
- 用户端只能查看状态 **1已预约** 和 **2进行中** 的会议
- 状态 **3已结束** 和 **4已取消** 的会议对用户端不可见
---
## 接口汇总表
| 接口路径 | 方法 | 描述 | 权限要求 |
|---------|------|------|---------|
| `/meeting/get_meeting` | POST | 获取会议信息 | 登录用户 |
| `/meeting/get_meetings_public` | POST | 获取会议列表 | 登录用户 |
---
## 请求示例
```bash
curl -X POST http://localhost:10002/meeting/get_meeting \
-H "Content-Type: application/json" \
-H "token: your_token" \
-d '{
"meetingID": "meeting123"
}'
```
### 获取会议列表
```bash
curl -X POST http://localhost:10002/meeting/get_meetings_public \
-H "Content-Type: application/json" \
-H "token: your_token" \
-d '{
"status": 1,
"keyword": "产品",
"pagination": {
"pageNumber": 1,
"showNumber": 20
}
}'
```
### 会议签到
```bash
curl -X POST http://localhost:10002/meeting/check_in \
-H "Content-Type: application/json" \
-H "token: your_token" \
-d '{
"meetingID": "meeting123"
}'
```
### 检查用户是否已签到
```bash
curl -X POST http://localhost:10002/meeting/check_user_check_in \
-H "Content-Type: application/json" \
-H "token: your_token" \
-d '{
"meetingID": "meeting123"
}'
```
### 获取会议签到列表
```bash
curl -X POST http://localhost:10002/meeting/get_check_ins \
-H "Content-Type: application/json" \
-H "token: your_token" \
-d '{
"meetingID": "meeting123",
"pagination": {
"pageNumber": 1,
"showNumber": 20
}
}'
```
### 获取会议签到统计
```bash
curl -X POST http://localhost:10002/meeting/get_check_in_stats \
-H "Content-Type: application/json" \
-H "token: your_token" \
-d '{
"meetingID": "meeting123"
}'
```
---
**最后更新时间**: 2025-01-23

183
docs/readme/README_cs.md Normal file
View File

@@ -0,0 +1,183 @@
<p align="center">
<a href="https://openim.io">
<img src="../../assets/logo-gif/openim-logo.gif" width="60%" height="30%"/>
</a>
</p>
<div align="center">
[![Stars](https://img.shields.io/github/stars/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=ff69b4)](https://github.com/openimsdk/open-im-server-deploy/stargazers)
[![Forks](https://img.shields.io/github/forks/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=blue)](https://github.com/openimsdk/open-im-server-deploy/network/members)
[![Codecov](https://img.shields.io/codecov/c/github/openimsdk/open-im-server-deploy?style=for-the-badge&logo=codecov&colorB=orange)](https://app.codecov.io/gh/openimsdk/open-im-server-deploy)
[![Go Report Card](https://goreportcard.com/badge/github.com/openimsdk/open-im-server-deploy?style=for-the-badge)](https://goreportcard.com/report/github.com/openimsdk/open-im-server-deploy)
[![Go Reference](https://img.shields.io/badge/Go%20Reference-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://pkg.go.dev/git.imall.cloud/openim/open-im-server-deploy)
[![License](https://img.shields.io/badge/license-Apache--2.0-green?style=for-the-badge)](https://github.com/openimsdk/open-im-server-deploy/blob/main/LICENSE)
[![Slack](https://img.shields.io/badge/Slack-500%2B-blueviolet?style=for-the-badge&logo=slack&logoColor=white)](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
[![Best Practices](https://img.shields.io/badge/Best%20Practices-purple?style=for-the-badge)](https://www.bestpractices.dev/projects/8045)
[![Good First Issues](https://img.shields.io/github/issues/openimsdk/open-im-server-deploy/good%20first%20issue?style=for-the-badge&logo=github)](https://github.com/openimsdk/open-im-server-deploy/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22good+first+issue%22)
[![Language](https://img.shields.io/badge/Language-Go-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://golang.org/)
<p align="center">
<a href="../../README.md">English</a> ·
<a href="../../README_zh_CN.md">中文</a> ·
<a href="./README_uk.md">Українська</a> ·
<a href="./README_cs.md">Česky</a> ·
<a href="./README_hu.md">Magyar</a> ·
<a href="./README_es.md">Español</a> ·
<a href="./README_fa.md">فارسی</a> ·
<a href="./README_fr.md">Français</a> ·
<a href="./README_de.md">Deutsch</a> ·
<a href="./README_pl.md">Polski</a> ·
<a href="./README_id.md">Indonesian</a> ·
<a href="./README_fi.md">Suomi</a> ·
<a href="./README_ml.md">മലയാളം</a> ·
<a href="./README_ja.md">日本語</a> ·
<a href="./README_nl.md">Nederlands</a> ·
<a href="./README_it.md">Italiano</a> ·
<a href="./README_ru.md">Русский</a> ·
<a href="./README_pt_BR.md">Português (Brasil)</a> ·
<a href="./README_eo.md">Esperanto</a> ·
<a href="./README_ko.md">한국어</a> ·
<a href="./README_ar.md">العربي</a> ·
<a href="./README_vi.md">Tiếng Việt</a> ·
<a href="./README_da.md">Dansk</a> ·
<a href="./README_el.md">Ελληνικά</a> ·
<a href="./README_tr.md">Türkçe</a>
</p>
</div>
</p>
## Ⓜ️ O OpenIM
OpenIM je platforma služeb speciálně navržená pro integraci chatu, audio-video hovorů, upozornění a chatbotů AI do aplikací. Poskytuje řadu výkonných rozhraní API a webhooků, které vývojářům umožňují snadno začlenit tyto interaktivní funkce do svých aplikací. OpenIM není samostatná chatovací aplikace, ale spíše slouží jako platforma pro podporu jiných aplikací při dosahování bohatých komunikačních funkcí. Následující diagram ilustruje interakci mezi AppServer, AppClient, OpenIMServer a OpenIMSDK pro podrobné vysvětlení.
![App-OpenIM Relationship](../images/oepnim-design.png)
## 🚀 O OpenIMSDK
**OpenIMSDK** je IM SDK navržený pro**OpenIMServer**, vytvořený speciálně pro vkládání do klientských aplikací. Jeho hlavní vlastnosti a moduly jsou následující:
- 🌟 Hlavní vlastnosti:
- 📦 Místní úložiště
- 🔔 Zpětná volání posluchačů
- 🛡️ API obalování
- 🌐 Správa připojení
- 📚 hlavní moduly:
1. 🚀 Inicializace a přihlášení
2. 👤 Správa uživatelů
3. 👫 Správa přátel
4. 🤖 Skupinové funkce
5. 💬 Zpracování konverzace
Je postaven pomocí Golang a podporuje nasazení napříč platformami, což zajišťuje konzistentní přístup na všech platformách.
👉 **[Prozkoumat GO SDK](https://github.com/openimsdk/openim-sdk-core)**
## 🌐 O OpenIMServeru
- **OpenIMServer** má následující vlastnosti:
- 🌐 Architektura mikroslužeb: Podporuje režim clusteru, včetně brány a více služeb RPC.
- 🚀 Různé metody nasazení: Podporuje nasazení prostřednictvím zdrojového kódu, Kubernetes nebo Docker.
- Podpora masivní uživatelské základny: Super velké skupiny se stovkami tisíc uživatelů, desítkami milionů uživatelů a miliardami zpráv.
### Vylepšené obchodní funkce:
- **REST API**: OpenIMServer nabízí REST API pro podnikové systémy, jejichž cílem je poskytnout podnikům více funkcí, jako je vytváření skupin a odesílání push zpráv přes backendová rozhraní.
- **Webhooks**: OpenIMServer poskytuje možnosti zpětného volání pro rozšíření více obchodních formulářů. Zpětné volání znamená, že OpenIMServer odešle požadavek na obchodní server před nebo po určité události, jako jsou zpětná volání před nebo po odeslání zprávy.
👉 **[Další informace](https://docs.openim.io/guides/introduction/product)**
## :building_construction: Celková architektura
Ponořte se do srdce funkčnosti Open-IM-Server s naším diagramem architektury.
![Overall Architecture](../images/architecture-layers.png)
## :rocket: Rychlý start
Podporujeme mnoho platforem. Zde jsou adresy pro rychlou práci na webové stránce:
👉 **[Online webová ukázka OpenIM](https://web-enterprise.rentsoft.cn/)**
🤲 Pro usnadnění uživatelské zkušenosti nabízíme různá řešení nasazení. Způsob nasazení si můžete vybrat ze seznamu níže:
- **[Průvodce nasazením zdrojového kódu](https://docs.openim.io/guides/gettingStarted/imSourceCodeDeployment)**
- **[Docker Deployment Guide](https://docs.openim.io/guides/gettingStarted/dockerCompose)**
- **[Průvodce nasazením Kubernetes](https://docs.openim.io/guides/gettingStarted/k8s-deployment)**
- **[Průvodce nasazením pro vývojáře Mac](https://docs.openim.io/guides/gettingstarted/mac-deployment-guide)**
## :hammer_and_wrench: Chcete-li začít vyvíjet OpenIM
[![Open in Dev Container](https://img.shields.io/static/v1?label=Dev%20Container&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/github/openimsdk/open-im-server-deploy)
OpenIM Naším cílem je vybudovat špičkovou open source komunitu. Máme soubor standardů v [komunitním repozitáři](https://github.com/OpenIMSDK/community).
Pokud byste chtěli přispět do tohoto úložiště Open-IM-Server, přečtěte si naši [dokumentaci pro přispěvatele](https://github.com/openimsdk/open-im-server-deploy/blob/main/CONTRIBUTING.md).
Než začnete, ujistěte se, že jsou vaše změny vyžadovány. Nejlepší pro to je vytvořit [nová diskuze](https://github.com/openimsdk/open-im-server-deploy/discussions/new/choose) NEBO [Slack Communication](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A), nebo pokud narazíte na problém, [nahlásit jej](https://github.com/openimsdk/open-im-server-deploy/issues/new/choose) jako první.
- [OpenIM API Reference](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/api.md)
- [Protokolování OpenIM Bash](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/bash-log.md)
- [Akce OpenIM CI/CD](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/cicd-actions.md)
- [Konvence kódu OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/code-conventions.md)
- [Pokyny k zavázání OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/commit.md)
- [Průvodce vývojem OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/development.md)
- [Struktura adresáře OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/directory.md)
- [Nastavení prostředí OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/environment.md)
- [Referenční kód chybového kódu OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/error-code.md)
- [Pracovní postup OpenIM Git](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/git-workflow.md)
- [OpenIM Git Cherry Pick Guide](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/gitcherry-pick.md)
- [Pracovní postup OpenIM GitHub](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/github-workflow.md)
- [standardy kódu OpenIM Go](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/go-code.md)
- [Pokyny pro obrázky OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/images.md)
- [Počáteční konfigurace OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/init-config.md)
- [Průvodce instalací OpenIM Docker](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-docker.md)
- [nstalace systému OpenIM OpenIM Linux](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-openim-linux-system.md)
- [OpenIM Linux Development Guide](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/linux-development.md)
- [Průvodce místními akcemi OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/local-actions.md)
- [Konvence protokolování OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/logging.md)
- [Offline nasazení OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/offline-deployment.md)
- [Nástroje protokolu OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/protoc-tools.md)
- [Příručka testování OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/test.md)
- [OpenIM Utility Go](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-go.md)
- [OpenIM Makefile Utilities](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-makefile.md)
- [OpenIM Script Utilities](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-scripts.md)
- [OpenIM Versioning](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/version.md)
- [Spravovat backend a monitorovat nasazení](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/prometheus-grafana.md)
- [Průvodce nasazením pro vývojáře Mac pro OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/mac-developer-deployment-guide.md)
## :busts_in_silhouette: Společenství
- 📚 [Komunita OpenIM](https://github.com/OpenIMSDK/community)
- 💕 [Zájmová skupina OpenIM](https://github.com/Openim-sigs)
- 🚀 [Připojte se k naší komunitě Slack](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
- :eyes: [Připojte se k našemu wechatu](https://openim-1253691595.cos.ap-nanjing.myqcloud.com/WechatIMG20.jpeg)
## :calendar: Komunitní setkání
Chceme, aby se do naší komunity a přispívání kódu zapojil kdokoli, nabízíme dárky a odměny a vítáme vás, abyste se k nám připojili každý čtvrtek večer.
Naše konference je v [OpenIM Slack](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A) 🎯, pak můžete vyhledat kanál Open-IM-Server a připojit se
Zaznamenáváme si každou [dvoutýdenní schůzku](https://github.com/orgs/OpenIMSDK/discussions/categories/meeting)do [diskuzí na GitHubu](https://github.com/openimsdk/open-im-server-deploy/discussions/categories/meeting), naše historické poznámky ze schůzek a také záznamy schůzek jsou k dispozici na [Dokumenty Google :bookmark_tabs:](https://docs.google.com/document/d/1nx8MDpuG74NASx081JcCpxPgDITNTpIIos0DS6Vr9GU/edit?usp=sharing).
## :eyes: Kdo používá OpenIM
Podívejte se na naši stránku [případové studie uživatelů](https://github.com/OpenIMSDK/community/blob/main/ADOPTERS.md), kde najdete seznam uživatelů projektu. Neváhejte zanechat[📝komentář](https://github.com/openimsdk/open-im-server-deploy/issues/379) a podělte se o svůj případ použití.
## :page_facing_up: License
OpenIM je licencován pod licencí Apache 2.0. Úplný text licence naleznete v [LICENCE](https://github.com/openimsdk/open-im-server-deploy/tree/main/LICENSE).
Logo OpenIM, včetně jeho variací a animovaných verzí, zobrazené v tomto úložišti [OpenIM](https://github.com/openimsdk/open-im-server-deploy)v adresářích [assets/logo](./assets/logo) a [assets/logo-gif](assets/logo-gif) je chráněno autorským právem.
## 🔮 Děkujeme našim přispěvatelům!
<a href="https://github.com/openimsdk/open-im-server-deploy/graphs/contributors">
<img src="https://contrib.rocks/image?repo=openimsdk/open-im-server-deploy" />
</a>

185
docs/readme/README_da.md Normal file
View File

@@ -0,0 +1,185 @@
<p align="center">
<a href="https://openim.io">
<img src="../../assets/logo-gif/openim-logo.gif" width="60%" height="30%"/>
</a>
</p>
<div align="center">
[![Stars](https://img.shields.io/github/stars/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=ff69b4)](https://github.com/openimsdk/open-im-server-deploy/stargazers)
[![Forks](https://img.shields.io/github/forks/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=blue)](https://github.com/openimsdk/open-im-server-deploy/network/members)
[![Codecov](https://img.shields.io/codecov/c/github/openimsdk/open-im-server-deploy?style=for-the-badge&logo=codecov&colorB=orange)](https://app.codecov.io/gh/openimsdk/open-im-server-deploy)
[![Go Report Card](https://goreportcard.com/badge/github.com/openimsdk/open-im-server-deploy?style=for-the-badge)](https://goreportcard.com/report/github.com/openimsdk/open-im-server-deploy)
[![Go Reference](https://img.shields.io/badge/Go%20Reference-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://pkg.go.dev/git.imall.cloud/openim/open-im-server-deploy)
[![License](https://img.shields.io/badge/license-Apache--2.0-green?style=for-the-badge)](https://github.com/openimsdk/open-im-server-deploy/blob/main/LICENSE)
[![Slack](https://img.shields.io/badge/Slack-500%2B-blueviolet?style=for-the-badge&logo=slack&logoColor=white)](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
[![Best Practices](https://img.shields.io/badge/Best%20Practices-purple?style=for-the-badge)](https://www.bestpractices.dev/projects/8045)
[![Good First Issues](https://img.shields.io/github/issues/openimsdk/open-im-server-deploy/good%20first%20issue?style=for-the-badge&logo=github)](https://github.com/openimsdk/open-im-server-deploy/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22good+first+issue%22)
[![Language](https://img.shields.io/badge/Language-Go-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://golang.org/)
<p align="center">
<a href="../../README.md">English</a> ·
<a href="../../README_zh_CN.md">中文</a> ·
<a href="./README_uk.md">Українська</a> ·
<a href="./README_cs.md">Česky</a> ·
<a href="./README_hu.md">Magyar</a> ·
<a href="./README_es.md">Español</a> ·
<a href="./README_fa.md">فارسی</a> ·
<a href="./README_fr.md">Français</a> ·
<a href="./README_de.md">Deutsch</a> ·
<a href="./README_pl.md">Polski</a> ·
<a href="./README_id.md">Indonesian</a> ·
<a href="./README_fi.md">Suomi</a> ·
<a href="./README_ml.md">മലയാളം</a> ·
<a href="./README_ja.md">日本語</a> ·
<a href="./README_nl.md">Nederlands</a> ·
<a href="./README_it.md">Italiano</a> ·
<a href="./README_ru.md">Русский</a> ·
<a href="./README_pt_BR.md">Português (Brasil)</a> ·
<a href="./README_eo.md">Esperanto</a> ·
<a href="./README_ko.md">한국어</a> ·
<a href="./README_ar.md">العربي</a> ·
<a href="./README_vi.md">Tiếng Việt</a> ·
<a href="./README_da.md">Dansk</a> ·
<a href="./README_el.md">Ελληνικά</a> ·
<a href="./README_tr.md">Türkçe</a>
</p>
</div>
</p>
## :busts_in_silhouette: Fællesskab
- 📚 [OpenIM-fællesskab](https://github.com/OpenIMSDK/community)
- 💕 [OpenIM-interessegruppe](https://github.com/Openim-sigs)
- 🚀 [Deltag i vores Slack-fællesskab](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
- :eyes: [Deltag i vores WeChat (微信群)](https://openim-1253691595.cos.ap-nanjing.myqcloud.com/WechatIMG20.jpeg)
- 👫 [Deltag i vores Reddit](https://www.reddit.com/r/OpenIMessaging)
- 💬 [Følg vores Twitter-konto](https://twitter.com/openimsdk)
## Ⓜ️ Om OpenIM
OpenIM er en serviceplatform designet specifikt til integration af chat, lyd-videoopkald, notifikationer og AI-chatbots i applikationer. Den tilbyder en række kraftfulde API'er og Webhooks, som gør det let for udviklere at integrere disse interaktive funktioner i deres applikationer. OpenIM er ikke en selvstændig chatapplikation, men fungerer snarere som en platform, der understøtter andre applikationer i at opnå omfattende kommunikationsfunktionaliteter. Følgende diagram illustrerer interaktionen mellem AppServer, AppClient, OpenIMServer og OpenIMSDK for at forklare detaljeret.
![App-OpenIM Relationship](../images/oepnim-design.png)
## 🚀 Om OpenIMSDK
**OpenIMSDK** er en IM SDK designet til **OpenIMServer**, skabt specifikt til indlejring i klientapplikationer. Dens vigtigste funktioner og moduler er som følger:
- 🌟 Hovedfunktioner:
- 📦 Lokal lagring
- 🔔 Lytter-callbacks
- 🛡️ API-indkapsling
- 🌐 Forbindelsesstyring
## 📚 Hovedmoduler:
1. 🚀 Initialisering og login
2. 👤 Brugerstyring
3. 👫 Venstyring
4. 🤖 Gruppefunktioner
5. 💬 Håndtering af samtaler
Det er bygget ved hjælp af Golang og understøtter tværplatformsudrulning, hvilket sikrer en konsekvent adgangsoplevelse på tværs af alle platforme.
👉 **[Udforsk GO SDK](https://github.com/openimsdk/openim-sdk-core)**
## 🌐 Om OpenIMServer
- **OpenIMServer** har følgende karakteristika:
- 🌐 Mikroservicarkitektur: Understøtter klyngetilstand, inklusive en gateway og flere rpc-tjenester.
- 🚀 Forskellige udrulningsmetoder: Understøtter udrulning via kildekode, Kubernetes eller Docker.
- Støtte til massiv brugerbase: Super store grupper med hundredtusinder af brugere, titusinder af brugere og milliarder af beskeder.
### Forbedret forretningsfunktionalitet:
- **REST API**OpenIMServer tilbyder REST API'er til forretningssystemer, med det formål at give virksomheder flere funktioner, såsom at oprette grupper og sende push-beskeder gennem backend-grænseflader.
- **Webhooks**OpenIMServer giver mulighed for callback-funktionalitet for at udvide flere forretningsformer. Et callback betyder, at OpenIMServer sender en anmodning til forretningsserveren før eller efter en bestemt begivenhed, som callbacks før eller efter at have sendt en besked.
👉 **[Lær mere](https://docs.openim.io/guides/introduction/product)**
## :building_construction: Samlet Arkitektur
Dyk ned i hjertet af Open-IM-Servers funktionalitet med vores arkitekturdiagram.
![Overall Architecture](../images/architecture-layers.png)
## :rocket: Hurtig start
Vi understøtter mange platforme. Her er adresserne for hurtig oplevelse på websiden:
👉 **[OpenIM online demo](https://www.openim.io/zh/commercial)**
🤲 For at lette brugeroplevelsen tilbyder vi forskellige udrulningsløsninger. Du kan vælge din udrulningsmetode fra listen nedenfor:
- **[Vejledning til udrulning af kildekode](https://docs.openim.io/guides/gettingStarted/imSourceCodeDeployment)**
- **[Vejledning til Docker-udrulning](https://docs.openim.io/guides/gettingStarted/dockerCompose)**
- **[Vejledning til Kubernetes-udrulning](https://docs.openim.io/guides/gettingStarted/k8s-deployment)**
- **[Vejledning til Mac-udviklerudrulning](https://docs.openim.io/guides/gettingstarted/mac-deployment-guide)**
## :hammer_and_wrench: For at starte udviklingen af OpenIM
[![Open in Dev Container](https://img.shields.io/static/v1?label=Dev%20Container&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/github/openimsdk/open-im-server-deploy)
OpenIM Vores mål er at bygge et topniveau åben kildekode-fællesskab. Vi har et sæt standarder i [Community-repositoriet](https://github.com/OpenIMSDK/community).
Hvis du gerne vil bidrage til dette Open-IM-Server-repositorium, bedes du læse vores [dokumentation for bidragydere](https://github.com/openimsdk/open-im-server-deploy/blob/main/CONTRIBUTING.md).
Før du starter, skal du sikre dig, at dine ændringer er efterspurgte. Det bedste for det er at oprette en [ny diskussion](https://github.com/openimsdk/open-im-server-deploy/discussions/new/choose) ELLER [Slack-kommunikation](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A), eller hvis du finder et problem, [rapportere det](https://github.com/openimsdk/open-im-server-deploy/issues/new/choose) først.
- [OpenIM API-referencer](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/api.md)
- [OpenIM Bash-logging](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/bash-log.md)
- [OpenIM CI/CD-handlinger](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/cicd-actions.md)
- [OpenIM kodekonventioner](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/code-conventions.md)
- [OpenIM commit-retningslinjer](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/commit.md)
- [OpenIM udviklingsguide](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/development.md)
- [OpenIM mappestruktur](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/directory.md)
- [OpenIM miljøopsætning](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/environment.md)
- [OpenIM fejlkode-reference](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/error-code.md)
- [OpenIM Git-arbejdsgang](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/git-workflow.md)
- [OpenIM Git Cherry Pick-guide](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/gitcherry-pick.md)
- [OpenIM GitHub-arbejdsgang](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/github-workflow.md)
- [OpenIM Go kode-standarder](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/go-code.md)
- [OpenIM billedretningslinjer](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/images.md)
- [OpenIM initialkonfiguration](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/init-config.md)
- [OpenIM Docker installationsguide](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-docker.md)
- [OpenIM OpenIM Linux-systeminstallation](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-openim-linux-system.md)
- [OpenIM Linux-udviklingsguide](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/linux-development.md)
- [OpenIM lokale handlingsguide](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/local-actions.md)
- [OpenIM logningskonventioner](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/logging.md)
- [OpenIM offline-udrulning](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/offline-deployment.md)
- [OpenIM Protoc-værktøjer](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/protoc-tools.md)
- [OpenIM testguide](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/test.md)
- [OpenIM Utility Go](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-go.md)
- [OpenIM Makefile-værktøjer](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-makefile.md)
- [OpenIM skriptværktøjer](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-scripts.md)
- [OpenIM versionsstyring](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/version.md)
- [Administrer backend og overvåg udrulning](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/prometheus-grafana.md)
- [Mac-udviklerudrulningsguide for OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/mac-developer-deployment-guide.md)
## :calendar: Fællesskabsmøder
Vi ønsker, at alle involverer sig i vores fællesskab og bidrager med kode, vi tilbyder gaver og belønninger, og vi byder dig velkommen til at deltage hver torsdag aften.
Vores konference er på [OpenIM Slack](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A) 🎯, derefter kan du søge Open-IM-Server pipeline for at deltage.
Vi tager [notater](https://github.com/orgs/OpenIMSDK/discussions/categories/meeting) af hvert fjortendages møde i [GitHub-diskussioner](https://github.com/openimsdk/open-im-server-deploy/discussions/categories/meeting), Vores historiske mødenotater samt genudsendelser af møderne er tilgængelige på [Google Docs](https://docs.google.com/document/d/1nx8MDpuG74NASx081JcCpxPgDITNTpIIos0DS6Vr9GU/edit?usp=sharing) 📑.
## :eyes: Hvem Bruger OpenIM
Tjek vores side med [brugercasestudier](https://github.com/OpenIMSDK/community/blob/main/ADOPTERS.md) for en liste over projektbrugerne. Tøv ikke med at efterlade en 📝[kommentar](https://github.com/openimsdk/open-im-server-deploy/issues/379) og dele dit brugstilfælde.
## :page_facing_up: Licens
OpenIM er licenseret under Apache 2.0-licensen. Se [LICENSE](https://github.com/openimsdk/open-im-server-deploy/tree/main/LICENSE) for den fulde licens tekst.
OpenIM-logoet, inklusive dets variationer og animerede versioner, vist i dette repositorium [OpenIM](https://github.com/openimsdk/open-im-server-deploy) under mapperne [assets/logo](../../assets/logo) og [assets/logo-gif](../../assets/logo-gif), er beskyttet af ophavsretslove.
## 🔮 Tak til vores bidragydere!
<a href="https://github.com/openimsdk/open-im-server-deploy/graphs/contributors">
<img src="https://contrib.rocks/image?repo=openimsdk/open-im-server-deploy" />
</a>

183
docs/readme/README_el.md Normal file
View File

@@ -0,0 +1,183 @@
<p align="center">
<a href="https://openim.io">
<img src="../../assets/logo-gif/openim-logo.gif" width="60%" height="30%"/>
</a>
</p>
<div align="center">
[![Stars](https://img.shields.io/github/stars/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=ff69b4)](https://github.com/openimsdk/open-im-server-deploy/stargazers)
[![Forks](https://img.shields.io/github/forks/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=blue)](https://github.com/openimsdk/open-im-server-deploy/network/members)
[![Codecov](https://img.shields.io/codecov/c/github/openimsdk/open-im-server-deploy?style=for-the-badge&logo=codecov&colorB=orange)](https://app.codecov.io/gh/openimsdk/open-im-server-deploy)
[![Go Report Card](https://goreportcard.com/badge/github.com/openimsdk/open-im-server-deploy?style=for-the-badge)](https://goreportcard.com/report/github.com/openimsdk/open-im-server-deploy)
[![Go Reference](https://img.shields.io/badge/Go%20Reference-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://pkg.go.dev/git.imall.cloud/openim/open-im-server-deploy)
[![License](https://img.shields.io/badge/license-Apache--2.0-green?style=for-the-badge)](https://github.com/openimsdk/open-im-server-deploy/blob/main/LICENSE)
[![Slack](https://img.shields.io/badge/Slack-500%2B-blueviolet?style=for-the-badge&logo=slack&logoColor=white)](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
[![Best Practices](https://img.shields.io/badge/Best%20Practices-purple?style=for-the-badge)](https://www.bestpractices.dev/projects/8045)
[![Good First Issues](https://img.shields.io/github/issues/openimsdk/open-im-server-deploy/good%20first%20issue?style=for-the-badge&logo=github)](https://github.com/openimsdk/open-im-server-deploy/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22good+first+issue%22)
[![Language](https://img.shields.io/badge/Language-Go-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://golang.org/)
<p align="center">
<a href="../../README.md">English</a> ·
<a href="../../README_zh_CN.md">中文</a> ·
<a href="./README_uk.md">Українська</a> ·
<a href="./README_cs.md">Česky</a> ·
<a href="./README_hu.md">Magyar</a> ·
<a href="./README_es.md">Español</a> ·
<a href="./README_fa.md">فارسی</a> ·
<a href="./README_fr.md">Français</a> ·
<a href="./README_de.md">Deutsch</a> ·
<a href="./README_pl.md">Polski</a> ·
<a href="./README_id.md">Indonesian</a> ·
<a href="./README_fi.md">Suomi</a> ·
<a href="./README_ml.md">മലയാളം</a> ·
<a href="./README_ja.md">日本語</a> ·
<a href="./README_nl.md">Nederlands</a> ·
<a href="./README_it.md">Italiano</a> ·
<a href="./README_ru.md">Русский</a> ·
<a href="./README_pt_BR.md">Português (Brasil)</a> ·
<a href="./README_eo.md">Esperanto</a> ·
<a href="./README_ko.md">한국어</a> ·
<a href="./README_ar.md">العربي</a> ·
<a href="./README_vi.md">Tiếng Việt</a> ·
<a href="./README_da.md">Dansk</a> ·
<a href="./README_el.md">Ελληνικά</a> ·
<a href="./README_tr.md">Türkçe</a>
</p>
</div>
</p>
## Ⓜ️ Σχετικά με το OpenIM
Το OpenIM είναι μια πλατφόρμα υπηρεσιών σχεδιασμένη ειδικά για την ενσωμάτωση συνομιλίας, κλήσεων ήχου-βίντεο, ειδοποιήσεων και chatbots AI σε εφαρμογές. Παρέχει μια σειρά από ισχυρά API και Webhooks, επιτρέποντας στους προγραμματιστές να ενσωματώσουν εύκολα αυτές τις αλληλεπιδραστικές λειτουργίες στις εφαρμογές τους. Το OpenIM δεν είναι μια αυτόνομη εφαρμογή συνομιλίας, αλλά λειτουργεί ως πλατφόρμα υποστήριξης άλλων εφαρμογών για την επίτευξη πλούσιων λειτουργιών επικοινωνίας. Το παρακάτω διάγραμμα απεικονίζει την αλληλεπίδραση μεταξύ AppServer, AppClient, OpenIMServer και OpenIMSDK για να εξηγήσει αναλυτικά.
![App-OpenIM Relationship](../../docs/images/oepnim-design.png)
## 🚀 Σχετικά με το OpenIMSDK
Το **OpenIMSDK** είναι ένα SDK για αμεση ανταλλαγή μηνυμάτων σχεδιασμένο για το **OpenIMServer**, δημιουργήθηκε ειδικά για ενσωμάτωση σε εφαρμογές πελατών. Οι κύριες δυνατότητες και μονάδες του είναι οι εξής:
- 🌟 Κύριες Δυνατότητες:
- 📦 Τοπική αποθήκευση
- 🔔 Callbacks ακροατών
- 🛡️ Περιτύλιγμα API
- 🌐 Διαχείριση σύνδεσης
- 📚 Κύριες Μονάδες:
1. 🚀 Αρχικοποίηση και Σύνδεση
2. 👤 Διαχείριση Χρηστών
3. 👫 Διαχείριση Φίλων
4. 🤖 Λειτουργίες Ομάδας
5. 💬 Διαχείριση Συνομιλιών
Είναι κατασκευασμένο χρησιμοποιώντας Golang και υποστηρίζει διασταυρούμενη πλατφόρμα ανάπτυξης, διασφαλίζοντας μια συνεπή εμπειρία πρόσβασης σε όλες τις πλατφόρμες.
👉 **[Εξερευνήστε το GO SDK](https://github.com/openimsdk/openim-sdk-core)**
## 🌐 Σχετικά με το OpenIMServer
- Το **OpenIMServer** έχει τις ακόλουθες χαρακτηριστικές:
- 🌐 Αρχιτεκτονική μικροϋπηρεσιών: Υποστηρίζει λειτουργία σε σύμπλεγμα, περιλαμβάνοντας έναν πύλη και πολλαπλές υπηρεσίες rpc.
- 🚀 Διάφοροι τρόποι ανάπτυξης: Υποστηρίζει ανάπτυξη μέσω πηγαίου κώδικα, Kubernetes, ή Docker.
- Υποστήριξη για τεράστια βάση χρηστών: Πολύ μεγάλες ομάδες με εκατοντάδες χιλιάδες χρήστες, δεκάδες εκατομμύρια χρήστες και δισεκατομμύρια μηνύματα.
### Ενισχυμένη Επιχειρηματική Λειτουργικότητα:
- **REST API**: Το OpenIMServer προσφέρει REST APIs για επιχειρηματικά συστήματα, με στόχο την ενδυνάμωση των επιχειρήσεων με περισσότερες λειτουργικότητες, όπως η δημιουργία ομάδων και η αποστολή μηνυμάτων push μέσω backend διεπαφών.
- **Webhooks**: Το OpenIMServer παρέχει δυνατότητες επανάκλησης για την επέκταση περισσότερων επιχειρηματικών μορφών. Μια επανάκληση σημαίνει ότι το OpenIMServer στέλνει ένα αίτημα στον επιχειρηματικό διακομιστή πριν ή μετά από ένα συγκεκριμένο γεγονός, όπως επανακλήσεις πριν ή μετά την αποστολή ενός μηνύματος.
👉 **[Μάθετε περισσότερα](https://docs.openim.io/guides/introduction/product)**
## :building_construction: Συνολική Αρχιτεκτονική
Εξερευνήστε σε βάθος τη λειτουργικότητα του Open-IM-Server με το διάγραμμα αρχιτεκτονικής μας.
![Overall Architecture](../../docs/images/architecture-layers.png)
## :rocket: Γρήγορη Εκκίνηση
Υποστηρίζουμε πολλές πλατφόρμες. Εδώ είναι οι διευθύνσεις για γρήγορη εμπειρία στην πλευρά του διαδικτύου:
👉 **[Διαδικτυακή επίδειξη του OpenIM](https://web-enterprise.rentsoft.cn/)**
🤲 Για να διευκολύνουμε την εμπειρία του χρήστη, προσφέρουμε διάφορες λύσεις ανάπτυξης. Μπορείτε να επιλέξετε τη μέθοδο ανάπτυξης σας από την παρακάτω λίστα:
- **[Οδηγός Ανάπτυξης Κώδικα Πηγής](https://docs.openim.io/guides/gettingStarted/imSourceCodeDeployment)**
- **[δηγός Ανάπτυξης μέσω Docker](https://docs.openim.io/guides/gettingStarted/dockerCompose)**
- **[Οδηγός Ανάπτυξης Kubernetes](https://docs.openim.io/guides/gettingStarted/k8s-deployment)**
- **[Οδηγός Ανάπτυξης για Αναπτυξιακούς στο Mac](https://docs.openim.io/guides/gettingstarted/mac-deployment-guide)**
## :hammer_and_wrench: Για να Αρχίσετε την Ανάπτυξη του OpenIM
[![Άνοιγμα σε Dev Container](https://img.shields.io/static/v1?label=Dev%20Container&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/github/openimsdk/open-im-server-deploy)
OpenIM Στόχος μας είναι να δημιουργήσουμε μια κορυφαίου επιπέδου ανοιχτή πηγή κοινότητας. Διαθέτουμε ένα σύνολο προτύπων, στο [Αποθετήριο Κοινότητας](https://github.com/OpenIMSDK/community).
Εάν θέλετε να συνεισφέρετε σε αυτό το αποθετήριο Open-IM-Server, παρακαλούμε διαβάστε την [τεκμηρίωση συνεισφέροντος](https://github.com/openimsdk/open-im-server-deploy/blob/main/CONTRIBUTING.md).
Πριν ξεκινήσετε, παρακαλούμε βεβαιωθείτε ότι οι αλλαγές σας είναι ζητούμενες. Το καλύτερο για αυτό είναι να δημιουργήσετε ένα [νέα συζήτηση](https://github.com/openimsdk/open-im-server-deploy/discussions/new/choose) ή [Επικοινωνία Slack](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A), ή αν βρείτε ένα ζήτημα, [αναφέρετέ το](https://github.com/openimsdk/open-im-server-deploy/issues/new/choose) πρώτα.
- [Αναφορά API του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/api.md)
- [Καταγραφή Bash του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/bash-log.md)
- [Ενέργειες CI/CD του OpenIMs](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/cicd-actions.md)
- [Συμβάσεις Κώδικα του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/code-conventions.md)
- [Οδηγίες Commit του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/commit.md)
- [Οδηγός Ανάπτυξης του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/development.md)
- [Δομή Καταλόγου του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/directory.md)
- [Ρύθμιση Περιβάλλοντος του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/environment.md)
- [Αναφορά Κωδικών Σφάλματος του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/error-code.md)
- [Ροή Εργασίας Git του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/git-workflow.md)
- [Οδηγός Cherry Pick του Git του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/gitcherry-pick.md)
- [Ροή Εργασίας GitHub του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/github-workflow.md)
- [Πρότυπα Κώδικα Go του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/go-code.md)
- [Οδηγίες Εικόνας του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/images.md)
- [Αρχική Διαμόρφωση του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/init-config.md)
- [Οδηγός Εγκατάστασης Docker του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-docker.md)
- [Οδηγός Εγκατάστασης Συστήματος Linux του Open](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-openim-linux-system.md)
- [Οδηγός Ανάπτυξης Linux του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/linux-development.md)
- [Οδηγός Τοπικών Δράσεων του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/local-actions.md)
- [Συμβάσεις Καταγραφής του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/logging.md)
- [Αποστολή Εκτός Σύνδεσης του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/offline-deployment.md)
- [Εργαλεία Protoc του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/protoc-tools.md)
- [Οδηγός Δοκιμών του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/test.md)
- [Χρησιμότητα Go του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-go.md)
- [Χρησιμότητες Makefile του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-makefile.md)
- [Χρησιμότητες Σεναρίου του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-scripts.md)
- [Έκδοση του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/version.md)
- [Διαχείριση backend και παρακολούθηση ανάπτυξης](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/prometheus-grafana.md)
- [Οδηγός Ανάπτυξης για Προγραμματιστές Mac του OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/mac-developer-deployment-guide.md)
## :busts_in_silhouette: Κοινότητα
- 📚 [Κοινότητα OpenIM](https://github.com/OpenIMSDK/community)
- 💕 [Ομάδα Ενδιαφέροντος OpenIM](https://github.com/Openim-sigs)
- 🚀 [Εγγραφείτε στην κοινότητα Slack μας](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
- :eyes: [γγραφείτε στην ομάδα μας wechat (微信群)](https://openim-1253691595.cos.ap-nanjing.myqcloud.com/WechatIMG20.jpeg)
## :calendar: Συναντήσεις της κοινότητας
Θέλουμε οποιονδήποτε να εμπλακεί στην κοινότητά μας και να συνεισφέρει κώδικα. Προσφέρουμε δώρα και ανταμοιβές και σας καλωσορίζουμε να μας ενταχθείτε κάθε Πέμπτη βράδυ.
Η διάσκεψή μας είναι στο [OpenIM Slack](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A) 🎯, στη συνέχεια μπορείτε να αναζητήσετε τη διαδικασία Open-IM-Server για να συμμετάσχετε
Κάνουμε σημειώσεις για κάθε μια [Σημειώνουμε κάθε διμηνιαία συνάντηση](https://github.com/orgs/OpenIMSDK/discussions/categories/meeting) στις [συζητήσεις του GitHub](https://github.com/openimsdk/open-im-server-deploy/discussions/categories/meeting), Οι ιστορικές μας σημειώσεις συναντήσεων, καθώς και οι επαναλήψεις των συναντήσεων είναι διαθέσιμες στο[Έγγραφα της Google :bookmark_tabs:](https://docs.google.com/document/d/1nx8MDpuG74NASx081JcCpxPgDITNTpIIos0DS6Vr9GU/edit?usp=sharing).
## :eyes: Ποιοί Χρησιμοποιούν το OpenIM
Ελέγξτε τη σελίδα με τις [μελέτες περίπτωσης χρήσης ](https://github.com/OpenIMSDK/community/blob/main/ADOPTERS.md) μας για μια λίστα των χρηστών του έργου. Μην διστάσετε να αφήσετε ένα[📝σχόλιο](https://github.com/openimsdk/open-im-server-deploy/issues/379) και να μοιραστείτε την περίπτωση χρήσης σας.
## :page_facing_up: Άδεια Χρήσης
Το OpenIM διατίθεται υπό την άδεια Apache 2.0. Δείτε τη [ΑΔΕΙΑ ΧΡΗΣΗΣ](https://github.com/openimsdk/open-im-server-deploy/tree/main/LICENSE) για το πλήρες κείμενο της άδειας.
Το λογότυπο του OpenIM, συμπεριλαμβανομένων των παραλλαγών και των κινούμενων εικόνων, που εμφανίζονται σε αυτό το αποθετήριο[OpenIM](https://github.com/openimsdk/open-im-server-deploy) υπό τις διευθύνσεις [assets/logo](../../assets/logo) και [assets/logo-gif](../../assets/logo-gif) προστατεύονται από τους νόμους περί πνευματικής ιδιοκτησίας.
## 🔮 Ευχαριστούμε τους συνεισφέροντες μας!
<a href="https://github.com/openimsdk/open-im-server-deploy/graphs/contributors">
<img src="https://contrib.rocks/image?repo=openimsdk/open-im-server-deploy" />
</a>

185
docs/readme/README_es.md Normal file
View File

@@ -0,0 +1,185 @@
<p align="center">
<a href="https://openim.io">
<img src="../../assets/logo-gif/openim-logo.gif" width="60%" height="30%"/>
</a>
</p>
<div align="center">
[![Stars](https://img.shields.io/github/stars/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=ff69b4)](https://github.com/openimsdk/open-im-server-deploy/stargazers)
[![Forks](https://img.shields.io/github/forks/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=blue)](https://github.com/openimsdk/open-im-server-deploy/network/members)
[![Codecov](https://img.shields.io/codecov/c/github/openimsdk/open-im-server-deploy?style=for-the-badge&logo=codecov&colorB=orange)](https://app.codecov.io/gh/openimsdk/open-im-server-deploy)
[![Go Report Card](https://goreportcard.com/badge/github.com/openimsdk/open-im-server-deploy?style=for-the-badge)](https://goreportcard.com/report/github.com/openimsdk/open-im-server-deploy)
[![Go Reference](https://img.shields.io/badge/Go%20Reference-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://pkg.go.dev/git.imall.cloud/openim/open-im-server-deploy)
[![License](https://img.shields.io/badge/license-Apache--2.0-green?style=for-the-badge)](https://github.com/openimsdk/open-im-server-deploy/blob/main/LICENSE)
[![Slack](https://img.shields.io/badge/Slack-500%2B-blueviolet?style=for-the-badge&logo=slack&logoColor=white)](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
[![Best Practices](https://img.shields.io/badge/Best%20Practices-purple?style=for-the-badge)](https://www.bestpractices.dev/projects/8045)
[![Good First Issues](https://img.shields.io/github/issues/openimsdk/open-im-server-deploy/good%20first%20issue?style=for-the-badge&logo=github)](https://github.com/openimsdk/open-im-server-deploy/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22good+first+issue%22)
[![Language](https://img.shields.io/badge/Language-Go-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://golang.org/)
<p align="center">
<a href="../../README.md">English</a> ·
<a href="../../README_zh_CN.md">中文</a> ·
<a href="./README_uk.md">Українська</a> ·
<a href="./README_cs.md">Česky</a> ·
<a href="./README_hu.md">Magyar</a> ·
<a href="./README_es.md">Español</a> ·
<a href="./README_fa.md">فارسی</a> ·
<a href="./README_fr.md">Français</a> ·
<a href="./README_de.md">Deutsch</a> ·
<a href="./README_pl.md">Polski</a> ·
<a href="./README_id.md">Indonesian</a> ·
<a href="./README_fi.md">Suomi</a> ·
<a href="./README_ml.md">മലയാളം</a> ·
<a href="./README_ja.md">日本語</a> ·
<a href="./README_nl.md">Nederlands</a> ·
<a href="./README_it.md">Italiano</a> ·
<a href="./README_ru.md">Русский</a> ·
<a href="./README_pt_BR.md">Português (Brasil)</a> ·
<a href="./README_eo.md">Esperanto</a> ·
<a href="./README_ko.md">한국어</a> ·
<a href="./README_ar.md">العربي</a> ·
<a href="./README_vi.md">Tiếng Việt</a> ·
<a href="./README_da.md">Dansk</a> ·
<a href="./README_el.md">Ελληνικά</a> ·
<a href="./README_tr.md">Türkçe</a>
</p>
</div>
</p>
## Ⓜ️ Acerca de OpenIM
OpenIM es una plataforma de servicio diseñada específicamente para integrar chat, llamadas de audio y video, notificaciones y chatbots de IA en aplicaciones. Proporciona una gama de potentes API y Webhooks, lo que permite a los desarrolladores incorporar fácilmente estas características interactivas en sus aplicaciones. OpenIM no es una aplicación de chat independiente, sino que sirve como una plataforma para apoyar a otras aplicaciones en lograr funcionalidades de comunicación enriquecidas. El siguiente diagrama ilustra la interacción entre AppServer, AppClient, OpenIMServer y OpenIMSDK para explicar en detalle.
![Relación App-OpenIM](../../docs/images/oepnim-design.png)
## 🚀 Acerca de OpenIMSDK
**OpenIMSDK** es un SDK de mensajería instantánea diseñado para **OpenIMServer**, creado específicamente para su incorporación en aplicaciones cliente. Sus principales características y módulos son los siguientes:
- 🌟 Características Principales:
- 📦 Almacenamiento local
- 🔔 Callbacks de escuchas
- 🛡️ Envoltura de API
- 🌐 Gestión de conexiones
- 📚 Módulos Principales:
1. 🚀 Inicialización y acceso
2. 👤 Gestión de usuarios
3. 👫 Gestión de amigos
4. 🤖 Funciones de grupo
5. 💬 Manejo de conversaciones
Está construido con Golang y soporta despliegue multiplataforma, asegurando una experiencia de acceso consistente en todas las plataformas.
👉 **[Explora el SDK de GO](https://github.com/openimsdk/openim-sdk-core)**
## 🌐 Acerca de OpenIMServer
- **OpenIMServer** tiene las siguientes características:
- 🌐 Arquitectura de microservicios: Soporta modo cluster, incluyendo un gateway y múltiples servicios rpc.
- 🚀 Métodos de despliegue diversos: Soporta el despliegue a través de código fuente, Kubernetes o Docker.
- Soporte para una base de usuarios masiva: Grupos super grandes con cientos de miles de usuarios, decenas de millones de usuarios y miles de millones de mensajes.
### Funcionalidad Empresarial Mejorada:
- **API REST**: OpenIMServer ofrece APIs REST para sistemas empresariales, destinadas a empoderar a las empresas con más funcionalidades, como la creación de grupos y el envío de mensajes push a través de interfaces de backend.
- **Webhooks**: OpenIMServer proporciona capacidades de callback para extender más formas de negocio. Un callback significa que OpenIMServer envía una solicitud al servidor empresarial antes o después de un cierto evento, como callbacks antes o después de enviar un mensaje.
👉 **[Aprende más](https://docs.openim.io/guides/introduction/product)**
## :building_construction: Arquitectura General
Adéntrate en el corazón de la funcionalidad de Open-IM-Server con nuestro diagrama de arquitectura.
![Arquitectura General](../../docs/images/architecture-layers.png)
## :rocket: Inicio Rápido
:rocket: Inicio Rápido
Apoyamos muchas plataformas. Aquí están las direcciones para una experiencia rápida en el lado web:
👉 **[ Demostración web en línea de OpenIM](https://web-enterprise.rentsoft.cn/)**
🤲 Para facilitar la experiencia del usuario, ofrecemos varias soluciones de despliegue. Puedes elegir tu método de despliegue de la lista a continuación:
- **[Guía de Despliegue de Código Fuente](https://docs.openim.io/guides/gettingStarted/imSourceCodeDeployment)**
- **[Guía de Despliegue con Docker](https://docs.openim.io/guides/gettingStarted/dockerCompose)**
- **[Guía de Despliegue con Kubernetes](https://docs.openim.io/guides/gettingStarted/k8s-deployment)**
- **[Guía de Despliegue para Desarrolladores en Mac](https://docs.openim.io/guides/gettingstarted/mac-deployment-guide)**
## :hammer_and_wrench: Para Comenzar a Desarrollar en OpenIM
[![Abrir en Contenedor de Desarrollo](https://img.shields.io/static/v1?label=Dev%20Container&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/github/openimsdk/open-im-server-deploy)
Nuestro objetivo en OpenIM es construir una comunidad de código abierto de nivel superior. Tenemos un conjunto de estándares,
en el [repositorio de la Comunidad.](https://github.com/OpenIMSDK/community).
Si te gustaría contribuir a este repositorio de Open-IM-Server, por favor lee nuestra [documentación para colaboradores](https://github.com/openimsdk/open-im-server-deploy/blob/main/CONTRIBUTING.md).
Antes de comenzar, asegúrate de que tus cambios sean demandados. Lo mejor para eso es crear una [nueva discusión](https://github.com/openimsdk/open-im-server-deploy/discussions/new/choose) O [Comunicación en Slack](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A), o si encuentras un problema, [repórtalo](https://github.com/openimsdk/open-im-server-deploy/issues/new/choose) primero.
- [Referencia de API de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/api.md)
- [Registro de Bash de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/bash-log.md)
- [Acciones de CI/CD de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/cicd-actions.md)
- [Convenciones de Código de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/code-conventions.md)
- [Guías de Commit de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/commit.md)
- [Guía de Desarrollo de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/development.md)
- [Estructura de Directorios de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/directory.md)
- [Configuración de Entorno de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/environment.md)
- [Referencia de Códigos de Error de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/error-code.md)
- [Flujo de Trabajo de Git de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/git-workflow.md)
- [Guía de Cherry Pick de Git de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/gitcherry-pick.md)
- [Flujo de Trabajo de GitHub de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/github-workflow.md)
- [Estándares de Código Go de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/go-code.md)
- [Guías de Imágenes de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/images.md)
- [Configuración Inicial de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/init-config.md)
- [Guía de Instalación de Docker de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-docker.md)
- [Instalación del Sistema Linux de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-openim-linux-system.md)
- [Guía de Desarrollo Linux de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/linux-development.md)
- [Guía de Acciones Locales de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/local-actions.md)
- [Convenciones de Registro de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/logging.md)
- [Despliegue sin Conexión de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/offline-deployment.md)
- [Herramientas Protoc de OpenIMM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/protoc-tools.md)
- [Guía de Pruebas de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/test.md)
- [Utilidades Go de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-go.md)
- [Utilidades de Makefile de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-makefile.md)
- [Utilidades de Script de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-scripts.md)
- [Versionado de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/version.md)
- [Gestión de backend y despliegue de monitoreo](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/prometheus-grafana.md)
- [Guía de Despliegue para Desarrolladores Mac de OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/mac-developer-deployment-guide.md)
## :busts_in_silhouette: Comunidad
- 📚 [Comunidad de OpenIM](https://github.com/OpenIMSDK/community)
- 💕 [Grupo de Interés de OpenIM](https://github.com/Openim-sigs)
- 🚀 [Únete a nuestra comunidad de Slack](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
- :eyes: [Únete a nuestro wechat (微信群)](https://openim-1253691595.cos.ap-nanjing.myqcloud.com/WechatIMG20.jpeg)
## :calendar: Reuniones de la Comunidad
Queremos que cualquiera se involucre en nuestra comunidad y contribuya con código, ofrecemos regalos y recompensas, y te damos la bienvenida para que te unas a nosotros cada jueves por la noche.
Nuestra conferencia está en [OpenIM Slack](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A) 🎯, luego puedes buscar el pipeline de Open-IM-Server para unirte
Tomamos notas de cada [reunión quincenal](https://github.com/orgs/OpenIMSDK/discussions/categories/meeting) en [discusiones de GitHub](https://github.com/openimsdk/open-im-server-deploy/discussions/categories/meeting), Nuestras notas de reuniones históricas, así como las repeticiones de las reuniones están disponibles en [Google Docs :bookmark_tabs:](https://docs.google.com/document/d/1nx8MDpuG74NASx081JcCpxPgDITNTpIIos0DS6Vr9GU/edit?usp=sharing).
## :eyes: Quiénes Están Usando OpenIM
Consulta nuestros [estudios de caso de usuarios](https://github.com/OpenIMSDK/community/blob/main/ADOPTERS.md) página para obtener una lista de los usuarios del proyecto. No dudes en dejar un [📝comentario](https://github.com/openimsdk/open-im-server-deploy/issues/379) y compartir tu caso de uso.
## :page_facing_up: Licencia
OpenIM está bajo la licencia Apache 2.0. Consulta [LICENSE](https://github.com/openimsdk/open-im-server-deploy/tree/main/LICENSE) para ver el texto completo de la licencia.
El logotipo de OpenIM, incluyendo sus variaciones y versiones animadas, que se muestran en este repositorio [OpenIM](https://github.com/openimsdk/open-im-server-deploy) en los directorios [assets/logo](../../assets/logo) y [assets/logo-gif](assets/logo-gif) están protegidos por las leyes de derechos de autor.
## 🔮 iGracias a nuestros colaboradores!
<a href="https://github.com/openimsdk/open-im-server-deploy/graphs/contributors">
<img src="https://contrib.rocks/image?repo=openimsdk/open-im-server-deploy" />
</a>

183
docs/readme/README_fa.md Normal file
View File

@@ -0,0 +1,183 @@
<p align="center">
<a href="https://openim.io">
<img src="../../assets/logo-gif/openim-logo.gif" width="60%" height="30%"/>
</a>
</p>
<div align="center">
[![Stars](https://img.shields.io/github/stars/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=ff69b4)](https://github.com/openimsdk/open-im-server-deploy/stargazers)
[![Forks](https://img.shields.io/github/forks/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=blue)](https://github.com/openimsdk/open-im-server-deploy/network/members)
[![Codecov](https://img.shields.io/codecov/c/github/openimsdk/open-im-server-deploy?style=for-the-badge&logo=codecov&colorB=orange)](https://app.codecov.io/gh/openimsdk/open-im-server-deploy)
[![Go Report Card](https://goreportcard.com/badge/github.com/openimsdk/open-im-server-deploy?style=for-the-badge)](https://goreportcard.com/report/github.com/openimsdk/open-im-server-deploy)
[![Go Reference](https://img.shields.io/badge/Go%20Reference-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://pkg.go.dev/git.imall.cloud/openim/open-im-server-deploy)
[![License](https://img.shields.io/badge/license-Apache--2.0-green?style=for-the-badge)](https://github.com/openimsdk/open-im-server-deploy/blob/main/LICENSE)
[![Slack](https://img.shields.io/badge/Slack-500%2B-blueviolet?style=for-the-badge&logo=slack&logoColor=white)](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
[![Best Practices](https://img.shields.io/badge/Best%20Practices-purple?style=for-the-badge)](https://www.bestpractices.dev/projects/8045)
[![Good First Issues](https://img.shields.io/github/issues/openimsdk/open-im-server-deploy/good%20first%20issue?style=for-the-badge&logo=github)](https://github.com/openimsdk/open-im-server-deploy/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22good+first+issue%22)
[![Language](https://img.shields.io/badge/Language-Go-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://golang.org/)
<p align="center">
<a href="../../README.md">English</a> ·
<a href="../../README_zh_CN.md">中文</a> ·
<a href="./README_uk.md">Українська</a> ·
<a href="./README_cs.md">Česky</a> ·
<a href="./README_hu.md">Magyar</a> ·
<a href="./README_es.md">Español</a> ·
<a href="./README_fa.md">فارسی</a> ·
<a href="./README_fr.md">Français</a> ·
<a href="./README_de.md">Deutsch</a> ·
<a href="./README_pl.md">Polski</a> ·
<a href="./README_id.md">Indonesian</a> ·
<a href="./README_fi.md">Suomi</a> ·
<a href="./README_ml.md">മലയാളം</a> ·
<a href="./README_ja.md">日本語</a> ·
<a href="./README_nl.md">Nederlands</a> ·
<a href="./README_it.md">Italiano</a> ·
<a href="./README_ru.md">Русский</a> ·
<a href="./README_pt_BR.md">Português (Brasil)</a> ·
<a href="./README_eo.md">Esperanto</a> ·
<a href="./README_ko.md">한국어</a> ·
<a href="./README_ar.md">العربي</a> ·
<a href="./README_vi.md">Tiếng Việt</a> ·
<a href="./README_da.md">Dansk</a> ·
<a href="./README_el.md">Ελληνικά</a> ·
<a href="./README_tr.md">Türkçe</a>
</p>
</div>
</p>
## درباره OpenIM Ⓜ️
OpenIM یک پلتفرم خدماتی است که به طور خاص برای ادغام چت، تماس های صوتی و تصویری، اعلان ها و چت ربات های هوش مصنوعی در برنامه ها طراحی شده است. این مجموعه ای از API ها و Webhook های قدرتمند را ارائه می دهد که به توسعه دهندگان این امکان را می دهد تا به راحتی این ویژگی های تعاملی را در برنامه های خود بگنجانند. OpenIM یک برنامه چت مستقل نیست، بلکه به عنوان یک پلتفرم برای پشتیبانی از برنامه های کاربردی دیگر در دستیابی به قابلیت های ارتباطی غنی عمل می کند. نمودار زیر تعامل بین AppServer، AppClient، OpenIMServer و OpenIMSDK را برای توضیح جزئیات نشان می دهد.
![App-OpenIM Relationship](../images/oepnim-design.png)
## 🚀 درباره OpenIMSDK
**OpenIMSDK** یک IM SDK است که برای **OpenIMServer** طراحی شده است که به طور خاص برای جاسازی در برنامه های مشتری ایجاد شده است. ویژگی ها و ماژول های اصلی آن به شرح زیر است:
- 🌟 ویژگی های اصلی:
- 📦 ذخیره سازی محلی
- 🔔 پاسخ تماس شنونده
- 🛡️ بسته بندی API
- 🌐 مدیریت اتصال
- 📚 ماژول های اصلی:
1. 🚀 مقداردهی اولیه و ورود
2. 👤 مدیریت کاربر
3. 👫 مدیریت دوست
4. 🤖 توابع گروه
5. 💬 مدیریت مکالمه
این برنامه با استفاده از Golang ساخته شده است و از استقرار چند پلت فرم پشتیبانی می کند و تجربه دسترسی ثابت را در تمام پلتفرم ها تضمین می کند.
👉 **[کاوش GO SDK](https://github.com/openimsdk/openim-sdk-core)**
## 🌐 درباره OpenIMServer
- **OpenIMServer** دارای ویژگی های زیر است:
- 🌐 معماری Microservice: از حالت کلاستر، از جمله یک دروازه و چندین سرویس rpc پشتیبانی می کند.
- 🚀 روش‌های استقرار متنوع: از استقرار از طریق کد منبع، Kubernetes یا Docker پشتیبانی می‌کند.
- پشتیبانی از پایگاه عظیم کاربران: گروه های فوق العاده بزرگ با صدها هزار کاربر، ده ها میلیون کاربر و میلیاردها پیام.
### عملکردهای تجاری پیشرفته:
- **REST API**: OpenIMServer APIهای REST را برای سیستم‌های تجاری ارائه می‌کند، با هدف توانمندسازی کسب‌وکارها با قابلیت‌های بیشتر، مانند ایجاد گروه‌ها و ارسال پیام‌های فشار از طریق رابط‌های باطنی.
- **Webhooks**: OpenIMServer قابلیت های پاسخ به تماس را برای گسترش بیشتر فرم های تجاری ارائه می دهد. پاسخ به تماس به این معنی است که OpenIMServer درخواستی را قبل یا بعد از یک رویداد خاص به سرور تجاری ارسال می کند، مانند تماس های قبل یا بعد از ارسال یک پیام.
👉 **[بیشتر بدانید](https://docs.openim.io/guides/introduction/product)**
## :building_construction: معماری کلی
با نمودار معماری ما به قلب عملکرد Open-IM-Server بپردازید.
![Overall Architecture](../images/architecture-layers.png)
## :rocket: شروع سریع
ما از بسیاری از پلتفرم ها پشتیبانی می کنیم. در اینجا آدرس هایی برای تجربه سریع در سمت وب آمده است:
👉 **[نسخه نمایشی وب آنلاین OpenIM](https://web-enterprise.rentsoft.cn/)**
🤲 برای تسهیل تجربه کاربر، ما راه حل های مختلف استقرار را ارائه می دهیم. می توانید روش استقرار خود را از لیست زیر انتخاب کنید:
- **[راهنمای استقرار کد منبع](https://docs.openim.io/guides/gettingStarted/imSourceCodeDeployment)**
- **[راهنمای استقرار داکر](https://docs.openim.io/guides/gettingStarted/dockerCompose)**
- **[راهنمای استقرار Kubernetes](https://docs.openim.io/guides/gettingStarted/k8s-deployment)**
- **[راهنمای استقرار توسعه دهنده مک](https://docs.openim.io/guides/gettingstarted/mac-deployment-guide)**
## :hammer_and_wrench: برای شروع توسعه OpenIM
[![Open in Dev Container](https://img.shields.io/static/v1?label=Dev%20Container&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/github/openimsdk/open-im-server-deploy)
OpenIM هدف ما ایجاد یک جامعه منبع باز سطح بالا است. ما مجموعه ای از استانداردها را در [مخزن انجمن](https://github.com/OpenIMSDK/community) داریم..
اگر می‌خواهید در این مخزن Open-IM-Server مشارکت کنید، لطفاً [مستندات مشارکت‌کننده](https://github.com/openimsdk/open-im-server-deploy/blob/main/CONTRIBUTING.md) ما را بخوانید.
قبل از شروع، لطفاً مطمئن شوید که تغییرات شما مورد تقاضا هستند. بهترین کار برای آن این است که یک [بحث جدید](https://github.com/openimsdk/open-im-server-deploy/discussions/new/choose) یا [ارتباط اسلک](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A) ایجاد کنید، یا اگر مشکلی پیدا کردید، ابتدا [آن را گزارش کنید](https://github.com/openimsdk/open-im-server-deploy/issues/new/choose).
- [مرجع OpenIM API](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/api.md)
- [OpenIM Bash Logging](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/bash-log.md)
- [OpenIM CI/CD Actions](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/cicd-actions.md)
- [کنوانسیون کد OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/code-conventions.md)
- [دستورالعمل های تعهد OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/commit.md)
- [راهنمای توسعه OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/development.md)
- [ساختار دایرکتوری OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/directory.md)
- [تنظیم محیط OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/environment.md)
- [مرجع کد خطا OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/error-code.md)
- [OpenIM Git Workflow](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/git-workflow.md)
- [راهنمای انتخاب گیلاس OpenIM Git](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/gitcherry-pick.md)
- [OpenIM GitHub Workflow](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/github-workflow.md)
- [استانداردهای کد OpenIM Go](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/go-code.md)
- [دستورالعمل های تصویر OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/images.md)
- [پیکربندی اولیه OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/init-config.md)
- [راهنمای نصب OpenIM Docker](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-docker.md)
- [نصب سیستم OpenIM Linux OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-openim-linux-system.md)
- [راهنمای توسعه OpenIM Linux](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/linux-development.md)
- [راهنمای اقدامات محلی OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/local-actions.md)
- [OpenIM Logging Conventions](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/logging.md)
- [استقرار آفلاین OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/offline-deployment.md)
- [OpenIM Protoc Tools](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/protoc-tools.md)
- [راهنمای تست OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/test.md)
- [OpenIM Utility Go](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-go.md)
- [OpenIM Makefile Utilities](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-makefile.md)
- [ابزارهای OpenIM Script](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-scripts.md)
- [نسخه OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/version.md)
- [مدیریت استقرار باطن و نظارت](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/prometheus-grafana.md)
- [راهنمای استقرار توسعه دهنده مک برای OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/mac-developer-deployment-guide.md)
## :busts_in_silhouette: انجمن
- 📚 [انجمن OpenIM](https://github.com/OpenIMSDK/community)
- 💕 [گروه علاقه OpenIM](https://github.com/Openim-sigs)
- 🚀 [به انجمن Slack ما بپیوندید](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
- :eyes: [به وی چت ما بپیوندید](https://openim-1253691595.cos.ap-nanjing.myqcloud.com/WechatIMG20.jpeg)
## :calendar: جلسات جامعه
ما می‌خواهیم هر کسی در انجمن ما مشارکت کند و در کد مشارکت کند، ما هدایا و جوایزی ارائه می‌کنیم، و از شما استقبال می‌کنیم که هر پنجشنبه شب به ما بپیوندید.
کنفرانس ما در [OpenIM Slack](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A) 🎯 است، سپس می توانید خط لوله Open-IM-Server را برای پیوستن جستجو کنید.
ما از هر [جلسه دو هفته‌ای](https://github.com/orgs/OpenIMSDK/discussions/categories/meeting) در [بحث‌های GitHub](https://github.com/openimsdk/open-im-server-deploy/discussions/categories/meeting) یادداشت‌برداری می‌کنیم، یادداشت‌های جلسه تاریخی ما، و همچنین بازپخش جلسات در [Google Docs :bookmark_tabs:](https://docs.google.com/document/d/1nx8MDpuG74NASx081JcCpxPgDITNTpIIos0DS6Vr9GU/edit?usp=sharing) موجود است.
## :eyes: چه کسانی از OpenIM استفاده می کنند
صفحه [مطالعات موردی کاربر](https://github.com/OpenIMSDK/community/blob/main/ADOPTERS.md) ما را برای لیستی از کاربران پروژه بررسی کنید. از گذاشتن [نظر📝](https://github.com/openimsdk/open-im-server-deploy/issues/379) و به اشتراک گذاری مورد استفاده خود دریغ نکنید.
## :page_facing_up: مجوز
OpenIM تحت مجوز Apache 2.0 مجوز دارد. برای متن کامل مجوز به [LICENSE](https://github.com/openimsdk/open-im-server-deploy/tree/main/LICENSE) مراجعه کنید.
نشان‌واره OpenIM، شامل انواع و نسخه‌های متحرک آن، که در این مخزن [OpenIM](https://github.com/openimsdk/open-im-server-deploy) تحت فهرست‌های [assets/logo](./assets/logo) و [assets/logo-gif](assets/logo-gif) نمایش داده می‌شود، توسط قوانین حق چاپ محافظت می‌شود.
## 🔮 با تشکر از همکاران ما!
<a href="https://github.com/openimsdk/open-im-server-deploy/graphs/contributors">
<img src="https://contrib.rocks/image?repo=openimsdk/open-im-server-deploy" />
</a>

172
docs/readme/README_fr.md Normal file
View File

@@ -0,0 +1,172 @@
<p align="center">
<a href="https://openim.io">
<img src="../../assets/logo-gif/openim-logo.gif" width="60%" height="30%"/>
</a>
</p>
<div align="center">
[![Stars](https://img.shields.io/github/stars/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=ff69b4)](https://github.com/openimsdk/open-im-server-deploy/stargazers)
[![Forks](https://img.shields.io/github/forks/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=blue)](https://github.com/openimsdk/open-im-server-deploy/network/members)
[![Codecov](https://img.shields.io/codecov/c/github/openimsdk/open-im-server-deploy?style=for-the-badge&logo=codecov&colorB=orange)](https://app.codecov.io/gh/openimsdk/open-im-server-deploy)
[![Go Report Card](https://goreportcard.com/badge/github.com/openimsdk/open-im-server-deploy?style=for-the-badge)](https://goreportcard.com/report/github.com/openimsdk/open-im-server-deploy)
[![Go Reference](https://img.shields.io/badge/Go%20Reference-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://pkg.go.dev/git.imall.cloud/openim/open-im-server-deploy)
[![License](https://img.shields.io/badge/license-Apache--2.0-green?style=for-the-badge)](https://github.com/openimsdk/open-im-server-deploy/blob/main/LICENSE)
[![Slack](https://img.shields.io/badge/Slack-500%2B-blueviolet?style=for-the-badge&logo=slack&logoColor=white)](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
[![Best Practices](https://img.shields.io/badge/Best%20Practices-purple?style=for-the-badge)](https://www.bestpractices.dev/projects/8045)
[![Good First Issues](https://img.shields.io/github/issues/openimsdk/open-im-server-deploy/good%20first%20issue?style=for-the-badge&logo=github)](https://github.com/openimsdk/open-im-server-deploy/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22good+first+issue%22)
[![Language](https://img.shields.io/badge/Language-Go-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://golang.org/)
<p align="center">
<a href="../../README.md">English</a> ·
<a href="../../README_zh_CN.md">中文</a> ·
<a href="./README_uk.md">Українська</a> ·
<a href="./README_cs.md">Česky</a> ·
<a href="./README_hu.md">Magyar</a> ·
<a href="./README_es.md">Español</a> ·
<a href="./README_fa.md">فارسی</a> ·
<a href="./README_fr.md">Français</a> ·
<a href="./README_de.md">Deutsch</a> ·
<a href="./README_pl.md">Polski</a> ·
<a href="./README_id.md">Indonesian</a> ·
<a href="./README_fi.md">Suomi</a> ·
<a href="./README_ml.md">മലയാളം</a> ·
<a href="./README_ja.md">日本語</a> ·
<a href="./README_nl.md">Nederlands</a> ·
<a href="./README_it.md">Italiano</a> ·
<a href="./README_ru.md">Русский</a> ·
<a href="./README_pt_BR.md">Português (Brasil)</a> ·
<a href="./README_eo.md">Esperanto</a> ·
<a href="./README_ko.md">한국어</a> ·
<a href="./README_ar.md">العربي</a> ·
<a href="./README_vi.md">Tiếng Việt</a> ·
<a href="./README_da.md">Dansk</a> ·
<a href="./README_el.md">Ελληνικά</a> ·
<a href="./README_tr.md">Türkçe</a>
</p>
</div>
</p>
## Ⓜ️ À propos de OpenIM
OpenIM est une plateforme de services conçue spécifiquement pour intégrer des fonctionnalités de communication telles que le chat, les appels audio et vidéo, les notifications, ainsi que les robots de chat IA dans les applications. Elle offre une série d'API puissantes et de Webhooks, permettant aux développeurs d'incorporer facilement ces caractéristiques interactives dans leurs applications. OpenIM n'est pas en soi une application de chat autonome, mais sert de plateforme supportant d'autres applications pour réaliser des fonctionnalités de communication enrichies. L'image ci-dessous montre les relations d'interaction entre AppServer, AppClient, OpenIMServer et OpenIMSDK pour illustrer spécifiquement.
![Relation App-OpenIM](../../images/oepnim-design.png)
## 🚀 À propos de OpenIMSDK
**OpenIMSDK** est un SDK IM conçu pour **OpenIMServer** spécialement créé pour être intégré dans les applications clientes. Ses principales fonctionnalités et modules comprennent :
- 🌟 Fonctionnalités clés :
- 📦 Stockage local
- 🔔 Rappels de l'écouteur
- 🛡️ Encapsulation d'API
- 🌐 Gestion de la connexion
## 📚 Modules principaux
1. 🚀 Initialisation et connexion
2. 👤 Gestion des utilisateurs
3. 👫 Gestion des amis
4. 🤖 Fonctionnalités de groupe
5. 💬 Traitement des conversations
Il est construit avec Golang et supporte le déploiement multiplateforme, assurant une expérience d'accès cohérente sur toutes les plateformes。
👉 **[Explorer le SDK GO](https://github.com/openimsdk/openim-sdk-core)**
## 🌐 À propos de OpenIMServer
- **OpenIMServer** présente les caractéristiques suivantes
- 🌐 Architecture microservices : prend en charge le mode cluster, incluant le gateway (passerelle) et plusieurs services rpc。
- 🚀 Divers modes de déploiement : supporte le déploiement via le code source, Kubernetes ou Docker。
- Support d'une masse d'utilisateurs : plus de cent mille pour les super grands groupes, des millions d'utilisateurs, et des milliards de messages。
### Fonctionnalités commerciales améliorées :
- **REST API**OpenIMServer fournit une REST API pour les systèmes commerciaux, visant à accorder plus de fonctionnalités, telles que la création de groupes via l'interface backend, l'envoi de messages push, etc。
- **Webhooks**OpenIMServer offre des capacités de rappel pour étendre davantage les formes d'entreprise. Un rappel signifie que OpenIMServer enverra une requête au serveur d'entreprise avant ou après qu'un événement se soit produit, comme un rappel avant ou après l'envoi d'un message。
👉 **[En savoir plus](https://docs.openim.io/guides/introduction/product)**
## :building_construction: Architecture globale
Plongez dans le cœur de la fonctionnalité d'Open-IM-Server avec notre diagramme d'architecture.
![Architecture globale](../../images/architecture-layers.png)
## :rocket: Démarrage rapide
Nous prenons en charge de nombreuses plateformes. Voici les adresses pour une expérience rapide du côté web :
👉 **[Démo web en ligne OpenIM](https://www.openim.io/zh/commercial)**
🤲 Pour faciliter l'expérience utilisateur, nous proposons plusieurs solutions de déploiement. Vous pouvez choisir votre méthode de déploiement selon la liste ci-dessous
- **[Guide de déploiement du code source](https://docs.openim.io/guides/gettingStarted/imSourceCodeDeployment)**
- **[Guide de déploiement Docker](https://docs.openim.io/guides/gettingStarted/dockerCompose)**
- **[Guide de déploiement Kubernetes](https://docs.openim.io/guides/gettingStarted/k8s-deployment)**
- **[Guide de déploiement pour développeur Mac](https://docs.openim.io/guides/gettingstarted/mac-deployment-guide)**
## :hammer_and_wrench: Commencer à développer avec OpenIM
Chez OpenIM, notre objectif est de construire une communauté open source de premier plan. Nous avons un ensemble de standards, disponibles dans le[ dépôt communautaire](https://github.com/OpenIMSDK/community)。
Si vous souhaitez contribuer à ce dépôt Open-IM-Server, veuillez lire notre[ document pour les contributeurs](https://github.com/openimsdk/open-im-server-deploy/blob/main/CONTRIBUTING.md)。
Avant de commencer, assurez-vous que vos modifications sont nécessaires. La meilleure manière est de créer une[ nouvelle discussion ](https://github.com/openimsdk/open-im-server-deploy/discussions/new/choose) ou une [ communication Slack,](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)ou si vous identifiez un problème, de[ signaler d'abord ](https://github.com/openimsdk/open-im-server-deploy/issues/new/choose)。
- [Référence de l'API OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/api.md)
- [Journalisation Bash OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/bash-log.md)
- [Actions CI/CD OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/cicd-actions.md)
- [Conventions de code OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/code-conventions.md)
- [Directives de commit OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/commit.md)
- [Guide de développement OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/development.md)
- [Structure de répertoire OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/directory.md)
- [Configuration de l'environnement OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/environment.md)
- [Référence des codes d'erreur OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/error-code.md)
- [Workflow Git OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/git-workflow.md)
- [Guide Cherry Pick Git OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/gitcherry-pick.md)
- [Workflow GitHub OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/github-workflow.md)
- [Normes de code Go OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/go-code.md)
- [Directives d'image OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/images.md)
- [Configuration initiale OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/init-config.md)
- [Guide d'installation Docker OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-docker.md)
- [Installation du système Linux OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-openim-linux-system.md)
- [Guide de développement Linux OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/linux-development.md)
- [Guide des actions locales OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/local-actions.md)
- [Conventions de journalisation OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/logging.md)
- [Déploiement hors ligne OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/offline-deployment.md)
- [Outils Protoc OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/protoc-tools.md)
- [Guide de test OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/test.md)
- [Utilitaire Go OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-go.md)
- [Utilitaires Makefile OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-makefile.md)
- [Utilitaires de script OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-scripts.md)
- [Versionnement OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/version.md)
- [Gérer le déploiement du backend et la surveillance](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/prometheus-grafana.md)
- [Guide de déploiement pour développeur Mac pour OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/mac-developer-deployment-guide.md)
> ## :calendar: Réunions de la Communauté
Nous voulons que tout le monde s'implique dans notre communauté et contribue au code, nous offrons des cadeaux et des récompenses, et nous vous invitons à nous rejoindre chaque jeudi soir.
Notre conférence se trouve dans le [ Slack OpenIM ](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A) 🎯, ensuite vous pouvez rechercher le pipeline Open-IM-Server pour rejoindre
Nous prenons des notes de chaque [réunion bihebdomadaire ](https://github.com/orgs/OpenIMSDK/discussions/categories/meeting) dans les [discussions GitHub](https://github.com/openimsdk/open-im-server-deploy/discussions/categories/meeting), Nos notes de réunion historiques, ainsi que les rediffusions des réunions sont disponibles sur [ Google Docs :bookmark_tabs:](https://docs.google.com/document/d/1nx8MDpuG74NASx081JcCpxPgDITNTpIIos0DS6Vr9GU/edit?usp=sharing).
## :eyes: Qui Utilise OpenIM
Consultez notre page [ études de cas d'utilisateurs ](https://github.com/OpenIMSDK/community/blob/main/ADOPTERS.md) pour une liste des utilisateurs du projet. N'hésitez pas à laisser un [📝commentaire](https://github.com/openimsdk/open-im-server-deploy/issues/379) et partager votre cas d'utilisation.
## :page_facing_up: License
OpenIM est sous licence Apache 2.0. Voir [LICENSE](https://github.com/openimsdk/open-im-server-deploy/tree/main/LICENSE) pour le texte complet de la licence.
Le logo OpenIM, y compris ses variations et versions animées, affiché dans ce dépôt[OpenIM](https://github.com/openimsdk/open-im-server-deploy) sous les répertoires [assets/logo](../../assets/logo) et [assets/logo-gif](assets/logo-gif) sont protégés par les lois sur le droit d'auteur.
## 🔮 Merci à nos contributeurs !
<a href="https://github.com/openimsdk/open-im-server-deploy/graphs/contributors">
<img src="https://contrib.rocks/image?repo=openimsdk/open-im-server-deploy" />
</a>

183
docs/readme/README_hu.md Normal file
View File

@@ -0,0 +1,183 @@
<p align="center">
<a href="https://openim.io">
<img src="../../assets/logo-gif/openim-logo.gif" width="60%" height="30%"/>
</a>
</p>
<div align="center">
[![Stars](https://img.shields.io/github/stars/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=ff69b4)](https://github.com/openimsdk/open-im-server-deploy/stargazers)
[![Forks](https://img.shields.io/github/forks/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=blue)](https://github.com/openimsdk/open-im-server-deploy/network/members)
[![Codecov](https://img.shields.io/codecov/c/github/openimsdk/open-im-server-deploy?style=for-the-badge&logo=codecov&colorB=orange)](https://app.codecov.io/gh/openimsdk/open-im-server-deploy)
[![Go Report Card](https://goreportcard.com/badge/github.com/openimsdk/open-im-server-deploy?style=for-the-badge)](https://goreportcard.com/report/github.com/openimsdk/open-im-server-deploy)
[![Go Reference](https://img.shields.io/badge/Go%20Reference-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://pkg.go.dev/git.imall.cloud/openim/open-im-server-deploy)
[![License](https://img.shields.io/badge/license-Apache--2.0-green?style=for-the-badge)](https://github.com/openimsdk/open-im-server-deploy/blob/main/LICENSE)
[![Slack](https://img.shields.io/badge/Slack-500%2B-blueviolet?style=for-the-badge&logo=slack&logoColor=white)](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
[![Best Practices](https://img.shields.io/badge/Best%20Practices-purple?style=for-the-badge)](https://www.bestpractices.dev/projects/8045)
[![Good First Issues](https://img.shields.io/github/issues/openimsdk/open-im-server-deploy/good%20first%20issue?style=for-the-badge&logo=github)](https://github.com/openimsdk/open-im-server-deploy/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22good+first+issue%22)
[![Language](https://img.shields.io/badge/Language-Go-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://golang.org/)
<p align="center">
<a href="../../README.md">English</a> ·
<a href="../../README_zh_CN.md">中文</a> ·
<a href="./README_uk.md">Українська</a> ·
<a href="./README_cs.md">Česky</a> ·
<a href="./README_hu.md">Magyar</a> ·
<a href="./README_es.md">Español</a> ·
<a href="./README_fa.md">فارسی</a> ·
<a href="./README_fr.md">Français</a> ·
<a href="./README_de.md">Deutsch</a> ·
<a href="./README_pl.md">Polski</a> ·
<a href="./README_id.md">Indonesian</a> ·
<a href="./README_fi.md">Suomi</a> ·
<a href="./README_ml.md">മലയാളം</a> ·
<a href="./README_ja.md">日本語</a> ·
<a href="./README_nl.md">Nederlands</a> ·
<a href="./README_it.md">Italiano</a> ·
<a href="./README_ru.md">Русский</a> ·
<a href="./README_pt_BR.md">Português (Brasil)</a> ·
<a href="./README_eo.md">Esperanto</a> ·
<a href="./README_ko.md">한국어</a> ·
<a href="./README_ar.md">العربي</a> ·
<a href="./README_vi.md">Tiếng Việt</a> ·
<a href="./README_da.md">Dansk</a> ·
<a href="./README_el.md">Ελληνικά</a> ·
<a href="./README_tr.md">Türkçe</a>
</p>
</div>
</p>
## Ⓜ️ Az OpenIM-ről
Az OpenIM egy szolgáltatási platform, amelyet kifejezetten a csevegés, az audio-video hívások, az értesítések és az AI chatbotok alkalmazásokba történő integrálására terveztek. Számos hatékony API-t és Webhookot kínál, lehetővé téve a fejlesztők számára, hogy ezeket az interaktív szolgáltatásokat könnyen beépítsék alkalmazásaikba. Az OpenIM nem egy önálló csevegőalkalmazás, hanem platformként szolgál más alkalmazások támogatására a gazdag kommunikációs funkciók elérésében. A következő diagram az AppServer, az AppClient, az OpenIMServer és az OpenIMSDK közötti interakciót szemlélteti részletesen.
![App-OpenIM Relationship](../images/oepnim-design.png)
## 🚀 Az OpenIMSDK-ról
Az **OpenIMSDK** egy **OpenIMServer** számára készült azonnali üzenetküldő SDK, amelyet kifejezetten ügyfélalkalmazásokba való beágyazáshoz hoztak létre. Fő jellemzői és moduljai a következők:
- 🌟 Főbb jellemzők:
- 📦 Helyi raktár
- 🔔 Hallgatói visszahívások
- 🛡️ API-csomagolás
- 🌐 Kapcsolatkezelés
- 📚 Fő modulok:
1. 🚀 Inicializálás és bejelentkezés
2. 👤 Felhasználókezelés
3. 👫 Barátkezelés
4. 🤖 Csoportfunkciók
5. 💬 Beszélgetéskezelés
Golang használatával készült, és támogatja a többplatformos telepítést, biztosítva a konzisztens hozzáférési élményt minden platformon.
👉 **[Fedezze fel a GO SDK-t](https://github.com/openimsdk/openim-sdk-core)**
## 🌐 Az OpenIMServerről
- **OpenIMServer** a következő jellemzőkkel rendelkezik:
- 🌐 Mikroszolgáltatási architektúra: Támogatja a fürt módot, beleértve az átjárót és több rpc szolgáltatást.
- 🚀 Változatos telepítési módszerek: Támogatja a forráskódon, Kubernetesen vagy Dockeren keresztül történő telepítést.
- Hatalmas felhasználói bázis támogatása: Szuper nagy csoportok több százezer felhasználóval, több tízmillió felhasználóval és több milliárd üzenettel.
### Továbbfejlesztett üzleti funkcionalitás:
- **REST API**: Az OpenIMServer REST API-kat kínál az üzleti rendszerek számára, amelyek célja, hogy a vállalkozásokat több funkcióval ruházza fel, mint például csoportok létrehozása és push üzenetek küldése háttérfelületeken keresztül.
- **Webhooks**: Az OpenIMServer visszahívási lehetőségeket biztosít több üzleti forma kiterjesztéséhez. A visszahívás azt jelenti, hogy az OpenIMServer kérelmet küld az üzleti szervernek egy bizonyos esemény előtt vagy után, például visszahívásokat üzenet küldése előtt vagy után.
👉 **[Tudj meg többet](https://docs.openim.io/guides/introduction/product)**
## :building_construction: Általános építészet
Merüljön el az Open-IM-Server funkcióinak szívében az architektúra diagramunk segítségével.
![Overall Architecture](../images/architecture-layers.png)
## :rocket: Gyors indítás
Számos platformot támogatunk. Íme a címek a gyors weboldali használathoz:
👉 **[OpenIM online webdemó](https://web-enterprise.rentsoft.cn/)**
🤲 A felhasználói élmény megkönnyítése érdekében különféle telepítési megoldásokat kínálunk. Az alábbi listából választhatja ki a telepítési módot:
- **[Forráskód-telepítési útmutató](https://docs.openim.io/guides/gettingStarted/imSourceCodeDeployment)**
- **[Docker telepítési útmutató](https://docs.openim.io/guides/gettingStarted/dockerCompose)**
- **[Kubernetes telepítési útmutató](https://docs.openim.io/guides/gettingStarted/k8s-deployment)**
- **[Mac fejlesztői telepítési útmutató](https://docs.openim.io/guides/gettingstarted/mac-deployment-guide)**
## :hammer_and_wrench: Az OpenIM fejlesztésének megkezdéséhez
[![Open in Dev Container](https://img.shields.io/static/v1?label=Dev%20Container&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/github/openimsdk/open-im-server-deploy)
OpenIM Célunk egy felső szintű nyílt forráskódú közösség felépítése. Van egy szabványkészletünk a [Közösségi adattárban](https://github.com/OpenIMSDK/community).
Ha hozzá szeretne járulni ehhez az Open-IM-Server adattárhoz, kérjük, olvassa el [közreműködői dokumentációnkat](https://github.com/openimsdk/open-im-server-deploy/blob/main/CONTRIBUTING.md).
Mielőtt elkezdené, győződjön meg arról, hogy a változtatásokra van-e igény. Erre a legjobb egy [új beszélgetés](https://github.com/openimsdk/open-im-server-deploy/discussions/new/choose) VAGY [Slack Communication](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)létrehozása, vagy ha problémát talál, először [jelentse](https://github.com/openimsdk/open-im-server-deploy/issues/new/choose) first.
- [OpenIM API referencia](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/api.md)
- [OpenIM Bash naplózás](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/bash-log.md)
- [OpenIM CI/CD műveletek](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/cicd-actions.md)
- [OpenIM Code-egyezmények](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/code-conventions.md)
- [OpenIM Commit Guidelines](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/commit.md)
- [OpenIM fejlesztési útmutató](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/development.md)
- [OpenIM címtárszerkezet](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/directory.md)
- [OpenIM környezet beállítása](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/environment.md)
- [OpenIM hibakód hivatkozás](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/error-code.md)
- [OpenIM Git Workflow](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/git-workflow.md)
- [OpenIM Git Cherry Pick Guide](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/gitcherry-pick.md)
- [OpenIM GitHub munkafolyamat](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/github-workflow.md)
- [OpenIM Go Code szabványok](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/go-code.md)
- [OpenIM képre vonatkozó irányelvek](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/images.md)
- [OpenIM kezdeti konfiguráció](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/init-config.md)
- [OpenIM Docker telepítési útmutató](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-docker.md)
- [OpenIM OpenIM Linux rendszertelepítés](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-openim-linux-system.md)
- [OpenIM Linux fejlesztési útmutató](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/linux-development.md)
- [OpenIM helyi műveletek útmutatója](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/local-actions.md)
- [OpenIM naplózási egyezmények](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/logging.md)
- [OpenIM offline telepítés](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/offline-deployment.md)
- [OpenIM Protoc Tools](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/protoc-tools.md)
- [OpenIM tesztelési útmutató](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/test.md)
- [OpenIM Utility Go](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-go.md)
- [OpenIM Makefile Utilities](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-makefile.md)
- [OpenIM Script Utilities](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-scripts.md)
- [OpenIM verzió](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/version.md)
- [A háttérrendszer kezelése és a telepítés figyelése](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/prometheus-grafana.md)
- [Mac Developer Deployment Guide for OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/mac-developer-deployment-guide.md)
## :busts_in_silhouette: Közösség
- 📚 [OpenIM közösség](https://github.com/OpenIMSDK/community)
- 💕 [OpenIM érdeklődési csoport](https://github.com/Openim-sigs)
- 🚀 [Csatlakozz a Slack közösségünkhöz](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
- :eyes: [Csatlakozz a wechathez](https://openim-1253691595.cos.ap-nanjing.myqcloud.com/WechatIMG20.jpeg)
## :calendar: Közösségi Találkozók
Szeretnénk, ha bárki bekapcsolódna közösségünkbe és hozzájárulna kódunkhoz, ajándékokat és jutalmakat kínálunk, és szeretettel várjuk, hogy csatlakozzon hozzánk minden csütörtök este.
Konferenciánk az [OpenIM Slack](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A) 🎯alatt van, akkor kereshet az Open-IM-Server folyamatban a csatlakozáshoz
A [GitHub-beszélgetések](https://github.com/orgs/OpenIMSDK/discussions/categories/meeting)minden [kéthetente történő megbeszélésről](https://github.com/openimsdk/open-im-server-deploy/discussions/categories/meeting) jegyzeteket készítünk. A találkozók történeti feljegyzései, valamint az értekezletek visszajátszásai a [Google Dokumentumok :bookmark_tabs:](https://docs.google.com/document/d/1nx8MDpuG74NASx081JcCpxPgDITNTpIIos0DS6Vr9GU/edit?usp=sharing) webhelyen érhetők el.
## :eyes: Kik használják az OpenIM-et
Tekintse meg [felhasználói esettanulmányok](https://github.com/OpenIMSDK/community/blob/main/ADOPTERS.md) oldalunkat a projekt felhasználóinak listájáért. Ne habozzon, hagyjon [📝megjegyzést](https://github.com/openimsdk/open-im-server-deploy/issues/379), és ossza meg használati esetét.
## :page_facing_up: Engedély
Az OpenIM licence az Apache 2.0 licence alá tartozik. A teljes licencszövegért lásd: [LICENSE](https://github.com/openimsdk/open-im-server-deploy/tree/main/LICENSE).
Az ebben az [OpenIM](https://github.com/openimsdk/open-im-server-deploy) tárolóban az [assets/logo](./assets/logo) és [assets/logo-gif](assets/logo-gif) könyvtárak alatt megjelenő OpenIM logót, beleértve annak változatait és animált változatait, szerzői jogi törvények védik.
## 🔮 Köszönjük közreműködőinknek!
<a href="https://github.com/openimsdk/open-im-server-deploy/graphs/contributors">
<img src="https://contrib.rocks/image?repo=openimsdk/open-im-server-deploy" />
</a>

183
docs/readme/README_ja.md Normal file
View File

@@ -0,0 +1,183 @@
<p align="center">
<a href="https://openim.io">
<img src="../../assets/logo-gif/openim-logo.gif" width="60%" height="30%"/>
</a>
</p>
<div align="center">
[![Stars](https://img.shields.io/github/stars/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=ff69b4)](https://github.com/openimsdk/open-im-server-deploy/stargazers)
[![Forks](https://img.shields.io/github/forks/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=blue)](https://github.com/openimsdk/open-im-server-deploy/network/members)
[![Codecov](https://img.shields.io/codecov/c/github/openimsdk/open-im-server-deploy?style=for-the-badge&logo=codecov&colorB=orange)](https://app.codecov.io/gh/openimsdk/open-im-server-deploy)
[![Go Report Card](https://goreportcard.com/badge/github.com/openimsdk/open-im-server-deploy?style=for-the-badge)](https://goreportcard.com/report/github.com/openimsdk/open-im-server-deploy)
[![Go Reference](https://img.shields.io/badge/Go%20Reference-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://pkg.go.dev/git.imall.cloud/openim/open-im-server-deploy)
[![License](https://img.shields.io/badge/license-Apache--2.0-green?style=for-the-badge)](https://github.com/openimsdk/open-im-server-deploy/blob/main/LICENSE)
[![Slack](https://img.shields.io/badge/Slack-500%2B-blueviolet?style=for-the-badge&logo=slack&logoColor=white)](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
[![Best Practices](https://img.shields.io/badge/Best%20Practices-purple?style=for-the-badge)](https://www.bestpractices.dev/projects/8045)
[![Good First Issues](https://img.shields.io/github/issues/openimsdk/open-im-server-deploy/good%20first%20issue?style=for-the-badge&logo=github)](https://github.com/openimsdk/open-im-server-deploy/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22good+first+issue%22)
[![Language](https://img.shields.io/badge/Language-Go-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://golang.org/)
<p align="center">
<a href="../../README.md">English</a> ·
<a href="../../README_zh_CN.md">中文</a> ·
<a href="./README_uk.md">Українська</a> ·
<a href="./README_cs.md">Česky</a> ·
<a href="./README_hu.md">Magyar</a> ·
<a href="./README_es.md">Español</a> ·
<a href="./README_fa.md">فارسی</a> ·
<a href="./README_fr.md">Français</a> ·
<a href="./README_de.md">Deutsch</a> ·
<a href="./README_pl.md">Polski</a> ·
<a href="./README_id.md">Indonesian</a> ·
<a href="./README_fi.md">Suomi</a> ·
<a href="./README_ml.md">മലയാളം</a> ·
<a href="./README_ja.md">日本語</a> ·
<a href="./README_nl.md">Nederlands</a> ·
<a href="./README_it.md">Italiano</a> ·
<a href="./README_ru.md">Русский</a> ·
<a href="./README_pt_BR.md">Português (Brasil)</a> ·
<a href="./README_eo.md">Esperanto</a> ·
<a href="./README_ko.md">한국어</a> ·
<a href="./README_ar.md">العربي</a> ·
<a href="./README_vi.md">Tiếng Việt</a> ·
<a href="./README_da.md">Dansk</a> ·
<a href="./README_el.md">Ελληνικά</a> ·
<a href="./README_tr.md">Türkçe</a>
</p>
</div>
</p>
## Ⓜ️ OpenIM について
OpenIM は、アプリケーション内でチャット、音声通話、通知、AI チャットボットなどの通信機能を統合するために特別に設計されたサービスプラットフォームです。一連の強力な API と Webhooks を提供することで、開発者はアプリケーションに簡単にこれらの通信機能を統合できます。OpenIM 自体は独立したチャットアプリではなく、アプリケーションにサポートを提供し、豊富な通信機能を実現するプラットフォームです。以下の図は、AppServer、AppClient、OpenIMServer、OpenIMSDK 間の相互作用を示しています。
![App-OpenIM Relationship](../images/oepnim-design.png)
## 🚀 OpenIMSDK について
**OpenIMSDK**は、**OpenIMServer**用に設計された IM SDK で、クライアントアプリケーションに組み込むためのものです。主な機能とモジュールは以下の通りです:
- 🌟 主な機能:
- 📦 ローカルストレージ
- 🔔 リスナーコールバック
- 🛡️ API のラッピング
- 🌐 接続管理
## 📚 主なモジュール:
1. 🚀 初初期化とログイン
2. 👤 ユーザー管理
3. 👫 友達管理
4. 🤖 グループ機能
5. 💬 会話処理
Golang を使用して構築され、クロスプラットフォームの導入をサポートし、すべてのプラットフォームで一貫したアクセス体験を提供します。
👉 **[GO SDK を探索する](https://github.com/openimsdk/openim-sdk-core)**
## 🌐 OpenIMServer について
- **OpenIMServer** には以下の特徴があります:
- 🌐 マイクロサービスアーキテクチャクラスターモードをサポートし、ゲートウェイgatewayと複数の rpc サービスを含みます。
- 🚀 多様なデプロイメント方法ソースコード、kubernetes、または docker でのデプロイメントをサポートします。
- 海量ユーザーサポート:十万人規模の超大型グループ、千万人のユーザー、および百億のメッセージ
### 強化されたビジネス機能:
- **REST API**OpenIMServer は、ビジネスシステム用の REST API を提供しており、ビジネスにさらに多くの機能を提供することを目指しています。たとえば、バックエンドインターフェースを通じてグループを作成したり、プッシュメッセージを送信したりするなどです。
- **Webhooks**OpenIMServer は、より多くのビジネス形態を拡張するためのコールバック機能を提供しています。コールバックとは、特定のイベントが発生する前後に、OpenIMServer がビジネスサーバーにリクエストを送信することを意味します。例えば、メッセージ送信の前後のコールバックなどです。
👉 **[もっと詳しく知る](https://docs.openim.io/guides/introduction/product)**
## :building_construction: 全体のアーキテクチャ
Open-IM-Server の機能の核心に迫るために、アーキテクチャダイアグラムをご覧ください。
![Overall Architecture](../images/architecture-layers.png)
## :rocket: クイックスタート
iOS/Android/H5/PC/Web でのオンライン体験:
👉 **[OpenIM online demo](https://www.openim.io/zh/commercial)**
🤲 ユーザー体験を容易にするために、私たちは様々なデプロイメントソリューションを提供しています。以下のリストから、ご自身のデプロイメント方法を選択できます:
- **[ソースコードデプロイメントガイド](https://docs.openim.io/guides/gettingStarted/imSourceCodeDeployment)**
- **[Docker デプロイメントガイド](https://docs.openim.io/guides/gettingStarted/dockerCompose)**
- **[Kubernetes デプロイメントガイド](https://docs.openim.io/guides/gettingStarted/k8s-deployment)**
- **[Mac 開発者向けデプロイメントガイド](https://docs.openim.io/guides/gettingstarted/mac-deployment-guide)**
## :hammer_and_wrench: OpenIM の開発を始める
[![Open in Dev Container](https://img.shields.io/static/v1?label=Dev%20Container&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/github/openimsdk/open-im-server-deploy)
OpenIM 私たちの目標は、トップレベルのオープンソースコミュニティを構築することです。[コミュニティリポジトリ](https://github.com/OpenIMSDK/community)には一連の基準があります。
この Open-IM-Server リポジトリに貢献したい場合は、[貢献者ドキュメントをお読みください](https://github.com/openimsdk/open-im-server-deploy/blob/main/CONTRIBUTING.md)。
始める前に、変更に必要があることを確認してください。最良の方法は、[新しいディスカッション](https://github.com/openimsdk/open-im-server-deploy/discussions/new/choose)や[Slack](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)での通信を作成すること、または問題を発見した場合は、まずそれを[報告](https://github.com/openimsdk/open-im-server-deploy/issues/new/choose)することです。
- [OpenIM API リファレンス](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/api.md)
- [OpenIM Bash ロギング](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/bash-log.md)
- [OpenIM CI/CD アクション](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/cicd-actions.md)
- [OpenIM コード規約](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/code-conventions.md)
- [OpenIM コミットガイドライン](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/commit.md)
- [OpenIM 開発ガイド](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/development.md)
- [OpenIM ディレクトリ構造](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/directory.md)
- [OpenIM 環境設定](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/environment.md)
- [OpenIM エラーコードリファレンス](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/error-code.md)
- [OpenIM Git ワークフロー](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/git-workflow.md)
- [OpenIM Git チェリーピックガイド](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/gitcherry-pick.md)
- [OpenIM GitHub ワークフロー](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/github-workflow.md)
- [OpenIM Go コード基準](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/go-code.md)
- [OpenIM 画像ガイドライン](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/images.md)
- [OpenIM 初期設定](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/init-config.md)
- [OpenIM Docker インストールガイド](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-docker.md)
- [OpenIM Linux システムインストール](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-openim-linux-system.md)
- [OpenIM Linux 開発ガイド](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/linux-development.md)
- [OpenIM ローカルアクションガイド](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/local-actions.md)
- [OpenIM ロギング規約](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/logging.md)
- [OpenIM オフラインデプロイメント](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/offline-deployment.md)
- [OpenIM Protoc ツール](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/protoc-tools.md)
- [OpenIM テスティングガイド](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/test.md)
- [OpenIM ユーティリティ Go](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-go.md)
- [OpenIM Makefile ユーティリティ](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-makefile.md)
- [OpenIM スクリプトユーティリティ](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-scripts.md)
- [OpenIM バージョニング](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/version.md)
- [バックエンド管理とモニターデプロイメント](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/prometheus-grafana.md)
- [OpenIM 用 Mac 開発者デプロイメントガイド](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/mac-developer-deployment-guide.md)
## :busts_in_silhouette: コミュニティ
- 📚 [OpenIM コミュニティ](https://github.com/OpenIMSDK/community)
- 💕 [OpenIM 興味グループ](https://github.com/Openim-sigs)
- 🚀 [私たちの Slack コミュニティに参加する](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
- :eyes: [私たちの WeChat微信群に参加する](https://openim-1253691595.cos.ap-nanjing.myqcloud.com/WechatIMG20.jpeg)
## :calendar: コミュニティミーティング
私たちは、誰もがコミュニティに参加し、コードに貢献してもらいたいと考えています。私たちは、ギフトや報酬を提供し、毎週木曜日の夜に参加していただくことを歓迎します。
私たちの会議は[OpenIM Slack](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)🎯 で行われます。そこで Open-IM-Server パイプラインを検索して参加できます。
私たちは[隔週の会議](https://github.com/orgs/OpenIMSDK/discussions/categories/meeting)のメモを[GitHub ディスカッション](https://github.com/openimsdk/open-im-server-deploy/discussions/categories/meeting)に記録しています。歴史的な会議のメモや会議のリプレイは[Google Docs📑](https://docs.google.com/document/d/1nx8MDpuG74NASx081JcCpxPgDITNTpIIos0DS6Vr9GU/edit?usp=sharing)で利用可能です。
## :eyes: OpenIM を使用している人たち
プロジェクトユーザーのリストについては、[ユーザーケーススタディ](https://github.com/OpenIMSDK/community/blob/main/ADOPTERS.md)ページをご覧ください。[コメント 📝](https://github.com/openimsdk/open-im-server-deploy/issues/379)を残して、あなたの使用例を共有することを躊躇しないでください。
## :page_facing_up: ライセンス
OpenIM は Apache 2.0 ライセンスの下でライセンスされています。完全なライセンステキストについては、[LICENSE](https://github.com/openimsdk/open-im-server-deploy/tree/main/LICENSE)を参照してください。
このリポジトリに表示される[OpenIM](https://github.com/openimsdk/open-im-server-deploy)ロゴ、そのバリエーション、およびアニメーションバージョン([assets/logo](./assets/logo)および[assets/logo-gif](assets/logo-gif)ディレクトリ内)は、著作権法によって保護されています。
## 🔮 貢献者の皆様に感謝します!
<a href="https://github.com/openimsdk/open-im-server-deploy/graphs/contributors">
<img src="https://contrib.rocks/image?repo=openimsdk/open-im-server-deploy" />
</a>

183
docs/readme/README_ko.md Normal file
View File

@@ -0,0 +1,183 @@
<p align="center">
<a href="https://openim.io">
<img src="../../assets/logo-gif/openim-logo.gif" width="60%" height="30%"/>
</a>
</p>
<div align="center">
[![Stars](https://img.shields.io/github/stars/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=ff69b4)](https://github.com/openimsdk/open-im-server-deploy/stargazers)
[![Forks](https://img.shields.io/github/forks/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=blue)](https://github.com/openimsdk/open-im-server-deploy/network/members)
[![Codecov](https://img.shields.io/codecov/c/github/openimsdk/open-im-server-deploy?style=for-the-badge&logo=codecov&colorB=orange)](https://app.codecov.io/gh/openimsdk/open-im-server-deploy)
[![Go Report Card](https://goreportcard.com/badge/github.com/openimsdk/open-im-server-deploy?style=for-the-badge)](https://goreportcard.com/report/github.com/openimsdk/open-im-server-deploy)
[![Go Reference](https://img.shields.io/badge/Go%20Reference-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://pkg.go.dev/git.imall.cloud/openim/open-im-server-deploy)
[![License](https://img.shields.io/badge/license-Apache--2.0-green?style=for-the-badge)](https://github.com/openimsdk/open-im-server-deploy/blob/main/LICENSE)
[![Slack](https://img.shields.io/badge/Slack-500%2B-blueviolet?style=for-the-badge&logo=slack&logoColor=white)](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
[![Best Practices](https://img.shields.io/badge/Best%20Practices-purple?style=for-the-badge)](https://www.bestpractices.dev/projects/8045)
[![Good First Issues](https://img.shields.io/github/issues/openimsdk/open-im-server-deploy/good%20first%20issue?style=for-the-badge&logo=github)](https://github.com/openimsdk/open-im-server-deploy/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22good+first+issue%22)
[![Language](https://img.shields.io/badge/Language-Go-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://golang.org/)
<p align="center">
<a href="../../README.md">English</a> ·
<a href="../../README_zh_CN.md">中文</a> ·
<a href="./README_uk.md">Українська</a> ·
<a href="./README_cs.md">Česky</a> ·
<a href="./README_hu.md">Magyar</a> ·
<a href="./README_es.md">Español</a> ·
<a href="./README_fa.md">فارسی</a> ·
<a href="./README_fr.md">Français</a> ·
<a href="./README_de.md">Deutsch</a> ·
<a href="./README_pl.md">Polski</a> ·
<a href="./README_id.md">Indonesian</a> ·
<a href="./README_fi.md">Suomi</a> ·
<a href="./README_ml.md">മലയാളം</a> ·
<a href="./README_ja.md">日本語</a> ·
<a href="./README_nl.md">Nederlands</a> ·
<a href="./README_it.md">Italiano</a> ·
<a href="./README_ru.md">Русский</a> ·
<a href="./README_pt_BR.md">Português (Brasil)</a> ·
<a href="./README_eo.md">Esperanto</a> ·
<a href="./README_ko.md">한국어</a> ·
<a href="./README_ar.md">العربي</a> ·
<a href="./README_vi.md">Tiếng Việt</a> ·
<a href="./README_da.md">Dansk</a> ·
<a href="./README_el.md">Ελληνικά</a> ·
<a href="./README_tr.md">Türkçe</a>
</p>
</div>
</p>
## Ⓜ️ OpenIM에 대하여
OpenIM은 채팅, 오디오-비디오 통화, 알림 및 AI 챗봇을 애플리케이션에 통합하기 위해 특별히 설계된 서비스 플랫폼입니다. 이 플랫폼은 강력한 API와 웹훅을 제공하여 개발자가 이러한 상호작용 기능을 애플리케이션에 쉽게 통합할 수 있게 합니다. OpenIM은 독립 실행형 채팅 애플리케이션이 아니라, 다른 애플리케이션들이 풍부한 커뮤니케이션 기능을 달성할 수 있도록 지원하는 플랫폼으로서의 역할을 합니다. 다음 다이어그램은 AppServer, AppClient, OpenIMServer, 및 OpenIMSDK 간의 상호작용을 자세히 설명하기 위해 제시되었습니다.
![App-OpenIM Relationship](../images/oepnim-design.png)
## 🚀 OpenIMSDK에 대하여
**OpenIMSDK**는**OpenIMServer**를 위해 특별히 제작된 IM SDK로, 클라이언트 애플리케이션 내에 내장하기 위해 설계되었습니다. 그 주요 기능 및 모듈은 다음과 같습니다:
- 🌟 주요 기능:
- 📦 로컬 스토리지
- 🔔 리스너 콜백
- 🛡️ API 래핑
- 🌐 연결 관리
## 📚 주요 모듈:
1. 🚀 초기화 및 로그인
2. 👤 사용자 관리
3. 👫 친구 관리
4. 🤖 그룹 기능
5. 💬 대화 처리
이는 Golang을 사용하여 구축되었으며, 모든 플랫폼에서 일관된 접근 경험을 보장하는 크로스 플랫폼 배포를 지원합니다.
👉 **[GO SDK 탐색하기](https://github.com/openimsdk/openim-sdk-core)**
## 🌐 OpenIMServer에 대하여
- **OpenIMServer** 는 다음과 같은 특성을 가지고 있습니다:
- 🌐 마이크로서비스 아키텍처: 게이트웨이 및 다수의 rpc 서비스를 포함하는 클러스터 모드를 지원합니다.
- 🚀 다양한 배포 방법: 소스 코드, 쿠버네티스 또는 도커를 통한 배포를 지원합니다.
- 대규모 사용자 기반 지원: 수십만 명의 사용자를 포함하는 초대형 그룹, 수천만 명의 사용자 및 수십억 건의 메시지를 지원합니다.
### 강화된 비즈니스 기능:
- **REST API**OpenIMServer는 비즈니스 시스템을 위한 REST API를 제공하여, 백엔드 인터페이스를 통해 그룹 생성 및 푸시 메시지 전송과 같은 더 많은 기능을 비즈니스에 제공하기 위해 설계되었습니다.
- **Webhooks**OpenIMServer는 더 많은 비즈니스 형태를 확장할 수 있는 콜백 기능을 제공합니다. 콜백이란 메시지 전송 전후와 같은 특정 이벤트 전후에 OpenIMServer가 비즈니스 서버로 요청을 보내는 것을 의미합니다.
👉 **[더 알아보기](https://docs.openim.io/guides/introduction/product)**
## :building_construction: 전체 아키텍처
Open-IM-Server의 기능의 핵심으로 들어가 우리의 아키텍처 다이어그램을 자세히 살펴보세요.
![Overall Architecture](../images/architecture-layers.png)
## :rocket: 빠른 시작
우리는 많은 플랫폼을 지원합니다. 웹 측에서 빠른 체험을 위한 주소는 다음과 같습니다:
👉 **[OpenIM online demo](https://www.openim.io/zh/commercial)**
🤲 사용자 경험을 용이하게 하기 위해, 다양한 배포 솔루션을 제공합니다. 아래 목록에서 배포 방법을 선택할 수 있습니다:
- **[소스 코드 배포 가이드](https://docs.openim.io/guides/gettingStarted/imSourceCodeDeployment)**
- **[docker 배포 가이드](https://docs.openim.io/guides/gettingStarted/dockerCompose)**
- **[Kubernetes 배포 가이드](https://docs.openim.io/guides/gettingStarted/k8s-deployment)**
- **[Mac 개발자 배포 가이드](https://docs.openim.io/guides/gettingstarted/mac-deployment-guide)**
## :hammer_and_wrench: OpenIM 개발 시작하기
[![Open in Dev Container](https://img.shields.io/static/v1?label=Dev%20Container&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/github/openimsdk/open-im-server-deploy)
OpenIM의 목표는 최상위 수준의 오픈 소스 커뮤니티를 구축하는 것입니다. 우리는 [커뮤니티 리포지토리에서](https://github.com/OpenIMSDK/community) 일련의 표준을 가지고 있습니다.
이 Open-IM-Server 리포지토리에 기여하고 싶다면, 우리의 [기여자 문서](https://github.com/openimsdk/open-im-server-deploy/blob/main/CONTRIBUTING.md)를 읽어주세요.
시작하기 전에, 변경 사항이 필요한지 확인해 주세요. 가장 좋은 방법은 [새로운 토론](https://github.com/openimsdk/open-im-server-deploy/discussions/new/choose)을 생성하거나 [Slack 통신을](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A) 하거나, 문제를 발견했다면 먼저 [보고](https://github.com/openimsdk/open-im-server-deploy/issues/new/choose)하는 것입니다.
- [OpenIM API 참조](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/api.md)
- [OpenIM Bash 로깅](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/bash-log.md)
- [OpenIM CI/CD 액션](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/cicd-actions.md)
- [OpenIM 코드 규칙](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/code-conventions.md)
- [OpenIM 커밋 가이드라인](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/commit.md)
- [OpenIM 개발 가이드](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/development.md)
- [OpenIM 디렉토리 구조](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/directory.md)
- [OpenIM 환경 설정](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/environment.md)
- [OpenIM 오류 코드 참조](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/error-code.md)
- [OpenIM Git 작업 흐름](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/git-workflow.md)
- [OpenIM Git 체리 픽 가이드](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/gitcherry-pick.md)
- [OpenIM GitHub 작업 흐름](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/github-workflow.md)
- [OpenIM Go 코드 표준](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/go-code.md)
- [OpenIM 이미지 가이드라인](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/images.md)
- [OpenIM 초기 구성](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/init-config.md)
- [OpenIM docker 설치 가이드](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-docker.md)
- [OpenIM OpenIM Linux 설치](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-openim-linux-system.md)
- [OpenIM Linux 개발 가이드](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/linux-development.md)
- [OpenIM 로컬 액션 가이드](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/local-actions.md)
- [OpenIM 로깅 규칙](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/logging.md)
- [OpenIM 오프라인 배포](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/offline-deployment.md)
- [OpenIM Protoc 도구](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/protoc-tools.md)
- [OpenIM 테스트 가이드](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/test.md)
- [OpenIM 유틸리티 Go](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-go.md)
- [OpenIM 메이크파일 유틸리티](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-makefile.md)
- [OpenIM 스크립트 유틸리티](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-scripts.md)
- [OpenIM 버전 관리](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/version.md)
- [백엔드 관리 및 모니터 배포](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/prometheus-grafana.md)
- [맥 개발자 배포 가이드 for OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/mac-developer-deployment-guide.md)
## :busts_in_silhouette: 커뮤니티
- 📚 [OpenIM 커뮤니티](https://github.com/OpenIMSDK/community)
- 💕 [OpenIM 관심 그룹](https://github.com/Openim-sigs)
- 🚀 [우리의 Slack 커뮤니티에 가입하기](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
- :eyes: [우리의 위챗(微信群)에 가입하기](https://openim-1253691595.cos.ap-nanjing.myqcloud.com/WechatIMG20.jpeg)
## :calendar: 커뮤니티 미팅
우리는 누구나 커뮤니티에 참여하고 코드를 기여할 수 있도록 하며, 선물과 보상을 제공하며, 매주 목요일 밤에 여러분을 환영합니다.
우리의 회의는 [OpenIM Slack](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A) 🎯에서 이루어지며, Open-IM-Server 파이프라인을 검색하여 참여할 수 있습니다.
우리는 격주 회의의 메모를 [GitHub 토론](https://github.com/openimsdk/open-im-server-deploy/discussions/categories/meeting)에서 기록하며, 우리의 역사적 [회의](https://github.com/orgs/OpenIMSDK/discussions/categories/meeting) 노트와 회의 재생은 [Google Docs 📑](https://docs.google.com/document/d/1nx8MDpuG74NASx081JcCpxPgDITNTpIIos0DS6Vr9GU/edit?usp=sharing)에서 이용할 수 있습니다.
## :eyes: OpenIM을 사용하는 사람들
프로젝트 사용자 목록을 위한 우리의 [사용자 사례 연구](https://github.com/OpenIMSDK/community/blob/main/ADOPTERS.md) 페이지를 확인하세요. 사용 사례를 공유하고 싶다면 주저하지 말고 [📝코멘트](https://github.com/openimsdk/open-im-server-deploy/issues/379)를 남겨주세요.
## :page_facing_up: 라이선스
OpenIM은 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 전체 라이선스 텍스트는 [LICENSE](https://github.com/openimsdk/open-im-server-deploy/tree/main/LICENSE)에서 확인할 수 있습니다.
이 리포지토리 [OpenIM](https://github.com/openimsdk/open-im-server-deploy)에 표시된 OpenIM 로고, 그 변형 및 애니메이션 버전은 [assets/logo](../../assets/logo) 및 [assets/logo-gif](../../assets/logo-gif) 디렉토리 아래에 있으며, 저작권 법에 의해 보호됩니다.
## 🔮 우리의 기여자들에게 감사합니다!
<a href="https://github.com/openimsdk/open-im-server-deploy/graphs/contributors">
<img src="https://contrib.rocks/image?repo=openimsdk/open-im-server-deploy" />
</a>

183
docs/readme/README_tr.md Normal file
View File

@@ -0,0 +1,183 @@
<p align="center">
<a href="https://openim.io">
<img src="../../assets/logo-gif/openim-logo.gif" width="60%" height="30%"/>
</a>
</p>
<div align="center">
[![Stars](https://img.shields.io/github/stars/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=ff69b4)](https://github.com/openimsdk/open-im-server-deploy/stargazers)
[![Forks](https://img.shields.io/github/forks/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=blue)](https://github.com/openimsdk/open-im-server-deploy/network/members)
[![Codecov](https://img.shields.io/codecov/c/github/openimsdk/open-im-server-deploy?style=for-the-badge&logo=codecov&colorB=orange)](https://app.codecov.io/gh/openimsdk/open-im-server-deploy)
[![Go Report Card](https://goreportcard.com/badge/github.com/openimsdk/open-im-server-deploy?style=for-the-badge)](https://goreportcard.com/report/github.com/openimsdk/open-im-server-deploy)
[![Go Reference](https://img.shields.io/badge/Go%20Reference-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://pkg.go.dev/git.imall.cloud/openim/open-im-server-deploy)
[![License](https://img.shields.io/badge/license-Apache--2.0-green?style=for-the-badge)](https://github.com/openimsdk/open-im-server-deploy/blob/main/LICENSE)
[![Slack](https://img.shields.io/badge/Slack-500%2B-blueviolet?style=for-the-badge&logo=slack&logoColor=white)](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
[![Best Practices](https://img.shields.io/badge/Best%20Practices-purple?style=for-the-badge)](https://www.bestpractices.dev/projects/8045)
[![Good First Issues](https://img.shields.io/github/issues/openimsdk/open-im-server-deploy/good%20first%20issue?style=for-the-badge&logo=github)](https://github.com/openimsdk/open-im-server-deploy/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22good+first+issue%22)
[![Language](https://img.shields.io/badge/Language-Go-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://golang.org/)
<p align="center">
<a href="../../README.md">English</a> ·
<a href="../../README_zh_CN.md">中文</a> ·
<a href="./README_uk.md">Українська</a> ·
<a href="./README_cs.md">Česky</a> ·
<a href="./README_hu.md">Magyar</a> ·
<a href="./README_es.md">Español</a> ·
<a href="./README_fa.md">فارسی</a> ·
<a href="./README_fr.md">Français</a> ·
<a href="./README_de.md">Deutsch</a> ·
<a href="./README_pl.md">Polski</a> ·
<a href="./README_id.md">Indonesian</a> ·
<a href="./README_fi.md">Suomi</a> ·
<a href="./README_ml.md">മലയാളം</a> ·
<a href="./README_ja.md">日本語</a> ·
<a href="./README_nl.md">Nederlands</a> ·
<a href="./README_it.md">Italiano</a> ·
<a href="./README_ru.md">Русский</a> ·
<a href="./README_pt_BR.md">Português (Brasil)</a> ·
<a href="./README_eo.md">Esperanto</a> ·
<a href="./README_ko.md">한국어</a> ·
<a href="./README_ar.md">العربي</a> ·
<a href="./README_vi.md">Tiếng Việt</a> ·
<a href="./README_da.md">Dansk</a> ·
<a href="./README_el.md">Ελληνικά</a> ·
<a href="./README_tr.md">Türkçe</a>
</p>
</div>
</p>
## Ⓜ️ OpenIM Hakkında
OpenIM, uygulamalara sohbet, sesli-görüntülü aramalar, bildirimler ve AI sohbet robotları entegre etmek için özel olarak tasarlanmış bir hizmet platformudur. Güçlü API'ler ve Webhook'lar sunarak, geliştiricilerin bu etkileşimli özellikleri uygulamalarına kolayca dahil etmelerini sağlar. OpenIM bağımsız bir sohbet uygulaması değildir, ancak zengin iletişim işlevselliği sağlama amacıyla diğer uygulamaları destekleyen bir platform olarak hizmet verir. Aşağıdaki diyagram, AppServer, AppClient, OpenIMServer ve OpenIMSDK arasındaki etkileşimi detaylandırmak için açıklar.
![App-OpenIM Relationship](../images/oepnim-design.png)
## 🚀 OpenIMSDK Hakkında
**OpenIMSDK**, müşteri uygulamalarına gömülmek üzere özel olarak oluşturulan **OpenIMServer** için tasarlanmış bir IM SDK'sıdır. Ana özellikleri ve modülleri aşağıdaki gibidir:
- 🌟 Ana Özellikler:
- 📦 Yerel depolama
- 🔔 Dinleyici geri çağırmaları
- 🛡️ API sarımı
- 🌐 Bağlantı yönetimi
## 📚 Ana Modüller:
1. 🚀 Başlatma ve Giriş
2. 👤 Kullanıcı Yönetimi
3. 👫 Arkadaş Yönetimi
4. 🤖 Grup Fonksiyonları
5. 💬 Konuşma Yönetimi
Golang kullanılarak inşa edilmiş ve tüm platformlarda tutarlı bir erişim deneyimi sağlayacak şekilde çapraz platform dağıtımını destekler.
👉 **[GO SDK Keşfet](https://github.com/openimsdk/openim-sdk-core)**
## 🌐 OpenIMServer Hakkında
- **OpenIMServer** aşağıdaki özelliklere sahiptir:
- 🌐 Mikroservis mimarisi: Bir kapı ve çoklu rpc servisleri içeren küme modunu destekler.
- 🚀 Çeşitli dağıtım yöntemleri: Kaynak kodu, Kubernetes veya Docker aracılığıyla dağıtımı destekler.
- Büyük kullanıcı tabanı desteği: Yüz binlerce kullanıcısı olan süper büyük gruplar, on milyonlarca kullanıcı ve milyarlarca mesaj.
### Geliştirilmiş İşlevsellik:
- **REST API**OpenIMServer, işletmeleri gruplar oluşturma ve arka plan arayüzleri aracılığıyla itme mesajları gönderme gibi daha fazla işlevsellikle güçlendirmeyi amaçlayan iş sistemleri için REST API'leri sunar.
- **Webhooks**OpenIMServer, daha fazla iş formunu genişletme yetenekleri sağlayan geri çağırma özellikleri sunar. Geri çağırma, OpenIMServer'ın belirli bir olaydan önce veya sonra, örneğin bir mesaj göndermeden önce veya sonra iş sunucusuna bir istek göndermesi anlamına gelir.
👉 **[Daha fazla bilgi edinin](https://docs.openim.io/guides/introduction/product)**
## :building_construction: Genel Mimarisi
Mimari diyagramımızla Open-IM-Server'ın işlevselliğinin kalbine dalın.
![Overall Architecture](../images/architecture-layers.png)
## :rocket: Hızlı Başlangıç
Birçok platformu destekliyoruz. Web tarafında hızlı deneyim için adresler şunlardır:
👉 **[OpenIM online demo](https://www.openim.io/zh/commercial)**
🤲 Kullanıcı deneyimini kolaylaştırmak için çeşitli dağıtım çözümleri sunuyoruz. Aşağıdaki listeden dağıtım yönteminizi seçebilirsiniz:
- **[Kaynak Kodu Dağıtım Kılavuzu](https://docs.openim.io/guides/gettingStarted/imSourceCodeDeployment)**
- **[Docker Dağıtım Kılavuzu](https://docs.openim.io/guides/gettingStarted/dockerCompose)**
- **[Kubernetes Dağıtım Kılavuzu](https://docs.openim.io/guides/gettingStarted/k8s-deployment)**
- **[Mac Geliştirici Dağıtım Kılavuzu](https://docs.openim.io/guides/gettingstarted/mac-deployment-guide)**
## :hammer_and_wrench: OpenIM Geliştirmeye Başlamak
[![Open in Dev Container](https://img.shields.io/static/v1?label=Dev%20Container&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/github/openimsdk/open-im-server-deploy)
OpenIM Amacımız, üst düzey bir açık kaynak topluluğu oluşturmaktır. [Topluluk deposunda](https://github.com/OpenIMSDK/community) bir dizi standartımız var.
Bu Open-IM-Server deposuna katkıda bulunmak istiyorsanız, lütfen katkıda bulunanlar için [dokümantasyonumuzu](https://github.com/openimsdk/open-im-server-deploy/blob/main/CONTRIBUTING.md) okuyun.
Başlamadan önce, lütfen değişikliklerinizin talep edildiğinden emin olun. Bunun için en iyisi, [yeni bir tartışma OLUŞTURMAK](https://github.com/openimsdk/open-im-server-deploy/discussions/new/choose) veya [Slack İletişimi](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A) kurmak, ya da bir sorun bulursanız, önce bunu [rapor](https://github.com/openimsdk/open-im-server-deploy/issues/new/choose) etmektir.
- [OpenIM API Referansı](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/api.md)
- [OpenIM Bash Günlüğü](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/bash-log.md)
- [OpenIM CI/CD İşlemleri](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/cicd-actions.md)
- [OpenIM Kod Kuralları](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/code-conventions.md)
- [OpenIM Taahhüt Kuralları](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/commit.md)
- [OpenIM Geliştirme Kılavuzu](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/development.md)
- [OpenIM Dizin Yapısı](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/directory.md)
- [OpenIM Ortam Kurulumu](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/environment.md)
- [OpenIM Hata Kodu Referansı](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/error-code.md)
- [OpenIM Git İş Akışı](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/git-workflow.md)
- [OpenIM Git Cherry Pick Kılavuzu](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/gitcherry-pick.md)
- [OpenIM GitHub İş Akışı](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/github-workflow.md)
- [OpenIM Go Kod Standartları](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/go-code.md)
- [OpenIM Görüntü Kuralları](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/images.md)
- [OpenIM İlk Yapılandırma](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/init-config.md)
- [OpenIM Docker Kurulum Kılavuzu](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-docker.md)
- [OpenIM Linux Sistem Kurulumu](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-openim-linux-system.md)
- [OpenIM Linux Geliştirme Kılavuzu](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/linux-development.md)
- [OpenIM Yerel İşlemler Kılavuzu](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/local-actions.md)
- [OpenIM Günlük Kuralları](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/logging.md)
- [OpenIM Çevrimdışı Dağıtım](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/offline-deployment.md)
- [OpenIM Protoc Araçları](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/protoc-tools.md)
- [OpenIM Test Kılavuzu](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/test.md)
- [OpenIM Yardımcı Go](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-go.md)
- [OpenIM Makefile Yardımcı Programları](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-makefile.md)
- [OOpenIM Betik Yardımcı Programları](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-scripts.md)
- [OpenIM Sürümleme](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/version.md)
- [Arka uç yönetimi ve izleme dağıtımı](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/prometheus-grafana.md)
- [Mac Geliştirici Dağıtım Kılavuzu for OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/mac-developer-deployment-guide.md)
## :busts_in_silhouette: Topluluk
- 📚 [OpenIM Topluluğu](https://github.com/OpenIMSDK/community)
- 💕 [OpenIM İlgi Grubu](https://github.com/Openim-sigs)
- 🚀 [Slack topluluğumuza katılın](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
- :eyes: [Wechat grubumuza katılın (微信群)](https://openim-1253691595.cos.ap-nanjing.myqcloud.com/WechatIMG20.jpeg)
## :calendar: Topluluk Toplantıları
Topluluğumuza herkesin katılmasını ve kod katkısında bulunmasını istiyoruz, hediyeler ve ödüller sunuyoruz ve sizi her Perşembe gecesi bize katılmaya davet ediyoruz.
Konferansımız [OpenIM Slack'te](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A) 🎯, ardından Open-IM-Server boru hattını arayıp katılabilirsiniz.
İki haftada bir yapılan toplantının [notlarını](https://github.com/orgs/OpenIMSDK/discussions/categories/meeting) [GitHub tartışmalarında alıyoruz](https://github.com/openimsdk/open-im-server-deploy/discussions/categories/meeting), Tarihi toplantı notlarımız ve toplantıların tekrarları [Google Docs'ta](https://docs.google.com/document/d/1nx8MDpuG74NASx081JcCpxPgDITNTpIIos0DS6Vr9GU/edit?usp=sharing) 📑 mevcut.
## :eyes: Kimler OpenIM Kullanıyor
Proje kullanıcılarının bir listesi için [kullanıcı vaka çalışmaları](https://github.com/OpenIMSDK/community/blob/main/ADOPTERS.md) sayfamıza göz atın. Bir 📝[yorum](https://github.com/openimsdk/open-im-server-deploy/issues/379) bırakmaktan ve kullanım durumunuzu paylaşmaktan çekinmeyin.
## :page_facing_up: Lisans
OpenIM, Apache 2.0 lisansı altında lisanslanmıştır. Tam lisans metni için [LICENSE'ı](https://github.com/openimsdk/open-im-server-deploy/tree/main/LICENSE) görün.
Bu depoda, [assets/logo](../../assets/logo) ve [assets/logo-gif](../../assets/logo-gif) dizinlerinde görüntülenen [OpenIM](https://github.com/openimsdk/open-im-server-deploy) logosu, çeşitleri ve animasyonlu versiyonları, telif hakkı yasaları tarafından korunmaktadır.
## 🔮 Katkıda bulunanlarımıza teşekkürler!
<a href="https://github.com/openimsdk/open-im-server-deploy/graphs/contributors">
<img src="https://contrib.rocks/image?repo=openimsdk/open-im-server-deploy" />
</a>

183
docs/readme/README_uk.md Normal file
View File

@@ -0,0 +1,183 @@
<p align="center">
<a href="https://openim.io">
<img src="../../assets/logo-gif/openim-logo.gif" width="60%" height="30%"/>
</a>
</p>
<div align="center">
[![Stars](https://img.shields.io/github/stars/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=ff69b4)](https://github.com/openimsdk/open-im-server-deploy/stargazers)
[![Forks](https://img.shields.io/github/forks/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=blue)](https://github.com/openimsdk/open-im-server-deploy/network/members)
[![Codecov](https://img.shields.io/codecov/c/github/openimsdk/open-im-server-deploy?style=for-the-badge&logo=codecov&colorB=orange)](https://app.codecov.io/gh/openimsdk/open-im-server-deploy)
[![Go Report Card](https://goreportcard.com/badge/github.com/openimsdk/open-im-server-deploy?style=for-the-badge)](https://goreportcard.com/report/github.com/openimsdk/open-im-server-deploy)
[![Go Reference](https://img.shields.io/badge/Go%20Reference-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://pkg.go.dev/git.imall.cloud/openim/open-im-server-deploy)
[![License](https://img.shields.io/badge/license-Apache--2.0-green?style=for-the-badge)](https://github.com/openimsdk/open-im-server-deploy/blob/main/LICENSE)
[![Slack](https://img.shields.io/badge/Slack-500%2B-blueviolet?style=for-the-badge&logo=slack&logoColor=white)](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
[![Best Practices](https://img.shields.io/badge/Best%20Practices-purple?style=for-the-badge)](https://www.bestpractices.dev/projects/8045)
[![Good First Issues](https://img.shields.io/github/issues/openimsdk/open-im-server-deploy/good%20first%20issue?style=for-the-badge&logo=github)](https://github.com/openimsdk/open-im-server-deploy/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22good+first+issue%22)
[![Language](https://img.shields.io/badge/Language-Go-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://golang.org/)
<p align="center">
<a href="../../README.md">English</a> ·
<a href="../../README_zh_CN.md">中文</a> ·
<a href="./README_uk.md">Українська</a> ·
<a href="./README_cs.md">Česky</a> ·
<a href="./README_hu.md">Magyar</a> ·
<a href="./README_es.md">Español</a> ·
<a href="./README_fa.md">فارسی</a> ·
<a href="./README_fr.md">Français</a> ·
<a href="./README_de.md">Deutsch</a> ·
<a href="./README_pl.md">Polski</a> ·
<a href="./README_id.md">Indonesian</a> ·
<a href="./README_fi.md">Suomi</a> ·
<a href="./README_ml.md">മലയാളം</a> ·
<a href="./README_ja.md">日本語</a> ·
<a href="./README_nl.md">Nederlands</a> ·
<a href="./README_it.md">Italiano</a> ·
<a href="./README_ru.md">Русский</a> ·
<a href="./README_pt_BR.md">Português (Brasil)</a> ·
<a href="./README_eo.md">Esperanto</a> ·
<a href="./README_ko.md">한국어</a> ·
<a href="./README_ar.md">العربي</a> ·
<a href="./README_vi.md">Tiếng Việt</a> ·
<a href="./README_da.md">Dansk</a> ·
<a href="./README_el.md">Ελληνικά</a> ·
<a href="./README_tr.md">Türkçe</a>
</p>
</div>
</p>
## Ⓜ️ Про OpenIM
OpenIM — це сервісна платформа, спеціально розроблена для інтеграції чату, аудіо-відеодзвінків, сповіщень і чат-ботів штучного інтелекту в програми. Він надає ряд потужних API і веб-хуків, що дозволяє розробникам легко включати ці інтерактивні функції у свої програми. OpenIM не є окремою програмою для чату, а скоріше служить платформою для підтримки інших програм у досягненні широких можливостей спілкування. На наступній діаграмі детально показано взаємодію між AppServer, AppClient, OpenIMServer і OpenIMSDK.
![App-OpenIM Relationship](../images/oepnim-design.png)
## 🚀 Про OpenIMSDK
**OpenIMSDK** це пакет IM SDK, розроблений для **OpenIMServer**, створений спеціально для вбудовування в клієнтські програми. Його основні функції та модулі такі:
- 🌟 Основні характеристики:
- 📦 Локальне сховище
- 🔔 Зворотні виклики слухача
- 🛡️ Обгортка API
- 🌐 Керування підключенням
- 📚 Основні модулі:
1. 🚀 Ініціалізація та вхід
2. 👤 Керування користувачами
3. 👫 Керування друзями
4. 🤖 Групові функції
5. 💬 Ведення розмови
Він створений за допомогою Golang і підтримує кросплатформне розгортання, забезпечуючи послідовний доступ на всіх платформах.
👉 **[Дослідити GO SDK](https://github.com/openimsdk/openim-sdk-core)**
## 🌐 Про OpenIMServer
- **OpenIMServer** має такі характеристики:
- 🌐 Архітектура мікросервісу: підтримує режим кластера, включаючи шлюз і кілька служб rpc.
- 🚀 Різноманітні методи розгортання: підтримує розгортання через вихідний код, Kubernetes або Docker.
- Підтримка величезної бази користувачів: надвеликі групи із сотнями тисяч користувачів, десятками мільйонів користувачів і мільярдами повідомлень.
### Розширена бізнес-функціональність:
- **REST API**: OpenIMServer пропонує REST API для бізнес-систем, спрямованих на надання компаніям додаткових можливостей, таких як створення груп і надсилання push-повідомлень через серверні інтерфейси.
- **Веб-перехоплення**: OpenIMServer надає можливості зворотного виклику, щоб розширити більше бізнес-форм. Зворотний виклик означає, що OpenIMServer надсилає запит на бізнес-сервер до або після певної події, як зворотні виклики до або після надсилання повідомлення.
👉 **[Докладніше](https://docs.openim.io/guides/introduction/product)**
## :building_construction: Загальна архітектура
Пориньте в серце функціональності Open-IM-Server за допомогою нашої діаграми архітектури.
![Overall Architecture](../images/architecture-layers.png)
## :rocket: Швидкий початок
Ми підтримуємо багато платформ. Ось адреси для швидкого використання веб-сайту:
👉 **[Онлайн-демонстрація OpenIM](https://web-enterprise.rentsoft.cn/)**
🤲 Щоб полегшити роботу користувача, ми пропонуємо різні рішення для розгортання. Ви можете вибрати спосіб розгортання зі списку нижче:
- **[Посібник із розгортання вихідного коду](https://docs.openim.io/guides/gettingStarted/imSourceCodeDeployment)**
- **[Посібник із розгортання Docker](https://docs.openim.io/guides/gettingStarted/dockerCompose)**
- **[Посібник із розгортання Kubernetes](https://docs.openim.io/guides/gettingStarted/k8s-deployment)**
- **[Посібник із розгортання розробника Mac](https://docs.openim.io/guides/gettingstarted/mac-deployment-guide)**
## :hammer_and_wrench: Щоб розпочати розробку OpenIM
[![Відкрити в контейнері для розробників](https://img.shields.io/static/v1?label=Dev%20Container&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/github/openimsdk/open-im-server-deploy)
OpenIM. Наша мета — побудувати спільноту з відкритим кодом найвищого рівня. У нас є набір стандартів у [репозиторії спільноти](https://github.com/OpenIMSDK/community).
Якщо ви хочете внести свій внесок у це сховище Open-IM-Server, прочитайте нашу [документацію для учасників](https://github.com/openimsdk/open-im-server-deploy/blob/main/CONTRIBUTING.md).
Перш ніж почати, переконайтеся, що ваші зміни затребувані. Найкраще для цього створити [нове обговорення](https://github.com/openimsdk/open-im-server-deploy/discussions/new/choose) АБО [Нездійснене спілкування](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)або, якщо ви виявите проблему, спершу [повідомити про неї](https://github.com/openimsdk/open-im-server-deploy/issues/new/choose).
- [Довідка щодо API OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/api.md)
- [Ведення журналу OpenIM Bash](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/bash-log.md)
- [Дії OpenIM CI/CD](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/cicd-actions.md)
- [Положення про код OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/code-conventions.md)
- [Інструкції щодо фіксації OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/commit.md)
- [Посібник з розробки OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/development.md)
- [Структура каталогу OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/directory.md)
- [Налаштування середовища OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/environment.md)
- [Довідка про код помилки OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/error-code.md)
- [Робочий процес OpenIM Git](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/git-workflow.md)
- [Посібник із вибору OpenIM Git Cherry](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/gitcherry-pick.md)
- [Робочий процес OpenIM GitHub](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/github-workflow.md)
- [Стандарти коду OpenIM Go](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/go-code.md)
- [Інструкції щодо зображення OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/images.md)
- [Початкова конфігурація OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/init-config.md)
- [Посібник із встановлення OpenIM Docker](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-docker.md)
- [Встановлення системи OpenIM OpenIM Linux](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-openim-linux-system.md)
- [Посібник із розробки OpenIM Linux](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/linux-development.md)
- [Локальний посібник із дій OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/local-actions.md)
- [Положення про протоколювання OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/logging.md)
- [Офлайн-розгортання OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/offline-deployment.md)
- [Інструменти OpenIM Protoc](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/protoc-tools.md)
- [Посібник з тестування OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/test.md)
- [Утиліта OpenIM Go](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-go.md)
- [Утиліти OpenIM Makefile](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-makefile.md)
- [Утиліти сценарію OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-scripts.md)
- [Версії OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/version.md)
- [Керування серверною частиною та моніторинг розгортання](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/prometheus-grafana.md)
- [Посібник із розгортання розробника Mac для OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/mac-developer-deployment-guide.md)
## :busts_in_silhouette: Спільнота
- 📚 [Спільнота OpenIM](https://github.com/OpenIMSDK/community)
- 💕 [Група інтересів OpenIM](https://github.com/Openim-sigs)
- 🚀 [Приєднайтеся до нашої спільноти Slack](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
- :eyes: [Приєднайтеся до нашого wechat](https://openim-1253691595.cos.ap-nanjing.myqcloud.com/WechatIMG20.jpeg)
## :calendar: Збори громади
Ми хочемо, щоб будь-хто долучився до нашої спільноти та додав код, ми пропонуємо подарунки та нагороди, і ми запрошуємо вас приєднатися до нас щочетверга ввечері.
Наша конференція знаходиться в [OpenIM Slack](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A) 🎯, тоді ви можете шукати конвеєр Open-IM-Server, щоб приєднатися.
Ми робимо нотатки про кожну [двотижневу зустріч](https://github.com/orgs/OpenIMSDK/discussions/categories/meeting)в [обговореннях GitHub](https://github.com/openimsdk/open-im-server-deploy/discussions/categories/meeting). Наші історичні нотатки зустрічей, а також повтори зустрічей доступні в[Google Docs :bookmark_tabs:](https://docs.google.com/document/d/1nx8MDpuG74NASx081JcCpxPgDITNTpIIos0DS6Vr9GU/edit?usp=sharing).
## :eyes: Хто використовує OpenIM
Перегляньте нашу сторінку [тематичні дослідження користувачів](https://github.com/OpenIMSDK/community/blob/main/ADOPTERS.md), щоб отримати список користувачів проекту. Не соромтеся залишити [📝коментар](https://github.com/openimsdk/open-im-server-deploy/issues/379)і поділитися своїм випадком використання.
## :page_facing_up: Ліцензія
OpenIM ліцензовано за ліцензією Apache 2.0. Див. [ЛІЦЕНЗІЯ](https://github.com/openimsdk/open-im-server-deploy/tree/main/LICENSE) для повного тексту ліцензії.
Логотип OpenIM, включаючи його варіації та анімовані версії, що відображаються в цьому сховищі[OpenIM](https://github.com/openimsdk/open-im-server-deploy)у каталогах [assets/logo](./assets/logo)і [assets/logo-gif](assets/logo-gif) , захищені законами про авторське право.
## 🔮 Дякуємо нашим дописувачам!
<a href="https://github.com/openimsdk/open-im-server-deploy/graphs/contributors">
<img src="https://contrib.rocks/image?repo=openimsdk/open-im-server-deploy" />
</a>

183
docs/readme/README_vi.md Normal file
View File

@@ -0,0 +1,183 @@
<p align="center">
<a href="https://openim.io">
<img src="../../assets/logo-gif/openim-logo.gif" width="60%" height="30%"/>
</a>
</p>
<div align="center">
[![Stars](https://img.shields.io/github/stars/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=ff69b4)](https://github.com/openimsdk/open-im-server-deploy/stargazers)
[![Forks](https://img.shields.io/github/forks/openimsdk/open-im-server-deploy?style=for-the-badge&logo=github&colorB=blue)](https://github.com/openimsdk/open-im-server-deploy/network/members)
[![Codecov](https://img.shields.io/codecov/c/github/openimsdk/open-im-server-deploy?style=for-the-badge&logo=codecov&colorB=orange)](https://app.codecov.io/gh/openimsdk/open-im-server-deploy)
[![Go Report Card](https://goreportcard.com/badge/github.com/openimsdk/open-im-server-deploy?style=for-the-badge)](https://goreportcard.com/report/github.com/openimsdk/open-im-server-deploy)
[![Go Reference](https://img.shields.io/badge/Go%20Reference-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://pkg.go.dev/git.imall.cloud/openim/open-im-server-deploy)
[![License](https://img.shields.io/badge/license-Apache--2.0-green?style=for-the-badge)](https://github.com/openimsdk/open-im-server-deploy/blob/main/LICENSE)
[![Slack](https://img.shields.io/badge/Slack-500%2B-blueviolet?style=for-the-badge&logo=slack&logoColor=white)](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
[![Best Practices](https://img.shields.io/badge/Best%20Practices-purple?style=for-the-badge)](https://www.bestpractices.dev/projects/8045)
[![Good First Issues](https://img.shields.io/github/issues/openimsdk/open-im-server-deploy/good%20first%20issue?style=for-the-badge&logo=github)](https://github.com/openimsdk/open-im-server-deploy/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22good+first+issue%22)
[![Language](https://img.shields.io/badge/Language-Go-blue.svg?style=for-the-badge&logo=go&logoColor=white)](https://golang.org/)
<p align="center">
<a href="../../README.md">English</a> ·
<a href="../../README_zh_CN.md">中文</a> ·
<a href="./README_uk.md ">Українська</a> ·
<a href="./README_cs.md">Česky</a> ·
<a href="./README_hu.md">Magyar</a> ·
<a href="./README_es.md">Español</a> ·
<a href="./README_fa.md">فارسی</a> ·
<a href="./README_fr.md">Français</a> ·
<a href="./README_de.md">Deutsch</a> ·
<a href="./README_pl.md">Polski</a> ·
<a href="./README_id.md">Indonesian</a> ·
<a href="./README_fi.md">Suomi</a> ·
<a href="./README_ml.md">മലയാളം</a> ·
<a href="./README_ja.md">日本語</a> ·
<a href="./README_nl.md">Nederlands</a> ·
<a href="./README_it.md">Italiano</a> ·
<a href="./README_ru.md">Русский</a> ·
<a href="./README_pt_BR.md">Português (Brasil)</a> ·
<a href="./README_eo.md">Esperanto</a> ·
<a href="./README_ko.md">한국어</a> ·
<a href="./README_ar.md">العربي</a> ·
<a href="./README_vi.md">Tiếng Việt</a> ·
<a href="./README_da.md">Dansk</a> ·
<a href="./README_el.md">Ελληνικά</a> ·
<a href="./README_tr.md">Türkçe</a>
</p>
</div>
</p>
## Ⓜ️ Về OpenIM
OpenIM là một nền tảng dịch vụ được thiết kế đặc biệt cho việc tích hợp chat, cuộc gọi âm thanh-video, thông báo và chatbot AI vào các ứng dụng. Nó cung cấp một loạt các API mạnh mẽ và Webhooks, giúp các nhà phát triển dễ dàng tích hợp các tính năng tương tác này vào ứng dụng của mình. OpenIM không phải là một ứng dụng chat độc lập, mà là một nền tảng hỗ trợ các ứng dụng khác để đạt được các chức năng giao tiếp phong phú. Sơ đồ sau đây minh họa sự tương tác giữa AppServer, AppClient, OpenIMServer và OpenIMSDK để giải thích chi tiết.
![App-OpenIM Relationship](../../docs/images/oepnim-design.png)
## 🚀 Về OpenIMSDK
**OpenIMSDK** là một SDK IM được thiết kế cho **OpenIMServer**, được tạo ra đặc biệt để nhúng vào các ứng dụng khách. Các tính năng chính và các mô-đun của nó như sau:
- 🌟 Các Tính Năng Chính:
- 📦 Lưu trữ cục bộ
- 🔔 Gọi lại sự kiện (Listener callbacks)
- 🛡️ Bọc API
- 🌐 Quản lý kết nối
- 📚 Các Mô-đun Chính:
1. 🚀 Khởi tạo và Đăng nhập
2. 👤 Quản lý Người dùng
3. 👫 Quản lý Bạn bè
4. 🤖 Chức năng Nhóm
5. 💬 Xử lý Cuộc trò chuyện
Nó được xây dựng bằng Golang và hỗ trợ triển khai đa nền tảng, đảm bảo trải nghiệm truy cập nhất quán trên tất cả các nền tảng
👉 **[Khám phá GO SDK](https://github.com/openimsdk/openim-sdk-core)**
## 🌐 Về OpenIMServer
- **OpenIMServer** có những đặc điểm sau:
- 🌐 Kiến trúc vi dịch vụ: Hỗ trợ chế độ cluster, bao gồm một gateway và nhiều dịch vụ rpc.
- 🚀 Phương pháp triển khai đa dạng: Hỗ trợ triển khai qua mã nguồn, Kubernetes hoặc Docker.
- Hỗ trợ cho cơ sở người dùng lớn: Nhóm siêu lớn với hàng trăm nghìn người dùng, hàng chục triệu người dùng và hàng tỷ tin nhắn.
### Tăng cường Chức năng Kinh doanh:
- **REST API**: OpenIMServer cung cấp REST APIs cho các hệ thống kinh doanh, nhằm tăng cường khả năng cho doanh nghiệp với nhiều chức năng hơn, như tạo nhóm và gửi tin nhắn đẩy qua giao diện backend.
- **Webhooks**: OpenIMServer cung cấp khả năng gọi lại để mở rộng thêm hình thức kinh doanh. Một gọi lại có nghĩa là OpenIMServer gửi một yêu cầu đến máy chủ kinh doanh trước hoặc sau một sự kiện nhất định, giống như gọi lại trước hoặc sau khi gửi một tin nhắn.
👉 **[Learn more](https://docs.openim.io/guides/introduction/product)**
## :building_construction: Kiến trúc tổng thể
Làm sâu sắc vào trái tim của chức năng Open-IM-Server với sơ đồ kiến trúc của chúng tôi.
![Overall Architecture](../../docs/images/architecture-layers.png)
## :rocket: Bắt đầu nhanh
Chúng tôi hỗ trợ nhiều nền tảng. Dưới đây là các địa chỉ để trải nghiệm nhanh trên phía web
👉 **[Demo web trực tuyến OpenIM](https://web-enterprise.rentsoft.cn/)**
🤲 Để tạo thuận lợi cho trải nghiệm người dùng, chúng tôi cung cấp các giải pháp triển khai đa dạng. Bạn có thể chọn phương thức triển khai từ danh sách dưới đây:
- **[Hướng dẫn Triển khai Mã Nguồn](https://docs.openim.io/guides/gettingStarted/imSourceCodeDeployment)**
- **[Hướng dẫn Triển khai Docker](https://docs.openim.io/guides/gettingStarted/dockerCompose)**
- **[Hướng dẫn Triển khai Kubernetes](https://docs.openim.io/guides/gettingStarted/k8s-deployment)**
- **[Hướng dẫn Triển khai cho Nhà Phát Triển Mac](https://docs.openim.io/guides/gettingstarted/mac-deployment-guide)**
## :hammer_and_wrench: Để Bắt Đầu Phát Triển OpenIM
[![Mở trong Dev Contain](https://img.shields.io/static/v1?label=Dev%20Container&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/github/openimsdk/open-im-server-deploy)
Mục tiêu của OpenIM là xây dựng một cộng đồng mã nguồn mở cấp cao. Chúng tôi có một bộ tiêu chuẩn, Trong [kho lưu trữ Cộng đồng](https://github.com/OpenIMSDK/community).
Nếu bạn muốn đóng góp cho kho lưu trữ Open-IM-Server này, vui lòng đọc [tài liệu hướng dẫn cho người đóng góp](https://github.com/openimsdk/open-im-server-deploy/blob/main/CONTRIBUTING.md).
Trước khi bạn bắt đầu, hãy chắc chắn rằng các thay đổi của bạn được yêu cầu. Cách tốt nhất là tạo một [cuộc thảo luận mới](https://github.com/openimsdk/open-im-server-deploy/discussions/new/choose) hoặc [Giao tiếp Slack](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A), hoặc nếu bạn tìm thấy một vấn đề, [báo cáo nó ](https://github.com/openimsdk/open-im-server-deploy/issues/new/choose) trước.
- [Tham khảo API OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/api.md)
- [Nhật ký Bash OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/bash-log.md)
- [Hành động CI/CD OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/cicd-actions.md)
- [Quy ước Mã OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/code-conventions.md)
- [Hướng dẫn Commit OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/commit.md)
- [Hướng dẫn Phát triển OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/development.md)
- [Cấu trúc Thư mục OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/directory.md)
- [Cài đặt Môi trường OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/environment.md)
- [Tham khảo Mã Lỗi OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/error-code.md)
- [Quy trình Git OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/git-workflow.md)
- [Hướng dẫn Cherry Pick Git OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/gitcherry-pick.md)
- [Quy trình GitHub OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/github-workflow.md)
- [Tiêu chuẩn Mã Go OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/go-code.md)
- [Hướng dẫn Hình ảnh OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/images.md)
- [Cấu hình Ban đầu OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/init-config.md)
- [Hướng dẫn Cài đặt Docker OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-docker.md)
- [Hướng dẫn Cài đặt Hệ thống Linux OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/install-openim-linux-system.md)
- [Hướng dẫn Phát triển Linux OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/linux-development.md)
- [Hướng dẫn Hành động Địa phương OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/local-actions.md)
- [Quy ước Nhật ký OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/logging.md)
- [Triển khai Ngoại tuyến OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/offline-deployment.md)
- [Công cụ Protoc OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/protoc-tools.md)
- [Hướng dẫn Kiểm thử OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/test.md)
- [Utility Go OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-go.md)
- [Tiện ích Makefile OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-makefile.md)
- [Tiện ích Kịch bản OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/util-scripts.md)
- [Quản lý Phiên bản OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/version.md)
- [Quản lý triển khai và giám sát backend](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/prometheus-grafana.md)
- [Hướng dẫn Triển khai cho Nhà Phát triển Mac OpenIM](https://github.com/openimsdk/open-im-server-deploy/tree/main/docs/contrib/mac-developer-deployment-guide.md)
## :busts_in_silhouette: Cộng đồng
- 📚 [Cộng đồng OpenIM](https://github.com/OpenIMSDK/community)
- 💕 [Nhóm Quan tâm OpenIM](https://github.com/Openim-sigs)
- 🚀 [Tham gia cộng đồng Slack của chúng tôi](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A)
- :eyes: [Tham gia nhóm WeChat của chúng tôi (微信群)](https://openim-1253691595.cos.ap-nanjing.myqcloud.com/WechatIMG20.jpeg)
## :calendar: Cuộc họp Cộng đồng
Chúng tôi muốn bất kỳ ai cũng có thể tham gia cộng đồng và đóng góp mã nguồn, chúng tôi cung cấp quà tặng và phần thưởng, và chúng tôi chào đón bạn tham gia cùng chúng tôi mỗi tối thứ Năm.
Hội nghị của chúng tôi được tổ chức trên Slack của [OpenIM Slack](https://join.slack.com/t/openimsdk/shared_invite/zt-2ijy1ys1f-O0aEDCr7ExRZ7mwsHAVg9A) 🎯, sau đó bạn có thể tìm kiếm pipeline Open-IM-Server để tham gia
Chúng tôi ghi chú mỗi [cuộc họp hai tuần một lần](https://github.com/orgs/OpenIMSDK/discussions/categories/meeting) trong [các cuộc thảo luận GitHub](https://github.com/openimsdk/open-im-server-deploy/discussions/categories/meeting), ghi chú cuộc họp lịch sử của chúng tôi cũng như các bản ghi lại của cuộc họp có sẵn tại [Google Docs :bookmark_tabs:](https://docs.google.com/document/d/1nx8MDpuG74NASx081JcCpxPgDITNTpIIos0DS6Vr9GU/edit?usp=sharing).
## :eyes: Ai Đang Sử Dụng OpenIM
Xem trangr [các nghiên cứu trường hợp người dùng](https://github.com/OpenIMSDK/community/blob/main/ADOPTERS.md) của chúng tôi để biết danh sách các người dùng dự án. Đừng ngần ngại để lại [📝bình luận](https://github.com/openimsdk/open-im-server-deploy/issues/379) và chia sẻ trường hợp sử dụng của bạn.
## :page_facing_up: Giấy phép
OpenIM được cấp phép theo giấy phép Apache 2.0. Xem [GIẤY PHÉP](https://github.com/openimsdk/open-im-server-deploy/tree/main/LICENSE) để biết toàn bộ nội dung giấy phép.
Logo OpenIM, bao gồm các biến thể và phiên bản hoạt hình, được hiển thị trong kho lưu trữ này [OpenIM](https://github.com/openimsdk/open-im-server-deploy) dưới các thư mục [assets/logo](../../assets/logo) và [assets/logo-gif](assets/logo-gif) được bảo vệ bởi luật bản quyền.
## 🔮 Cảm ơn các đóng góp của bạn!
<a href="https://github.com/openimsdk/open-im-server-deploy/graphs/contributors">
<img src="https://contrib.rocks/image?repo=openimsdk/open-im-server-deploy" />
</a>

565
docs/redpacket-api.md Normal file
View File

@@ -0,0 +1,565 @@
# 红包接口文档
## 接口列表
### 1. 发送红包
**接口地址**: `POST /redpacket/send_redpacket`
**接口描述**: 在群聊中发送红包,发送用户默认为群主
**请求参数**:
```json
{
"groupID": "group123", // 群ID必填string
"redPacketType": 1, // 红包类型必填int321-普通红包平均分配2-拼手气红包(随机分配)
"totalAmount": 10000, // 总金额必填int64单位
"totalCount": 10, // 总个数必填int32
"blessing": "恭喜发财" // 祝福语可选string
}
```
**参数说明**:
- `groupID`: 群ID必须是已存在的群
- `redPacketType`: 红包类型
- `1`: 普通红包,每个红包金额 = 总金额 / 总个数
- `2`: 拼手气红包,金额随机分配
- `totalAmount`: 总金额单位例如10000 = 100元
- `totalCount`: 红包总个数必须大于0
- `blessing`: 祝福语,可选
**响应参数**:
```json
{
"errCode": 0, // 错误码0表示成功
"errMsg": "", // 错误信息
"errDlt": "", // 错误详情
"data": {
"redPacketID": "rp_1234567890abcdef", // 红包IDstring
"serverMsgID": "msg_1234567890abcdef", // 服务器消息IDstring
"clientMsgID": "client_1234567890", // 客户端消息IDstring
"sendTime": 1704067200000 // 发送时间戳int64毫秒
}
}
```
**响应说明**:
- `redPacketID`: 红包唯一标识,用于后续领取、查询等操作
- `serverMsgID`: 服务器生成的消息ID
- `clientMsgID`: 客户端消息ID
- `sendTime`: 发送时间戳(毫秒)
**错误码**:
- `0`: 成功
- `1001`: 参数错误(金额、个数、类型等)
- `1002`: 群不存在
- `1003`: 群主不存在
- `1004`: 创建红包记录失败
- `1005`: 发送消息失败
**请求示例**:
```bash
curl -X POST http://localhost:10002/redpacket/send_redpacket \
-H "Content-Type: application/json" \
-H "token: your_token" \
-d '{
"groupID": "group123",
"redPacketType": 1,
"totalAmount": 10000,
"totalCount": 10,
"blessing": "恭喜发财"
}'
```
**响应示例**:
```json
{
"errCode": 0,
"errMsg": "",
"errDlt": "",
"data": {
"redPacketID": "rp_1234567890abcdef",
"serverMsgID": "msg_1234567890abcdef",
"clientMsgID": "client_1234567890",
"sendTime": 1704067200000
}
}
```
## 业务规则
1. **发送用户**: 自动使用群主作为发送用户,无需在请求中指定
2. **红包类型**:
- 普通红包type=1: 每个红包金额 = 总金额 / 总个数(向下取整,最后一个红包包含余数)
- 拼手气红包type=2: 金额随机分配,保证最后一个红包能领完剩余金额
3. **过期时间**: 红包默认24小时后过期
4. **红包状态**:
- `0`: 进行中(可领取)
- `1`: 已领完
- `2`: 已过期
5. **消息类型**: 红包消息使用自定义消息类型 `110``constant.Custom`),通过 `description` 字段标识二级类型为 `"redpacket"`
## 数据库记录
发送红包时会自动创建以下数据库记录:
**red_packets 表**:
- 记录红包基本信息(金额、个数、类型等)
- 记录红包状态和剩余信息
- 记录过期时间
**消息记录**:
- 在群聊中发送一条红包消息
- 消息内容包含红包ID和基本信息
- 群成员可以看到红包消息
## 注意事项
1. 只支持群聊,不支持单聊
2. 发送用户固定为群主,不能指定其他用户
3. 红包金额单位是"分",不是"元"
4. 红包个数必须大于0
5. 总金额必须大于0
6. 红包类型只能是1或2
### 2. 领取红包
**接口地址**: `POST /redpacket/receive`
**接口描述**: 领取红包,支持普通红包和拼手气红包
**请求参数**:
```json
{
"redPacketID": "rp_1234567890abcdef" // 红包ID必填string
}
```
**参数说明**:
- `redPacketID`: 红包ID从发送红包接口的响应中获取
**响应参数**:
```json
{
"errCode": 0, // 错误码0表示成功
"errMsg": "", // 错误信息
"errDlt": "", // 错误详情
"data": {
"redPacketID": "rp_1234567890abcdef", // 红包IDstring
"amount": 1000, // 领取金额int64单位
"isLucky": false // 是否为手气最佳bool仅拼手气红包有效
}
}
```
**响应说明**:
- `redPacketID`: 红包ID
- `amount`: 领取到的金额,单位:分
- `isLucky`: 是否为手气最佳,仅拼手气红包有效
- `true`: 是手气最佳(领取金额最大)
- `false`: 不是手气最佳
**错误码**:
- `0`: 成功
- `1001`: 参数错误红包ID为空
- `1004`: 红包不存在RecordNotFoundError
- `1801`: 红包已被领完RedPacketFinishedError
- `1802`: 红包已过期RedPacketExpiredError
- `1803`: 用户已领取过该红包RedPacketAlreadyReceivedError
- `500`: 服务器内部错误Redis队列操作失败等
**请求示例**:
```bash
curl -X POST http://localhost:10002/redpacket/receive \
-H "Content-Type: application/json" \
-H "token: your_token" \
-d '{
"redPacketID": "rp_1234567890abcdef"
}'
```
**响应示例**:
```json
{
"errCode": 0,
"errMsg": "",
"errDlt": "",
"data": {
"redPacketID": "rp_1234567890abcdef",
"amount": 1000,
"isLucky": false
}
}
```
**业务规则**:
1. **领取限制**:
- 每个用户只能领取一次
- 红包必须处于"进行中"状态
- 红包不能已过期
- 红包不能已被领完
2. **金额分配**:
- **普通红包type=1**: 金额 = 剩余金额 / 剩余个数(向下取整,最后一个包含余数)
- **拼手气红包type=2**: 从Redis队列中获取预分配的随机金额
3. **手气最佳判断**:
- 仅拼手气红包有效
- 领取金额最大的用户被标记为手气最佳
- 如果有多个相同最大金额,第一个领取的会被标记为手气最佳
4. **消息更新**:
- 领取红包后,客户端下次拉取消息时会自动看到已领取状态
- 消息同步时会动态填充领取信息(`IsReceived``ReceiveInfo`
5. **原子操作**:
- 领取操作是原子的,确保并发安全
- 使用数据库事务保证数据一致性
### 3. 查询红包列表(后台管理接口)
**接口地址**: `POST /redpacket/get_redpackets_by_group`
**接口描述**: 根据群ID查询红包列表支持查询所有红包或指定群的红包
**请求参数**:
```json
{
"groupID": "group123", // 群ID选填string不填或为空则查询所有红包
"pagination": {
"pageNumber": 1, // 页码选填int32从1开始默认1
"showNumber": 20 // 每页数量选填int32默认20
}
}
```
**参数说明**:
- `groupID`: 群ID选填
- 如果为空或不传,则查询所有红包
- 如果指定群ID则只查询该群的红包
- `pagination`: 分页参数,选填
- `pageNumber`: 页码从1开始默认1
- `showNumber`: 每页数量默认20
**响应参数**:
```json
{
"errCode": 0,
"errMsg": "",
"errDlt": "",
"data": {
"total": 100, // 总数int64
"redPackets": [ // 红包列表array
{
"redPacketID": "rp_1234567890abcdef", // 红包IDstring
"sendUserID": "user123", // 发送者IDstring
"groupID": "group123", // 群IDstring
"groupName": "测试群", // 群名称string
"redPacketType": 1, // 红包类型int321-普通红包2-拼手气红包
"totalAmount": 10000, // 总金额int64单位
"totalCount": 10, // 总个数int32
"remainAmount": 5000, // 剩余金额int64单位
"remainCount": 5, // 剩余个数int32
"blessing": "恭喜发财", // 祝福语string
"status": 0, // 状态int320-进行中1-已领完2-已过期
"expireTime": 1704153600000, // 过期时间戳int64毫秒
"createTime": 1704067200000 // 创建时间戳int64毫秒
}
]
}
}
```
**响应说明**:
- `total`: 符合条件的红包总数
- `redPackets`: 红包列表,按创建时间倒序排列
- 每个红包包含完整的信息ID、发送者、群ID、群名称、类型、金额、个数、剩余信息、状态等
- `groupName`: 群名称,通过批量查询群信息获取,如果群不存在或查询失败则为空字符串
**错误码**:
- `0`: 成功
- `1001`: 参数错误
- `500`: 服务器内部错误
**请求示例**:
```bash
# 查询所有红包
curl -X POST http://localhost:10002/redpacket/get_redpackets_by_group \
-H "Content-Type: application/json" \
-H "token: your_token" \
-d '{
"pagination": {
"pageNumber": 1,
"showNumber": 20
}
}'
# 查询指定群的红包
curl -X POST http://localhost:10002/redpacket/get_redpackets_by_group \
-H "Content-Type: application/json" \
-H "token: your_token" \
-d '{
"groupID": "group123",
"pagination": {
"pageNumber": 1,
"showNumber": 20
}
}'
```
**响应示例**:
```json
{
"errCode": 0,
"errMsg": "",
"errDlt": "",
"data": {
"total": 100,
"redPackets": [
{
"redPacketID": "rp_1234567890abcdef",
"sendUserID": "user123",
"groupID": "group123",
"groupName": "测试群",
"redPacketType": 1,
"totalAmount": 10000,
"totalCount": 10,
"remainAmount": 5000,
"remainCount": 5,
"blessing": "恭喜发财",
"status": 0,
"expireTime": 1704153600000,
"createTime": 1704067200000
}
]
}
}
```
### 4. 查询红包领取情况(后台管理接口)
**接口地址**: `POST /redpacket/get_receive_info`
**接口描述**: 查询指定红包的领取情况,包括所有领取记录和详细信息
**请求参数**:
```json
{
"redPacketID": "rp_1234567890abcdef" // 红包ID必填string
}
```
**参数说明**:
- `redPacketID`: 红包ID必填
**响应参数**:
```json
{
"errCode": 0,
"errMsg": "",
"errDlt": "",
"data": {
"redPacketID": "rp_1234567890abcdef", // 红包IDstring
"totalAmount": 10000, // 总金额int64单位
"totalCount": 10, // 总个数int32
"remainAmount": 5000, // 剩余金额int64单位
"remainCount": 5, // 剩余个数int32
"status": 0, // 状态int320-进行中1-已领完2-已过期
"receives": [ // 领取记录列表array
{
"receiveID": "rec_1234567890", // 领取记录IDstring
"receiveUserID": "user456", // 领取者IDstring
"amount": 1000, // 领取金额int64单位
"receiveTime": 1704070800000, // 领取时间戳int64毫秒
"isLucky": false // 是否为手气最佳bool仅拼手气红包有效
}
]
}
}
```
**响应说明**:
- `redPacketID`: 红包ID
- `totalAmount`: 红包总金额
- `totalCount`: 红包总个数
- `remainAmount`: 剩余金额
- `remainCount`: 剩余个数
- `status`: 红包状态
- `receives`: 领取记录列表,按领取时间正序排列
- `receiveID`: 领取记录ID
- `receiveUserID`: 领取者用户ID
- `amount`: 领取的金额
- `receiveTime`: 领取时间戳
- `isLucky`: 是否为手气最佳(仅拼手气红包有效)
**错误码**:
- `0`: 成功
- `1001`: 参数错误红包ID为空
- `1004`: 红包不存在
- `500`: 服务器内部错误
**请求示例**:
```bash
curl -X POST http://localhost:10002/redpacket/get_receive_info \
-H "Content-Type: application/json" \
-H "token: your_token" \
-d '{
"redPacketID": "rp_1234567890abcdef"
}'
```
**响应示例**:
```json
{
"errCode": 0,
"errMsg": "",
"errDlt": "",
"data": {
"redPacketID": "rp_1234567890abcdef",
"totalAmount": 10000,
"totalCount": 10,
"remainAmount": 5000,
"remainCount": 5,
"status": 0,
"receives": [
{
"receiveID": "rec_1234567890",
"receiveUserID": "user456",
"amount": 1000,
"receiveTime": 1704070800000,
"isLucky": false
},
{
"receiveID": "rec_1234567891",
"receiveUserID": "user789",
"amount": 2000,
"receiveTime": 1704071400000,
"isLucky": true
}
]
}
}
```
### 5. 暂停红包(后台管理接口)
**接口地址**: `POST /redpacket/pause`
**接口描述**: 暂停红包清空Redis队列使红包无法继续被领取仅对拼手气红包有效
**请求参数**:
```json
{
"redPacketID": "rp_1234567890abcdef" // 红包ID必填string
}
```
**参数说明**:
- `redPacketID`: 红包ID必填
**响应参数**:
```json
{
"errCode": 0,
"errMsg": "",
"errDlt": "",
"data": {
"redPacketID": "rp_1234567890abcdef" // 红包IDstring
}
}
```
**响应说明**:
- `redPacketID`: 红包ID
**错误码**:
- `0`: 成功
- `1001`: 参数错误红包ID为空
- `1004`: 红包不存在
- `500`: 服务器内部错误Redis操作失败等
**请求示例**:
```bash
curl -X POST http://localhost:10002/redpacket/pause \
-H "Content-Type: application/json" \
-H "token: your_token" \
-d '{
"redPacketID": "rp_1234567890abcdef"
}'
```
**响应示例**:
```json
{
"errCode": 0,
"errMsg": "",
"errDlt": "",
"data": {
"redPacketID": "rp_1234567890abcdef"
}
}
```
**业务规则**:
1. **暂停操作**:
- 清空该红包在Redis中的队列`redpacket:queue:{redPacketID}`
- 清空后,后续领取请求会因队列为空而失败(返回 `1801: red packet has been finished`
- 已领取的记录不受影响,只是无法继续领取
2. **红包类型**:
- **拼手气红包type=2**: 会清空Redis队列
- **普通红包type=1**: 没有Redis队列直接返回成功
3. **注意事项**:
- 暂停操作不可逆清空后的Redis队列无法恢复
- 暂停后,红包状态不会自动更新,但实际已无法领取
- 建议在暂停后手动更新红包状态为"已领完"或"已过期"
## 接口汇总
| 接口路径 | 方法 | 描述 | 类型 |
|---------|------|------|------|
| `/redpacket/send_redpacket` | POST | 发送红包 | 用户接口 |
| `/redpacket/receive` | POST | 领取红包 | 用户接口 |
| `/redpacket/get_redpackets_by_group` | POST | 查询红包列表 | 后台管理接口 |
| `/redpacket/get_receive_info` | POST | 查询红包领取情况 | 后台管理接口 |
| `/redpacket/pause` | POST | 暂停红包 | 后台管理接口 |
## 错误码汇总
| 错误码 | 说明 | 适用接口 |
|--------|------|----------|
| `0` | 成功 | 所有接口 |
| `1001` | 参数错误 | 所有接口 |
| `1004` | 记录不存在 | 领取、查询、暂停接口 |
| `1801` | 红包已被领完 | 领取接口 |
| `1802` | 红包已过期 | 领取接口 |
| `1803` | 用户已领取过该红包 | 领取接口 |
| `500` | 服务器内部错误 | 所有接口 |
## 客户端消息结构
客户端收到的红包消息结构请参考:[红包消息结构文档](./redpacket-message-structure.md)

390
docs/redpacket-flow.md Normal file
View File

@@ -0,0 +1,390 @@
# 红包系统完整流程文档
## 一、整体架构设计
### 核心原则
- **Redis 负责并发控制与计算**:使用 Lua 脚本实现原子操作
- **MongoDB 负责最终记录与查询**:异步写入,不参与并发竞争
- **立即返回 + 异步写入**:提升响应速度,降低延迟
- **失败补偿机制**:使用 Redis Stream 确保数据最终一致性
### 数据流向
```
客户端请求
Go API无状态
Redis Lua脚本原子抢红包← 并发控制核心
立即返回结果 ✅
异步写入 MongoDBgoroutine
├─ 写入领取记录
├─ 更新钱包余额
└─ 写入补偿Stream
```
---
## 二、发送红包流程SendRedPacket
### 1. 参数验证
- 验证 `totalAmount > 0`
- 验证 `totalCount > 0`
- 验证 `redPacketType` 为 1普通或 2拼手气
### 2. 群信息验证
- 获取群信息,验证群是否存在
- 获取群主ID发送用户默认为群主
- 获取群主用户信息(昵称、头像)
### 3. 生成红包ID和基本信息
- 生成红包ID`MD5(sendUserID + groupID + timestamp)`
- 计算会话ID
- 设置过期时间24小时
### 4. 初始化Redis数据结构关键步骤
#### Redis Key 设计
- `rp:{packetId}:list` - 红包金额队列List
- `rp:{packetId}:users` - 已领取用户集合Set
- 过期时间24小时
#### 普通红包type=1
```go
avgAmount := totalAmount / totalCount
for i := 0; i < totalCount; i++ {
RPush("rp:{packetId}:list", avgAmount) // 每个元素都是平均金额
}
Expire("rp:{packetId}:list", 24h)
Expire("rp:{packetId}:users", 24h)
```
#### 拼手气红包type=2
```go
amounts := allocateRandomAmounts(totalAmount, totalCount) // 预先分配随机金额
for _, amount := range amounts {
RPush("rp:{packetId}:list", amount) // 每个元素是不同的随机金额
}
Expire("rp:{packetId}:list", 24h)
Expire("rp:{packetId}:users", 24h)
```
**拼手气红包分配算法**
- 确保每个红包至少 1 分
- 前 n-1 个红包:在最小金额和最大金额之间随机分配
- 最后一个红包:直接分配剩余金额
- 打乱顺序增加随机性
### 5. 创建MongoDB记录
```go
redPacketRecord := &model.RedPacket{
RedPacketID: redPacketID,
SendUserID: sendUserID,
GroupID: groupID,
RedPacketType: req.RedPacketType,
TotalAmount: req.TotalAmount,
TotalCount: req.TotalCount,
RemainAmount: req.TotalAmount, // 初始等于总金额
RemainCount: req.TotalCount, // 初始等于总个数
Status: Active,
ExpireTime: expireTime,
CreateTime: time.Now(),
}
```
### 6. 发送消息
- 构建红包消息内容(自定义消息格式)
- 通过 RPC 发送消息到群聊
### 7. 返回响应
- 返回 `redPacketID``serverMsgID``clientMsgID``sendTime`
---
## 三、领取红包流程ReceiveRedPacket
### 1. 参数验证
- 获取用户ID从token中
- 验证请求参数
### 2. 红包状态检查
- 查询MongoDB获取红包基本信息
- 检查红包是否过期(`Status == Expired`
- **注意**不检查是否已领完因为Redis会处理
### 3. 【核心】Redis Lua脚本抢红包
#### Lua脚本逻辑
```lua
-- KEYS[1] = rp:{packetId}:list (红包金额队列)
-- KEYS[2] = rp:{packetId}:users (已领取用户集合)
-- ARGV[1] = userId
-- 步骤1检查是否已领取
if redis.call('SISMEMBER', KEYS[2], ARGV[1]) == 1 then
return -1 -- 用户已领取
end
-- 步骤2从队列中抢红包原子操作
local money = redis.call('LPOP', KEYS[1])
if not money then
return -2 -- 红包已领完
end
-- 步骤3记录用户已领取原子操作
redis.call('SADD', KEYS[2], ARGV[1])
-- 步骤4返回金额
return money
```
#### 返回值处理
- `-1` → 用户已领取 → 返回 `ErrRedPacketAlreadyReceived`
- `-2` → 红包已领完 → 返回 `ErrRedPacketFinished`
- `>0` → 领取成功 → 返回金额(分)
### 4. 立即返回结果
```go
resp.RedPacketID = req.RedPacketID
resp.Amount = amount
resp.IsLucky = false
apiresp.GinSuccess(c, resp) // 立即返回不等待MongoDB写入
```
### 5. 【异步写入】后台goroutine处理
#### 5.1 写入补偿Stream
```go
streamKey := "rp:" + redPacketID + ":stream"
XAdd(streamKey, {
"userID": userID,
"amount": amount,
"time": timestamp
})
```
**作用**:用于失败补偿,确保数据最终一致性
#### 5.2 写入MongoDB领取记录
```go
receiveRecord := &model.RedPacketReceive{
ReceiveID: receiveID,
RedPacketID: redPacketID,
ReceiveUserID: userID,
Amount: amount,
ReceiveTime: time.Now(),
IsLucky: false,
}
Create(receiveRecord)
```
**幂等性保护**
- 唯一索引:`(receive_user_id, red_packet_id)`
- 如果唯一索引冲突E11000错误说明已写入忽略错误
#### 5.3 更新钱包余额
```go
// 查询或创建钱包
wallet := Take(userID)
if not exists {
Create(wallet) // 初始余额为0
}
// 使用版本号乐观锁更新余额
UpdateBalanceWithVersion(userID, "add", amount, oldVersion)
// 如果版本号冲突自动重试最多3次
// 创建余额记录
CreateBalanceRecord({
Operation: "add",
Amount: amount,
Remark: "领取红包: " + redPacketID
})
```
---
## 四、并发控制机制
### 1. Redis层面核心
- **Lua脚本原子性**:整个抢红包过程是原子操作
- **LPOP原子性**:从队列中取出金额是原子操作
- **SADD原子性**:记录用户是原子操作
- **SISMEMBER检查**:防止重复领取
### 2. MongoDB层面兜底
- **唯一索引**`(receive_user_id, red_packet_id)` 唯一索引
- **幂等写入**:如果已存在,忽略重复写入错误
### 3. 钱包余额更新
- **版本号乐观锁**:使用 `version` 字段防止并发覆盖
- **自动重试**并发冲突时自动重试最多3次
---
## 五、失败补偿机制
### 1. Redis Stream记录
- 每次领取成功后写入Redis Stream
- Stream包含`userID``amount``time`
### 2. 补偿Worker待实现
```go
// 后台worker消费Stream
for {
messages := XRead("rp:{packetId}:stream", lastID)
for _, msg := range messages {
// 检查MongoDB是否已写入
if !ExistsInMongoDB(msg.userID, msg.redPacketID) {
// 重新写入MongoDB
WriteToMongoDB(msg)
}
// ACK消息
XAck(streamKey, msg.ID)
}
}
```
### 3. 补偿场景
- Redis成功但MongoDB写入失败
- 服务宕机导致异步写入中断
- 网络闪断导致写入失败
---
## 六、Redis Key设计总结
| Key | 类型 | 说明 | 过期时间 |
|-----|------|------|----------|
| `rp:{packetId}:list` | List | 红包金额队列 | 24小时 |
| `rp:{packetId}:users` | Set | 已领取用户集合 | 24小时 |
| `rp:{packetId}:stream` | Stream | 领取日志流(补偿用) | 24小时 |
---
## 七、数据一致性保证
### 1. 强一致性Redis
- Redis Lua脚本保证抢红包的原子性
- 确保不会超发、不会重复领取
### 2. 最终一致性MongoDB
- 异步写入MongoDB可能短暂延迟
- 唯一索引确保幂等性
- 补偿机制确保最终一致
### 3. 钱包余额
- 使用版本号乐观锁
- 自动重试机制
- 确保余额更新成功
---
## 八、性能特点
### 1. 高并发支持
- Redis Lua脚本原子操作天然支持高并发
- 支持万人同时抢红包
### 2. 低延迟
- 立即返回结果不等待MongoDB写入
- 响应时间主要取决于Redis性能
### 3. 高可用
- MongoDB不参与并发竞争避免被打爆
- 异步写入不影响主流程
- 补偿机制确保数据不丢失
---
## 九、关键代码位置
### 发送红包
- `internal/api/redpacket.go:SendRedPacket()` - 主流程
- `internal/api/redpacket.go:allocateRandomAmounts()` - 拼手气红包分配算法
### 领取红包
- `internal/api/redpacket.go:ReceiveRedPacket()` - 主流程
- `internal/api/redpacket.go:grabRedPacketFromRedis()` - Redis Lua脚本执行
- `internal/api/redpacket.go:grabRedPacketLuaScript` - Lua脚本定义
- `internal/api/redpacket.go:writeRedPacketRecordToMongoDB()` - 异步写入MongoDB
- `internal/api/redpacket.go:updateWalletBalanceAsync()` - 异步更新钱包余额
- `internal/api/redpacket.go:writeToCompensationStream()` - 写入补偿Stream
### Redis Key生成
- `internal/api/redpacket.go:getRedPacketQueueKey()` - 队列Key
- `internal/api/redpacket.go:getRedPacketUsersKey()` - 用户Set Key
- `internal/api/redpacket.go:getRedPacketStreamKey()` - Stream Key
---
## 十、注意事项
1. **Redis必须可用**发送和领取红包都依赖Redis
2. **MongoDB异步写入**:可能短暂延迟,但不影响用户体验
3. **补偿机制**需要实现后台worker消费Stream
4. **唯一索引**MongoDB领取记录的唯一索引是幂等性的关键
5. **钱包余额**:异步更新,可能有短暂延迟
---
## 十一、流程图
### 发送红包流程图
```
验证参数
验证群信息
生成红包ID
初始化Redis关键
├─ 普通红包推送N个平均金额
└─ 拼手气红包推送N个随机金额
创建MongoDB记录
发送消息
返回结果
```
### 领取红包流程图
```
验证参数
查询红包基本信息
检查是否过期
【核心】Redis Lua脚本抢红包
├─ 检查是否已领取SISMEMBER
├─ 抢红包LPOP
└─ 记录用户SADD
立即返回结果 ✅
异步写入goroutine
├─ 写入补偿Stream
├─ 写入MongoDB领取记录
└─ 更新钱包余额
```
---
## 十二、错误处理
### 发送红包错误
- Redis不可用 → 返回错误,不允许发送
- MongoDB写入失败 → 返回错误,不允许发送
### 领取红包错误
- 红包不存在 → 返回 `red packet not found`
- 红包已过期 → 返回 `red packet expired`
- 用户已领取 → 返回 `red packet already received`Redis检查
- 红包已领完 → 返回 `red packet finished`Redis检查
- Redis不可用 → 返回 `redis client is not available`
### 异步写入错误
- MongoDB写入失败 → 记录日志,补偿机制处理
- 钱包余额更新失败 → 记录日志,可手动补偿
- Stream写入失败 → 记录日志,不影响主流程

View File

@@ -0,0 +1,208 @@
# 红包功能实现方案
## 功能概述
实现类似微信的抢红包功能,包括:
- 发送红包(普通红包、拼手气红包)
- 领取红包
- 查看红包详情和领取记录
- 红包过期处理
## 需要修改的文件清单
### 1. 消息类型定义
**文件**: `../protocol/constant/constant.go`
- 添加 `RedPacket = 123` 消息类型常量
-`ContentType2PushContent` 映射中添加红包推送内容
### 2. 数据库模型
**新建文件**: `pkg/common/storage/model/redpacket.go`
- `RedPacket` - 红包主表
- `RedPacketReceive` - 红包领取记录表
### 3. 数据库操作接口
**新建文件**: `pkg/common/storage/database/redpacket.go`
- 定义红包数据库操作接口
### 4. MongoDB实现
**新建文件**: `pkg/common/storage/database/mgo/redpacket.go`
- 实现红包数据库操作
### 5. RPC服务
**新建目录**: `internal/rpc/redpacket/`
- `redpacket.go` - 红包RPC服务实现
- `server.go` - RPC服务注册
### 6. API接口
**新建文件**: `internal/api/redpacket.go`
- 发送红包接口
- 领取红包接口
- 查询红包详情接口
- 查询红包领取记录接口
### 7. 消息类型处理
**修改文件**:
- `internal/api/msg.go` - 添加红包消息解析
- `internal/rpc/msg/verify.go` - 添加红包消息封装
- `pkg/apistruct/msg.go` - 添加红包消息结构体
### 8. 推送处理
**修改文件**: `internal/push/offlinepush_handler.go`
- 添加红包消息的离线推送内容
### 9. 路由注册
**修改文件**: `internal/api/router.go`
- 注册红包相关路由
## 数据库表设计
### red_packets 表
```go
type RedPacket struct {
RedPacketID string `bson:"red_packet_id"` // 红包ID
SendUserID string `bson:"send_user_id"` // 发送者ID
GroupID string `bson:"group_id"` // 群ID群红包
ConversationID string `bson:"conversation_id"` // 会话ID
SessionType int32 `bson:"session_type"` // 会话类型
RedPacketType int32 `bson:"red_packet_type"` // 红包类型1-普通红包2-拼手气红包
TotalAmount int64 `bson:"total_amount"` // 总金额(分)
TotalCount int32 `bson:"total_count"` // 总个数
RemainAmount int64 `bson:"remain_amount"` // 剩余金额(分)
RemainCount int32 `bson:"remain_count"` // 剩余个数
Blessing string `bson:"blessing"` // 祝福语
Status int32 `bson:"status"` // 状态0-进行中1-已领完2-已过期
ExpireTime time.Time `bson:"expire_time"` // 过期时间
CreateTime time.Time `bson:"create_time"` // 创建时间
Ex string `bson:"ex"` // 扩展字段
}
```
### red_packet_receives 表
```go
type RedPacketReceive struct {
ReceiveID string `bson:"receive_id"` // 领取记录ID
RedPacketID string `bson:"red_packet_id"` // 红包ID
ReceiveUserID string `bson:"receive_user_id"` // 领取者ID
Amount int64 `bson:"amount"` // 领取金额(分)
ReceiveTime time.Time `bson:"receive_time"` // 领取时间
Ex string `bson:"ex"` // 扩展字段
}
```
## API接口设计
### 1. 发送红包 ✅ 已实现
```
POST /redpacket/send_redpacket
Request:
{
"groupID": "group123", // 群ID必填
"redPacketType": 1, // 红包类型1-普通红包2-拼手气红包(必填)
"totalAmount": 10000, // 总金额(分)(必填)
"totalCount": 10, // 总个数(必填)
"blessing": "恭喜发财" // 祝福语(可选)
}
Response:
{
"redPacketID": "rp123", // 红包ID
"serverMsgID": "msg123", // 服务器消息ID
"clientMsgID": "client123", // 客户端消息ID
"sendTime": 1234567890 // 发送时间戳(毫秒)
}
```
**特性**:
- 只支持群聊
- 发送用户默认为群主(自动获取)
- 自动创建数据库记录
- 自动发送红包消息到群聊
### 2. 领取红包
```
POST /redpacket/receive
Request:
{
"redPacketID": "rp123"
}
Response:
{
"amount": 1000, // 领取金额(分)
"remainAmount": 9000,
"remainCount": 9,
"status": 0 // 0-进行中1-已领完
}
```
### 3. 查询红包详情
```
GET /redpacket/detail?redPacketID=rp123
Response:
{
"redPacketID": "rp123",
"sendUserID": "user123",
"totalAmount": 10000,
"totalCount": 10,
"remainAmount": 9000,
"remainCount": 9,
"blessing": "恭喜发财",
"status": 0,
"receiveList": [...]
}
```
### 4. 查询红包领取记录
```
GET /redpacket/receives?redPacketID=rp123
Response:
{
"total": 1,
"receives": [
{
"receiveUserID": "user456",
"amount": 1000,
"receiveTime": "2024-01-01T10:00:00Z"
}
]
}
```
## 业务逻辑
### 发送红包流程
1. 验证参数(金额、个数、类型)
2. 创建红包记录
3. 发送红包消息ContentType=RedPacket
4. 返回红包ID和消息ID
### 领取红包流程
1. 验证红包是否存在且可领取
2. 检查用户是否已领取
3. 计算领取金额(普通红包平均分配,拼手气红包随机)
4. 更新红包记录(剩余金额、剩余个数)
5. 创建领取记录
6. 如果领完,更新红包状态
7. 发送领取通知消息
### 红包过期处理
- 建议使用定时任务检查过期红包
- 过期红包状态更新为已过期
- 剩余金额退回(如需要)
## 注意事项
1. **并发控制**:领取红包需要使用分布式锁,防止重复领取
2. **金额计算**:拼手气红包需要保证最后一个红包能领完剩余金额
3. **消息推送**:红包消息需要特殊推送内容
4. **数据一致性**:红包金额和领取记录需要事务保证一致性
5. **性能优化**:红包详情查询需要缓存优化
## 实现步骤
1. ✅ 定义消息类型常量
2. ✅ 创建数据库模型
3. ✅ 实现数据库操作
4. ✅ 实现RPC服务
5. ✅ 实现API接口
6. ✅ 添加消息类型处理
7. ✅ 添加推送处理
8. ✅ 测试和优化

View File

@@ -0,0 +1,289 @@
# 红包消息结构文档
## 客户端收到的推送消息结构
### 完整消息结构 (MsgData)
客户端通过WebSocket或HTTP拉取收到的红包消息消息结构如下
```json
{
"clientMsgID": "client_1234567890abcdef", // 客户端消息IDstring
"serverMsgID": "msg_1234567890abcdef", // 服务器消息IDstring
"sendID": "user_owner123", // 发送者ID群主IDstring
"recvID": "", // 接收者ID群消息为空string
"groupID": "group123", // 群IDstring
"senderPlatformID": 0, // 发送者平台IDint320表示系统
"senderNickname": "群主昵称", // 发送者昵称string
"senderFaceURL": "https://...", // 发送者头像URLstring
"sessionType": 3, // 会话类型int323-群聊
"msgFrom": 200, // 消息来源int32200-系统消息
"contentType": 110, // 消息类型int32110-自定义消息
"content": "{\"data\":\"{\\\"redPacketID\\\":\\\"rp_123\\\",\\\"redPacketType\\\":1,\\\"blessing\\\":\\\"恭喜发财\\\"}\",\"description\":\"redpacket\",\"extension\":\"\"}", // 消息内容JSON字符串自定义消息格式
"seq": 123456, // 消息序号int64
"sendTime": 1704067200000, // 发送时间戳int64毫秒
"createTime": 1704067200000, // 创建时间戳int64毫秒
"status": 2, // 消息状态int322-发送成功
"isRead": false, // 是否已读bool
"options": { // 消息选项map[string]bool
"history": true, // 是否保存历史
"persistent": true, // 是否持久化
"offlinePush": true, // 是否离线推送
"unreadCount": true, // 是否计入未读数
"conversationUpdate": true, // 是否更新会话
"senderSync": true // 是否同步给发送者
},
"offlinePushInfo": { // 离线推送信息(可选)
"title": "[HONGBAO]", // 推送标题
"desc": "[HONGBAO]", // 推送描述
"ex": "", // 扩展字段
"iosPushSound": "", // iOS推送声音
"iosBadgeCount": false // iOS角标计数
},
"atUserIDList": [], // @用户列表string[]
"attachedInfo": "", // 附加信息string
"ex": "" // 扩展字段string
}
```
### Content字段解析
`content` 字段是一个JSON字符串需要先解析为 `CustomElem` 结构(自定义消息格式),然后从 `data` 字段中解析出 `RedPacketElem` 结构:
#### CustomElem 结构(自定义消息外层结构)
```json
{
"data": "{\"redPacketID\":\"rp_123\",\"redPacketType\":1,\"blessing\":\"恭喜发财\",\"isReceived\":false,\"receiveInfo\":null}", // 红包数据的JSON字符串string必填
"description": "redpacket", // 二级类型标识string"redpacket"表示红包消息
"extension": "" // 扩展字段string可选
}
```
#### RedPacketElem 结构从data字段中解析
```json
{
"redPacketID": "rp_1234567890abcdef", // 红包IDstring必填
"redPacketType": 1, // 红包类型int32必填1-普通红包2-拼手气红包
"blessing": "恭喜发财", // 祝福语string可选
"isReceived": false, // 当前用户是否已领取bool服务器填充
"receiveInfo": null // 领取信息RedPacketReceiveInfo仅拼手气红包且已领取时返回
}
```
#### RedPacketReceiveInfo 结构(领取信息)
```json
{
"amount": 1000, // 领取金额int64单位
"receiveTime": 1704067200000, // 领取时间戳int64毫秒
"isLucky": false // 是否为手气最佳bool仅拼手气红包有效
}
```
#### 字段说明
| 字段名 | 类型 | 必填 | 说明 |
|--------|------|------|------|
| `redPacketID` | string | 是 | 红包唯一标识用于后续领取、查询等操作总金额、总个数等信息可通过红包ID查询获取 |
| `redPacketType` | int32 | 是 | 红包类型1-普通红包平均分配2-拼手气红包(随机分配) |
| `blessing` | string | 否 | 祝福语 |
| `isReceived` | bool | 是 | 当前用户是否已领取服务器根据用户ID自动填充 |
| `receiveInfo` | RedPacketReceiveInfo | 否 | 领取信息,仅当 `isReceived=true``redPacketType=2`(拼手气红包)时返回 |
#### receiveInfo 字段说明
| 字段名 | 类型 | 说明 |
|--------|------|------|
| `amount` | int64 | 领取金额,单位:分 |
| `receiveTime` | int64 | 领取时间戳,毫秒 |
| `isLucky` | bool | 是否为手气最佳(仅拼手气红包有效) |
### 消息类型常量
- **ContentType**: `110` (`constant.Custom` - 自定义消息)
- **二级类型标识**: `"redpacket"` (存储在 `CustomElem.description` 字段中)
- **SessionType**: `3` (`constant.ReadGroupChatType` - 群聊)
- **MsgFrom**: `200` (`constant.SysMsgType` - 系统消息)
### 客户端解析示例
#### JavaScript/TypeScript
```typescript
interface RedPacketReceiveInfo {
amount: number; // 领取金额(分)
receiveTime: number; // 领取时间戳(毫秒)
isLucky: boolean; // 是否为手气最佳
}
interface RedPacketElem {
redPacketID: string;
redPacketType: number; // 1-普通红包2-拼手气红包
blessing?: string;
isReceived: boolean; // 当前用户是否已领取
receiveInfo?: RedPacketReceiveInfo; // 领取信息(仅拼手气红包且已领取时返回)
}
interface CustomElem {
data: string; // 红包数据的JSON字符串
description: string; // 二级类型标识:"redpacket"
extension?: string; // 扩展字段
}
interface RedPacketMessage {
clientMsgID: string;
serverMsgID: string;
sendID: string;
groupID: string;
contentType: number; // 110 (自定义消息)
content: string; // CustomElem的JSON字符串
sendTime: number;
// ... 其他字段
}
// 解析消息
function parseRedPacketMessage(msg: RedPacketMessage): RedPacketElem | null {
// 检查是否为自定义消息类型
if (msg.contentType !== 110) {
return null;
}
try {
// 先解析自定义消息结构
const customElem: CustomElem = JSON.parse(msg.content);
// 检查二级类型是否为红包
if (customElem.description !== "redpacket") {
return null;
}
// 从data字段中解析红包数据
const redPacketElem: RedPacketElem = JSON.parse(customElem.data);
return redPacketElem;
} catch (e) {
console.error('Failed to parse red packet content:', e);
return null;
}
}
```
#### Go
```go
type RedPacketReceiveInfo struct {
Amount int64 `json:"amount"` // 领取金额(分)
ReceiveTime int64 `json:"receiveTime"` // 领取时间戳(毫秒)
IsLucky bool `json:"isLucky"` // 是否为手气最佳
}
type RedPacketElem struct {
RedPacketID string `json:"redPacketID"`
RedPacketType int32 `json:"redPacketType"`
TotalAmount int64 `json:"totalAmount"`
TotalCount int32 `json:"totalCount"`
Blessing string `json:"blessing"`
IsReceived bool `json:"isReceived"` // 当前用户是否已领取
ReceiveInfo *RedPacketReceiveInfo `json:"receiveInfo,omitempty"` // 领取信息(仅拼手气红包且已领取时返回)
}
type CustomElem struct {
Data string `json:"data"` // 红包数据的JSON字符串
Description string `json:"description"` // 二级类型标识:"redpacket"
Extension string `json:"extension"` // 扩展字段
}
func ParseRedPacketContent(content []byte) (*RedPacketElem, error) {
// 先解析自定义消息结构
var customElem CustomElem
if err := json.Unmarshal(content, &customElem); err != nil {
return nil, err
}
// 检查二级类型是否为红包
if customElem.Description != "redpacket" {
return nil, fmt.Errorf("not a red packet message")
}
// 从data字段中解析红包数据
var redPacketElem RedPacketElem
if err := json.Unmarshal([]byte(customElem.Data), &redPacketElem); err != nil {
return nil, err
}
return &redPacketElem, nil
}
```
### 完整消息示例
```json
{
"clientMsgID": "client_1704067200000_abc123",
"serverMsgID": "msg_1704067200000_def456",
"sendID": "user_owner123",
"recvID": "",
"groupID": "group123",
"senderPlatformID": 0,
"senderNickname": "群主",
"senderFaceURL": "https://example.com/avatar.jpg",
"sessionType": 3,
"msgFrom": 200,
"contentType": 110,
"content": "{\"data\":\"{\\\"redPacketID\\\":\\\"rp_1234567890abcdef\\\",\\\"redPacketType\\\":1,\\\"blessing\\\":\\\"恭喜发财\\\",\\\"isReceived\\\":false,\\\"receiveInfo\\\":null}\",\"description\":\"redpacket\",\"extension\":\"\"}",
"seq": 123456,
"sendTime": 1704067200000,
"createTime": 1704067200000,
"status": 2,
"isRead": false,
"options": {
"history": true,
"persistent": true,
"offlinePush": true,
"unreadCount": true,
"conversationUpdate": true,
"senderSync": true
},
"offlinePushInfo": {
"title": "[HONGBAO]",
"desc": "[HONGBAO]"
},
"atUserIDList": [],
"attachedInfo": "",
"ex": ""
}
```
### 消息选项说明
| 选项名 | 说明 |
|--------|------|
| `history` | 是否保存到历史记录 |
| `persistent` | 是否持久化存储 |
| `offlinePush` | 是否离线推送 |
| `unreadCount` | 是否计入未读数 |
| `conversationUpdate` | 是否更新会话 |
| `senderSync` | 是否同步给发送者 |
### 注意事项
1. **Content字段**: 是JSON字符串需要先解析为 `CustomElem` 结构,然后从 `data` 字段中解析 `RedPacketElem`
2. **消息类型**: 使用自定义消息类型(`contentType = 110`),通过 `description` 字段标识二级类型为 `"redpacket"`
3. **二级类型扩展**: 未来可以扩展其他自定义消息类型,只需在 `description` 字段中使用不同的标识(如 `"wallet"``"coupon"` 等)
4. **金额单位**: `receiveInfo.amount` 单位是"分",不是"元"
5. **总金额和总个数**: 不在消息中传递,客户端可通过 `redPacketID` 调用查询接口获取详细信息
5. **红包类型**:
- `1` = 普通红包(平均分配)
- `2` = 拼手气红包(随机分配)
6. **发送者**: 固定为群主,`sendID` 为群主ID
7. **消息来源**: `msgFrom = 200` 表示系统消息
8. **会话类型**: `sessionType = 3` 表示群聊
9. **领取状态**: `isReceived` 字段由服务器根据当前用户ID自动填充客户端无需设置
10. **领取信息**: `receiveInfo` 仅在以下情况返回:
- `isReceived = true`(用户已领取)
- `redPacketType = 2`(拼手气红包)
- 普通红包(`redPacketType = 1`)即使已领取也不会返回 `receiveInfo`
11. **客户端存储**: 客户端收到消息后,应将 `isReceived``receiveInfo` 存储到本地用于UI展示
12. **兼容性**: 使用标准自定义消息类型无需修改客户端SDK只需在客户端添加红包消息的解析逻辑

267
docs/statistics-api.md Normal file
View File

@@ -0,0 +1,267 @@
# 统计接口文档
## 接口列表
### 1. POST /statistics/user/register
**用户注册统计**
**请求参数** (`UserRegisterCountReq`):
```json
{
"start": 0, // int64 - 开始时间(毫秒时间戳)
"end": 0 // int64 - 结束时间(毫秒时间戳)
}
```
**响应参数** (`UserRegisterCountResp`):
```json
{
"total": 0, // int64 - 总注册用户数
"before": 0, // int64 - 开始时间之前的注册用户数
"count": [] // []map[string]int64 - 时间段内每日注册用户数统计
}
```
---
### 2. POST /statistics/user/active
**活跃用户统计**
**请求参数** (`GetActiveUserReq`):
```json
{
"start": 0, // int64 - 开始时间(毫秒时间戳)
"end": 0, // int64 - 结束时间(毫秒时间戳)
"group": "", // string - 群ID选填
"ase": "", // string - 排序方式(选填)
"pagination": { // Pagination - 分页参数
"pageNumber": 1, // int32 - 页码从1开始
"showNumber": 10 // int32 - 每页数量
}
}
```
**响应参数** (`GetActiveUserResp`):
```json
{
"msgCount": 0, // int64 - 消息总数
"userCount": 0, // int64 - 活跃用户总数
"dateCount": [], // []map[string]int64 - 每日活跃用户数统计
"users": [ // []ActiveUser - 活跃用户列表
{
"user": { // UserInfo - 用户信息
"userID": "",
"nickname": "",
"faceURL": "",
// ... 其他用户字段
},
"count": 0 // int64 - 该用户发送的消息数
}
]
}
```
---
### 3. POST /statistics/group/create
**群创建统计**
**请求参数** (`GroupCreateCountReq`):
```json
{
"start": 0, // int64 - 开始时间(毫秒时间戳)
"end": 0 // int64 - 结束时间(毫秒时间戳)
}
```
**响应参数** (`GroupCreateCountResp`):
```json
{
"total": 0, // int64 - 总创建群数
"before": 0, // int64 - 开始时间之前创建的群数
"count": [] // []map[string]int64 - 时间段内每日创建群数统计
}
```
---
### 4. POST /statistics/group/active
**活跃群统计**
**请求参数** (`GetActiveGroupReq`):
```json
{
"start": 0, // int64 - 开始时间(毫秒时间戳)
"end": 0, // int64 - 结束时间(毫秒时间戳)
"ase": "", // string - 排序方式(选填)
"pagination": { // Pagination - 分页参数
"pageNumber": 1, // int32 - 页码从1开始
"showNumber": 10 // int32 - 每页数量
}
}
```
**响应参数** (`GetActiveGroupResp`):
```json
{
"msgCount": 0, // int64 - 消息总数
"groupCount": 0, // int64 - 活跃群总数
"dateCount": [], // []map[string]int64 - 每日活跃群数统计
"groups": [ // []ActiveGroup - 活跃群列表
{
"group": { // GroupInfo - 群信息
"groupID": "",
"groupName": "",
"faceURL": "",
// ... 其他群字段
},
"count": 0 // int64 - 该群发送的消息数
}
]
}
```
---
### 5. POST /statistics/online_user_count
**在线人数统计**
**请求参数**: 无
**响应参数** (`OnlineUserCountResp`):
```json
{
"onlineCount": 0 // int64 - 当前在线用户数
}
```
---
### 6. POST /statistics/online_user_count_trend
**在线人数走势统计**
**请求参数** (`OnlineUserCountTrendReq`):
```json
{
"startTime": 0, // int64 - 统计开始时间毫秒时间戳为空时默认最近24小时
"endTime": 0, // int64 - 统计结束时间(毫秒时间戳),为空时默认当前时间
"intervalMinutes": 15 // int32 - 统计间隔分钟仅支持15/30/60必填
}
```
**响应参数** (`OnlineUserCountTrendResp`):
```json
{
"intervalMinutes": 15, // int32 - 统计间隔(分钟)
"points": [ // []OnlineUserCountTrendItem - 走势数据点
{
"timestamp": 0, // int64 - 区间起始时间(毫秒时间戳)
"onlineCount": 0 // int64 - 区间内平均在线人数
}
]
}
```
---
### 7. POST /statistics/user_send_msg_count
**用户发送消息总数统计**
**请求参数** (`UserSendMsgCountReq`): 无
**响应参数** (`UserSendMsgCountResp`):
```json
{
"count24h": 0, // int64 - 最近24小时发送消息总数
"count7d": 0, // int64 - 最近7天发送消息总数
"count30d": 0 // int64 - 最近30天发送消息总数
}
```
---
### 8. POST /statistics/user_send_msg_count_trend
**用户发送消息走势统计**
**请求参数** (`UserSendMsgCountTrendReq`):
```json
{
"userID": "", // string - 发送者用户ID必填
"chatType": 1, // int32 - 聊天类型1-单聊2-群聊,必填
"startTime": 0, // int64 - 统计开始时间毫秒时间戳为空时默认最近24小时
"endTime": 0, // int64 - 统计结束时间(毫秒时间戳),为空时默认当前时间
"intervalMinutes": 15 // int32 - 统计间隔分钟仅支持15/30/60必填
}
```
**响应参数** (`UserSendMsgCountTrendResp`):
```json
{
"userID": "", // string - 发送者用户ID
"chatType": 1, // int32 - 聊天类型1-单聊2-群聊
"intervalMinutes": 15, // int32 - 统计间隔(分钟)
"points": [ // []UserSendMsgCountTrendItem - 走势数据点
{
"timestamp": 0, // int64 - 区间起始时间(毫秒时间戳)
"count": 0 // int64 - 区间内发送消息数
}
]
}
```
---
### 9. POST /statistics/user_send_msg_query
**用户发送消息查询**
**请求参数** (`UserSendMsgQueryReq`):
```json
{
"userID": "", // string - 用户ID选填
"startTime": 0, // int64 - 开始时间(毫秒时间戳,选填)
"endTime": 0, // int64 - 结束时间(毫秒时间戳,选填)
"content": "", // string - 内容搜索关键词(选填)
"pageNumber": 1, // int32 - 页码从1开始默认1
"showNumber": 50 // int32 - 每页条数默认50最大200
}
```
**响应参数** (`UserSendMsgQueryResp`):
```json
{
"count": 0, // int64 - 总记录数
"pageNumber": 1, // int32 - 当前页码
"showNumber": 50, // int32 - 每页条数
"records": [ // []UserSendMsgQueryRecord - 消息记录列表
{
"msgID": "", // string - 消息ID服务端消息ID
"sendID": "", // string - 发送者ID
"senderName": "", // string - 发送者昵称或名称
"recvID": "", // string - 接收者ID群聊为群ID
"recvName": "", // string - 接收者昵称或名称(群聊为群名称)
"contentType": 0, // int32 - 消息类型编号
"contentTypeName": "", // string - 消息类型名称(如:文本消息、图片消息等)
"sessionType": 0, // int32 - 聊天类型编号
"chatTypeName": "", // string - 聊天类型名称(如:单聊、群聊、通知)
"content": "", // string - 消息内容
"sendTime": 0 // int64 - 消息发送时间(毫秒时间戳)
}
]
}
```
---
## 注意事项
1. **权限要求**: 所有统计接口都需要管理员权限(`authverify.CheckAdmin`
2. **时间格式**: 所有时间字段均为毫秒时间戳int64
3. **统计间隔**: 走势统计接口的 `intervalMinutes` 仅支持 15、30、60 分钟
4. **分页参数**:
- `pageNumber` 从 1 开始
- `showNumber` 默认值不同接口可能不同,最大值为 200
5. **消息类型**:
- 文本消息、图片消息、语音消息、视频消息、文件消息、艾特消息、合并消息、名片消息、位置消息、自定义消息、撤回消息、Markdown消息等
6. **聊天类型**:
- 单聊1、群聊2、通知

92
docs/troubleshooting.md Normal file
View File

@@ -0,0 +1,92 @@
# OpenIM ACK 排障流程(标准化指南)
> **目标**:在 ACK/Kubernetes 环境下定位“消息不同步/推送缓慢”时,有一套可复用的排障步骤,避免因为主观猜测去改底层逻辑。
---
## 1. 明确现象与影响范围
- **收集信息**受影响的用户、群组、时间段、终端类型iOS/Android/H5
- **区分场景**:登录拉取历史 vs. 实时推送,是否所有人都不行、还是个别用户/群。
- **保存日志与报错**:客户端/服务端的时间点,便于与服务端日志对应。
> 不要在未复现/未收集信息的情况下就进行代码改动。
---
## 2. 逐层排查流程
### 2.1 API 层openim-api
1. 查看 `kubectl logs deploy/openim-api`,确认登录/发消息请求是否返回 200。
2. 如出现 `token invalid``rpc timeout` 等明确错误,先排除配置、网络等问题。
### 2.2 RPC 层openim-rpc-xxx
1. 针对消息问题,重点查看 `openim-rpc-msg``openim-rpc-group` 等服务日志。
2. 出现 `MsgToMongoMQ error``redis set failed` 等,说明生产端异常,需要先修复 RPC/存储配置。
### 2.3 Kafka & 消费端
1. 使用 `kubectl logs deploy/openim-msgtransfer``deploy/push-rpc-server`,查看是否有:
- `xxxConsumer err, will retry in 5 seconds`(真正的连不上 Kafka
- `Subscribe returned normally...`**正常现象**,新版 SDK 每条消息都会返回一次)。
2. 如怀疑 Kafka 累计延迟,可登录 Kafka 集群或使用 `kafka-consumer-groups.sh --describe` 查看 Lag。
### 2.4 持久化Mongo / Redis
1. 抽取异常消息的 conversationId & seq直接在 Mongo/Redis 中查询是否存在。
2. 若 Redis 缺失最新 seq说明 msgtransfer 未写入;继续回头查消费日志。
### 2.5 推送服务push与网关msggateway
1. `kubectl logs deploy/push-rpc-server`:关注推送 RPC 的失败/超时日志;
2. `kubectl logs deploy/messagegateway-rpc-server`:观察是否大量 `write: broken pipe`(通常是客户端断线,非服务异常);
3. 确认 `openim-push` 是否因为配置(厂商证书、推送速率限制)导致卡住。
### 2.6 客户端侧验证
- 使用不同终端iOS/Android/H5交叉验证
- 检查客户端本地缓存/seq 是否有延迟;必要时抓包或查看客户端日志。
---
## 3. 变更前的对照与验证
- **先查证**:如果怀疑配置/逻辑问题,先在官方仓库(`upstream/main`)对比差异,确认是否确实存在 bug。
- **最小化修改**:优先通过配置/运维手段解决(如重启 Pod、更新镜像、修复 Kafka 集群);代码层改动需:
1. 写清楚“问题现象 → 复现步骤 → 根因分析 → 预期影响”;
2. 在测试环境复盘,多人同行评审;
3. 修改后 `mage build` + `kubectl rollout` 验证,确保上下游联调通过。
- **禁止“先改再说”**:避免仅凭几行日志或猜测就改动核心组件(如 discovery、在线推送、MQ 消费),否则容易引入新的系统风险。
---
## 4. 常见误区与经验
- **“Subscribe returned normally” ≠ 错误**:新版本 `NewMConsumerGroupV2` 每处理一条消息就会返回,外层循环需要继续 `Subscribe`
- **ACK Pod 重建是常态**:官方推荐使用 Service DNS/Headless Service + readiness/liveness不要擅自关闭连接。
- **推送失败不等于刷新连接**:先确认网关/客户端状态,只有在明确连接池崩溃时才考虑 `ForceRefresh`
- **go mod tidy 的影响**:在本地执行 `go mod tidy` 可能引入上游依赖CI/build 失败时先恢复 `go.mod/go.sum`
---
## 5. 工具清单
- `kubectl logs/get/describe`:查看 Pod/Deployment 状态;
- `kubectl top pods -n <ns>`:实时查看 Pod CPU / MEM
- `kubectl top nodes`:评估集群整体资源是否紧张;
- `kubectl top node <name>`:关注某台节点是否 CPU / MEM / LOAD 异常;
- `kubectl rollout status deployment/<name>`:确认升级完成;
- `mage build`:本地编译检查;
- Kafka CLI 或监控平台:定位消费滞后;
- Prometheus/Grafana查看服务 CPU、内存、QPS、错误率、延迟等指标
- 日志聚合ELK / Loki 等):快速检索关键字;
- SSH 到节点(需要权限):
- `top` / `htop`:查看 CPU、内存占用
- `free -h`:系统整体内存状况;
- `df -h`:磁盘容量,防止磁盘打满影响容器;
- `du -sh /var/lib/docker`, `/var/log` 等目录,确认是否存在异常增长。
---
## 6. 复盘与持续改进
1. 每次重大故障后,输出“故障记录 + 根因 + 修复方案 + 预防措施”。
2. 同步更新此文档或内部 Wiki确保新同学也能快速掌握流程。
3. 定期与官方版本对齐,避免长期“漂移”导致的隐藏问题。
---
> 若有新的场景/问题,请在这里补充,保持流程可演进。

587
docs/webhook-config.md Normal file
View File

@@ -0,0 +1,587 @@
# Webhook 配置说明文档
## 概述
Webhook 配置用于设置 OpenIM 服务器在特定事件发生时的回调通知。配置支持从数据库动态读取,每小时自动刷新一次。如果数据库中没有配置或配置无效,将使用 `config/webhooks.yml` 中的默认配置。
## 配置结构
### 基础字段
- **url** (string, 必填): Webhook 回调服务器的地址,所有回调请求都会发送到这个地址
### BeforeConfig前置回调配置
前置回调在操作执行前触发,可以阻止或修改操作。
| 字段 | 类型 | 必填 | 说明 |
|------|------|------|------|
| enable | boolean | 是 | 是否启用该回调 |
| timeout | integer | 是 | 超时时间(秒) |
| failedContinue | boolean | 是 | 回调失败时是否继续执行原操作true=继续false=停止) |
| deniedTypes | array[int32] | 否 | 不触发回调的消息类型列表,空数组表示所有类型都触发 |
### AfterConfig后置回调配置
后置回调在操作执行后触发,用于通知和记录。
| 字段 | 类型 | 必填 | 说明 |
|------|------|------|------|
| enable | boolean | 是 | 是否启用该回调 |
| timeout | integer | 是 | 超时时间(秒) |
| attentionIds | array[string] | 否 | 仅对指定用户ID或群组ID触发回调空数组表示所有都触发 |
| deniedTypes | array[int32] | 否 | 不触发回调的消息类型列表,空数组表示所有类型都触发 |
## 支持的回调事件
### 消息相关
| 事件名称 | 类型 | 说明 |
|---------|------|------|
| beforeSendSingleMsg | BeforeConfig | 发送单聊消息前 |
| afterSendSingleMsg | AfterConfig | 发送单聊消息后 |
| beforeSendGroupMsg | BeforeConfig | 发送群聊消息前 |
| afterSendGroupMsg | AfterConfig | 发送群聊消息后 |
| beforeMsgModify | BeforeConfig | 修改消息前(可用于消息过滤) |
| afterMsgSaveDB | AfterConfig | 消息保存到数据库后 |
| afterRevokeMsg | AfterConfig | 撤回消息后 |
| afterGroupMsgRevoke | AfterConfig | 撤回群消息后 |
| afterGroupMsgRead | AfterConfig | 群消息已读后 |
| afterSingleMsgRead | AfterConfig | 单聊消息已读后 |
### 用户相关
| 事件名称 | 类型 | 说明 |
|---------|------|------|
| beforeUserRegister | BeforeConfig | 用户注册前 |
| afterUserRegister | AfterConfig | 用户注册后 |
| beforeUpdateUserInfo | BeforeConfig | 更新用户信息前 |
| afterUpdateUserInfo | AfterConfig | 更新用户信息后 |
| beforeUpdateUserInfoEx | BeforeConfig | 更新用户扩展信息前 |
| afterUpdateUserInfoEx | AfterConfig | 更新用户扩展信息后 |
| afterUserOnline | AfterConfig | 用户上线后 |
| afterUserOffline | AfterConfig | 用户下线后 |
| afterUserKickOff | AfterConfig | 用户被踢下线后 |
### 群组相关
| 事件名称 | 类型 | 说明 |
|---------|------|------|
| beforeCreateGroup | BeforeConfig | 创建群组前 |
| afterCreateGroup | AfterConfig | 创建群组后 |
| beforeSetGroupInfo | BeforeConfig | 设置群组信息前 |
| afterSetGroupInfo | AfterConfig | 设置群组信息后 |
| beforeSetGroupInfoEx | BeforeConfig | 设置群组扩展信息前 |
| afterSetGroupInfoEx | AfterConfig | 设置群组扩展信息后 |
| beforeMemberJoinGroup | BeforeConfig | 成员加入群组前 |
| afterJoinGroup | AfterConfig | 成员加入群组后 |
| beforeApplyJoinGroup | BeforeConfig | 申请加入群组前 |
| beforeInviteUserToGroup | BeforeConfig | 邀请用户加入群组前 |
| afterQuitGroup | AfterConfig | 退出群组后 |
| afterKickGroupMember | AfterConfig | 踢出群成员后 |
| afterDismissGroup | AfterConfig | 解散群组后 |
| afterTransferGroupOwner | AfterConfig | 转移群主后 |
| beforeSetGroupMemberInfo | BeforeConfig | 设置群成员信息前 |
| afterSetGroupMemberInfo | AfterConfig | 设置群成员信息后 |
### 好友相关
| 事件名称 | 类型 | 说明 |
|---------|------|------|
| beforeAddFriend | BeforeConfig | 添加好友前 |
| afterAddFriend | AfterConfig | 添加好友后 |
| beforeAddFriendAgree | BeforeConfig | 同意好友申请前 |
| afterAddFriendAgree | AfterConfig | 同意好友申请后 |
| afterDeleteFriend | AfterConfig | 删除好友后 |
| beforeSetFriendRemark | BeforeConfig | 设置好友备注前 |
| afterSetFriendRemark | AfterConfig | 设置好友备注后 |
| beforeImportFriends | BeforeConfig | 导入好友前 |
| afterImportFriends | AfterConfig | 导入好友后 |
| beforeAddBlack | BeforeConfig | 加入黑名单前 |
| afterRemoveBlack | AfterConfig | 移除黑名单后 |
### 推送相关
| 事件名称 | 类型 | 说明 |
|---------|------|------|
| beforeOfflinePush | BeforeConfig | 离线推送前 |
| beforeOnlinePush | BeforeConfig | 在线推送前 |
| beforeGroupOnlinePush | BeforeConfig | 群组在线推送前 |
### 会话相关
| 事件名称 | 类型 | 说明 |
|---------|------|------|
| beforeCreateSingleChatConversations | BeforeConfig | 创建单聊会话前 |
| afterCreateSingleChatConversations | AfterConfig | 创建单聊会话后 |
| beforeCreateGroupChatConversations | BeforeConfig | 创建群聊会话前 |
| afterCreateGroupChatConversations | AfterConfig | 创建群聊会话后 |
## JSON 配置示例
### 完整配置示例
```json
{
"url": "http://your-webhook-server:8080/callback",
"beforeSendSingleMsg": {
"enable": true,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"afterSendSingleMsg": {
"enable": true,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"beforeSendGroupMsg": {
"enable": true,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"afterSendGroupMsg": {
"enable": true,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"beforeMsgModify": {
"enable": true,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"afterMsgSaveDB": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"afterUserOnline": {
"enable": true,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"afterUserOffline": {
"enable": true,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"afterUserKickOff": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"beforeOfflinePush": {
"enable": false,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"beforeOnlinePush": {
"enable": false,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"beforeGroupOnlinePush": {
"enable": false,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"beforeAddFriend": {
"enable": false,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"beforeUpdateUserInfo": {
"enable": false,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"afterUpdateUserInfo": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"beforeCreateGroup": {
"enable": false,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"afterCreateGroup": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"beforeMemberJoinGroup": {
"enable": false,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"beforeSetGroupMemberInfo": {
"enable": false,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"afterSetGroupMemberInfo": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"afterQuitGroup": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"afterKickGroupMember": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"afterDismissGroup": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"beforeApplyJoinGroup": {
"enable": false,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"afterGroupMsgRead": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"afterSingleMsgRead": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"beforeUserRegister": {
"enable": false,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"afterUserRegister": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"afterTransferGroupOwner": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"beforeSetFriendRemark": {
"enable": false,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"afterSetFriendRemark": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"afterGroupMsgRevoke": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"afterJoinGroup": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"beforeInviteUserToGroup": {
"enable": false,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"afterSetGroupInfo": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"beforeSetGroupInfo": {
"enable": false,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"afterSetGroupInfoEx": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"beforeSetGroupInfoEx": {
"enable": false,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"afterRevokeMsg": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"beforeAddBlack": {
"enable": false,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"afterAddFriend": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"beforeAddFriendAgree": {
"enable": false,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"afterAddFriendAgree": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"afterDeleteFriend": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"beforeImportFriends": {
"enable": false,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"afterImportFriends": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"afterRemoveBlack": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"beforeCreateSingleChatConversations": {
"enable": false,
"timeout": 5,
"failedContinue": false,
"deniedTypes": []
},
"afterCreateSingleChatConversations": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"beforeCreateGroupChatConversations": {
"enable": false,
"timeout": 5,
"failedContinue": false,
"deniedTypes": []
},
"afterCreateGroupChatConversations": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"beforeUpdateUserInfoEx": {
"enable": false,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"afterUpdateUserInfoEx": {
"enable": false,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
}
}
```
### 最小配置示例(仅启用消息回调)
```json
{
"url": "http://your-webhook-server:8080/callback",
"beforeSendSingleMsg": {
"enable": true,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"afterSendSingleMsg": {
"enable": true,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
},
"beforeSendGroupMsg": {
"enable": true,
"timeout": 5,
"failedContinue": true,
"deniedTypes": []
},
"afterSendGroupMsg": {
"enable": true,
"timeout": 5,
"attentionIds": [],
"deniedTypes": []
}
}
```
### 过滤特定消息类型示例
```json
{
"url": "http://your-webhook-server:8080/callback",
"beforeSendSingleMsg": {
"enable": true,
"timeout": 5,
"failedContinue": true,
"deniedTypes": [101, 102]
}
}
```
### 仅关注特定用户/群组示例
```json
{
"url": "http://your-webhook-server:8080/callback",
"afterSendSingleMsg": {
"enable": true,
"timeout": 5,
"attentionIds": ["user001", "user002"],
"deniedTypes": []
},
"afterSendGroupMsg": {
"enable": true,
"timeout": 5,
"attentionIds": ["group001", "group002"],
"deniedTypes": []
}
}
```
## 配置说明
### URL 配置
- **格式**: `http://host:port/path``https://host:port/path`
- **示例**:
- `http://127.0.0.1:8080/callback`
- `http://webhook.example.com:8080/callback`
- `https://webhook.example.com/callback`
### timeout超时时间
- **单位**: 秒
- **建议值**: 5-30 秒
- **说明**: 如果回调服务器在超时时间内没有响应,将根据 `failedContinue` 决定是否继续执行
### failedContinue失败是否继续
- **仅适用于**: BeforeConfig 类型的事件
- **true**: 回调失败时继续执行原操作
- **false**: 回调失败时停止执行原操作
### deniedTypes拒绝的消息类型
- **类型**: 整数数组
- **说明**: 列表中的消息类型不会触发回调
- **空数组**: 表示所有消息类型都触发回调
- **常用消息类型**:
- 101: 文本消息
- 102: 图片消息
- 103: 语音消息
- 104: 视频消息
- 105: 文件消息
### attentionIds关注ID列表
- **仅适用于**: AfterConfig 类型的事件
- **类型**: 字符串数组
- **说明**:
- 对于消息回调仅对指定的用户ID或群组ID触发回调
- 空数组表示所有用户/群组都触发回调
- **示例**: `["user001", "user002", "group001"]`
## 配置存储
### 数据库存储
配置可以存储在 MongoDB 的 `system_configs` 表中:
- **表名**: `system_configs`
- **配置键**: `webhook_config`
- **值类型**: JSON (ValueType = 4)
### 配置优先级
1. **数据库配置**(如果存在且有效)
2. **文件配置**`config/webhooks.yml`
如果数据库中没有配置或配置无效(为空、禁用、格式错误等),将自动使用文件配置。
## 配置刷新
- **刷新间隔**: 30 秒调试模式生产环境建议改为1小时
- **自动刷新**: 服务启动后自动开始定时刷新
- **立即生效**: 配置更新后最多30秒内自动生效无需重启服务
## 注意事项
1. **URL 必须有效**: 配置的 URL 必须可访问,否则回调会失败
2. **超时设置**: 建议根据回调服务器的响应时间合理设置超时时间
3. **失败处理**: BeforeConfig 类型的回调建议设置 `failedContinue: true`,避免因回调失败影响正常业务
4. **性能考虑**: 启用过多回调可能影响系统性能,建议按需启用
5. **安全性**: 确保回调服务器有适当的认证机制

View File

@@ -0,0 +1,208 @@
# 使用 Ex 字段区分群类型方案
## 一、方案概述
使用群组的 `Ex` 扩展字段来区分不同类型的群,在客户端根据 `Ex` 字段控制功能展示,服务端保持统一的验证逻辑。
## 二、Ex 字段格式建议
### 2.1 JSON 格式
```json
{
"groupCategory": "super", // 群类型super(超级群)、normal(普通群)、work(工作群)
"features": {
"allowLink": true, // 是否允许发送链接
"allowQRCode": true, // 是否允许发送二维码
"showMemberList": true, // 是否显示成员列表
"showAdminPanel": false // 是否显示管理面板
},
"custom": {} // 其他自定义字段
}
```
### 2.2 简化格式(如果只需要区分类型)
```json
{
"type": "super" // super, normal, work
}
```
## 三、实现方式
### 3.1 创建群组时设置 Ex
**创建群组时**,在 `GroupInfo.Ex` 中设置群类型:
```go
// 创建超级群
groupInfo := &sdkws.GroupInfo{
GroupName: "超级群",
Ex: `{"type":"super"}`,
// ... 其他字段
}
// 创建普通群
groupInfo := &sdkws.GroupInfo{
GroupName: "普通群",
Ex: `{"type":"normal"}`,
// ... 其他字段
}
```
### 3.2 客户端解析 Ex 字段
**客户端获取群信息后**,解析 `Ex` 字段:
```javascript
// 示例JavaScript/TypeScript
function getGroupType(groupInfo) {
try {
const ex = JSON.parse(groupInfo.Ex || '{}');
return ex.type || 'normal'; // 默认为普通群
} catch (e) {
return 'normal';
}
}
// 根据群类型控制功能显示
function shouldShowFeature(groupInfo, feature) {
const type = getGroupType(groupInfo);
switch (feature) {
case 'memberList':
// 超级群可能不显示成员列表
return type !== 'super';
case 'adminPanel':
// 只有工作群显示管理面板
return type === 'work';
case 'linkMessage':
// 根据类型决定是否允许发送链接
return type !== 'super'; // 超级群不允许发送链接
default:
return true;
}
}
```
### 3.3 更新群信息时保持 Ex 字段
**使用 `SetGroupInfoEx` 接口更新群信息时**,可以更新 `Ex` 字段:
```go
// 更新群扩展信息
req := &pbgroup.SetGroupInfoExReq{
GroupID: groupID,
Ex: &wrapperspb.StringValue{
Value: `{"type":"super","features":{"allowLink":false}}`,
},
}
```
## 四、优势
### 4.1 服务端优势
1. **统一验证逻辑**:所有群组都使用 `WorkingGroup` 的完整验证,安全可靠
2. **无需修改代码**:不需要修改服务端的验证、推送等逻辑
3. **向后兼容**:不影响现有群组,新群组通过 Ex 字段区分
4. **灵活扩展**Ex 字段可以存储任意 JSON 数据,便于后续扩展
### 4.2 客户端优势
1. **完全可控**:客户端可以根据业务需求灵活控制功能展示
2. **易于实现**:只需要解析 JSON 并做条件判断
3. **不影响现有功能**:对没有 Ex 字段或 Ex 字段格式不正确的群组,可以设置默认行为
## 五、注意事项
### 5.1 Ex 字段格式
- **建议使用 JSON 格式**:便于解析和扩展
- **字段命名规范**:使用小驼峰或下划线命名
- **版本兼容**:如果后续需要修改格式,考虑版本号字段
### 5.2 默认值处理
- **客户端**:如果 Ex 字段为空或解析失败,应设置合理的默认值
- **服务端**:创建群组时,如果没有设置 Ex可以设置默认值
### 5.3 数据一致性
- **更新 Ex 字段时**:确保 JSON 格式正确
- **验证**:客户端解析 Ex 字段时,应该处理 JSON 解析错误
## 六、示例代码
### 6.1 Go 服务端示例
```go
// 创建群组时设置 Ex
func createSuperGroup(req *pbgroup.CreateGroupReq) {
req.GroupInfo.Ex = `{"type":"super","features":{"allowLink":false}}`
// ... 创建群组
}
// 解析 Ex 字段(如果需要)
func parseGroupEx(ex string) map[string]interface{} {
var result map[string]interface{}
if err := json.Unmarshal([]byte(ex), &result); err != nil {
return make(map[string]interface{})
}
return result
}
```
### 6.2 客户端示例React/TypeScript
```typescript
interface GroupEx {
type?: 'super' | 'normal' | 'work';
features?: {
allowLink?: boolean;
allowQRCode?: boolean;
showMemberList?: boolean;
};
}
function parseGroupEx(ex: string): GroupEx {
try {
return JSON.parse(ex || '{}') as GroupEx;
} catch {
return { type: 'normal' };
}
}
function useGroupFeatures(groupInfo: GroupInfo) {
const ex = parseGroupEx(groupInfo.Ex);
return {
canSendLink: ex.features?.allowLink !== false,
canSendQRCode: ex.features?.allowQRCode !== false,
showMemberList: ex.features?.showMemberList !== false,
isSuperGroup: ex.type === 'super',
};
}
```
## 七、总结
使用 `Ex` 字段区分群类型是一个**保守、安全、灵活**的方案:
-**服务端**:保持统一逻辑,无需修改验证和推送代码
-**客户端**:完全可控,根据业务需求灵活展示功能
-**扩展性**Ex 字段可以存储任意扩展信息
-**兼容性**:不影响现有群组和功能
这个方案避免了修改服务端核心逻辑带来的风险,同时提供了足够的灵活性来满足不同的业务需求。

View File

@@ -0,0 +1,34 @@
- open-im-server-deploy 在线人数统计
curl -sS -X POST "http://127.0.0.1:10002/statistics/online_user_count" \
-H "Content-Type: application/json" \
-H "token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySUQiOiJpbUFkbWluIiwiUGxhdGZvcm1JRCI6MTAsImV4cCI6MTc3NTI5NTQ1MCwiaWF0IjoxNzY3NTE5NDQ1fQ.IZxx7OoLbuFo6OHoE_W3MQ5TQkj4PKbyzkdL0n--9RE" \
-H "operationID: op_online_001" \
-d "{}"
- open-im-server-deploy 在线人数走势统计
curl -sS -X POST "http://127.0.0.1:10002/statistics/online_user_count_trend" \
-H "Content-Type: application/json" \
-H "token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySUQiOiJpbUFkbWluIiwiUGxhdGZvcm1JRCI6MTAsImV4cCI6MTc3NTI5NTQ1MCwiaWF0IjoxNzY3NTE5NDQ1fQ.IZxx7OoLbuFo6OHoE_W3MQ5TQkj4PKbyzkdL0n--9RE" \
-H "operationID: op_online_trend_001" \
-d '{"startTime":1700000000000,"endTime":1700086400000,"intervalMinutes":15}'
- open-im-server-deploy 用户发送消息总数统计
curl -sS -X POST "http://127.0.0.1:10002/statistics/user_send_msg_count" \
-H "Content-Type: application/json" \
-H "token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySUQiOiJpbUFkbWluIiwiUGxhdGZvcm1JRCI6MTAsImV4cCI6MTc3NTI5NTQ1MCwiaWF0IjoxNzY3NTE5NDQ1fQ.IZxx7OoLbuFo6OHoE_W3MQ5TQkj4PKbyzkdL0n--9RE" \
-H "operationID: op_msg_count_001" \
-d "{}"
- open-im-server-deploy 用户发送消息总数走势统计
curl -sS -X POST "http://127.0.0.1:10002/statistics/user_send_msg_count_trend" \
-H "Content-Type: application/json" \
-H "token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySUQiOiJpbUFkbWluIiwiUGxhdGZvcm1JRCI6MTAsImV4cCI6MTc3NTI5NTQ1MCwiaWF0IjoxNzY3NTE5NDQ1fQ.IZxx7OoLbuFo6OHoE_W3MQ5TQkj4PKbyzkdL0n--9RE" \
-H "operationID: op_msg_trend_001" \
-d '{"userID":"u001","chatType":1,"startTime":1700000000000,"endTime":1700086400000,"intervalMinutes":30}'
- open-im-server-deploy 用户发送消息筛选与查询
curl -sS -X POST "http://127.0.0.1:10002/statistics/user_send_msg_query" \
-H "Content-Type: application/json" \
-H "token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySUQiOiJpbUFkbWluIiwiUGxhdGZvcm1JRCI6MTAsImV4cCI6MTc3NTI5NTQ1MCwiaWF0IjoxNzY3NTE5NDQ1fQ.IZxx7OoLbuFo6OHoE_W3MQ5TQkj4PKbyzkdL0n--9RE" \
-H "operationID: op_msg_query_001" \
-d '{"userID":"u001","startTime":1700000000000,"endTime":1700086400000,"content":"关键词","pageNumber":1,"showNumber":50}'