diff --git a/Makefile b/Makefile
index 4d0b94a2..dd26e18c 100644
--- a/Makefile
+++ b/Makefile
@@ -68,6 +68,18 @@ windows-x64:
@echo Build paopao-ce [windows-x64] CGO_ENABLED=$(CGO_ENABLED)
@CGO_ENABLED=$(CGO_ENABLED) GOOS=windows GOARCH=amd64 go build -trimpath -tags '$(TAGS)' -ldflags '$(LDFLAGS)' -o $(RELEASE_WINDOWS_AMD64)/$(basename $(TARGET)).exe
+.PHONY: generate
+generate: gen-mir gen-grpc
+
+.PHONY: gen-mir
+gen-mir:
+ @go generate internal/mirc/main.go
+ @go fmt ./internal/mirc/...
+
+.PHONY: gen-grpc
+gen-grpc:
+ @go fmt ./internal/proto/...
+
clean:
@go clean
@find ./release -type f -exec rm -r {} +
diff --git a/README.md b/README.md
index abbc76d0..acc0d1d1 100644
--- a/README.md
+++ b/README.md
@@ -65,7 +65,7 @@ PaoPao主要由以下优秀的开源项目/工具构建
* Redis
* Zinc
-\* Zinc是一款轻量级全文搜索引擎,可以查阅 安装
+> Zinc是一款轻量级全文搜索引擎,可以查阅 安装
以上环境版本为PaoPao官方的开发版本,仅供参考,其他版本的环境未进行充分测试
@@ -314,40 +314,46 @@ release/paopao-ce --no-default-features --features sqlite3,localoss,loggerfile,r
```
目前支持的功能集合:
-* 数据库: MySQL/Sqlite3/PostgreSQL
- `Gorm` + `MySQL`/`Sqlite3`/`PostgreSQL` 使用[gorm](https://github.com/go-gorm/gorm)作为数据库的ORM,默认使用 `Grom` + `MySQL`组合(目前状态:稳定,默认,推荐使用);
- `Sqlx` + `MySQL`/`PostgreSQL` 使用[sqlx](https://github.com/jmoiron/sqlx)作为数据库的ORM(目前状态:WIP);
-* 对象存储: AliOSS/COS/HuaweiOBS/MinIO/LocalOSS
- `AliOSS` 阿里云对象存储服务;
- `COS` 腾讯云对象存储服务;
- `HuaweiOBS` 华为云对象存储服务;
- `MinIO` [MinIO](https://github.com/minio/minio)对象存储服务;
- `S3` AWS S3兼容的对象存储服务;
- `LocalOSS` 提供使用本地目录文件作为对象存储的功能,仅用于开发调试环境;
-* 缓存: Redis/SimpleCacheIndex/BigCacheIndex
- `SimpleCacheIndex` 提供简单的 广场推文列表 的缓存功能;
- `BigCacheIndex` 使用[BigCache](https://github.com/allegro/bigcache)缓存 广场推文列表,缓存每个用户每一页,简单做到千人千面(推荐使用);
-* 搜索: Zinc/Meili
- `Zinc` 基于[Zinc](https://github.com/zinclabs/zinc)搜索引擎提供推文搜索服务(目前状态: 稳定,推荐使用);
- `Meili` 基于[Meilisearch](https://github.com/meilisearch/meilisearch)搜索引擎提供推文搜索服务(目前状态: 稳定,推荐使用);
-* 日志: LoggerFile/LoggerZinc/LoggerMeili
- `LoggerFile` 使用文件写日志(目前状态: 稳定);
- `LoggerZinc` 使用[Zinc](https://github.com/zinclabs/zinc)写日志(目前状态: 稳定,推荐使用);
- `LoggerMeili` 使用[Meilisearch](https://github.com/meilisearch/meilisearch)写日志(目前状态: 内测阶段);
-* 用户关系模式: Friendship/Followship
- `Friendship` 弱关系好友模式,类似微信朋友圈(目前状态: 开发阶段);
- `Followship` 关注者模式,类似Twitter的Follow模式(目前状态: WIP);
-* 支付: Alipay
- `Alipay` 开启基于[支付宝开放平台](https://open.alipay.com/)的钱包功能;
-* 短信验证码: SmsJuhe(需要开启sms)
- `Sms` 开启短信验证码功能,用于手机绑定验证手机是否注册者的;功能如果没有开启,手机绑定时任意短信验证码都可以绑定手机;
-* 开发文档: Docs:OpenAPI
- `Docs:OpenAPI` 开启openapi文档功能,提供web api文档说明(visit http://127.0.0.1:8008/docs/openapi);
-* 其他: PhoneBind/OSS:Retention/OSS:TempDir
- `PhoneBind` 手机绑定功能;
- `OSS:Retention` 基于对象存储系统的对象过期自动删除特性实现 先创建临时对象再持久化的功能(目前状态: 内测阶段);
- `OSS:TempDir` 基于对象存储系统的对象拷贝/移动特性实现 先创建临时对象再持久化的功能(目前状态: 内测阶段);
-
+| 功能项 | 类别 | 状态 | 备注 |
+| ----- | ----- | ----- | ----- |
+|`OldWeb` | 子服务 | 稳定(默认) | 开启旧的Web服务 |
+|`Web` | 子服务 | WIP | 开启Web服务|
+|`Admin` | 子服务 | WIP | 开启Admin后台运维服务|
+|`SpaceX` | 子服务 | WIP | 开启SpaceX服务|
+|`Bot` | 子服务 | WIP | 开启Bot服务|
+|`NativeOBS` | 子服务 | WIP | 开启NativeOBS服务|
+|`Deprecated:Web` | 子服务 | 稳定 | Deprecated(关闭) OldWeb服务|
+|`Gorm` | 数据库 | 稳定(默认) | 使用[gorm](https://github.com/go-gorm/gorm)作为数据库的ORM,默认使用 `Gorm` + `MySQL`组合|
+|`Sqlx`| 数据库 | WIP | 使用[sqlx](https://github.com/jmoiron/sqlx)作为数据库的ORM|
+|`MySQL`| 数据库 | 稳定(默认) | 使用MySQL作为数据库|
+|`Postgres`| 数据库 | 稳定 | 使用PostgreSQL作为数据库|
+|`Sqlite3`| 数据库 | 稳定 | 使用Sqlite3作为数据库|
+|`AliOSS` | 对象存储 | 稳定(推荐) |阿里云对象存储服务|
+|`COS` | 对象存储 | 内测 |腾讯云对象存储服务|
+|`HuaweiOBS` | 对象存储 | 内测 |华为云对象存储服务|
+|`MinIO` | 对象存储 | 稳定 |[MinIO](https://github.com/minio/minio)对象存储服务|
+|`S3` | 对象存储 | 内测 |AWS S3兼容的对象存储服务|
+|`LocalOSS` | 对象存储 | 内测 |提供使用本地目录文件作为对象存储的功能,仅用于开发调试环境|
+|`OSS:Retention` | 对象存储 | 内测 |基于对象存储系统的对象过期自动删除特性实现 先创建临时对象再持久化的功能|
+|`OSS:TempDir` | 对象存储 | 内测 |基于对象存储系统的对象拷贝/移动特性实现 先创建临时对象再持久化的功能|
+|`Redis` | 缓存 | 稳定 | Redis缓存功能 |
+|`SimpleCacheIndex` | 缓存 | 稳定 | 提供简单的 广场推文列表 的缓存功能 |
+|`BigCacheIndex` | 缓存 | 稳定(推荐) | 使用[BigCache](https://github.com/allegro/bigcache)缓存 广场推文列表,缓存每个用户每一页,简单做到千人千面 |
+|`Zinc` | 搜索 | 稳定(推荐) | 基于[Zinc](https://github.com/zinclabs/zinc)搜索引擎提供推文搜索服务 |
+|`Meili` | 搜索 | 稳定(推荐) | 基于[Meilisearch](https://github.com/meilisearch/meilisearch)搜索引擎提供推文搜索服务 |
+|`Bleve` | 搜索 | WIP | 基于[Bleve](https://github.com/blevesearch/bleve)搜索引擎提供推文搜索服务 |
+|`LoggerFile` | 日志 | 稳定 | 使用文件写日志 |
+|`LoggerZinc` | 日志 | 稳定(推荐) | 使用[Zinc](https://github.com/zinclabs/zinc)写日志 |
+|`LoggerMeili` | 日志 | 内测 | 使用[Meilisearch](https://github.com/meilisearch/meilisearch)写日志 |
+|`Friendship` | 关系模式 | 内测(默认) | 弱关系好友模式,类似微信朋友圈 |
+|`Followship` | 关系模式 | WIP | 关注者模式,类似Twitter的Follow模式 |
+|`Alipay` | 支付 | 稳定 | 开启基于[支付宝开放平台](https://open.alipay.com/)的钱包功能 |
+|`Sms` | 短信验证 | 稳定 | 开启短信验证码功能,用于手机绑定验证手机是否注册者的;功能如果没有开启,手机绑定时任意短信验证码都可以绑定手机 |
+|`Docs:OpenAPI` | 开发文档 | 稳定 | 开启openapi文档功能,提供web api文档说明(visit http://127.0.0.1:8008/docs/openapi) |
+|`PhoneBind` | 其他 | 稳定 | 手机绑定功能 |
+
+> 功能项状态详情参考 [features-status](features-status.md).
+
### 搭建依赖环境
#### [Zinc](https://github.com/zinclabs/zinc) 搜索引擎:
* Zinc运行
@@ -498,7 +504,7 @@ jc/alimy
代码结构比较简单,很方便扩展,开发文档请参阅[docs](docs '开发文档').
## 👯♀️ 贡献
-paopao-ce 是一个利用 *业余时间* 本着 **"Just for fun just do it."** 的心态 *持续有序* **开发/优化/维护**的开源项目,没有KPI考核、没有Roadmap进度压力、没有技术支持日程安排,或许有些许不足之处,但是重在精神可嘉。 借用网络中的话 **"F\*k talk, f\*k of tech innovation, Shut up and give me your code."** 一切都因更好的体验,一切都是为了爱好,一切都在代码里;期待老铁们加入,一起开发、一起折腾、一起快乐。
+paopao-ce 是一个利用 *业余时间* 本着 **"Just for fun just do it."** 的心态 *持续有序* **开发/优化/维护**的开源项目,没有KPI考核、没有Roadmap进度压力、没有技术支持日程安排,或许有些许不足之处,但是重在精神可嘉。 借用网络中的话 **"F\*k talk, f\*k of tech innovation, Shut up and show me your code."** 一切都因更好的体验,一切都是为了爱好,一切都在代码里;期待老铁们加入,一起开发、一起折腾、一起快乐。
喜欢的朋友记得给个Star,欢迎贡献PR。
diff --git a/config.yaml.sample b/config.yaml.sample
index d776769b..2c6c1ae1 100644
--- a/config.yaml.sample
+++ b/config.yaml.sample
@@ -1,4 +1,5 @@
App: # APP基础设置项
+ RunMode: debug
AttachmentIncomeRate: 0.8
MaxCommentCount: 10
DefaultContextTimeout: 60
@@ -17,8 +18,40 @@ Features:
Slim: ["Base", "Sqlite3", "LocalOSS", "LoggerFile", "OSS:TempDir"]
Base: ["Redis", "PhoneBind"]
Docs: ["Docs:OpenAPI"]
+ Deprecated: ["Deprecated:OldWeb"]
+ Service: ["Admin", "SpaceX", "Bot", "LocalOSS"]
Option: ["SimpleCacheIndex"]
Sms: "SmsJuhe"
+WebServer: # Web服务
+ HttpIp: 0.0.0.0
+ HttpPort: 8010
+ ReadTimeout: 60
+ WriteTimeout: 60
+AdminServer: # Admin后台运维服务
+ HttpIp: 0.0.0.0
+ HttpPort: 8014
+ ReadTimeout: 60
+ WriteTimeout: 60
+SpaceXServer: # SpaceX服务
+ HttpIp: 0.0.0.0
+ HttpPort: 8012
+ ReadTimeout: 60
+ WriteTimeout: 60
+BotServer: # Bot服务
+ HttpIp: 0.0.0.0
+ HttpPort: 8016
+ ReadTimeout: 60
+ WriteTimeout: 60
+LocalossServer: # Localoss服务
+ HttpIp: 0.0.0.0
+ HttpPort: 8018
+ ReadTimeout: 60
+ WriteTimeout: 60
+DocsServer: # 开发文档服务
+ HttpIp: 0.0.0.0
+ HttpPort: 8011
+ ReadTimeout: 60
+ WriteTimeout: 60
SmsJuhe:
Gateway: https://v.juhe.cn/sms/send
Key:
diff --git a/docs/openapi/embed.go b/docs/openapi/embed.go
index 8500ca3c..e72721fb 100644
--- a/docs/openapi/embed.go
+++ b/docs/openapi/embed.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
//go:build docs
// +build docs
diff --git a/docs/proposal/005-引入go-mir优化后端架构设计.md b/docs/proposal/005-引入go-mir优化后端架构设计.md
new file mode 100644
index 00000000..24643b8c
--- /dev/null
+++ b/docs/proposal/005-引入go-mir优化后端架构设计.md
@@ -0,0 +1,37 @@
+| 编号 | 作者 | 发表时间 | 变更时间 | 版本 | 状态 |
+| ----- | ----- | ----- | ----- | ----- | ----- |
+| 005| 北野 | 2022-11-21 | 2022-12-10 | v1.0 | 提议 |
+
+### 引入go-mir优化后端架构设计
+ 引入[github.com/alimy/mir/v3](https://github.com/alimy/mir)优化后端的架构设计,使得后端代码更具扩展型。
+![](.assets/06-01.png)
+
+### 需求
+* 更方便添加后端功能项的实现;
+* 优化代码结构,模块化、清晰化代码布局,使得更具扩展性;
+* 兼容RESTful/gRPC 服务代码,RESTful API是服务于Web/Admin,gRPC API是提供给移动端(iOS/Android)的服务;
+
+### 方案
+
+依赖库:
+* [go-mir](https://github.com/alimy/mir)
+
+### 疑问
+
+1. 为什么引入go-mir?
+ * [go-mir](https://github.com/alimy/mir)是一套提供类似gRPC服务开发体验的快速开发RESTful API后端开发脚手架,巧妙的借用golang语法作为DSL描述RESTful API,通过代码生成的方式自动生成相对应的API接口、HTTP服务器框架初始化代码等,提供类似gRPC的开发体验,对后端开发者非常友好;
+ * 引入go-mir的另一个主要目的是加速后端服务的开发,更好的保证代码风格的一致性;
+ * 践行 [006-关于paopao-ce的结构设计](006-关于paopao-ce的结构设计.md);
+1. 为什么要兼容RESTful/gRPC服务?
+ * RESTful API是提供给Web端使用的,包括paopao-ce web端以及后期的运维端admin; gRPC API是提供给移动端(iOS/Android)使用的服务;
+ * RESTful API天然对web端浏览器友好,而gRPC生态对后端、移动端天然友好,可以根据google-protocol-buffers DSL定义服务API自动生成服务端、客户端代码,非常利于开发,特别是移动端开发,省去了编写客户端网络数据服务相关的业务逻辑,只需要专注于页面逻辑编写,后端数据获取的网络数据访问逻辑直接调用自动生成的gRPC API客户端代码即可,大大的减轻移动端开发的心智负担;
+ * 后端引入gRPC主要就是考虑到移动端(iOS/Android)开发的开发效率,在减轻移动端开发网络数据获取业务逻辑的心智负担上,gRPC生态与RESTful生态相比优势明显,因此强力引入;
+ * 再一个就是[go-mir](https://github.com/alimy/mir) v3为RESTful服务的开发提供类似gRPC服务的开发体验,也为后端兼容RESTful/gRPC服务创造了很好的条件,只要代码结构组织清晰,将会有很好的后端开发体验;
+ >*目前移动端 iOS/Android APP还在规划中,这里后续的后端gRPC API服务也是为此做准备,敬请期待~*
+
+### 更新记录
+#### v0.0(2022-11-21) - 北野
+* 初始文档
+
+#### v1.0(2022-12-10) - 北野
+* 添加内容
diff --git a/docs/proposal/README.md b/docs/proposal/README.md
index b1812170..12f8096e 100644
--- a/docs/proposal/README.md
+++ b/docs/proposal/README.md
@@ -2,4 +2,5 @@
* [001-关于paopao-ce的设计定位](001-关于paopao-ce的设计定位.md "关于paopao-ce的设计定位")
* [002-关于Friendship功能项的设计](002-关于Friendship功能项的设计.md "关于Friendship功能项的设计")
* [003-关于Followship功能项的设计](003-关于Followship功能项的设计.md "关于Followship功能项的设计")
-* [006-关于paopao-ce的结构设计](006-关于paopao-ce的结构设计.md "关于paopao-ce的结构设计")
\ No newline at end of file
+* [005-引入go-mir优化后端架构设计](005-引入go-mir优化后端架构设计.md "引入go-mir优化后端架构设计")
+* [006-关于paopao-ce的结构设计](006-关于paopao-ce的结构设计.md "关于paopao-ce的结构设计")
diff --git a/features-status.md b/features-status.md
new file mode 100644
index 00000000..38f8eb6e
--- /dev/null
+++ b/features-status.md
@@ -0,0 +1,163 @@
+## Features Status
+功能项状态说明。
+
+## 目前支持的功能集合
+#### 子服务
+* `OldWeb` 开启旧的Web服务(目前状态: 默认)
+ * [ ] 提按文档
+ * [x] 服务初始化逻辑
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+* `Web` 开启Web服务(目前状态: WIP)
+ * [ ] 提按文档
+ * [x] 服务初始化逻辑
+ * [ ] 接口定义
+ * [ ] 业务逻辑实现
+* `Admin` 开启Admin后台运维服务(目前状态: WIP)
+ * [ ] 提按文档
+ * [x] 服务初始化逻辑
+ * [ ] 接口定义
+ * [ ] 业务逻辑实现
+* `SpaceX` 开启SpaceX服务(目前状态: WIP)
+ * [ ] 提按文档
+ * [x] 服务初始化逻辑
+ * [ ] 接口定义
+ * [ ] 业务逻辑实现
+* `Bot` 开启Bot服务(目前状态: WIP)
+ * [ ] 提按文档
+ * [x] 服务初始化逻辑
+ * [ ] 接口定义
+ * [ ] 业务逻辑实现
+* `NativeOBS` 开启NativeOBS服务(目前状态: WIP)
+ * [ ] 提按文档
+ * [ ] 服务初始化逻辑
+ * [ ] 接口定义
+ * [ ] 业务逻辑实现
+* `Deprecated:OldWeb` Deprecated(关闭)旧的Web服务(目前状态: WIP)
+ * [ ] 提按文档
+ * [x] 服务初始化逻辑
+
+#### 数据库:
+* `Gorm` + `MySQL`/`Sqlite3`/`PostgreSQL`
+使用[gorm](https://github.com/go-gorm/gorm)作为数据库的ORM,默认使用 `Grom` + `MySQL`组合(目前状态:稳定,默认,推荐使用);
+ * [ ] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+* `Sqlx` + `MySQL`/`PostgreSQL`
+使用[sqlx](https://github.com/jmoiron/sqlx)作为数据库的ORM(目前状态:WIP);
+ * [ ] 提按文档
+ * [ ] 接口定义
+ * [ ] 业务逻辑实现
+
+#### 对象存储:
+* `AliOSS` 阿里云对象存储服务;
+ * [ ] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+* `COS` 腾讯云对象存储服务;
+ * [ ] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+* `HuaweiOBS` 华为云对象存储服务;
+ * [ ] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+* `MinIO` [MinIO](https://github.com/minio/minio)对象存储服务;
+ * [ ] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+* `S3` AWS S3兼容的对象存储服务;
+ * [ ] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+* `LocalOSS` 提供使用本地目录文件作为对象存储的功能,仅用于开发调试环境;
+ * [ ] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+* `OSS:Retention` 基于对象存储系统的对象过期自动删除特性实现 先创建临时对象再持久化的功能(目前状态: 内测阶段);
+ * [ ] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+* `OSS:TempDir` 基于对象存储系统的对象拷贝/移动特性实现 先创建临时对象再持久化的功能(目前状态: 内测阶段);
+ * [ ] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+
+#### 缓存:
+* `Redis` Redis缓存
+ * [ ] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+* `SimpleCacheIndex` 提供简单的 广场推文列表 的缓存功能能;
+ * [ ] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+* `BigCacheIndex` 使用[BigCache](https://github.com/allegro/bigcache)缓存 广场推文列表,缓存每个用户每一页,简单做到千人千面(推荐使用);
+ * [ ] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+
+#### 搜索:
+* `Zinc` 基于[Zinc](https://github.com/zinclabs/zinc)搜索引擎提供推文搜索服务(目前状态: 稳定,推荐使用);
+ * [ ] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+* `Meili` 基于[Meilisearch](https://github.com/meilisearch/meilisearch)搜索引擎提供推文搜索服务(目前状态: 稳定,推荐使用);
+ * [ ] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+* `Bleve` 基于[Bleve](https://github.com/blevesearch/bleve)搜索引擎提供推文搜索服务(目前状态: WIP);
+ * [ ] 提按文档
+ * [ ] 接口定义
+ * [ ] 业务逻辑实现
+#### 日志:
+* `LoggerFile` 使用文件写日志(目前状态: 稳定);
+ * [ ] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+* `LoggerZinc` 使用[Zinc](https://github.com/zinclabs/zinc)写日志(目前状态: 稳定,推荐使用);
+ * [ ] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+* `LoggerMeili` 使用[Meilisearch](https://github.com/meilisearch/meilisearch)写日志(目前状态: 内测阶段);
+ * [ ] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+
+#### 关系模式:
+* `Friendship` 弱关系好友模式,类似微信朋友圈(目前状态: 开发阶段);
+ * [x] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+* `Followship` 关注者模式,类似Twitter的Follow模式(目前状态: WIP);
+ * [ ] 提按文档
+ * [ ] 接口定义
+ * [ ] 业务逻辑实现
+
+### 支付:
+* `Alipay` 开启基于[支付宝开放平台](https://open.alipay.com/)的钱包功能;
+ * [ ] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+
+### 短信验证:
+* SmsJuhe(需要开启sms)
+ * [ ] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+* `Sms` 开启短信验证码功能,用于手机绑定验证手机是否注册者的;功能如果没有开启,手机绑定时任意短信验证码都可以绑定手机;
+ * [ ] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+
+### 开发文档:
+* `Docs:OpenAPI` 开启openapi文档功能,提供web api文档说明(visit http://127.0.0.1:8008/docs/openapi);
+ * [ ] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
+
+### 其他:
+* `PhoneBind` 手机绑定功能;
+ * [ ] 提按文档
+ * [x] 接口定义
+ * [x] 业务逻辑实现
diff --git a/go.mod b/go.mod
index 8f4c9435..80d99a7f 100644
--- a/go.mod
+++ b/go.mod
@@ -5,6 +5,8 @@ go 1.18
require (
github.com/Masterminds/semver/v3 v3.1.1
github.com/afocus/captcha v0.0.0-20191010092841-4bd1f21c8868
+ github.com/alimy/cfg v0.1.0
+ github.com/alimy/mir/v3 v3.0.0-alpha.6
github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible
github.com/allegro/bigcache/v3 v3.0.2
github.com/bytedance/sonic v1.5.0
diff --git a/go.sum b/go.sum
index 9221a97a..dee0dc5e 100644
--- a/go.sum
+++ b/go.sum
@@ -142,6 +142,10 @@ github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRF
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
github.com/alexflint/go-filemutex v0.0.0-20171022225611-72bdc8eae2ae/go.mod h1:CgnQgUtFrFz9mxFNtED3jI5tLDjKlOM+oUF/sTk6ps0=
github.com/alexflint/go-filemutex v1.1.0/go.mod h1:7P4iRhttt/nUvUOrYIhcpMzv2G6CY9UnI16Z+UJqRyk=
+github.com/alimy/cfg v0.1.0 h1:J7KDLEoVIjEBMGlQJb2ljad/d49gJ4Tsl2ogZ9XNhaY=
+github.com/alimy/cfg v0.1.0/go.mod h1:rOxbasTH2srl6StAjNF5Vyi8bfrdkl3fLGmOYtSw81c=
+github.com/alimy/mir/v3 v3.0.0-alpha.6 h1:4xcyE12MgzTbcIcYtnt3ILrVrxFjI71qhqh0JL2gB58=
+github.com/alimy/mir/v3 v3.0.0-alpha.6/go.mod h1:ybhT2ijOiDn0lLwWzIY6vXdv+uzZrctS7VFfczcXBWU=
github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible h1:9gWa46nstkJ9miBReJcN8Gq34cBFbzSpQZVVT9N09TM=
github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8=
github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM=
diff --git a/internal/conf/conf.go b/internal/conf/conf.go
index 97512264..bdadf5e4 100644
--- a/internal/conf/conf.go
+++ b/internal/conf/conf.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package conf
import (
@@ -5,7 +9,7 @@ import (
"sync"
"time"
- "github.com/rocboss/paopao-ce/pkg/cfg"
+ "github.com/alimy/cfg"
)
var (
@@ -19,7 +23,13 @@ var (
MysqlSetting *MySQLSettingS
PostgresSetting *PostgresSettingS
Sqlite3Setting *Sqlite3SettingS
- ServerSetting *ServerSettingS
+ ServerSetting *HttpServerSettingS
+ WebServerSetting *HttpServerSettingS
+ AdminServerSetting *HttpServerSettingS
+ SpaceXServerSetting *HttpServerSettingS
+ BotServerSetting *HttpServerSettingS
+ LocalossServerSetting *HttpServerSettingS
+ DocsServerSetting *HttpServerSettingS
AppSetting *AppSettingS
CacheIndexSetting *CacheIndexSettingS
SimpleCacheIndexSetting *SimpleCacheIndexSettingS
@@ -48,7 +58,7 @@ func setupSetting(suite []string, noDefault bool) error {
// initialize features configure
ss, kv := setting.featuresInfoFrom("Features")
- cfg.Initialize(ss, kv)
+ cfg.Initial(ss, kv)
if len(suite) > 0 {
cfg.Use(suite, noDefault)
}
@@ -56,6 +66,12 @@ func setupSetting(suite []string, noDefault bool) error {
objects := map[string]any{
"App": &AppSetting,
"Server": &ServerSetting,
+ "WebServer": &WebServerSetting,
+ "AdminServer": &AdminServerSetting,
+ "SpaceXServer": &SpaceXServerSetting,
+ "BotServer": &BotServerSetting,
+ "LocalossServer": &LocalossServerSetting,
+ "DocsServer": &DocsServerSetting,
"CacheIndex": &CacheIndexSetting,
"SimpleCacheIndex": &SimpleCacheIndexSetting,
"BigCacheIndex": &BigCacheIndexSetting,
@@ -134,3 +150,10 @@ func GetOssDomain() string {
}
return uri + AliOSSSetting.Domain + "/"
}
+
+func RunMode() string {
+ if !cfg.If("Deprecated:OldWeb") {
+ return ServerSetting.RunMode
+ }
+ return AppSetting.RunMode
+}
diff --git a/internal/conf/db.go b/internal/conf/db.go
index ef4f7c92..62ad7fe3 100644
--- a/internal/conf/db.go
+++ b/internal/conf/db.go
@@ -1,11 +1,15 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package conf
import (
"sync"
"time"
+ "github.com/alimy/cfg"
"github.com/go-redis/redis/v8"
- "github.com/rocboss/paopao-ce/pkg/cfg"
"github.com/sirupsen/logrus"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
diff --git a/internal/conf/db_cgo.go b/internal/conf/db_cgo.go
index 3ec8a218..218512a5 100644
--- a/internal/conf/db_cgo.go
+++ b/internal/conf/db_cgo.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
//go:build cgo
// +build cgo
diff --git a/internal/conf/db_nocgo.go b/internal/conf/db_nocgo.go
index 37937484..977a6695 100644
--- a/internal/conf/db_nocgo.go
+++ b/internal/conf/db_nocgo.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
//go:build !cgo
// +build !cgo
diff --git a/internal/conf/logger.go b/internal/conf/logger.go
index c65612dc..cbe3cc1b 100644
--- a/internal/conf/logger.go
+++ b/internal/conf/logger.go
@@ -1,9 +1,13 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package conf
import (
"io"
- "github.com/rocboss/paopao-ce/pkg/cfg"
+ "github.com/alimy/cfg"
"github.com/sirupsen/logrus"
"gopkg.in/natefinch/lumberjack.v2"
)
diff --git a/internal/conf/logger_meili.go b/internal/conf/logger_meili.go
index 756cc41f..2d3d439d 100644
--- a/internal/conf/logger_meili.go
+++ b/internal/conf/logger_meili.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package conf
import (
diff --git a/internal/conf/logger_zinc.go b/internal/conf/logger_zinc.go
index 211270c0..4f804cf8 100644
--- a/internal/conf/logger_zinc.go
+++ b/internal/conf/logger_zinc.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package conf
import (
diff --git a/internal/conf/settting.go b/internal/conf/settting.go
index 116fdf95..7067d18e 100644
--- a/internal/conf/settting.go
+++ b/internal/conf/settting.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package conf
import (
@@ -41,7 +45,7 @@ type LoggerMeiliSettingS struct {
MinWorker int
}
-type ServerSettingS struct {
+type HttpServerSettingS struct {
RunMode string
HttpIp string
HttpPort string
@@ -50,6 +54,7 @@ type ServerSettingS struct {
}
type AppSettingS struct {
+ RunMode string
MaxCommentCount int64
AttachmentIncomeRate float64
DefaultContextTimeout time.Duration
diff --git a/internal/core/authority.go b/internal/core/authority.go
index c016c840..05e3742a 100644
--- a/internal/core/authority.go
+++ b/internal/core/authority.go
@@ -1,7 +1,10 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package core
import (
- "github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/pkg/types"
)
@@ -33,23 +36,17 @@ const (
ActCreateActivationCode
)
-type act uint8
-
-type FriendFilter map[int64]types.Empty
-type FriendSet map[string]types.Empty
+type (
+ act uint8
-type Action struct {
- Act act
- UserId int64
-}
+ FriendFilter map[int64]types.Empty
+ FriendSet map[string]types.Empty
-// AuthorizationManageService 授权管理服务
-type AuthorizationManageService interface {
- IsAllow(user *model.User, action *Action) bool
- BeFriendFilter(userId int64) FriendFilter
- BeFriendIds(userId int64) ([]int64, error)
- MyFriendSet(userId int64) FriendSet
-}
+ Action struct {
+ Act act
+ UserId int64
+ }
+)
func (f FriendFilter) IsFriend(userId int64) bool {
_, yeah := f[userId]
@@ -57,7 +54,7 @@ func (f FriendFilter) IsFriend(userId int64) bool {
}
// IsAllow default true if user is admin
-func (a act) IsAllow(user *model.User, userId int64, isFriend bool, isActivation bool) bool {
+func (a act) IsAllow(user *User, userId int64, isFriend bool, isActivation bool) bool {
if user.IsAdmin {
return true
}
@@ -116,3 +113,11 @@ func (a act) IsAllow(user *model.User, userId int64, isFriend bool, isActivation
return false
}
+
+// AuthorizationManageService 授权管理服务
+type AuthorizationManageService interface {
+ IsAllow(user *User, action *Action) bool
+ BeFriendFilter(userId int64) FriendFilter
+ BeFriendIds(userId int64) ([]int64, error)
+ MyFriendSet(userId int64) FriendSet
+}
diff --git a/internal/core/cache.go b/internal/core/cache.go
index e4cf4cd9..d8b8cd10 100644
--- a/internal/core/cache.go
+++ b/internal/core/cache.go
@@ -1,6 +1,12 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package core
-import "github.com/rocboss/paopao-ce/internal/model"
+import (
+ "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr"
+)
const (
IdxActNop IdxAct = iota + 1
@@ -15,7 +21,7 @@ type IdxAct uint8
type IndexAction struct {
Act IdxAct
- Post *model.Post
+ Post *dbr.Post
}
func (a IdxAct) String() string {
@@ -37,7 +43,7 @@ func (a IdxAct) String() string {
}
}
-func NewIndexAction(act IdxAct, post *model.Post) *IndexAction {
+func NewIndexAction(act IdxAct, post *dbr.Post) *IndexAction {
return &IndexAction{
Act: act,
Post: post,
@@ -48,5 +54,5 @@ func NewIndexAction(act IdxAct, post *model.Post) *IndexAction {
type CacheIndexService interface {
IndexPostsService
- SendAction(act IdxAct, post *model.Post)
+ SendAction(act IdxAct, post *dbr.Post)
}
diff --git a/internal/core/comments.go b/internal/core/comments.go
index 9be29ed3..c5501b4b 100644
--- a/internal/core/comments.go
+++ b/internal/core/comments.go
@@ -1,24 +1,36 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package core
import (
- "github.com/rocboss/paopao-ce/internal/model"
+ "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr"
+)
+
+type (
+ Comment = dbr.Comment
+ CommentFormated = dbr.CommentFormated
+ CommentReply = dbr.CommentReply
+ CommentContent = dbr.CommentContent
+ CommentReplyFormated = dbr.CommentReplyFormated
)
// CommentService 评论检索服务
type CommentService interface {
- GetComments(conditions *model.ConditionsT, offset, limit int) ([]*model.Comment, error)
- GetCommentByID(id int64) (*model.Comment, error)
- GetCommentCount(conditions *model.ConditionsT) (int64, error)
- GetCommentReplyByID(id int64) (*model.CommentReply, error)
- GetCommentContentsByIDs(ids []int64) ([]*model.CommentContent, error)
- GetCommentRepliesByID(ids []int64) ([]*model.CommentReplyFormated, error)
+ GetComments(conditions *ConditionsT, offset, limit int) ([]*Comment, error)
+ GetCommentByID(id int64) (*Comment, error)
+ GetCommentCount(conditions *ConditionsT) (int64, error)
+ GetCommentReplyByID(id int64) (*CommentReply, error)
+ GetCommentContentsByIDs(ids []int64) ([]*CommentContent, error)
+ GetCommentRepliesByID(ids []int64) ([]*CommentReplyFormated, error)
}
// CommentManageService 评论管理服务
type CommentManageService interface {
- DeleteComment(comment *model.Comment) error
- CreateComment(comment *model.Comment) (*model.Comment, error)
- CreateCommentReply(reply *model.CommentReply) (*model.CommentReply, error)
- DeleteCommentReply(reply *model.CommentReply) error
- CreateCommentContent(content *model.CommentContent) (*model.CommentContent, error)
+ DeleteComment(comment *Comment) error
+ CreateComment(comment *Comment) (*Comment, error)
+ CreateCommentReply(reply *CommentReply) (*CommentReply, error)
+ DeleteCommentReply(reply *CommentReply) error
+ CreateCommentContent(content *CommentContent) (*CommentContent, error)
}
diff --git a/internal/core/core.go b/internal/core/core.go
index f0c158b1..9a8eb26f 100644
--- a/internal/core/core.go
+++ b/internal/core/core.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package core
// DataService 数据服务集成
diff --git a/internal/core/messages.go b/internal/core/messages.go
index aa08a1f8..57816480 100644
--- a/internal/core/messages.go
+++ b/internal/core/messages.go
@@ -1,15 +1,36 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package core
import (
- "github.com/rocboss/paopao-ce/internal/model"
+ "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr"
+)
+
+const (
+ MsgTypePost = dbr.MsgTypePost
+ MsgtypeComment = dbr.MsgtypeComment
+ MsgTypeReply = dbr.MsgTypeReply
+ MsgTypeWhisper = dbr.MsgTypeWhisper
+ MsgTypeRequestingFriend = dbr.MsgTypeRequestingFriend
+ MsgTypeSystem = dbr.MsgTypeSystem
+
+ MsgStatusUnread = dbr.MsgStatusUnread
+ MsgStatusReaded = dbr.MsgStatusReaded
+)
+
+type (
+ Message = dbr.Message
+ MessageFormated = dbr.MessageFormated
)
// MessageService 消息服务
type MessageService interface {
- CreateMessage(msg *model.Message) (*model.Message, error)
+ CreateMessage(msg *Message) (*Message, error)
GetUnreadCount(userID int64) (int64, error)
- GetMessageByID(id int64) (*model.Message, error)
- ReadMessage(message *model.Message) error
- GetMessages(conditions *model.ConditionsT, offset, limit int) ([]*model.MessageFormated, error)
- GetMessageCount(conditions *model.ConditionsT) (int64, error)
+ GetMessageByID(id int64) (*Message, error)
+ ReadMessage(message *Message) error
+ GetMessages(conditions *ConditionsT, offset, limit int) ([]*MessageFormated, error)
+ GetMessageCount(conditions *ConditionsT) (int64, error)
}
diff --git a/internal/core/search.go b/internal/core/search.go
index 3ac90288..74d6e029 100644
--- a/internal/core/search.go
+++ b/internal/core/search.go
@@ -1,7 +1,11 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package core
import (
- "github.com/rocboss/paopao-ce/internal/model"
+ "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr"
)
const (
@@ -9,28 +13,39 @@ const (
SearchTypeTag SearchType = "tag"
)
-type SearchType string
+const (
+ PostVisitPublic = dbr.PostVisitPublic
+ PostVisitPrivate = dbr.PostVisitPrivate
+ PostVisitFriend = dbr.PostVisitFriend
+ PostVisitInvalid = dbr.PostVisitInvalid
+)
-type QueryReq struct {
- Query string
- Visibility []model.PostVisibleT
- Type SearchType
-}
+type (
+ PostVisibleT = dbr.PostVisibleT
-type QueryResp struct {
- Items []*model.PostFormated
- Total int64
-}
+ SearchType string
-type TsDocItem struct {
- Post *model.Post
- Content string
-}
+ QueryReq struct {
+ Query string
+ Visibility []PostVisibleT
+ Type SearchType
+ }
+
+ QueryResp struct {
+ Items []*PostFormated
+ Total int64
+ }
+
+ TsDocItem struct {
+ Post *Post
+ Content string
+ }
+)
// TweetSearchService tweet search service interface
type TweetSearchService interface {
IndexName() string
AddDocuments(data []TsDocItem, primaryKey ...string) (bool, error)
DeleteDocuments(identifiers []string) error
- Search(user *model.User, q *QueryReq, offset, limit int) (*QueryResp, error)
+ Search(user *User, q *QueryReq, offset, limit int) (*QueryResp, error)
}
diff --git a/internal/core/security.go b/internal/core/security.go
index 63a7ac21..81a428af 100644
--- a/internal/core/security.go
+++ b/internal/core/security.go
@@ -1,13 +1,21 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package core
import (
- "github.com/rocboss/paopao-ce/internal/model"
+ "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr"
+)
+
+type (
+ Captcha = dbr.Captcha
)
// SecurityService 安全相关服务
type SecurityService interface {
- GetLatestPhoneCaptcha(phone string) (*model.Captcha, error)
- UsePhoneCaptcha(captcha *model.Captcha) error
+ GetLatestPhoneCaptcha(phone string) (*Captcha, error)
+ UsePhoneCaptcha(captcha *Captcha) error
SendPhoneCaptcha(phone string) error
}
diff --git a/internal/core/storage.go b/internal/core/storage.go
index 2a241bca..310edf29 100644
--- a/internal/core/storage.go
+++ b/internal/core/storage.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package core
import (
diff --git a/internal/core/topics.go b/internal/core/topics.go
index a894f9b2..138cc151 100644
--- a/internal/core/topics.go
+++ b/internal/core/topics.go
@@ -1,13 +1,22 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package core
import (
- "github.com/rocboss/paopao-ce/internal/model"
+ "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr"
+)
+
+type (
+ Tag = dbr.Tag
+ TagFormated = dbr.TagFormated
)
// TopicService 话题服务
type TopicService interface {
- CreateTag(tag *model.Tag) (*model.Tag, error)
- DeleteTag(tag *model.Tag) error
- GetTags(conditions *model.ConditionsT, offset, limit int) ([]*model.Tag, error)
- GetTagsByKeyword(keyword string) ([]*model.Tag, error)
+ CreateTag(tag *Tag) (*Tag, error)
+ DeleteTag(tag *Tag) error
+ GetTags(conditions *ConditionsT, offset, limit int) ([]*Tag, error)
+ GetTagsByKeyword(keyword string) ([]*Tag, error)
}
diff --git a/internal/core/tweets.go b/internal/core/tweets.go
index 1b454c6d..682cbd65 100644
--- a/internal/core/tweets.go
+++ b/internal/core/tweets.go
@@ -1,49 +1,83 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package core
import (
- "github.com/rocboss/paopao-ce/internal/model"
- "github.com/rocboss/paopao-ce/internal/model/rest"
+ "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr"
+)
+
+const (
+ AttachmentTypeImage = dbr.AttachmentTypeImage
+ AttachmentTypeVideo = dbr.AttachmentTypeVideo
+ AttachmentTypeOther = dbr.AttachmentTypeOther
+
+ // 类型,1标题,2文字段落,3图片地址,4视频地址,5语音地址,6链接地址,7附件资源
+ ContentTypeTitle = dbr.ContentTypeTitle
+ ContentTypeText = dbr.ContentTypeText
+ ContentTypeImage = dbr.ContentTypeImage
+ ContentTypeVideo = dbr.ContentTypeVideo
+ ContentTypeAudio = dbr.ContentTypeAudio
+ ContentTypeLink = dbr.ContentTypeLink
+ ContentTypeAttachment = dbr.ContentTypeAttachment
+ ContentTypeChargeAttachment = dbr.ContentTypeChargeAttachment
+)
+
+type (
+ PostStar = dbr.PostStar
+ PostCollection = dbr.PostCollection
+ PostAttachmentBill = dbr.PostAttachmentBill
+ PostContent = dbr.PostContent
+ Attachment = dbr.Attachment
+ AttachmentType = dbr.AttachmentType
+ PostContentT = dbr.PostContentT
+
+ IndexTweetList struct {
+ Tweets []*PostFormated
+ Total int64
+ }
)
// TweetService 推文检索服务
type TweetService interface {
- GetPostByID(id int64) (*model.Post, error)
- GetPosts(conditions *model.ConditionsT, offset, limit int) ([]*model.Post, error)
- GetPostCount(conditions *model.ConditionsT) (int64, error)
- GetUserPostStar(postID, userID int64) (*model.PostStar, error)
- GetUserPostStars(userID int64, offset, limit int) ([]*model.PostStar, error)
+ GetPostByID(id int64) (*Post, error)
+ GetPosts(conditions *ConditionsT, offset, limit int) ([]*Post, error)
+ GetPostCount(conditions *ConditionsT) (int64, error)
+ GetUserPostStar(postID, userID int64) (*PostStar, error)
+ GetUserPostStars(userID int64, offset, limit int) ([]*PostStar, error)
GetUserPostStarCount(userID int64) (int64, error)
- GetUserPostCollection(postID, userID int64) (*model.PostCollection, error)
- GetUserPostCollections(userID int64, offset, limit int) ([]*model.PostCollection, error)
+ GetUserPostCollection(postID, userID int64) (*PostCollection, error)
+ GetUserPostCollections(userID int64, offset, limit int) ([]*PostCollection, error)
GetUserPostCollectionCount(userID int64) (int64, error)
- GetPostAttatchmentBill(postID, userID int64) (*model.PostAttachmentBill, error)
- GetPostContentsByIDs(ids []int64) ([]*model.PostContent, error)
- GetPostContentByID(id int64) (*model.PostContent, error)
+ GetPostAttatchmentBill(postID, userID int64) (*PostAttachmentBill, error)
+ GetPostContentsByIDs(ids []int64) ([]*PostContent, error)
+ GetPostContentByID(id int64) (*PostContent, error)
}
// TweetManageService 推文管理服务,包括创建/删除/更新推文
type TweetManageService interface {
- CreateAttachment(attachment *model.Attachment) (*model.Attachment, error)
- CreatePost(post *model.Post) (*model.Post, error)
- DeletePost(post *model.Post) ([]string, error)
- LockPost(post *model.Post) error
- StickPost(post *model.Post) error
- VisiblePost(post *model.Post, visibility model.PostVisibleT) error
- UpdatePost(post *model.Post) error
- CreatePostStar(postID, userID int64) (*model.PostStar, error)
- DeletePostStar(p *model.PostStar) error
- CreatePostCollection(postID, userID int64) (*model.PostCollection, error)
- DeletePostCollection(p *model.PostCollection) error
- CreatePostContent(content *model.PostContent) (*model.PostContent, error)
+ CreateAttachment(attachment *Attachment) (*Attachment, error)
+ CreatePost(post *Post) (*Post, error)
+ DeletePost(post *Post) ([]string, error)
+ LockPost(post *Post) error
+ StickPost(post *Post) error
+ VisiblePost(post *Post, visibility PostVisibleT) error
+ UpdatePost(post *Post) error
+ CreatePostStar(postID, userID int64) (*PostStar, error)
+ DeletePostStar(p *PostStar) error
+ CreatePostCollection(postID, userID int64) (*PostCollection, error)
+ DeletePostCollection(p *PostCollection) error
+ CreatePostContent(content *PostContent) (*PostContent, error)
}
// TweetHelpService 推文辅助服务
type TweetHelpService interface {
- RevampPosts(posts []*model.PostFormated) ([]*model.PostFormated, error)
- MergePosts(posts []*model.Post) ([]*model.PostFormated, error)
+ RevampPosts(posts []*PostFormated) ([]*PostFormated, error)
+ MergePosts(posts []*Post) ([]*PostFormated, error)
}
// IndexPostsService 广场首页推文列表服务
type IndexPostsService interface {
- IndexPosts(user *model.User, offset int, limit int) (*rest.IndexTweetsResp, error)
+ IndexPosts(user *User, offset int, limit int) (*IndexTweetList, error)
}
diff --git a/internal/core/types.go b/internal/core/types.go
new file mode 100644
index 00000000..6ca95893
--- /dev/null
+++ b/internal/core/types.go
@@ -0,0 +1,24 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package core
+
+import (
+ "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr"
+)
+
+const (
+ UserStatusNormal = dbr.UserStatusNormal
+ UserStatusClosed = dbr.UserStatusClosed
+)
+
+type (
+ User = dbr.User
+ Post = dbr.Post
+ ConditionsT = dbr.ConditionsT
+ PostFormated = dbr.PostFormated
+ UserFormated = dbr.UserFormated
+ PostContentFormated = dbr.PostContentFormated
+ Model = dbr.Model
+)
diff --git a/internal/core/user.go b/internal/core/user.go
index cf0ebaa8..ed132dd3 100644
--- a/internal/core/user.go
+++ b/internal/core/user.go
@@ -1,19 +1,33 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package core
-import (
- "github.com/rocboss/paopao-ce/internal/model"
- "github.com/rocboss/paopao-ce/internal/model/rest"
+type (
+ ContactItem struct {
+ UserId int64 `json:"user_id"`
+ UserName string `json:"username"`
+ Nickname string `json:"nickname"`
+ Avatar string `json:"avatar"`
+ Phone string `json:"phone"`
+ }
+
+ ContactList struct {
+ Contacts []ContactItem `json:"contacts"`
+ Total int64 `json:"total"`
+ }
)
// UserManageService 用户管理服务
type UserManageService interface {
- GetUserByID(id int64) (*model.User, error)
- GetUserByUsername(username string) (*model.User, error)
- GetUserByPhone(phone string) (*model.User, error)
- GetUsersByIDs(ids []int64) ([]*model.User, error)
- GetUsersByKeyword(keyword string) ([]*model.User, error)
- CreateUser(user *model.User) (*model.User, error)
- UpdateUser(user *model.User) error
+ GetUserByID(id int64) (*User, error)
+ GetUserByUsername(username string) (*User, error)
+ GetUserByPhone(phone string) (*User, error)
+ GetUsersByIDs(ids []int64) ([]*User, error)
+ GetUsersByKeyword(keyword string) ([]*User, error)
+ CreateUser(user *User) (*User, error)
+ UpdateUser(user *User) error
}
// ContactManageService 联系人管理服务
@@ -22,6 +36,6 @@ type ContactManageService interface {
AddFriend(userId int64, friendId int64) error
RejectFriend(userId int64, friendId int64) error
DeleteFriend(userId int64, friendId int64) error
- GetContacts(userId int64, offset int, limit int) (*rest.ContactsResp, error)
+ GetContacts(userId int64, offset int, limit int) (*ContactList, error)
IsFriend(userID int64, friendID int64) bool
}
diff --git a/internal/core/version.go b/internal/core/version.go
index e603c0a5..07376c39 100644
--- a/internal/core/version.go
+++ b/internal/core/version.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package core
import (
diff --git a/internal/core/wallet.go b/internal/core/wallet.go
index 5b3a3391..c4792d3b 100644
--- a/internal/core/wallet.go
+++ b/internal/core/wallet.go
@@ -1,15 +1,24 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package core
import (
- "github.com/rocboss/paopao-ce/internal/model"
+ "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr"
+)
+
+type (
+ WalletStatement = dbr.WalletStatement
+ WalletRecharge = dbr.WalletRecharge
)
// WalletService wallet service interface
type WalletService interface {
- GetUserWalletBills(userID int64, offset, limit int) ([]*model.WalletStatement, error)
+ GetUserWalletBills(userID int64, offset, limit int) ([]*WalletStatement, error)
GetUserWalletBillCount(userID int64) (int64, error)
- GetRechargeByID(id int64) (*model.WalletRecharge, error)
- CreateRecharge(userId, amount int64) (*model.WalletRecharge, error)
- HandleRechargeSuccess(recharge *model.WalletRecharge, tradeNo string) error
- HandlePostAttachmentBought(post *model.Post, user *model.User) error
+ GetRechargeByID(id int64) (*WalletRecharge, error)
+ CreateRecharge(userId, amount int64) (*WalletRecharge, error)
+ HandleRechargeSuccess(recharge *WalletRecharge, tradeNo string) error
+ HandlePostAttachmentBought(post *Post, user *User) error
}
diff --git a/internal/dao/cache/bigcache.go b/internal/dao/cache/bigcache.go
index 4fce26de..8ec83c38 100644
--- a/internal/dao/cache/bigcache.go
+++ b/internal/dao/cache/bigcache.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package cache
import (
@@ -11,8 +15,6 @@ import (
"github.com/Masterminds/semver/v3"
"github.com/allegro/bigcache/v3"
"github.com/rocboss/paopao-ce/internal/core"
- "github.com/rocboss/paopao-ce/internal/model"
- "github.com/rocboss/paopao-ce/internal/model/rest"
"github.com/rocboss/paopao-ce/pkg/types"
"github.com/sirupsen/logrus"
)
@@ -24,7 +26,7 @@ var (
type postsEntry struct {
key string
- tweets *rest.IndexTweetsResp
+ tweets *core.IndexTweetList
}
type bigCacheIndexServant struct {
@@ -38,7 +40,7 @@ type bigCacheIndexServant struct {
preventDuration time.Duration
}
-func (s *bigCacheIndexServant) IndexPosts(user *model.User, offset int, limit int) (*rest.IndexTweetsResp, error) {
+func (s *bigCacheIndexServant) IndexPosts(user *core.User, offset int, limit int) (*core.IndexTweetList, error) {
key := s.keyFrom(user, offset, limit)
posts, err := s.getPosts(key)
if err == nil {
@@ -54,7 +56,7 @@ func (s *bigCacheIndexServant) IndexPosts(user *model.User, offset int, limit in
return posts, nil
}
-func (s *bigCacheIndexServant) getPosts(key string) (*rest.IndexTweetsResp, error) {
+func (s *bigCacheIndexServant) getPosts(key string) (*core.IndexTweetList, error) {
data, err := s.cache.Get(key)
if err != nil {
logrus.Debugf("bigCacheIndexServant.getPosts get posts by key: %s from cache err: %v", key, err)
@@ -62,7 +64,7 @@ func (s *bigCacheIndexServant) getPosts(key string) (*rest.IndexTweetsResp, erro
}
buf := bytes.NewBuffer(data)
dec := gob.NewDecoder(buf)
- var resp rest.IndexTweetsResp
+ var resp core.IndexTweetList
if err := dec.Decode(&resp); err != nil {
logrus.Debugf("bigCacheIndexServant.getPosts get posts from cache in decode err: %v", err)
return nil, err
@@ -70,7 +72,7 @@ func (s *bigCacheIndexServant) getPosts(key string) (*rest.IndexTweetsResp, erro
return &resp, nil
}
-func (s *bigCacheIndexServant) cachePosts(key string, tweets *rest.IndexTweetsResp) {
+func (s *bigCacheIndexServant) cachePosts(key string, tweets *core.IndexTweetList) {
entry := &postsEntry{key: key, tweets: tweets}
select {
case s.cachePostsCh <- entry:
@@ -96,7 +98,7 @@ func (s *bigCacheIndexServant) setPosts(entry *postsEntry) {
logrus.Debugf("bigCacheIndexServant.setPosts setPosts set cache by key: %s", entry.key)
}
-func (s *bigCacheIndexServant) keyFrom(user *model.User, offset int, limit int) string {
+func (s *bigCacheIndexServant) keyFrom(user *core.User, offset int, limit int) string {
var userId int64 = -1
if user != nil {
userId = user.ID
@@ -104,7 +106,7 @@ func (s *bigCacheIndexServant) keyFrom(user *model.User, offset int, limit int)
return fmt.Sprintf("index:%d:%d:%d", userId, offset, limit)
}
-func (s *bigCacheIndexServant) SendAction(act core.IdxAct, post *model.Post) {
+func (s *bigCacheIndexServant) SendAction(act core.IdxAct, post *core.Post) {
action := core.NewIndexAction(act, post)
select {
case s.indexActionCh <- action:
@@ -134,7 +136,7 @@ func (s *bigCacheIndexServant) handleIndexAction(action *core.IndexAction) {
// 创建/删除 私密推文特殊处理
switch act {
case core.IdxActCreatePost, core.IdxActDeletePost:
- if post.Visibility == model.PostVisitPrivate {
+ if post.Visibility == core.PostVisitPrivate {
s.deleteCacheByUserId(post.UserID, true)
return
}
diff --git a/internal/dao/cache/cache.go b/internal/dao/cache/cache.go
index 1b12ad88..773c9a2f 100644
--- a/internal/dao/cache/cache.go
+++ b/internal/dao/cache/cache.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package cache
import (
diff --git a/internal/dao/cache/none.go b/internal/dao/cache/none.go
index 79705280..ce6e1caf 100644
--- a/internal/dao/cache/none.go
+++ b/internal/dao/cache/none.go
@@ -1,10 +1,12 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package cache
import (
"github.com/Masterminds/semver/v3"
"github.com/rocboss/paopao-ce/internal/core"
- "github.com/rocboss/paopao-ce/internal/model"
- "github.com/rocboss/paopao-ce/internal/model/rest"
)
var (
@@ -16,11 +18,11 @@ type noneCacheIndexServant struct {
ips core.IndexPostsService
}
-func (s *noneCacheIndexServant) IndexPosts(user *model.User, offset int, limit int) (*rest.IndexTweetsResp, error) {
+func (s *noneCacheIndexServant) IndexPosts(user *core.User, offset int, limit int) (*core.IndexTweetList, error) {
return s.ips.IndexPosts(user, offset, limit)
}
-func (s *noneCacheIndexServant) SendAction(_act core.IdxAct, _post *model.Post) {
+func (s *noneCacheIndexServant) SendAction(_act core.IdxAct, _post *core.Post) {
// empty
}
diff --git a/internal/dao/cache/simple.go b/internal/dao/cache/simple.go
index afdea1be..ba674d1b 100644
--- a/internal/dao/cache/simple.go
+++ b/internal/dao/cache/simple.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package cache
import (
@@ -6,8 +10,6 @@ import (
"github.com/Masterminds/semver/v3"
"github.com/rocboss/paopao-ce/internal/core"
- "github.com/rocboss/paopao-ce/internal/model"
- "github.com/rocboss/paopao-ce/internal/model/rest"
"github.com/sirupsen/logrus"
)
@@ -20,21 +22,21 @@ type simpleCacheIndexServant struct {
ips core.IndexPostsService
indexActionCh chan core.IdxAct
- indexPosts *rest.IndexTweetsResp
+ indexPosts *core.IndexTweetList
atomicIndex atomic.Value
maxIndexSize int
checkTick *time.Ticker
expireIndexTick *time.Ticker
}
-func (s *simpleCacheIndexServant) IndexPosts(user *model.User, offset int, limit int) (*rest.IndexTweetsResp, error) {
- cacheResp := s.atomicIndex.Load().(*rest.IndexTweetsResp)
+func (s *simpleCacheIndexServant) IndexPosts(user *core.User, offset int, limit int) (*core.IndexTweetList, error) {
+ cacheResp := s.atomicIndex.Load().(*core.IndexTweetList)
end := offset + limit
if cacheResp != nil {
size := len(cacheResp.Tweets)
logrus.Debugf("simpleCacheIndexServant.IndexPosts get index posts from cache posts: %d offset:%d limit:%d start:%d, end:%d", size, offset, limit, offset, end)
if size >= end {
- return &rest.IndexTweetsResp{
+ return &core.IndexTweetList{
Tweets: cacheResp.Tweets[offset:end],
Total: cacheResp.Total,
}, nil
@@ -45,7 +47,7 @@ func (s *simpleCacheIndexServant) IndexPosts(user *model.User, offset int, limit
return s.ips.IndexPosts(user, offset, limit)
}
-func (s *simpleCacheIndexServant) SendAction(act core.IdxAct, _post *model.Post) {
+func (s *simpleCacheIndexServant) SendAction(act core.IdxAct, _post *core.Post) {
select {
case s.indexActionCh <- act:
logrus.Debugf("simpleCacheIndexServant.SendAction send indexAction by chan: %s", act)
diff --git a/internal/dao/dao.go b/internal/dao/dao.go
index 6f4a776a..d0b05c9c 100644
--- a/internal/dao/dao.go
+++ b/internal/dao/dao.go
@@ -1,15 +1,19 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package dao
import (
"sync"
+ "github.com/alimy/cfg"
"github.com/rocboss/paopao-ce/internal/core"
"github.com/rocboss/paopao-ce/internal/dao/jinzhu"
"github.com/rocboss/paopao-ce/internal/dao/sakila"
"github.com/rocboss/paopao-ce/internal/dao/search"
"github.com/rocboss/paopao-ce/internal/dao/slonik"
"github.com/rocboss/paopao-ce/internal/dao/storage"
- "github.com/rocboss/paopao-ce/pkg/cfg"
"github.com/sirupsen/logrus"
)
diff --git a/internal/dao/jinzhu/authority.go b/internal/dao/jinzhu/authority.go
index c0f59556..5932fa24 100644
--- a/internal/dao/jinzhu/authority.go
+++ b/internal/dao/jinzhu/authority.go
@@ -1,8 +1,12 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package jinzhu
import (
"github.com/rocboss/paopao-ce/internal/core"
- "github.com/rocboss/paopao-ce/internal/model"
+ "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr"
"github.com/rocboss/paopao-ce/pkg/types"
"gorm.io/gorm"
)
@@ -21,7 +25,7 @@ func newAuthorizationManageService(db *gorm.DB) core.AuthorizationManageService
}
}
-func (s *authorizationManageServant) IsAllow(user *model.User, action *core.Action) bool {
+func (s *authorizationManageServant) IsAllow(user *core.User, action *core.Action) bool {
// user is activation if had bind phone
isActivation := (len(user.Phone) != 0)
isFriend := s.isFriend(user.ID, action.UserId)
@@ -30,7 +34,7 @@ func (s *authorizationManageServant) IsAllow(user *model.User, action *core.Acti
}
func (s *authorizationManageServant) MyFriendSet(userId int64) core.FriendSet {
- ids, err := (&model.Contact{UserId: userId}).MyFriendIds(s.db)
+ ids, err := (&dbr.Contact{UserId: userId}).MyFriendIds(s.db)
if err != nil {
return core.FriendSet{}
}
@@ -43,7 +47,7 @@ func (s *authorizationManageServant) MyFriendSet(userId int64) core.FriendSet {
}
func (s *authorizationManageServant) BeFriendFilter(userId int64) core.FriendFilter {
- ids, err := (&model.Contact{FriendId: userId}).BeFriendIds(s.db)
+ ids, err := (&dbr.Contact{FriendId: userId}).BeFriendIds(s.db)
if err != nil {
return core.FriendFilter{}
}
@@ -56,12 +60,12 @@ func (s *authorizationManageServant) BeFriendFilter(userId int64) core.FriendFil
}
func (s *authorizationManageServant) BeFriendIds(userId int64) ([]int64, error) {
- return (&model.Contact{FriendId: userId}).BeFriendIds(s.db)
+ return (&dbr.Contact{FriendId: userId}).BeFriendIds(s.db)
}
func (s *authorizationManageServant) isFriend(userId int64, friendId int64) bool {
- contact, err := (&model.Contact{UserId: friendId, FriendId: userId}).GetByUserFriend(s.db)
- if err == nil || contact.Status == model.ContactStatusAgree {
+ contact, err := (&dbr.Contact{UserId: friendId, FriendId: userId}).GetByUserFriend(s.db)
+ if err == nil || contact.Status == dbr.ContactStatusAgree {
return true
}
return false
diff --git a/internal/dao/jinzhu/comments.go b/internal/dao/jinzhu/comments.go
index c15e74f3..1af9e5ce 100644
--- a/internal/dao/jinzhu/comments.go
+++ b/internal/dao/jinzhu/comments.go
@@ -1,8 +1,12 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package jinzhu
import (
"github.com/rocboss/paopao-ce/internal/core"
- "github.com/rocboss/paopao-ce/internal/model"
+ "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr"
"gorm.io/gorm"
)
@@ -31,42 +35,42 @@ func newCommentManageService(db *gorm.DB) core.CommentManageService {
}
}
-func (s *commentServant) GetComments(conditions *model.ConditionsT, offset, limit int) ([]*model.Comment, error) {
- return (&model.Comment{}).List(s.db, conditions, offset, limit)
+func (s *commentServant) GetComments(conditions *core.ConditionsT, offset, limit int) ([]*core.Comment, error) {
+ return (&dbr.Comment{}).List(s.db, conditions, offset, limit)
}
-func (s *commentServant) GetCommentByID(id int64) (*model.Comment, error) {
- comment := &model.Comment{
- Model: &model.Model{
+func (s *commentServant) GetCommentByID(id int64) (*core.Comment, error) {
+ comment := &dbr.Comment{
+ Model: &dbr.Model{
ID: id,
},
}
return comment.Get(s.db)
}
-func (s *commentServant) GetCommentReplyByID(id int64) (*model.CommentReply, error) {
- reply := &model.CommentReply{
- Model: &model.Model{
+func (s *commentServant) GetCommentReplyByID(id int64) (*core.CommentReply, error) {
+ reply := &dbr.CommentReply{
+ Model: &dbr.Model{
ID: id,
},
}
return reply.Get(s.db)
}
-func (s *commentServant) GetCommentCount(conditions *model.ConditionsT) (int64, error) {
- return (&model.Comment{}).Count(s.db, conditions)
+func (s *commentServant) GetCommentCount(conditions *core.ConditionsT) (int64, error) {
+ return (&dbr.Comment{}).Count(s.db, conditions)
}
-func (s *commentServant) GetCommentContentsByIDs(ids []int64) ([]*model.CommentContent, error) {
- commentContent := &model.CommentContent{}
- return commentContent.List(s.db, &model.ConditionsT{
+func (s *commentServant) GetCommentContentsByIDs(ids []int64) ([]*core.CommentContent, error) {
+ commentContent := &dbr.CommentContent{}
+ return commentContent.List(s.db, &dbr.ConditionsT{
"comment_id IN ?": ids,
}, 0, 0)
}
-func (s *commentServant) GetCommentRepliesByID(ids []int64) ([]*model.CommentReplyFormated, error) {
- CommentReply := &model.CommentReply{}
- replies, err := CommentReply.List(s.db, &model.ConditionsT{
+func (s *commentServant) GetCommentRepliesByID(ids []int64) ([]*core.CommentReplyFormated, error) {
+ CommentReply := &dbr.CommentReply{}
+ replies, err := CommentReply.List(s.db, &dbr.ConditionsT{
"comment_id IN ?": ids,
}, 0, 0)
@@ -83,7 +87,7 @@ func (s *commentServant) GetCommentRepliesByID(ids []int64) ([]*model.CommentRep
if err != nil {
return nil, err
}
- repliesFormated := []*model.CommentReplyFormated{}
+ repliesFormated := []*core.CommentReplyFormated{}
for _, reply := range replies {
replyFormated := reply.Format()
for _, user := range users {
@@ -101,22 +105,22 @@ func (s *commentServant) GetCommentRepliesByID(ids []int64) ([]*model.CommentRep
return repliesFormated, nil
}
-func (s *commentManageServant) DeleteComment(comment *model.Comment) error {
+func (s *commentManageServant) DeleteComment(comment *core.Comment) error {
return comment.Delete(s.db)
}
-func (s *commentManageServant) CreateComment(comment *model.Comment) (*model.Comment, error) {
+func (s *commentManageServant) CreateComment(comment *core.Comment) (*core.Comment, error) {
return comment.Create(s.db)
}
-func (s *commentManageServant) CreateCommentReply(reply *model.CommentReply) (*model.CommentReply, error) {
+func (s *commentManageServant) CreateCommentReply(reply *core.CommentReply) (*core.CommentReply, error) {
return reply.Create(s.db)
}
-func (s *commentManageServant) DeleteCommentReply(reply *model.CommentReply) error {
+func (s *commentManageServant) DeleteCommentReply(reply *core.CommentReply) error {
return reply.Delete(s.db)
}
-func (s *commentManageServant) CreateCommentContent(content *model.CommentContent) (*model.CommentContent, error) {
+func (s *commentManageServant) CreateCommentContent(content *core.CommentContent) (*core.CommentContent, error) {
return content.Create(s.db)
}
diff --git a/internal/dao/jinzhu/contacts.go b/internal/dao/jinzhu/contacts.go
index c55a94a0..c26ae4de 100644
--- a/internal/dao/jinzhu/contacts.go
+++ b/internal/dao/jinzhu/contacts.go
@@ -1,11 +1,14 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package jinzhu
import (
"time"
"github.com/rocboss/paopao-ce/internal/core"
- "github.com/rocboss/paopao-ce/internal/model"
- "github.com/rocboss/paopao-ce/internal/model/rest"
+ "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr"
"github.com/sirupsen/logrus"
"gorm.io/gorm"
)
@@ -24,14 +27,14 @@ func newContactManageService(db *gorm.DB) core.ContactManageService {
}
}
-func (s *contactManageServant) fetchOrNewContact(db *gorm.DB, userId int64, friendId int64, status int8) (*model.Contact, error) {
- contact := &model.Contact{
+func (s *contactManageServant) fetchOrNewContact(db *gorm.DB, userId int64, friendId int64, status int8) (*dbr.Contact, error) {
+ contact := &dbr.Contact{
UserId: userId,
FriendId: friendId,
}
contact, err := contact.FetchUser(db)
if err != nil {
- contact = &model.Contact{
+ contact = &dbr.Contact{
UserId: userId,
FriendId: friendId,
Status: status,
@@ -54,17 +57,17 @@ func (s *contactManageServant) RequestingFriend(userId int64, friendId int64, gr
}
}()
- contact, e := s.fetchOrNewContact(db, userId, friendId, model.ContactStatusRequesting)
+ contact, e := s.fetchOrNewContact(db, userId, friendId, dbr.ContactStatusRequesting)
if e != nil {
err = e
return
}
// 如果已经好友,啥也不干
- if contact.Status == model.ContactStatusAgree {
+ if contact.Status == dbr.ContactStatusAgree {
return nil
- } else if contact.Status == model.ContactStatusReject || contact.Status == model.ContactStatusDeleted {
- contact.Status = model.ContactStatusRequesting
+ } else if contact.Status == dbr.ContactStatusReject || contact.Status == dbr.ContactStatusDeleted {
+ contact.Status = dbr.ContactStatusRequesting
contact.IsDel = 0 // remove deleted flag if needed
if err = contact.UpdateInUnscoped(db); err != nil {
logrus.Errorf("contactManageServant.RequestingFriend update exsit contact err:%s", err)
@@ -72,13 +75,13 @@ func (s *contactManageServant) RequestingFriend(userId int64, friendId int64, gr
}
}
- msg := &model.Message{
+ msg := &dbr.Message{
SenderUserID: userId,
ReceiverUserID: friendId,
- Type: model.MsgTypeRequestingFriend,
+ Type: dbr.MsgTypeRequestingFriend,
Brief: "请求添加好友,并附言:",
Content: greetings,
- ReplyID: int64(model.ContactStatusRequesting),
+ ReplyID: int64(dbr.ContactStatusRequesting),
}
if _, err = msg.Create(db); err != nil {
logrus.Errorf("contactManageServant.RequestingFriend create message err:%s", err)
@@ -97,7 +100,7 @@ func (s *contactManageServant) AddFriend(userId int64, friendId int64) (err erro
}
}()
- contact := &model.Contact{
+ contact := &dbr.Contact{
UserId: friendId,
FriendId: userId,
}
@@ -105,23 +108,23 @@ func (s *contactManageServant) AddFriend(userId int64, friendId int64) (err erro
return
}
// 如果还不是请求好友,啥也不干
- if contact.Status != model.ContactStatusRequesting {
+ if contact.Status != dbr.ContactStatusRequesting {
logrus.Debugf("contactManageServant.AddFriend not reuesting status now so skip")
return nil
}
- contact.Status = model.ContactStatusAgree
+ contact.Status = dbr.ContactStatusAgree
if err = contact.Update(db); err != nil {
return err
}
- contact, err = s.fetchOrNewContact(db, userId, friendId, model.ContactStatusAgree)
+ contact, err = s.fetchOrNewContact(db, userId, friendId, dbr.ContactStatusAgree)
if err != nil {
return
}
// 如果已经好友,啥也不干
- if contact.Status != model.ContactStatusAgree {
- contact.Status = model.ContactStatusAgree
+ if contact.Status != dbr.ContactStatusAgree {
+ contact.Status = dbr.ContactStatusAgree
contact.IsDel = 0 // remove deleted flag
if err = contact.UpdateInUnscoped(db); err != nil {
logrus.Errorf("contactManageServant.AddFriend update contact err:%s", err)
@@ -129,8 +132,8 @@ func (s *contactManageServant) AddFriend(userId int64, friendId int64) (err erro
}
}
- args := []any{userId, friendId, friendId, userId, model.MsgTypeRequestingFriend, model.ContactStatusRequesting}
- msgs, e := (&model.Message{}).FetchBy(db, model.Predicates{
+ args := []any{userId, friendId, friendId, userId, dbr.MsgTypeRequestingFriend, dbr.ContactStatusRequesting}
+ msgs, e := (&dbr.Message{}).FetchBy(db, dbr.Predicates{
"((sender_user_id = ? AND receiver_user_id = ?) OR (sender_user_id = ? AND receiver_user_id = ?)) AND type = ? AND reply_id = ?": args,
})
if e != nil {
@@ -138,7 +141,7 @@ func (s *contactManageServant) AddFriend(userId int64, friendId int64) (err erro
return
}
for _, msg := range msgs {
- msg.ReplyID = int64(model.ContactStatusAgree)
+ msg.ReplyID = int64(dbr.ContactStatusAgree)
if err = msg.Update(db); err != nil {
return
}
@@ -156,7 +159,7 @@ func (s *contactManageServant) RejectFriend(userId int64, friendId int64) (err e
}
}()
- contact := &model.Contact{
+ contact := &dbr.Contact{
UserId: friendId,
FriendId: userId,
}
@@ -164,16 +167,16 @@ func (s *contactManageServant) RejectFriend(userId int64, friendId int64) (err e
return
}
// 如果还不是请求好友,啥也不干
- if contact.Status != model.ContactStatusRequesting {
+ if contact.Status != dbr.ContactStatusRequesting {
return nil
}
- contact.Status = model.ContactStatusReject
+ contact.Status = dbr.ContactStatusReject
if err = contact.Update(db); err != nil {
return err
}
- args := []any{friendId, userId, model.MsgTypeRequestingFriend, model.ContactStatusRequesting}
- msgs, e := (&model.Message{}).FetchBy(db, model.Predicates{
+ args := []any{friendId, userId, dbr.MsgTypeRequestingFriend, dbr.ContactStatusRequesting}
+ msgs, e := (&dbr.Message{}).FetchBy(db, dbr.Predicates{
"sender_user_id = ? AND receiver_user_id = ? AND type = ? AND reply_id = ?": args,
})
if e != nil {
@@ -181,7 +184,7 @@ func (s *contactManageServant) RejectFriend(userId int64, friendId int64) (err e
return
}
for _, msg := range msgs {
- msg.ReplyID = int64(model.ContactStatusReject)
+ msg.ReplyID = int64(dbr.ContactStatusReject)
if err = msg.Update(db); err != nil {
return
}
@@ -199,7 +202,7 @@ func (s *contactManageServant) DeleteFriend(userId int64, friendId int64) (err e
}
}()
- contact := &model.Contact{
+ contact := &dbr.Contact{
UserId: userId,
FriendId: friendId,
}
@@ -210,10 +213,10 @@ func (s *contactManageServant) DeleteFriend(userId int64, friendId int64) (err e
for _, contact := range contacts {
// 如果还不是好友,啥也不干
- if contact.Status != model.ContactStatusAgree {
+ if contact.Status != dbr.ContactStatusAgree {
continue
}
- contact.Status = model.ContactStatusDeleted
+ contact.Status = dbr.ContactStatusDeleted
contact.DeletedOn = time.Now().Unix()
contact.IsDel = 1
if err = contact.Update(db); err != nil {
@@ -223,11 +226,11 @@ func (s *contactManageServant) DeleteFriend(userId int64, friendId int64) (err e
return nil
}
-func (s *contactManageServant) GetContacts(userId int64, offset int, limit int) (*rest.ContactsResp, error) {
- contact := &model.Contact{}
- condition := model.ConditionsT{
+func (s *contactManageServant) GetContacts(userId int64, offset int, limit int) (*core.ContactList, error) {
+ contact := &dbr.Contact{}
+ condition := dbr.ConditionsT{
"user_id": userId,
- "status": model.ContactStatusAgree,
+ "status": dbr.ContactStatusAgree,
}
contacts, err := contact.List(s.db, condition, offset, limit)
if err != nil {
@@ -237,13 +240,13 @@ func (s *contactManageServant) GetContacts(userId int64, offset int, limit int)
if err != nil {
return nil, err
}
- resp := &rest.ContactsResp{
- Contacts: make([]rest.ContactItem, 0, len(contacts)),
+ resp := &core.ContactList{
+ Contacts: make([]core.ContactItem, 0, len(contacts)),
Total: total,
}
for _, c := range contacts {
if c.User != nil {
- resp.Contacts = append(resp.Contacts, rest.ContactItem{
+ resp.Contacts = append(resp.Contacts, core.ContactItem{
UserId: c.FriendId,
UserName: c.User.Username,
Nickname: c.User.Nickname,
@@ -256,12 +259,12 @@ func (s *contactManageServant) GetContacts(userId int64, offset int, limit int)
}
func (s *contactManageServant) IsFriend(userId int64, friendId int64) bool {
- contact := &model.Contact{
+ contact := &dbr.Contact{
UserId: friendId,
FriendId: userId,
}
contact, err := contact.GetByUserFriend(s.db)
- if err == nil && contact.Status == model.ContactStatusAgree {
+ if err == nil && contact.Status == dbr.ContactStatusAgree {
return true
}
return false
diff --git a/internal/model/attachment.go b/internal/dao/jinzhu/dbr/attachment.go
similarity index 65%
rename from internal/model/attachment.go
rename to internal/dao/jinzhu/dbr/attachment.go
index 0c748b00..b62a5d8b 100644
--- a/internal/model/attachment.go
+++ b/internal/dao/jinzhu/dbr/attachment.go
@@ -1,13 +1,17 @@
-package model
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package dbr
import "gorm.io/gorm"
type AttachmentType int
const (
- ATTACHMENT_TYPE_IMAGE AttachmentType = iota + 1
- ATTACHMENT_TYPE_VIDEO
- ATTACHMENT_TYPE_OTHER
+ AttachmentTypeImage AttachmentType = iota + 1
+ AttachmentTypeVideo
+ AttachmentTypeOther
)
type Attachment struct {
diff --git a/internal/model/captcha.go b/internal/dao/jinzhu/dbr/captcha.go
similarity index 82%
rename from internal/model/captcha.go
rename to internal/dao/jinzhu/dbr/captcha.go
index 210cc691..4567d4b3 100644
--- a/internal/model/captcha.go
+++ b/internal/dao/jinzhu/dbr/captcha.go
@@ -1,4 +1,8 @@
-package model
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package dbr
import "gorm.io/gorm"
diff --git a/internal/model/comment.go b/internal/dao/jinzhu/dbr/comment.go
similarity index 94%
rename from internal/model/comment.go
rename to internal/dao/jinzhu/dbr/comment.go
index 72494b53..80192df7 100644
--- a/internal/model/comment.go
+++ b/internal/dao/jinzhu/dbr/comment.go
@@ -1,4 +1,8 @@
-package model
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package dbr
import (
"time"
diff --git a/internal/model/comment_content.go b/internal/dao/jinzhu/dbr/comment_content.go
similarity index 85%
rename from internal/model/comment_content.go
rename to internal/dao/jinzhu/dbr/comment_content.go
index b7d42dfd..778f113a 100644
--- a/internal/model/comment_content.go
+++ b/internal/dao/jinzhu/dbr/comment_content.go
@@ -1,4 +1,8 @@
-package model
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package dbr
import (
"time"
@@ -47,7 +51,7 @@ func (c *CommentContent) Create(db *gorm.DB) (*CommentContent, error) {
}
func (c *CommentContent) MediaContentsByCommentId(db *gorm.DB, commentIds []int64) (contents []string, err error) {
- err = db.Model(c).Where("comment_id IN ? AND type = ?", commentIds, CONTENT_TYPE_IMAGE).Select("content").Find(&contents).Error
+ err = db.Model(c).Where("comment_id IN ? AND type = ?", commentIds, ContentTypeImage).Select("content").Find(&contents).Error
return
}
diff --git a/internal/model/comment_reply.go b/internal/dao/jinzhu/dbr/comment_reply.go
similarity index 94%
rename from internal/model/comment_reply.go
rename to internal/dao/jinzhu/dbr/comment_reply.go
index fd22702f..fe527be5 100644
--- a/internal/model/comment_reply.go
+++ b/internal/dao/jinzhu/dbr/comment_reply.go
@@ -1,4 +1,8 @@
-package model
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package dbr
import (
"time"
diff --git a/internal/model/contact.go b/internal/dao/jinzhu/dbr/contact.go
similarity index 95%
rename from internal/model/contact.go
rename to internal/dao/jinzhu/dbr/contact.go
index 14049f77..e8c12bd0 100644
--- a/internal/model/contact.go
+++ b/internal/dao/jinzhu/dbr/contact.go
@@ -1,4 +1,8 @@
-package model
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package dbr
import (
"github.com/sirupsen/logrus"
diff --git a/internal/model/message.go b/internal/dao/jinzhu/dbr/message.go
similarity index 95%
rename from internal/model/message.go
rename to internal/dao/jinzhu/dbr/message.go
index c1277cf7..6c952bae 100644
--- a/internal/model/message.go
+++ b/internal/dao/jinzhu/dbr/message.go
@@ -1,4 +1,8 @@
-package model
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package dbr
import "gorm.io/gorm"
diff --git a/internal/model/model.go b/internal/dao/jinzhu/dbr/model.go
similarity index 83%
rename from internal/model/model.go
rename to internal/dao/jinzhu/dbr/model.go
index 99bc8296..75e66561 100644
--- a/internal/model/model.go
+++ b/internal/dao/jinzhu/dbr/model.go
@@ -1,4 +1,8 @@
-package model
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package dbr
import (
"time"
diff --git a/internal/model/post.go b/internal/dao/jinzhu/dbr/post.go
similarity index 97%
rename from internal/model/post.go
rename to internal/dao/jinzhu/dbr/post.go
index ae428a9a..a47dedfc 100644
--- a/internal/model/post.go
+++ b/internal/dao/jinzhu/dbr/post.go
@@ -1,4 +1,8 @@
-package model
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package dbr
import (
"strings"
diff --git a/internal/model/post_attachment_bill.go b/internal/dao/jinzhu/dbr/post_attachment_bill.go
similarity index 81%
rename from internal/model/post_attachment_bill.go
rename to internal/dao/jinzhu/dbr/post_attachment_bill.go
index 8ee7aae6..7bdd812f 100644
--- a/internal/model/post_attachment_bill.go
+++ b/internal/dao/jinzhu/dbr/post_attachment_bill.go
@@ -1,4 +1,8 @@
-package model
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package dbr
import "gorm.io/gorm"
diff --git a/internal/model/post_collection.go b/internal/dao/jinzhu/dbr/post_collection.go
similarity index 93%
rename from internal/model/post_collection.go
rename to internal/dao/jinzhu/dbr/post_collection.go
index 0ea0cb29..04ca2647 100644
--- a/internal/model/post_collection.go
+++ b/internal/dao/jinzhu/dbr/post_collection.go
@@ -1,4 +1,8 @@
-package model
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package dbr
import (
"time"
diff --git a/internal/model/post_content.go b/internal/dao/jinzhu/dbr/post_content.go
similarity index 83%
rename from internal/model/post_content.go
rename to internal/dao/jinzhu/dbr/post_content.go
index b301de62..672cc57e 100644
--- a/internal/model/post_content.go
+++ b/internal/dao/jinzhu/dbr/post_content.go
@@ -1,4 +1,8 @@
-package model
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package dbr
import (
"time"
@@ -7,27 +11,26 @@ import (
)
// 类型,1标题,2文字段落,3图片地址,4视频地址,5语音地址,6链接地址,7附件资源
-
type PostContentT int
const (
- CONTENT_TYPE_TITLE PostContentT = iota + 1
- CONTENT_TYPE_TEXT
- CONTENT_TYPE_IMAGE
- CONTENT_TYPE_VIDEO
- CONTENT_TYPE_AUDIO
- CONTENT_TYPE_LINK
- CONTENT_TYPE_ATTACHMENT
- CONTENT_TYPE_CHARGE_ATTACHMENT
+ ContentTypeTitle PostContentT = iota + 1
+ ContentTypeText
+ ContentTypeImage
+ ContentTypeVideo
+ ContentTypeAudio
+ ContentTypeLink
+ ContentTypeAttachment
+ ContentTypeChargeAttachment
)
var (
mediaContentType = []PostContentT{
- CONTENT_TYPE_IMAGE,
- CONTENT_TYPE_VIDEO,
- CONTENT_TYPE_AUDIO,
- CONTENT_TYPE_ATTACHMENT,
- CONTENT_TYPE_CHARGE_ATTACHMENT,
+ ContentTypeImage,
+ ContentTypeVideo,
+ ContentTypeAudio,
+ ContentTypeAttachment,
+ ContentTypeChargeAttachment,
}
)
diff --git a/internal/model/post_star.go b/internal/dao/jinzhu/dbr/post_star.go
similarity index 93%
rename from internal/model/post_star.go
rename to internal/dao/jinzhu/dbr/post_star.go
index 3846a9c2..45c48f45 100644
--- a/internal/model/post_star.go
+++ b/internal/dao/jinzhu/dbr/post_star.go
@@ -1,4 +1,8 @@
-package model
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package dbr
import (
"time"
diff --git a/internal/model/tag.go b/internal/dao/jinzhu/dbr/tag.go
similarity index 92%
rename from internal/model/tag.go
rename to internal/dao/jinzhu/dbr/tag.go
index 34bb64f9..5193df26 100644
--- a/internal/model/tag.go
+++ b/internal/dao/jinzhu/dbr/tag.go
@@ -1,4 +1,8 @@
-package model
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package dbr
import (
"time"
diff --git a/internal/model/user.go b/internal/dao/jinzhu/dbr/user.go
similarity index 92%
rename from internal/model/user.go
rename to internal/dao/jinzhu/dbr/user.go
index 39c52d79..a10d5432 100644
--- a/internal/model/user.go
+++ b/internal/dao/jinzhu/dbr/user.go
@@ -1,4 +1,8 @@
-package model
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package dbr
import "gorm.io/gorm"
diff --git a/internal/model/wallet_recharge.go b/internal/dao/jinzhu/dbr/wallet_recharge.go
similarity index 80%
rename from internal/model/wallet_recharge.go
rename to internal/dao/jinzhu/dbr/wallet_recharge.go
index bfb3bc6f..14601cb0 100644
--- a/internal/model/wallet_recharge.go
+++ b/internal/dao/jinzhu/dbr/wallet_recharge.go
@@ -1,4 +1,8 @@
-package model
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package dbr
import "gorm.io/gorm"
diff --git a/internal/model/wallet_statement.go b/internal/dao/jinzhu/dbr/wallet_statement.go
similarity index 91%
rename from internal/model/wallet_statement.go
rename to internal/dao/jinzhu/dbr/wallet_statement.go
index 163e2430..890e34ec 100644
--- a/internal/model/wallet_statement.go
+++ b/internal/dao/jinzhu/dbr/wallet_statement.go
@@ -1,4 +1,8 @@
-package model
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package dbr
import "gorm.io/gorm"
diff --git a/internal/dao/jinzhu/index.go b/internal/dao/jinzhu/index.go
index 31712c61..7548de49 100644
--- a/internal/dao/jinzhu/index.go
+++ b/internal/dao/jinzhu/index.go
@@ -1,9 +1,12 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package jinzhu
import (
"github.com/rocboss/paopao-ce/internal/core"
- "github.com/rocboss/paopao-ce/internal/model"
- "github.com/rocboss/paopao-ce/internal/model/rest"
+ "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr"
"github.com/sirupsen/logrus"
"gorm.io/gorm"
)
@@ -40,20 +43,20 @@ func newSimpleIndexPostsService(db *gorm.DB) core.IndexPostsService {
}
// IndexPosts 根据userId查询广场推文列表,简单做到不同用户的主页都是不同的;
-func (s *indexPostsServant) IndexPosts(user *model.User, offset int, limit int) (*rest.IndexTweetsResp, error) {
- predicates := model.Predicates{
+func (s *indexPostsServant) IndexPosts(user *core.User, offset int, limit int) (*core.IndexTweetList, error) {
+ predicates := dbr.Predicates{
"ORDER": []any{"is_top DESC, latest_replied_on DESC"},
}
if user == nil {
- predicates["visibility = ?"] = []any{model.PostVisitPublic}
+ predicates["visibility = ?"] = []any{dbr.PostVisitPublic}
} else if !user.IsAdmin {
friendIds, _ := s.ams.BeFriendIds(user.ID)
friendIds = append(friendIds, user.ID)
- args := []any{model.PostVisitPublic, model.PostVisitPrivate, user.ID, model.PostVisitFriend, friendIds}
+ args := []any{dbr.PostVisitPublic, dbr.PostVisitPrivate, user.ID, dbr.PostVisitFriend, friendIds}
predicates["visibility = ? OR (visibility = ? AND user_id = ?) OR (visibility = ? AND user_id IN ?)"] = args
}
- posts, err := (&model.Post{}).Fetch(s.db, predicates, offset, limit)
+ posts, err := (&dbr.Post{}).Fetch(s.db, predicates, offset, limit)
if err != nil {
logrus.Debugf("gormIndexPostsServant.IndexPosts err: %v", err)
return nil, err
@@ -63,25 +66,25 @@ func (s *indexPostsServant) IndexPosts(user *model.User, offset int, limit int)
return nil, err
}
- total, err := (&model.Post{}).CountBy(s.db, predicates)
+ total, err := (&dbr.Post{}).CountBy(s.db, predicates)
if err != nil {
return nil, err
}
- return &rest.IndexTweetsResp{
+ return &core.IndexTweetList{
Tweets: formatPosts,
Total: total,
}, nil
}
// simpleCacheIndexGetPosts simpleCacheIndex 专属获取广场推文列表函数
-func (s *simpleIndexPostsServant) IndexPosts(_user *model.User, offset int, limit int) (*rest.IndexTweetsResp, error) {
- predicates := model.Predicates{
- "visibility = ?": []any{model.PostVisitPublic},
+func (s *simpleIndexPostsServant) IndexPosts(_user *core.User, offset int, limit int) (*core.IndexTweetList, error) {
+ predicates := dbr.Predicates{
+ "visibility = ?": []any{dbr.PostVisitPublic},
"ORDER": []any{"is_top DESC, latest_replied_on DESC"},
}
- posts, err := (&model.Post{}).Fetch(s.db, predicates, offset, limit)
+ posts, err := (&dbr.Post{}).Fetch(s.db, predicates, offset, limit)
if err != nil {
logrus.Debugf("gormSimpleIndexPostsServant.IndexPosts err: %v", err)
return nil, err
@@ -92,12 +95,12 @@ func (s *simpleIndexPostsServant) IndexPosts(_user *model.User, offset int, limi
return nil, err
}
- total, err := (&model.Post{}).CountBy(s.db, predicates)
+ total, err := (&dbr.Post{}).CountBy(s.db, predicates)
if err != nil {
return nil, err
}
- return &rest.IndexTweetsResp{
+ return &core.IndexTweetList{
Tweets: formatPosts,
Total: total,
}, nil
diff --git a/internal/dao/jinzhu/jinzhu.go b/internal/dao/jinzhu/jinzhu.go
index 9f5e1c66..dd20aeea 100644
--- a/internal/dao/jinzhu/jinzhu.go
+++ b/internal/dao/jinzhu/jinzhu.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
// Core service implement base gorm+mysql/postgresql/sqlite3.
// Jinzhu is the primary developer of gorm so use his name as
// package name as a saluter.
@@ -6,11 +10,11 @@ package jinzhu
import (
"github.com/Masterminds/semver/v3"
+ "github.com/alimy/cfg"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/core"
"github.com/rocboss/paopao-ce/internal/dao/cache"
"github.com/rocboss/paopao-ce/internal/dao/security"
- "github.com/rocboss/paopao-ce/pkg/cfg"
"github.com/sirupsen/logrus"
)
diff --git a/internal/dao/jinzhu/messages.go b/internal/dao/jinzhu/messages.go
index 3e282776..32edaac2 100644
--- a/internal/dao/jinzhu/messages.go
+++ b/internal/dao/jinzhu/messages.go
@@ -1,8 +1,12 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package jinzhu
import (
"github.com/rocboss/paopao-ce/internal/core"
- "github.com/rocboss/paopao-ce/internal/model"
+ "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr"
"gorm.io/gorm"
)
@@ -20,37 +24,37 @@ func newMessageService(db *gorm.DB) core.MessageService {
}
}
-func (d *messageServant) CreateMessage(msg *model.Message) (*model.Message, error) {
+func (d *messageServant) CreateMessage(msg *core.Message) (*core.Message, error) {
return msg.Create(d.db)
}
func (d *messageServant) GetUnreadCount(userID int64) (int64, error) {
- return (&model.Message{}).Count(d.db, &model.ConditionsT{
+ return (&dbr.Message{}).Count(d.db, &dbr.ConditionsT{
"receiver_user_id": userID,
- "is_read": model.MsgStatusUnread,
+ "is_read": dbr.MsgStatusUnread,
})
}
-func (d *messageServant) GetMessageByID(id int64) (*model.Message, error) {
- return (&model.Message{
- Model: &model.Model{
+func (d *messageServant) GetMessageByID(id int64) (*core.Message, error) {
+ return (&dbr.Message{
+ Model: &dbr.Model{
ID: id,
},
}).Get(d.db)
}
-func (d *messageServant) ReadMessage(message *model.Message) error {
+func (d *messageServant) ReadMessage(message *core.Message) error {
message.IsRead = 1
return message.Update(d.db)
}
-func (d *messageServant) GetMessages(conditions *model.ConditionsT, offset, limit int) ([]*model.MessageFormated, error) {
- messages, err := (&model.Message{}).List(d.db, conditions, offset, limit)
+func (d *messageServant) GetMessages(conditions *core.ConditionsT, offset, limit int) ([]*core.MessageFormated, error) {
+ messages, err := (&dbr.Message{}).List(d.db, conditions, offset, limit)
if err != nil {
return nil, err
}
- mfs := []*model.MessageFormated{}
+ mfs := []*dbr.MessageFormated{}
for _, message := range messages {
mf := message.Format()
mfs = append(mfs, mf)
@@ -59,6 +63,6 @@ func (d *messageServant) GetMessages(conditions *model.ConditionsT, offset, limi
return mfs, nil
}
-func (d *messageServant) GetMessageCount(conditions *model.ConditionsT) (int64, error) {
- return (&model.Message{}).Count(d.db, conditions)
+func (d *messageServant) GetMessageCount(conditions *core.ConditionsT) (int64, error) {
+ return (&dbr.Message{}).Count(d.db, conditions)
}
diff --git a/internal/dao/jinzhu/security.go b/internal/dao/jinzhu/security.go
index dfbe2c74..49f66074 100644
--- a/internal/dao/jinzhu/security.go
+++ b/internal/dao/jinzhu/security.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package jinzhu
import (
@@ -10,7 +14,7 @@ import (
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/core"
- "github.com/rocboss/paopao-ce/internal/model"
+ "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr"
"github.com/rocboss/paopao-ce/pkg/json"
"gopkg.in/resty.v1"
"gorm.io/gorm"
@@ -36,14 +40,14 @@ type juhePhoneCaptchaRsp struct {
}
// 获取最新短信验证码
-func (s *securityServant) GetLatestPhoneCaptcha(phone string) (*model.Captcha, error) {
- return (&model.Captcha{
+func (s *securityServant) GetLatestPhoneCaptcha(phone string) (*core.Captcha, error) {
+ return (&dbr.Captcha{
Phone: phone,
}).Get(s.db)
}
// 更新短信验证码
-func (s *securityServant) UsePhoneCaptcha(captcha *model.Captcha) error {
+func (s *securityServant) UsePhoneCaptcha(captcha *core.Captcha) error {
captcha.UseTimes++
return captcha.Update(s.db)
}
@@ -82,7 +86,7 @@ func (s *securityServant) SendPhoneCaptcha(phone string) error {
}
// 写入表
- captchaModel := &model.Captcha{
+ captchaModel := &dbr.Captcha{
Phone: phone,
Captcha: strconv.Itoa(captcha),
ExpiredOn: time.Now().Add(time.Minute * time.Duration(m)).Unix(),
diff --git a/internal/dao/jinzhu/topics.go b/internal/dao/jinzhu/topics.go
index 0524b71b..d5ce70a9 100644
--- a/internal/dao/jinzhu/topics.go
+++ b/internal/dao/jinzhu/topics.go
@@ -1,10 +1,14 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package jinzhu
import (
"strings"
"github.com/rocboss/paopao-ce/internal/core"
- "github.com/rocboss/paopao-ce/internal/model"
+ "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr"
"gorm.io/gorm"
)
@@ -22,28 +26,28 @@ func newTopicService(db *gorm.DB) core.TopicService {
}
}
-func (s *topicServant) CreateTag(tag *model.Tag) (*model.Tag, error) {
+func (s *topicServant) CreateTag(tag *core.Tag) (*core.Tag, error) {
return createTag(s.db, tag)
}
-func (s *topicServant) DeleteTag(tag *model.Tag) error {
+func (s *topicServant) DeleteTag(tag *core.Tag) error {
return deleteTag(s.db, tag)
}
-func (s *topicServant) GetTags(conditions *model.ConditionsT, offset, limit int) ([]*model.Tag, error) {
- return (&model.Tag{}).List(s.db, conditions, offset, limit)
+func (s *topicServant) GetTags(conditions *core.ConditionsT, offset, limit int) ([]*core.Tag, error) {
+ return (&dbr.Tag{}).List(s.db, conditions, offset, limit)
}
-func (s *topicServant) GetTagsByKeyword(keyword string) ([]*model.Tag, error) {
- tag := &model.Tag{}
+func (s *topicServant) GetTagsByKeyword(keyword string) ([]*core.Tag, error) {
+ tag := &dbr.Tag{}
keyword = "%" + strings.Trim(keyword, " ") + "%"
if keyword == "%%" {
- return tag.List(s.db, &model.ConditionsT{
+ return tag.List(s.db, &dbr.ConditionsT{
"ORDER": "quote_num DESC",
}, 0, 6)
} else {
- return tag.List(s.db, &model.ConditionsT{
+ return tag.List(s.db, &dbr.ConditionsT{
"tag LIKE ?": keyword,
"ORDER": "quote_num DESC",
}, 0, 6)
diff --git a/internal/dao/jinzhu/tweets.go b/internal/dao/jinzhu/tweets.go
index 12e6f21c..186b7280 100644
--- a/internal/dao/jinzhu/tweets.go
+++ b/internal/dao/jinzhu/tweets.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package jinzhu
import (
@@ -5,7 +9,7 @@ import (
"time"
"github.com/rocboss/paopao-ce/internal/core"
- "github.com/rocboss/paopao-ce/internal/model"
+ "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr"
"gorm.io/gorm"
)
@@ -48,7 +52,7 @@ func newTweetHelpService(db *gorm.DB) core.TweetHelpService {
}
// MergePosts post数据整合
-func (s *tweetHelpServant) MergePosts(posts []*model.Post) ([]*model.PostFormated, error) {
+func (s *tweetHelpServant) MergePosts(posts []*core.Post) ([]*core.PostFormated, error) {
postIds := make([]int64, 0, len(posts))
userIds := make([]int64, 0, len(posts))
for _, post := range posts {
@@ -66,18 +70,18 @@ func (s *tweetHelpServant) MergePosts(posts []*model.Post) ([]*model.PostFormate
return nil, err
}
- userMap := make(map[int64]*model.UserFormated, len(users))
+ userMap := make(map[int64]*dbr.UserFormated, len(users))
for _, user := range users {
userMap[user.ID] = user.Format()
}
- contentMap := make(map[int64][]*model.PostContentFormated, len(postContents))
+ contentMap := make(map[int64][]*dbr.PostContentFormated, len(postContents))
for _, content := range postContents {
contentMap[content.PostID] = append(contentMap[content.PostID], content.Format())
}
// 数据整合
- postsFormated := make([]*model.PostFormated, 0, len(posts))
+ postsFormated := make([]*dbr.PostFormated, 0, len(posts))
for _, post := range posts {
postFormated := post.Format()
postFormated.User = userMap[post.UserID]
@@ -88,7 +92,7 @@ func (s *tweetHelpServant) MergePosts(posts []*model.Post) ([]*model.PostFormate
}
// RevampPosts post数据整形修复
-func (s *tweetHelpServant) RevampPosts(posts []*model.PostFormated) ([]*model.PostFormated, error) {
+func (s *tweetHelpServant) RevampPosts(posts []*core.PostFormated) ([]*core.PostFormated, error) {
postIds := make([]int64, 0, len(posts))
userIds := make([]int64, 0, len(posts))
for _, post := range posts {
@@ -106,12 +110,12 @@ func (s *tweetHelpServant) RevampPosts(posts []*model.PostFormated) ([]*model.Po
return nil, err
}
- userMap := make(map[int64]*model.UserFormated, len(users))
+ userMap := make(map[int64]*dbr.UserFormated, len(users))
for _, user := range users {
userMap[user.ID] = user.Format()
}
- contentMap := make(map[int64][]*model.PostContentFormated, len(postContents))
+ contentMap := make(map[int64][]*dbr.PostContentFormated, len(postContents))
for _, content := range postContents {
contentMap[content.PostID] = append(contentMap[content.PostID], content.Format())
}
@@ -124,23 +128,23 @@ func (s *tweetHelpServant) RevampPosts(posts []*model.PostFormated) ([]*model.Po
return posts, nil
}
-func (s *tweetHelpServant) getPostContentsByIDs(ids []int64) ([]*model.PostContent, error) {
- return (&model.PostContent{}).List(s.db, &model.ConditionsT{
+func (s *tweetHelpServant) getPostContentsByIDs(ids []int64) ([]*dbr.PostContent, error) {
+ return (&dbr.PostContent{}).List(s.db, &dbr.ConditionsT{
"post_id IN ?": ids,
"ORDER": "sort ASC",
}, 0, 0)
}
-func (s *tweetHelpServant) getUsersByIDs(ids []int64) ([]*model.User, error) {
- user := &model.User{}
+func (s *tweetHelpServant) getUsersByIDs(ids []int64) ([]*dbr.User, error) {
+ user := &dbr.User{}
- return user.List(s.db, &model.ConditionsT{
+ return user.List(s.db, &dbr.ConditionsT{
"id IN ?": ids,
}, 0, 0)
}
-func (s *tweetManageServant) CreatePostCollection(postID, userID int64) (*model.PostCollection, error) {
- collection := &model.PostCollection{
+func (s *tweetManageServant) CreatePostCollection(postID, userID int64) (*core.PostCollection, error) {
+ collection := &dbr.PostCollection{
PostID: postID,
UserID: userID,
}
@@ -148,19 +152,19 @@ func (s *tweetManageServant) CreatePostCollection(postID, userID int64) (*model.
return collection.Create(s.db)
}
-func (s *tweetManageServant) DeletePostCollection(p *model.PostCollection) error {
+func (s *tweetManageServant) DeletePostCollection(p *core.PostCollection) error {
return p.Delete(s.db)
}
-func (s *tweetManageServant) CreatePostContent(content *model.PostContent) (*model.PostContent, error) {
+func (s *tweetManageServant) CreatePostContent(content *core.PostContent) (*core.PostContent, error) {
return content.Create(s.db)
}
-func (s *tweetManageServant) CreateAttachment(attachment *model.Attachment) (*model.Attachment, error) {
+func (s *tweetManageServant) CreateAttachment(attachment *core.Attachment) (*core.Attachment, error) {
return attachment.Create(s.db)
}
-func (s *tweetManageServant) CreatePost(post *model.Post) (*model.Post, error) {
+func (s *tweetManageServant) CreatePost(post *core.Post) (*core.Post, error) {
post.LatestRepliedOn = time.Now().Unix()
p, err := post.Create(s.db)
if err != nil {
@@ -170,11 +174,11 @@ func (s *tweetManageServant) CreatePost(post *model.Post) (*model.Post, error) {
return p, nil
}
-func (s *tweetManageServant) DeletePost(post *model.Post) ([]string, error) {
+func (s *tweetManageServant) DeletePost(post *core.Post) ([]string, error) {
var mediaContents []string
postId := post.ID
- postContent := &model.PostContent{}
+ postContent := &dbr.PostContent{}
err := s.db.Transaction(
func(tx *gorm.DB) error {
if contents, err := postContent.MediaContentsByPostId(tx, postId); err == nil {
@@ -218,8 +222,8 @@ func (s *tweetManageServant) DeletePost(post *model.Post) ([]string, error) {
}
func (s *tweetManageServant) deleteCommentByPostId(db *gorm.DB, postId int64) ([]string, error) {
- comment := &model.Comment{}
- commentContent := &model.CommentContent{}
+ comment := &dbr.Comment{}
+ commentContent := &dbr.CommentContent{}
// 获取推文的所有评论id
commentIds, err := comment.CommentIdsByPostId(db, postId)
@@ -244,19 +248,19 @@ func (s *tweetManageServant) deleteCommentByPostId(db *gorm.DB, postId int64) ([
}
// 删评论的评论
- if err = (&model.CommentReply{}).DeleteByCommentIds(db, commentIds); err != nil {
+ if err = (&dbr.CommentReply{}).DeleteByCommentIds(db, commentIds); err != nil {
return nil, err
}
return mediaContents, nil
}
-func (s *tweetManageServant) LockPost(post *model.Post) error {
+func (s *tweetManageServant) LockPost(post *core.Post) error {
post.IsLock = 1 - post.IsLock
return post.Update(s.db)
}
-func (s *tweetManageServant) StickPost(post *model.Post) error {
+func (s *tweetManageServant) StickPost(post *core.Post) error {
post.IsTop = 1 - post.IsTop
if err := post.Update(s.db); err != nil {
return err
@@ -265,7 +269,7 @@ func (s *tweetManageServant) StickPost(post *model.Post) error {
return nil
}
-func (s *tweetManageServant) VisiblePost(post *model.Post, visibility model.PostVisibleT) error {
+func (s *tweetManageServant) VisiblePost(post *core.Post, visibility core.PostVisibleT) error {
oldVisibility := post.Visibility
post.Visibility = visibility
// TODO: 这个判断是否可以不要呢
@@ -273,7 +277,7 @@ func (s *tweetManageServant) VisiblePost(post *model.Post, visibility model.Post
return nil
}
// 私密推文 特殊处理
- if visibility == model.PostVisitPrivate {
+ if visibility == dbr.PostVisitPrivate {
// 强制取消置顶
// TODO: 置顶推文用户是否有权设置成私密? 后续完善
post.IsTop = 0
@@ -288,14 +292,14 @@ func (s *tweetManageServant) VisiblePost(post *model.Post, visibility model.Post
// tag处理
tags := strings.Split(post.Tags, ",")
for _, t := range tags {
- tag := &model.Tag{
+ tag := &dbr.Tag{
Tag: t,
}
// TODO: 暂时宽松不处理错误,这里或许可以有优化,后续完善
- if oldVisibility == model.PostVisitPrivate {
+ if oldVisibility == dbr.PostVisitPrivate {
// 从私密转为非私密才需要重新创建tag
createTag(db, tag)
- } else if visibility == model.PostVisitPrivate {
+ } else if visibility == dbr.PostVisitPrivate {
// 从非私密转为私密才需要删除tag
deleteTag(db, tag)
}
@@ -305,7 +309,7 @@ func (s *tweetManageServant) VisiblePost(post *model.Post, visibility model.Post
return nil
}
-func (s *tweetManageServant) UpdatePost(post *model.Post) error {
+func (s *tweetManageServant) UpdatePost(post *core.Post) error {
if err := post.Update(s.db); err != nil {
return err
}
@@ -313,104 +317,104 @@ func (s *tweetManageServant) UpdatePost(post *model.Post) error {
return nil
}
-func (s *tweetManageServant) CreatePostStar(postID, userID int64) (*model.PostStar, error) {
- star := &model.PostStar{
+func (s *tweetManageServant) CreatePostStar(postID, userID int64) (*core.PostStar, error) {
+ star := &dbr.PostStar{
PostID: postID,
UserID: userID,
}
return star.Create(s.db)
}
-func (s *tweetManageServant) DeletePostStar(p *model.PostStar) error {
+func (s *tweetManageServant) DeletePostStar(p *core.PostStar) error {
return p.Delete(s.db)
}
-func (s *tweetServant) GetPostByID(id int64) (*model.Post, error) {
- post := &model.Post{
- Model: &model.Model{
+func (s *tweetServant) GetPostByID(id int64) (*core.Post, error) {
+ post := &dbr.Post{
+ Model: &dbr.Model{
ID: id,
},
}
return post.Get(s.db)
}
-func (s *tweetServant) GetPosts(conditions *model.ConditionsT, offset, limit int) ([]*model.Post, error) {
- return (&model.Post{}).List(s.db, conditions, offset, limit)
+func (s *tweetServant) GetPosts(conditions *core.ConditionsT, offset, limit int) ([]*core.Post, error) {
+ return (&dbr.Post{}).List(s.db, conditions, offset, limit)
}
-func (s *tweetServant) GetPostCount(conditions *model.ConditionsT) (int64, error) {
- return (&model.Post{}).Count(s.db, conditions)
+func (s *tweetServant) GetPostCount(conditions *core.ConditionsT) (int64, error) {
+ return (&dbr.Post{}).Count(s.db, conditions)
}
-func (s *tweetServant) GetUserPostStar(postID, userID int64) (*model.PostStar, error) {
- star := &model.PostStar{
+func (s *tweetServant) GetUserPostStar(postID, userID int64) (*core.PostStar, error) {
+ star := &dbr.PostStar{
PostID: postID,
UserID: userID,
}
return star.Get(s.db)
}
-func (s *tweetServant) GetUserPostStars(userID int64, offset, limit int) ([]*model.PostStar, error) {
- star := &model.PostStar{
+func (s *tweetServant) GetUserPostStars(userID int64, offset, limit int) ([]*core.PostStar, error) {
+ star := &dbr.PostStar{
UserID: userID,
}
- return star.List(s.db, &model.ConditionsT{
+ return star.List(s.db, &dbr.ConditionsT{
"ORDER": s.db.NamingStrategy.TableName("PostStar") + ".id DESC",
}, offset, limit)
}
func (s *tweetServant) GetUserPostStarCount(userID int64) (int64, error) {
- star := &model.PostStar{
+ star := &dbr.PostStar{
UserID: userID,
}
- return star.Count(s.db, &model.ConditionsT{})
+ return star.Count(s.db, &dbr.ConditionsT{})
}
-func (s *tweetServant) GetUserPostCollection(postID, userID int64) (*model.PostCollection, error) {
- star := &model.PostCollection{
+func (s *tweetServant) GetUserPostCollection(postID, userID int64) (*core.PostCollection, error) {
+ star := &dbr.PostCollection{
PostID: postID,
UserID: userID,
}
return star.Get(s.db)
}
-func (s *tweetServant) GetUserPostCollections(userID int64, offset, limit int) ([]*model.PostCollection, error) {
- collection := &model.PostCollection{
+func (s *tweetServant) GetUserPostCollections(userID int64, offset, limit int) ([]*core.PostCollection, error) {
+ collection := &dbr.PostCollection{
UserID: userID,
}
- return collection.List(s.db, &model.ConditionsT{
+ return collection.List(s.db, &dbr.ConditionsT{
"ORDER": s.db.NamingStrategy.TableName("PostCollection") + ".id DESC",
}, offset, limit)
}
func (s *tweetServant) GetUserPostCollectionCount(userID int64) (int64, error) {
- collection := &model.PostCollection{
+ collection := &dbr.PostCollection{
UserID: userID,
}
- return collection.Count(s.db, &model.ConditionsT{})
+ return collection.Count(s.db, &dbr.ConditionsT{})
}
-func (s *tweetServant) GetUserWalletBills(userID int64, offset, limit int) ([]*model.WalletStatement, error) {
- statement := &model.WalletStatement{
+func (s *tweetServant) GetUserWalletBills(userID int64, offset, limit int) ([]*core.WalletStatement, error) {
+ statement := &dbr.WalletStatement{
UserID: userID,
}
- return statement.List(s.db, &model.ConditionsT{
+ return statement.List(s.db, &dbr.ConditionsT{
"ORDER": "id DESC",
}, offset, limit)
}
func (s *tweetServant) GetUserWalletBillCount(userID int64) (int64, error) {
- statement := &model.WalletStatement{
+ statement := &dbr.WalletStatement{
UserID: userID,
}
- return statement.Count(s.db, &model.ConditionsT{})
+ return statement.Count(s.db, &dbr.ConditionsT{})
}
-func (s *tweetServant) GetPostAttatchmentBill(postID, userID int64) (*model.PostAttachmentBill, error) {
- bill := &model.PostAttachmentBill{
+func (s *tweetServant) GetPostAttatchmentBill(postID, userID int64) (*core.PostAttachmentBill, error) {
+ bill := &dbr.PostAttachmentBill{
PostID: postID,
UserID: userID,
}
@@ -418,16 +422,16 @@ func (s *tweetServant) GetPostAttatchmentBill(postID, userID int64) (*model.Post
return bill.Get(s.db)
}
-func (s *tweetServant) GetPostContentsByIDs(ids []int64) ([]*model.PostContent, error) {
- return (&model.PostContent{}).List(s.db, &model.ConditionsT{
+func (s *tweetServant) GetPostContentsByIDs(ids []int64) ([]*core.PostContent, error) {
+ return (&dbr.PostContent{}).List(s.db, &dbr.ConditionsT{
"post_id IN ?": ids,
"ORDER": "sort ASC",
}, 0, 0)
}
-func (s *tweetServant) GetPostContentByID(id int64) (*model.PostContent, error) {
- return (&model.PostContent{
- Model: &model.Model{
+func (s *tweetServant) GetPostContentByID(id int64) (*core.PostContent, error) {
+ return (&dbr.PostContent{
+ Model: &dbr.Model{
ID: id,
},
}).Get(s.db)
diff --git a/internal/dao/jinzhu/user.go b/internal/dao/jinzhu/user.go
index e1380f00..96d09fc1 100644
--- a/internal/dao/jinzhu/user.go
+++ b/internal/dao/jinzhu/user.go
@@ -1,10 +1,14 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package jinzhu
import (
"strings"
"github.com/rocboss/paopao-ce/internal/core"
- "github.com/rocboss/paopao-ce/internal/model"
+ "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr"
"gorm.io/gorm"
)
@@ -22,69 +26,69 @@ func newUserManageService(db *gorm.DB) core.UserManageService {
}
}
-func (s *userManageServant) GetUserByID(id int64) (*model.User, error) {
- user := &model.User{
- Model: &model.Model{
+func (s *userManageServant) GetUserByID(id int64) (*core.User, error) {
+ user := &dbr.User{
+ Model: &dbr.Model{
ID: id,
},
}
return user.Get(s.db)
}
-func (s *userManageServant) GetUserByUsername(username string) (*model.User, error) {
- user := &model.User{
+func (s *userManageServant) GetUserByUsername(username string) (*core.User, error) {
+ user := &dbr.User{
Username: username,
}
return user.Get(s.db)
}
-func (s *userManageServant) GetUserByPhone(phone string) (*model.User, error) {
- user := &model.User{
+func (s *userManageServant) GetUserByPhone(phone string) (*core.User, error) {
+ user := &dbr.User{
Phone: phone,
}
return user.Get(s.db)
}
-func (s *userManageServant) GetUsersByIDs(ids []int64) ([]*model.User, error) {
- user := &model.User{}
- return user.List(s.db, &model.ConditionsT{
+func (s *userManageServant) GetUsersByIDs(ids []int64) ([]*core.User, error) {
+ user := &dbr.User{}
+ return user.List(s.db, &dbr.ConditionsT{
"id IN ?": ids,
}, 0, 0)
}
-func (s *userManageServant) GetUsersByKeyword(keyword string) ([]*model.User, error) {
- user := &model.User{}
+func (s *userManageServant) GetUsersByKeyword(keyword string) ([]*core.User, error) {
+ user := &dbr.User{}
keyword = strings.Trim(keyword, " ") + "%"
if keyword == "%" {
- return user.List(s.db, &model.ConditionsT{
+ return user.List(s.db, &dbr.ConditionsT{
"ORDER": "id ASC",
}, 0, 6)
} else {
- return user.List(s.db, &model.ConditionsT{
+ return user.List(s.db, &dbr.ConditionsT{
"username LIKE ?": keyword,
}, 0, 6)
}
}
-func (s *userManageServant) GetTagsByKeyword(keyword string) ([]*model.Tag, error) {
- tag := &model.Tag{}
+func (s *userManageServant) GetTagsByKeyword(keyword string) ([]*core.Tag, error) {
+ tag := &dbr.Tag{}
keyword = "%" + strings.Trim(keyword, " ") + "%"
if keyword == "%%" {
- return tag.List(s.db, &model.ConditionsT{
+ return tag.List(s.db, &dbr.ConditionsT{
"ORDER": "quote_num DESC",
}, 0, 6)
} else {
- return tag.List(s.db, &model.ConditionsT{
+ return tag.List(s.db, &dbr.ConditionsT{
"tag LIKE ?": keyword,
"ORDER": "quote_num DESC",
}, 0, 6)
}
}
-func (s *userManageServant) CreateUser(user *model.User) (*model.User, error) {
+func (s *userManageServant) CreateUser(user *dbr.User) (*core.User, error) {
return user.Create(s.db)
}
-func (s *userManageServant) UpdateUser(user *model.User) error {
+func (s *userManageServant) UpdateUser(user *core.User) error {
return user.Update(s.db)
}
diff --git a/internal/dao/jinzhu/utils.go b/internal/dao/jinzhu/utils.go
index 8c866027..27766397 100644
--- a/internal/dao/jinzhu/utils.go
+++ b/internal/dao/jinzhu/utils.go
@@ -1,11 +1,15 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package jinzhu
import (
- "github.com/rocboss/paopao-ce/internal/model"
+ "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr"
"gorm.io/gorm"
)
-func createTag(db *gorm.DB, tag *model.Tag) (*model.Tag, error) {
+func createTag(db *gorm.DB, tag *dbr.Tag) (*dbr.Tag, error) {
t, err := tag.Get(db)
if err != nil {
tag.QuoteNum = 1
@@ -23,7 +27,7 @@ func createTag(db *gorm.DB, tag *model.Tag) (*model.Tag, error) {
return t, nil
}
-func deleteTag(db *gorm.DB, tag *model.Tag) error {
+func deleteTag(db *gorm.DB, tag *dbr.Tag) error {
tag, err := tag.Get(db)
if err != nil {
return err
@@ -33,7 +37,7 @@ func deleteTag(db *gorm.DB, tag *model.Tag) error {
}
func deleteTags(db *gorm.DB, tags []string) error {
- allTags, err := (&model.Tag{}).TagsFrom(db, tags)
+ allTags, err := (&dbr.Tag{}).TagsFrom(db, tags)
if err != nil {
return err
}
@@ -51,9 +55,9 @@ func deleteTags(db *gorm.DB, tags []string) error {
}
// 根据IDs获取用户列表
-func getUsersByIDs(db *gorm.DB, ids []int64) ([]*model.User, error) {
- user := &model.User{}
- return user.List(db, &model.ConditionsT{
+func getUsersByIDs(db *gorm.DB, ids []int64) ([]*dbr.User, error) {
+ user := &dbr.User{}
+ return user.List(db, &dbr.ConditionsT{
"id IN ?": ids,
}, 0, 0)
}
diff --git a/internal/dao/jinzhu/wallet.go b/internal/dao/jinzhu/wallet.go
index 3b4f9ea1..7b2023d7 100644
--- a/internal/dao/jinzhu/wallet.go
+++ b/internal/dao/jinzhu/wallet.go
@@ -1,9 +1,13 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package jinzhu
import (
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/core"
- "github.com/rocboss/paopao-ce/internal/model"
+ "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr"
"gorm.io/gorm"
)
@@ -21,17 +25,17 @@ func newWalletService(db *gorm.DB) core.WalletService {
}
}
-func (d *walletServant) GetRechargeByID(id int64) (*model.WalletRecharge, error) {
- recharge := &model.WalletRecharge{
- Model: &model.Model{
+func (d *walletServant) GetRechargeByID(id int64) (*core.WalletRecharge, error) {
+ recharge := &dbr.WalletRecharge{
+ Model: &dbr.Model{
ID: id,
},
}
return recharge.Get(d.db)
}
-func (d *walletServant) CreateRecharge(userId, amount int64) (*model.WalletRecharge, error) {
- recharge := &model.WalletRecharge{
+func (d *walletServant) CreateRecharge(userId, amount int64) (*core.WalletRecharge, error) {
+ recharge := &dbr.WalletRecharge{
UserID: userId,
Amount: amount,
}
@@ -39,26 +43,26 @@ func (d *walletServant) CreateRecharge(userId, amount int64) (*model.WalletRecha
return recharge.Create(d.db)
}
-func (d *walletServant) GetUserWalletBills(userID int64, offset, limit int) ([]*model.WalletStatement, error) {
- statement := &model.WalletStatement{
+func (d *walletServant) GetUserWalletBills(userID int64, offset, limit int) ([]*core.WalletStatement, error) {
+ statement := &dbr.WalletStatement{
UserID: userID,
}
- return statement.List(d.db, &model.ConditionsT{
+ return statement.List(d.db, &dbr.ConditionsT{
"ORDER": "id DESC",
}, offset, limit)
}
func (d *walletServant) GetUserWalletBillCount(userID int64) (int64, error) {
- statement := &model.WalletStatement{
+ statement := &dbr.WalletStatement{
UserID: userID,
}
- return statement.Count(d.db, &model.ConditionsT{})
+ return statement.Count(d.db, &dbr.ConditionsT{})
}
-func (d *walletServant) HandleRechargeSuccess(recharge *model.WalletRecharge, tradeNo string) error {
- user, _ := (&model.User{
- Model: &model.Model{
+func (d *walletServant) HandleRechargeSuccess(recharge *core.WalletRecharge, tradeNo string) error {
+ user, _ := (&dbr.User{
+ Model: &dbr.Model{
ID: recharge.UserID,
},
}).Get(d.db)
@@ -71,7 +75,7 @@ func (d *walletServant) HandleRechargeSuccess(recharge *model.WalletRecharge, tr
}
// 新增账单
- if err := tx.Create(&model.WalletStatement{
+ if err := tx.Create(&dbr.WalletStatement{
UserID: user.ID,
ChangeAmount: recharge.Amount,
BalanceSnapshot: user.Balance + recharge.Amount,
@@ -93,7 +97,7 @@ func (d *walletServant) HandleRechargeSuccess(recharge *model.WalletRecharge, tr
})
}
-func (d *walletServant) HandlePostAttachmentBought(post *model.Post, user *model.User) error {
+func (d *walletServant) HandlePostAttachmentBought(post *core.Post, user *core.User) error {
return d.db.Transaction(func(tx *gorm.DB) error {
// 扣除金额
if err := tx.Model(user).Update("balance", gorm.Expr("balance - ?", post.AttachmentPrice)).Error; err != nil {
@@ -102,7 +106,7 @@ func (d *walletServant) HandlePostAttachmentBought(post *model.Post, user *model
}
// 新增账单
- if err := tx.Create(&model.WalletStatement{
+ if err := tx.Create(&dbr.WalletStatement{
PostID: post.ID,
UserID: user.ID,
ChangeAmount: -post.AttachmentPrice,
@@ -113,7 +117,7 @@ func (d *walletServant) HandlePostAttachmentBought(post *model.Post, user *model
}
// 新增附件购买记录
- if err := tx.Create(&model.PostAttachmentBill{
+ if err := tx.Create(&dbr.PostAttachmentBill{
PostID: post.ID,
UserID: user.ID,
PaidAmount: post.AttachmentPrice,
@@ -124,8 +128,8 @@ func (d *walletServant) HandlePostAttachmentBought(post *model.Post, user *model
// 对附件主新增账单
income := int64(float64(post.AttachmentPrice) * conf.AppSetting.AttachmentIncomeRate)
if income > 0 {
- master := &model.User{
- Model: &model.Model{
+ master := &dbr.User{
+ Model: &dbr.Model{
ID: post.UserID,
},
}
@@ -137,7 +141,7 @@ func (d *walletServant) HandlePostAttachmentBought(post *model.Post, user *model
}
// 新增账单
- if err := tx.Create(&model.WalletStatement{
+ if err := tx.Create(&dbr.WalletStatement{
PostID: post.ID,
UserID: master.ID,
ChangeAmount: income,
diff --git a/internal/dao/sakila/sakila.go b/internal/dao/sakila/sakila.go
index 6efdffa6..d82a0d23 100644
--- a/internal/dao/sakila/sakila.go
+++ b/internal/dao/sakila/sakila.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
// Core service implement base sqlx+mysql. All sub-service
// will declare here and provide initial function.
diff --git a/internal/dao/search/bridge.go b/internal/dao/search/bridge.go
index 84f469a5..f23aaa25 100644
--- a/internal/dao/search/bridge.go
+++ b/internal/dao/search/bridge.go
@@ -1,10 +1,13 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package search
import (
"time"
"github.com/rocboss/paopao-ce/internal/core"
- "github.com/rocboss/paopao-ce/internal/model"
"github.com/sirupsen/logrus"
)
@@ -43,7 +46,7 @@ func (s *bridgeTweetSearchServant) DeleteDocuments(identifiers []string) error {
return nil
}
-func (s *bridgeTweetSearchServant) Search(user *model.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) {
+func (s *bridgeTweetSearchServant) Search(user *core.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) {
return s.ts.Search(user, q, offset, limit)
}
diff --git a/internal/dao/search/filter.go b/internal/dao/search/filter.go
index 229f2482..5840e189 100644
--- a/internal/dao/search/filter.go
+++ b/internal/dao/search/filter.go
@@ -1,8 +1,11 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package search
import (
"github.com/rocboss/paopao-ce/internal/core"
- "github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/pkg/types"
)
@@ -10,19 +13,19 @@ type tweetSearchFilter struct {
ams core.AuthorizationManageService
}
-func (s *tweetSearchFilter) filterResp(user *model.User, resp *core.QueryResp) {
+func (s *tweetSearchFilter) filterResp(user *core.User, resp *core.QueryResp) {
// 管理员不过滤
if user != nil && user.IsAdmin {
return
}
- var item *model.PostFormated
+ var item *core.PostFormated
items := resp.Items
latestIndex := len(items) - 1
if user == nil {
for i := 0; i <= latestIndex; i++ {
item = items[i]
- if item.Visibility != model.PostVisitPublic {
+ if item.Visibility != core.PostVisitPublic {
items[i] = items[latestIndex]
items = items[:latestIndex]
resp.Total--
@@ -36,8 +39,8 @@ func (s *tweetSearchFilter) filterResp(user *model.User, resp *core.QueryResp) {
friendFilter[user.ID] = types.Empty{}
for i := 0; i <= latestIndex; i++ {
item = items[i]
- cutFriend = (item.Visibility == model.PostVisitFriend && !friendFilter.IsFriend(item.UserID))
- cutPrivate = (item.Visibility == model.PostVisitPrivate && user.ID != item.UserID)
+ cutFriend = (item.Visibility == core.PostVisitFriend && !friendFilter.IsFriend(item.UserID))
+ cutPrivate = (item.Visibility == core.PostVisitPrivate && user.ID != item.UserID)
if cutFriend || cutPrivate {
items[i] = items[latestIndex]
items = items[:latestIndex]
diff --git a/internal/dao/search/meili.go b/internal/dao/search/meili.go
index 321953ee..b2ee4d16 100644
--- a/internal/dao/search/meili.go
+++ b/internal/dao/search/meili.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package search
import (
@@ -7,7 +11,6 @@ import (
"github.com/Masterminds/semver/v3"
"github.com/meilisearch/meilisearch-go"
"github.com/rocboss/paopao-ce/internal/core"
- "github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/pkg/json"
"github.com/sirupsen/logrus"
)
@@ -28,20 +31,20 @@ type meiliTweetSearchServant struct {
}
type postInfo struct {
- ID int64 `json:"id"`
- UserID int64 `json:"user_id"`
- CommentCount int64 `json:"comment_count"`
- CollectionCount int64 `json:"collection_count"`
- UpvoteCount int64 `json:"upvote_count"`
- Visibility model.PostVisibleT `json:"visibility"`
- IsTop int `json:"is_top"`
- IsEssence int `json:"is_essence"`
- IsLock int `json:"is_lock"`
- LatestRepliedOn int64 `json:"latest_replied_on"`
- CreatedOn int64 `json:"created_on"`
- ModifiedOn int64 `json:"modified_on"`
- AttachmentPrice int64 `json:"attachment_price"`
- IPLoc string `json:"ip_loc"`
+ ID int64 `json:"id"`
+ UserID int64 `json:"user_id"`
+ CommentCount int64 `json:"comment_count"`
+ CollectionCount int64 `json:"collection_count"`
+ UpvoteCount int64 `json:"upvote_count"`
+ Visibility core.PostVisibleT `json:"visibility"`
+ IsTop int `json:"is_top"`
+ IsEssence int `json:"is_essence"`
+ IsLock int `json:"is_lock"`
+ LatestRepliedOn int64 `json:"latest_replied_on"`
+ CreatedOn int64 `json:"created_on"`
+ ModifiedOn int64 `json:"modified_on"`
+ AttachmentPrice int64 `json:"attachment_price"`
+ IPLoc string `json:"ip_loc"`
}
func (s *meiliTweetSearchServant) Name() string {
@@ -78,7 +81,7 @@ func (s *meiliTweetSearchServant) DeleteDocuments(identifiers []string) error {
return nil
}
-func (s *meiliTweetSearchServant) Search(user *model.User, q *core.QueryReq, offset, limit int) (resp *core.QueryResp, err error) {
+func (s *meiliTweetSearchServant) Search(user *core.User, q *core.QueryReq, offset, limit int) (resp *core.QueryResp, err error) {
if q.Type == core.SearchTypeDefault && q.Query != "" {
resp, err = s.queryByContent(user, q, offset, limit)
} else if q.Type == core.SearchTypeTag && q.Query != "" {
@@ -96,7 +99,7 @@ func (s *meiliTweetSearchServant) Search(user *model.User, q *core.QueryReq, off
return
}
-func (s *meiliTweetSearchServant) queryByContent(user *model.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) {
+func (s *meiliTweetSearchServant) queryByContent(user *core.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) {
request := &meilisearch.SearchRequest{
Offset: int64(offset),
Limit: int64(limit),
@@ -117,7 +120,7 @@ func (s *meiliTweetSearchServant) queryByContent(user *model.User, q *core.Query
return s.postsFrom(resp)
}
-func (s *meiliTweetSearchServant) queryByTag(user *model.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) {
+func (s *meiliTweetSearchServant) queryByTag(user *core.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) {
request := &meilisearch.SearchRequest{
Offset: int64(offset),
Limit: int64(limit),
@@ -141,7 +144,7 @@ func (s *meiliTweetSearchServant) queryByTag(user *model.User, q *core.QueryReq,
return s.postsFrom(resp)
}
-func (s *meiliTweetSearchServant) queryAny(user *model.User, offset, limit int) (*core.QueryResp, error) {
+func (s *meiliTweetSearchServant) queryAny(user *core.User, offset, limit int) (*core.QueryResp, error) {
request := &meilisearch.SearchRequest{
Offset: int64(offset),
Limit: int64(limit),
@@ -161,7 +164,7 @@ func (s *meiliTweetSearchServant) queryAny(user *model.User, offset, limit int)
return s.postsFrom(resp)
}
-func (s *meiliTweetSearchServant) filterList(user *model.User) string {
+func (s *meiliTweetSearchServant) filterList(user *core.User) string {
if user == nil {
return s.publicFilter
}
@@ -174,7 +177,7 @@ func (s *meiliTweetSearchServant) filterList(user *model.User) string {
}
func (s *meiliTweetSearchServant) postsFrom(resp *meilisearch.SearchResponse) (*core.QueryResp, error) {
- posts := make([]*model.PostFormated, 0, len(resp.Hits))
+ posts := make([]*core.PostFormated, 0, len(resp.Hits))
for _, hit := range resp.Hits {
raw, err := json.Marshal(hit)
if err != nil {
@@ -184,7 +187,7 @@ func (s *meiliTweetSearchServant) postsFrom(resp *meilisearch.SearchResponse) (*
if err = json.Unmarshal(raw, p); err != nil {
return nil, err
}
- posts = append(posts, &model.PostFormated{
+ posts = append(posts, &core.PostFormated{
ID: p.ID,
UserID: p.UserID,
CommentCount: p.CommentCount,
diff --git a/internal/dao/search/search.go b/internal/dao/search/search.go
index 1dda80ef..baf0923b 100644
--- a/internal/dao/search/search.go
+++ b/internal/dao/search/search.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package search
import (
@@ -6,7 +10,6 @@ import (
"github.com/meilisearch/meilisearch-go"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/core"
- "github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/pkg/zinc"
"github.com/sirupsen/logrus"
)
@@ -40,9 +43,9 @@ func NewMeiliTweetSearchService(ams core.AuthorizationManageService) (core.Tweet
},
client: client,
index: client.Index(s.Index),
- publicFilter: fmt.Sprintf("visibility=%d", model.PostVisitPublic),
- privateFilter: fmt.Sprintf("visibility=%d AND user_id=", model.PostVisitPrivate),
- friendFilter: fmt.Sprintf("visibility=%d", model.PostVisitFriend),
+ publicFilter: fmt.Sprintf("visibility=%d", core.PostVisitPublic),
+ privateFilter: fmt.Sprintf("visibility=%d AND user_id=", core.PostVisitPrivate),
+ friendFilter: fmt.Sprintf("visibility=%d", core.PostVisitFriend),
}
return mts, mts
}
@@ -55,9 +58,9 @@ func NewZincTweetSearchService(ams core.AuthorizationManageService) (core.TweetS
},
indexName: s.Index,
client: zinc.NewClient(s),
- publicFilter: fmt.Sprintf("visibility:%d", model.PostVisitPublic),
- privateFilter: fmt.Sprintf("visibility:%d AND user_id:%%d", model.PostVisitPrivate),
- friendFilter: fmt.Sprintf("visibility:%d", model.PostVisitFriend),
+ publicFilter: fmt.Sprintf("visibility:%d", core.PostVisitPublic),
+ privateFilter: fmt.Sprintf("visibility:%d AND user_id:%%d", core.PostVisitPrivate),
+ friendFilter: fmt.Sprintf("visibility:%d", core.PostVisitFriend),
}
zts.createIndex()
diff --git a/internal/dao/search/zinc.go b/internal/dao/search/zinc.go
index c038cb90..ea9a7fa5 100644
--- a/internal/dao/search/zinc.go
+++ b/internal/dao/search/zinc.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package search
import (
@@ -5,7 +9,6 @@ import (
"github.com/Masterminds/semver/v3"
"github.com/rocboss/paopao-ce/internal/core"
- "github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/pkg/json"
"github.com/rocboss/paopao-ce/pkg/zinc"
"github.com/sirupsen/logrus"
@@ -73,7 +76,7 @@ func (s *zincTweetSearchServant) DeleteDocuments(identifiers []string) error {
return nil
}
-func (s *zincTweetSearchServant) Search(user *model.User, q *core.QueryReq, offset, limit int) (resp *core.QueryResp, err error) {
+func (s *zincTweetSearchServant) Search(user *core.User, q *core.QueryReq, offset, limit int) (resp *core.QueryResp, err error) {
if q.Type == core.SearchTypeDefault && q.Query != "" {
resp, err = s.queryByContent(user, q, offset, limit)
} else if q.Type == core.SearchTypeTag && q.Query != "" {
@@ -91,7 +94,7 @@ func (s *zincTweetSearchServant) Search(user *model.User, q *core.QueryReq, offs
return
}
-func (s *zincTweetSearchServant) queryByContent(user *model.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) {
+func (s *zincTweetSearchServant) queryByContent(user *core.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) {
resp, err := s.client.EsQuery(s.indexName, map[string]any{
"query": map[string]any{
"match_phrase": map[string]any{
@@ -108,7 +111,7 @@ func (s *zincTweetSearchServant) queryByContent(user *model.User, q *core.QueryR
return s.postsFrom(resp)
}
-func (s *zincTweetSearchServant) queryByTag(user *model.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) {
+func (s *zincTweetSearchServant) queryByTag(user *core.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) {
resp, err := s.client.ApiQuery(s.indexName, map[string]any{
"search_type": "querystring",
"query": map[string]any{
@@ -124,7 +127,7 @@ func (s *zincTweetSearchServant) queryByTag(user *model.User, q *core.QueryReq,
return s.postsFrom(resp)
}
-func (s *zincTweetSearchServant) queryAny(user *model.User, offset, limit int) (*core.QueryResp, error) {
+func (s *zincTweetSearchServant) queryAny(user *core.User, offset, limit int) (*core.QueryResp, error) {
queryMap := map[string]any{
"query": map[string]any{
"match_all": map[string]string{},
@@ -141,9 +144,9 @@ func (s *zincTweetSearchServant) queryAny(user *model.User, offset, limit int) (
}
func (s *zincTweetSearchServant) postsFrom(resp *zinc.QueryResultT) (*core.QueryResp, error) {
- posts := make([]*model.PostFormated, 0, len(resp.Hits.Hits))
+ posts := make([]*core.PostFormated, 0, len(resp.Hits.Hits))
for _, hit := range resp.Hits.Hits {
- item := &model.PostFormated{}
+ item := &core.PostFormated{}
raw, err := json.Marshal(hit.Source)
if err != nil {
return nil, err
diff --git a/internal/dao/security/attachment.go b/internal/dao/security/attachment.go
index 3bd79461..706621ac 100644
--- a/internal/dao/security/attachment.go
+++ b/internal/dao/security/attachment.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package security
import (
diff --git a/internal/dao/slonik/slonik.go b/internal/dao/slonik/slonik.go
index 8cfb49c3..bb8f82ad 100644
--- a/internal/dao/slonik/slonik.go
+++ b/internal/dao/slonik/slonik.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
// Core service implement base sqlx+postgresql. All sub-service
// will declare here and provide initial function.
diff --git a/internal/dao/storage/alioss.go b/internal/dao/storage/alioss.go
index 3519cba5..e72fa44c 100644
--- a/internal/dao/storage/alioss.go
+++ b/internal/dao/storage/alioss.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package storage
import (
diff --git a/internal/dao/storage/cos.go b/internal/dao/storage/cos.go
index f7a7ebad..3c2ea65f 100644
--- a/internal/dao/storage/cos.go
+++ b/internal/dao/storage/cos.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package storage
import (
diff --git a/internal/dao/storage/huaweiobs.go b/internal/dao/storage/huaweiobs.go
index 31656e6c..7db9818b 100644
--- a/internal/dao/storage/huaweiobs.go
+++ b/internal/dao/storage/huaweiobs.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package storage
import (
diff --git a/internal/dao/storage/localoss.go b/internal/dao/storage/localoss.go
index f2ba55ab..584fea91 100644
--- a/internal/dao/storage/localoss.go
+++ b/internal/dao/storage/localoss.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package storage
import (
diff --git a/internal/dao/storage/minio.go b/internal/dao/storage/minio.go
index b4da9fed..3859a5b7 100644
--- a/internal/dao/storage/minio.go
+++ b/internal/dao/storage/minio.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package storage
import (
diff --git a/internal/dao/storage/storage.go b/internal/dao/storage/storage.go
index 8e124047..0f03fa20 100644
--- a/internal/dao/storage/storage.go
+++ b/internal/dao/storage/storage.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package storage
import (
@@ -8,13 +12,13 @@ import (
"strconv"
"time"
+ "github.com/alimy/cfg"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/core"
- "github.com/rocboss/paopao-ce/pkg/cfg"
"github.com/sirupsen/logrus"
"github.com/tencentyun/cos-go-sdk-v5"
)
diff --git a/internal/internal.go b/internal/internal.go
index 8d51c97a..a8c0934f 100644
--- a/internal/internal.go
+++ b/internal/internal.go
@@ -1,9 +1,13 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package internal
import (
"github.com/rocboss/paopao-ce/internal/migration"
- "github.com/rocboss/paopao-ce/internal/routers/api"
- "github.com/rocboss/paopao-ce/internal/service"
+ "github.com/rocboss/paopao-ce/internal/servants/web/broker"
+ "github.com/rocboss/paopao-ce/internal/servants/web/routers/api"
)
func Initialize() {
@@ -11,6 +15,6 @@ func Initialize() {
migration.Run()
// initialize service
- service.Initialize()
+ broker.Initialize()
api.Initialize()
}
diff --git a/internal/migration/migration.go b/internal/migration/migration.go
index 44c16fb4..1cac6012 100644
--- a/internal/migration/migration.go
+++ b/internal/migration/migration.go
@@ -1,10 +1,14 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
//go:build !migration
// +build !migration
package migration
import (
- "github.com/rocboss/paopao-ce/pkg/cfg"
+ "github.com/alimy/cfg"
"github.com/sirupsen/logrus"
)
diff --git a/internal/migration/migration_embed.go b/internal/migration/migration_embed.go
index 84952538..02ede293 100644
--- a/internal/migration/migration_embed.go
+++ b/internal/migration/migration_embed.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
//go:build migration
// +build migration
@@ -6,6 +10,7 @@ package migration
import (
"database/sql"
+ "github.com/alimy/cfg"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database"
"github.com/golang-migrate/migrate/v4/database/mysql"
@@ -14,7 +19,6 @@ import (
"github.com/golang-migrate/migrate/v4/source"
"github.com/golang-migrate/migrate/v4/source/iofs"
"github.com/rocboss/paopao-ce/internal/conf"
- "github.com/rocboss/paopao-ce/pkg/cfg"
"github.com/rocboss/paopao-ce/scripts/migration"
"github.com/sirupsen/logrus"
)
diff --git a/internal/mirc/README.md b/internal/mirc/README.md
new file mode 100644
index 00000000..064cbe21
--- /dev/null
+++ b/internal/mirc/README.md
@@ -0,0 +1,2 @@
+### Mirc for paopao-ce
+RESTful API for paopao-ce use [go-mir](https://github.com/alimy/mir) to generate service interface code automatic.
diff --git a/internal/mirc/auto/api/m/v1/user.go b/internal/mirc/auto/api/m/v1/user.go
new file mode 100644
index 00000000..431343e7
--- /dev/null
+++ b/internal/mirc/auto/api/m/v1/user.go
@@ -0,0 +1,140 @@
+// Code generated by go-mir. DO NOT EDIT.
+
+package v1
+
+import (
+ "net/http"
+
+ "github.com/alimy/mir/v3"
+ "github.com/gin-gonic/gin"
+)
+
+type LoginReq struct {
+ AgentInfo AgentInfo `json:"agent_info"`
+ Name string `json:"name"`
+ Passwd string `json:"passwd"`
+}
+
+type AgentInfo struct {
+ Platform string `json:"platform"`
+ UserAgent string `json:"user_agent"`
+}
+
+type LoginResp struct {
+ UserInfo
+ ServerInfo ServerInfo `json:"server_info"`
+ JwtToken string `json:"jwt_token"`
+}
+
+type ServerInfo struct {
+ ApiVer string `json:"api_ver"`
+}
+
+type UserInfo struct {
+ Name string `json:"name"`
+}
+
+type User interface {
+ // Chain provide handlers chain for gin
+ Chain() gin.HandlersChain
+
+ Logout() mir.Error
+ Login(*LoginReq) (*LoginResp, mir.Error)
+
+ mustEmbedUnimplementedUserServant()
+}
+
+type UserBinding interface {
+ BindLogin(*gin.Context) (*LoginReq, mir.Error)
+
+ mustEmbedUnimplementedUserBinding()
+}
+
+type UserRender interface {
+ RenderLogout(*gin.Context, mir.Error)
+ RenderLogin(*gin.Context, *LoginResp, mir.Error)
+
+ mustEmbedUnimplementedUserRender()
+}
+
+// RegisterUserServant register User servant to gin
+func RegisterUserServant(e *gin.Engine, s User, b UserBinding, r UserRender) {
+ router := e.Group("m/v1")
+ // use chain for router
+ middlewares := s.Chain()
+ router.Use(middlewares...)
+
+ // register routes info to router
+ router.Handle("POST", "/user/logout/", func(c *gin.Context) {
+ select {
+ case <-c.Request.Context().Done():
+ return
+ default:
+ }
+
+ r.RenderLogout(c, s.Logout())
+ })
+
+ router.Handle("POST", "/user/login/", func(c *gin.Context) {
+ select {
+ case <-c.Request.Context().Done():
+ return
+ default:
+ }
+
+ req, err := b.BindLogin(c)
+ if err != nil {
+ r.RenderLogin(c, nil, err)
+ return
+ }
+ resp, err := s.Login(req)
+ r.RenderLogin(c, resp, err)
+ })
+
+}
+
+// UnimplementedUserServant can be embedded to have forward compatible implementations.
+type UnimplementedUserServant struct {
+}
+
+func (UnimplementedUserServant) Chain() gin.HandlersChain {
+ return nil
+}
+
+func (UnimplementedUserServant) Logout() mir.Error {
+ return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented))
+}
+
+func (UnimplementedUserServant) Login(req *LoginReq) (*LoginResp, mir.Error) {
+ return nil, mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented))
+}
+
+func (UnimplementedUserServant) mustEmbedUnimplementedUserServant() {}
+
+// UnimplementedUserRender can be embedded to have forward compatible implementations.
+type UnimplementedUserRender struct {
+ RenderAny func(*gin.Context, any, mir.Error)
+}
+
+func (r *UnimplementedUserRender) RenderLogout(c *gin.Context, err mir.Error) {
+ r.RenderAny(c, nil, err)
+}
+
+func (r *UnimplementedUserRender) RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) {
+ r.RenderAny(c, data, err)
+}
+
+func (r *UnimplementedUserRender) mustEmbedUnimplementedUserRender() {}
+
+// UnimplementedUserBinding can be embedded to have forward compatible implementations.
+type UnimplementedUserBinding struct {
+ BindAny func(*gin.Context, any) mir.Error
+}
+
+func (b *UnimplementedUserBinding) BindLogin(c *gin.Context) (*LoginReq, mir.Error) {
+ obj := new(LoginReq)
+ err := b.BindAny(c, obj)
+ return obj, err
+}
+
+func (b *UnimplementedUserBinding) mustEmbedUnimplementedUserBinding() {}
diff --git a/internal/mirc/auto/api/r/v1/user.go b/internal/mirc/auto/api/r/v1/user.go
new file mode 100644
index 00000000..1850b157
--- /dev/null
+++ b/internal/mirc/auto/api/r/v1/user.go
@@ -0,0 +1,140 @@
+// Code generated by go-mir. DO NOT EDIT.
+
+package v1
+
+import (
+ "net/http"
+
+ "github.com/alimy/mir/v3"
+ "github.com/gin-gonic/gin"
+)
+
+type LoginReq struct {
+ AgentInfo AgentInfo `json:"agent_info"`
+ Name string `json:"name"`
+ Passwd string `json:"passwd"`
+}
+
+type AgentInfo struct {
+ Platform string `json:"platform"`
+ UserAgent string `json:"user_agent"`
+}
+
+type LoginResp struct {
+ UserInfo
+ ServerInfo ServerInfo `json:"server_info"`
+ JwtToken string `json:"jwt_token"`
+}
+
+type ServerInfo struct {
+ ApiVer string `json:"api_ver"`
+}
+
+type UserInfo struct {
+ Name string `json:"name"`
+}
+
+type User interface {
+ // Chain provide handlers chain for gin
+ Chain() gin.HandlersChain
+
+ Logout() mir.Error
+ Login(*LoginReq) (*LoginResp, mir.Error)
+
+ mustEmbedUnimplementedUserServant()
+}
+
+type UserBinding interface {
+ BindLogin(*gin.Context) (*LoginReq, mir.Error)
+
+ mustEmbedUnimplementedUserBinding()
+}
+
+type UserRender interface {
+ RenderLogout(*gin.Context, mir.Error)
+ RenderLogin(*gin.Context, *LoginResp, mir.Error)
+
+ mustEmbedUnimplementedUserRender()
+}
+
+// RegisterUserServant register User servant to gin
+func RegisterUserServant(e *gin.Engine, s User, b UserBinding, r UserRender) {
+ router := e.Group("r/v1")
+ // use chain for router
+ middlewares := s.Chain()
+ router.Use(middlewares...)
+
+ // register routes info to router
+ router.Handle("POST", "/user/logout/", func(c *gin.Context) {
+ select {
+ case <-c.Request.Context().Done():
+ return
+ default:
+ }
+
+ r.RenderLogout(c, s.Logout())
+ })
+
+ router.Handle("POST", "/user/login/", func(c *gin.Context) {
+ select {
+ case <-c.Request.Context().Done():
+ return
+ default:
+ }
+
+ req, err := b.BindLogin(c)
+ if err != nil {
+ r.RenderLogin(c, nil, err)
+ return
+ }
+ resp, err := s.Login(req)
+ r.RenderLogin(c, resp, err)
+ })
+
+}
+
+// UnimplementedUserServant can be embedded to have forward compatible implementations.
+type UnimplementedUserServant struct {
+}
+
+func (UnimplementedUserServant) Chain() gin.HandlersChain {
+ return nil
+}
+
+func (UnimplementedUserServant) Logout() mir.Error {
+ return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented))
+}
+
+func (UnimplementedUserServant) Login(req *LoginReq) (*LoginResp, mir.Error) {
+ return nil, mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented))
+}
+
+func (UnimplementedUserServant) mustEmbedUnimplementedUserServant() {}
+
+// UnimplementedUserRender can be embedded to have forward compatible implementations.
+type UnimplementedUserRender struct {
+ RenderAny func(*gin.Context, any, mir.Error)
+}
+
+func (r *UnimplementedUserRender) RenderLogout(c *gin.Context, err mir.Error) {
+ r.RenderAny(c, nil, err)
+}
+
+func (r *UnimplementedUserRender) RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) {
+ r.RenderAny(c, data, err)
+}
+
+func (r *UnimplementedUserRender) mustEmbedUnimplementedUserRender() {}
+
+// UnimplementedUserBinding can be embedded to have forward compatible implementations.
+type UnimplementedUserBinding struct {
+ BindAny func(*gin.Context, any) mir.Error
+}
+
+func (b *UnimplementedUserBinding) BindLogin(c *gin.Context) (*LoginReq, mir.Error) {
+ obj := new(LoginReq)
+ err := b.BindAny(c, obj)
+ return obj, err
+}
+
+func (b *UnimplementedUserBinding) mustEmbedUnimplementedUserBinding() {}
diff --git a/internal/mirc/auto/api/s/v1/user.go b/internal/mirc/auto/api/s/v1/user.go
new file mode 100644
index 00000000..ef2c855b
--- /dev/null
+++ b/internal/mirc/auto/api/s/v1/user.go
@@ -0,0 +1,150 @@
+// Code generated by go-mir. DO NOT EDIT.
+
+package v1
+
+import (
+ "net/http"
+
+ "github.com/alimy/mir/v3"
+ "github.com/gin-gonic/gin"
+)
+
+type LoginReq struct {
+ AgentInfo AgentInfo `json:"agent_info"`
+ Name string `json:"name"`
+ Passwd string `json:"passwd"`
+}
+
+type AgentInfo struct {
+ Platform string `json:"platform"`
+ UserAgent string `json:"user_agent"`
+}
+
+type LoginResp struct {
+ UserInfo
+ ServerInfo ServerInfo `json:"server_info"`
+ JwtToken string `json:"jwt_token"`
+}
+
+type ServerInfo struct {
+ ApiVer string `json:"api_ver"`
+}
+
+type UserInfo struct {
+ Name string `json:"name"`
+}
+
+type User interface {
+ Logout() mir.Error
+ Login(*LoginReq) (*LoginResp, mir.Error)
+ Index() mir.Error
+
+ mustEmbedUnimplementedUserServant()
+}
+
+type UserBinding interface {
+ BindLogin(*gin.Context) (*LoginReq, mir.Error)
+
+ mustEmbedUnimplementedUserBinding()
+}
+
+type UserRender interface {
+ RenderLogout(*gin.Context, mir.Error)
+ RenderLogin(*gin.Context, *LoginResp, mir.Error)
+ RenderIndex(*gin.Context, mir.Error)
+
+ mustEmbedUnimplementedUserRender()
+}
+
+// RegisterUserServant register User servant to gin
+func RegisterUserServant(e *gin.Engine, s User, b UserBinding, r UserRender) {
+ router := e.Group("s/v1")
+
+ // register routes info to router
+ router.Handle("POST", "/user/logout/", func(c *gin.Context) {
+ select {
+ case <-c.Request.Context().Done():
+ return
+ default:
+ }
+
+ r.RenderLogout(c, s.Logout())
+ })
+
+ router.Handle("POST", "/user/login/", func(c *gin.Context) {
+ select {
+ case <-c.Request.Context().Done():
+ return
+ default:
+ }
+
+ req, err := b.BindLogin(c)
+ if err != nil {
+ r.RenderLogin(c, nil, err)
+ return
+ }
+ resp, err := s.Login(req)
+ r.RenderLogin(c, resp, err)
+ })
+
+ router.Handle("GET", "/index/", func(c *gin.Context) {
+ select {
+ case <-c.Request.Context().Done():
+ return
+ default:
+ }
+
+ r.RenderIndex(c, s.Index())
+ })
+
+}
+
+// UnimplementedUserServant can be embedded to have forward compatible implementations.
+type UnimplementedUserServant struct {
+}
+
+func (UnimplementedUserServant) Logout() mir.Error {
+ return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented))
+}
+
+func (UnimplementedUserServant) Login(req *LoginReq) (*LoginResp, mir.Error) {
+ return nil, mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented))
+}
+
+func (UnimplementedUserServant) Index() mir.Error {
+ return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented))
+}
+
+func (UnimplementedUserServant) mustEmbedUnimplementedUserServant() {}
+
+// UnimplementedUserRender can be embedded to have forward compatible implementations.
+type UnimplementedUserRender struct {
+ RenderAny func(*gin.Context, any, mir.Error)
+}
+
+func (r *UnimplementedUserRender) RenderLogout(c *gin.Context, err mir.Error) {
+ r.RenderAny(c, nil, err)
+}
+
+func (r *UnimplementedUserRender) RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) {
+ r.RenderAny(c, data, err)
+}
+
+func (r *UnimplementedUserRender) RenderIndex(c *gin.Context, err mir.Error) {
+ r.RenderAny(c, nil, err)
+}
+
+func (r *UnimplementedUserRender) mustEmbedUnimplementedUserRender() {}
+
+// UnimplementedUserBinding can be embedded to have forward compatible implementations.
+type UnimplementedUserBinding struct {
+ BindAny func(*gin.Context, any) mir.Error
+}
+
+func (b *UnimplementedUserBinding) BindLogin(c *gin.Context) (*LoginReq, mir.Error) {
+ obj := new(LoginReq)
+ err := b.BindAny(c, obj)
+ return obj, err
+}
+
+func (b *UnimplementedUserBinding) mustEmbedUnimplementedUserBinding() {}
diff --git a/internal/mirc/auto/api/v1/web_core.go b/internal/mirc/auto/api/v1/web_core.go
new file mode 100644
index 00000000..613977fe
--- /dev/null
+++ b/internal/mirc/auto/api/v1/web_core.go
@@ -0,0 +1,184 @@
+// Code generated by go-mir. DO NOT EDIT.
+
+package v1
+
+import (
+ "net/http"
+
+ "github.com/alimy/mir/v3"
+ "github.com/gin-gonic/gin"
+)
+
+type LoginReq struct {
+ AgentInfo AgentInfo `json:"agent_info"`
+ Name string `json:"name"`
+ Passwd string `json:"passwd"`
+}
+
+type AgentInfo struct {
+ Platform string `json:"platform"`
+ UserAgent string `json:"user_agent"`
+}
+
+type LoginResp struct {
+ UserInfo
+ ServerInfo ServerInfo `json:"server_info"`
+ JwtToken string `json:"jwt_token"`
+}
+
+type ServerInfo struct {
+ ApiVer string `json:"api_ver"`
+}
+
+type UserInfo struct {
+ Name string `json:"name"`
+}
+
+type WebCore interface {
+ // Chain provide handlers chain for gin
+ Chain() gin.HandlersChain
+
+ Logout() mir.Error
+ Login(*LoginReq) (*LoginResp, mir.Error)
+ Articles() mir.Error
+ Index() mir.Error
+
+ mustEmbedUnimplementedWebCoreServant()
+}
+
+type WebCoreBinding interface {
+ BindLogin(*gin.Context) (*LoginReq, mir.Error)
+
+ mustEmbedUnimplementedWebCoreBinding()
+}
+
+type WebCoreRender interface {
+ RenderLogout(*gin.Context, mir.Error)
+ RenderLogin(*gin.Context, *LoginResp, mir.Error)
+ RenderArticles(*gin.Context, mir.Error)
+ RenderIndex(*gin.Context, mir.Error)
+
+ mustEmbedUnimplementedWebCoreRender()
+}
+
+// RegisterWebCoreServant register WebCore servant to gin
+func RegisterWebCoreServant(e *gin.Engine, s WebCore, b WebCoreBinding, r WebCoreRender) {
+ router := e.Group("v1")
+ // use chain for router
+ middlewares := s.Chain()
+ router.Use(middlewares...)
+
+ // register routes info to router
+ router.Handle("POST", "/user/logout/", func(c *gin.Context) {
+ select {
+ case <-c.Request.Context().Done():
+ return
+ default:
+ }
+
+ r.RenderLogout(c, s.Logout())
+ })
+
+ router.Handle("POST", "/user/login/", func(c *gin.Context) {
+ select {
+ case <-c.Request.Context().Done():
+ return
+ default:
+ }
+
+ req, err := b.BindLogin(c)
+ if err != nil {
+ r.RenderLogin(c, nil, err)
+ return
+ }
+ resp, err := s.Login(req)
+ r.RenderLogin(c, resp, err)
+ })
+
+ {
+ h := func(c *gin.Context) {
+ select {
+ case <-c.Request.Context().Done():
+ return
+ default:
+ }
+
+ r.RenderArticles(c, s.Articles())
+ }
+ router.Handle("HEAD", "/articles/:category/", h)
+ router.Handle("GET", "/articles/:category/", h)
+ }
+
+ router.Handle("GET", "/index/", func(c *gin.Context) {
+ select {
+ case <-c.Request.Context().Done():
+ return
+ default:
+ }
+
+ r.RenderIndex(c, s.Index())
+ })
+
+}
+
+// UnimplementedWebCoreServant can be embedded to have forward compatible implementations.
+type UnimplementedWebCoreServant struct {
+}
+
+func (UnimplementedWebCoreServant) Chain() gin.HandlersChain {
+ return nil
+}
+
+func (UnimplementedWebCoreServant) Logout() mir.Error {
+ return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented))
+}
+
+func (UnimplementedWebCoreServant) Login(req *LoginReq) (*LoginResp, mir.Error) {
+ return nil, mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented))
+}
+
+func (UnimplementedWebCoreServant) Articles() mir.Error {
+ return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented))
+}
+
+func (UnimplementedWebCoreServant) Index() mir.Error {
+ return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented))
+}
+
+func (UnimplementedWebCoreServant) mustEmbedUnimplementedWebCoreServant() {}
+
+// UnimplementedWebCoreRender can be embedded to have forward compatible implementations.
+type UnimplementedWebCoreRender struct {
+ RenderAny func(*gin.Context, any, mir.Error)
+}
+
+func (r *UnimplementedWebCoreRender) RenderLogout(c *gin.Context, err mir.Error) {
+ r.RenderAny(c, nil, err)
+}
+
+func (r *UnimplementedWebCoreRender) RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) {
+ r.RenderAny(c, data, err)
+}
+
+func (r *UnimplementedWebCoreRender) RenderArticles(c *gin.Context, err mir.Error) {
+ r.RenderAny(c, nil, err)
+}
+
+func (r *UnimplementedWebCoreRender) RenderIndex(c *gin.Context, err mir.Error) {
+ r.RenderAny(c, nil, err)
+}
+
+func (r *UnimplementedWebCoreRender) mustEmbedUnimplementedWebCoreRender() {}
+
+// UnimplementedWebCoreBinding can be embedded to have forward compatible implementations.
+type UnimplementedWebCoreBinding struct {
+ BindAny func(*gin.Context, any) mir.Error
+}
+
+func (b *UnimplementedWebCoreBinding) BindLogin(c *gin.Context) (*LoginReq, mir.Error) {
+ obj := new(LoginReq)
+ err := b.BindAny(c, obj)
+ return obj, err
+}
+
+func (b *UnimplementedWebCoreBinding) mustEmbedUnimplementedWebCoreBinding() {}
diff --git a/internal/mirc/auto/api/x/v1/user.go b/internal/mirc/auto/api/x/v1/user.go
new file mode 100644
index 00000000..89a3b086
--- /dev/null
+++ b/internal/mirc/auto/api/x/v1/user.go
@@ -0,0 +1,140 @@
+// Code generated by go-mir. DO NOT EDIT.
+
+package v1
+
+import (
+ "net/http"
+
+ "github.com/alimy/mir/v3"
+ "github.com/gin-gonic/gin"
+)
+
+type LoginReq struct {
+ AgentInfo AgentInfo `json:"agent_info"`
+ Name string `json:"name"`
+ Passwd string `json:"passwd"`
+}
+
+type AgentInfo struct {
+ Platform string `json:"platform"`
+ UserAgent string `json:"user_agent"`
+}
+
+type LoginResp struct {
+ UserInfo
+ ServerInfo ServerInfo `json:"server_info"`
+ JwtToken string `json:"jwt_token"`
+}
+
+type ServerInfo struct {
+ ApiVer string `json:"api_ver"`
+}
+
+type UserInfo struct {
+ Name string `json:"name"`
+}
+
+type User interface {
+ // Chain provide handlers chain for gin
+ Chain() gin.HandlersChain
+
+ Logout() mir.Error
+ Login(*LoginReq) (*LoginResp, mir.Error)
+
+ mustEmbedUnimplementedUserServant()
+}
+
+type UserBinding interface {
+ BindLogin(*gin.Context) (*LoginReq, mir.Error)
+
+ mustEmbedUnimplementedUserBinding()
+}
+
+type UserRender interface {
+ RenderLogout(*gin.Context, mir.Error)
+ RenderLogin(*gin.Context, *LoginResp, mir.Error)
+
+ mustEmbedUnimplementedUserRender()
+}
+
+// RegisterUserServant register User servant to gin
+func RegisterUserServant(e *gin.Engine, s User, b UserBinding, r UserRender) {
+ router := e.Group("x/v1")
+ // use chain for router
+ middlewares := s.Chain()
+ router.Use(middlewares...)
+
+ // register routes info to router
+ router.Handle("POST", "/user/logout/", func(c *gin.Context) {
+ select {
+ case <-c.Request.Context().Done():
+ return
+ default:
+ }
+
+ r.RenderLogout(c, s.Logout())
+ })
+
+ router.Handle("POST", "/user/login/", func(c *gin.Context) {
+ select {
+ case <-c.Request.Context().Done():
+ return
+ default:
+ }
+
+ req, err := b.BindLogin(c)
+ if err != nil {
+ r.RenderLogin(c, nil, err)
+ return
+ }
+ resp, err := s.Login(req)
+ r.RenderLogin(c, resp, err)
+ })
+
+}
+
+// UnimplementedUserServant can be embedded to have forward compatible implementations.
+type UnimplementedUserServant struct {
+}
+
+func (UnimplementedUserServant) Chain() gin.HandlersChain {
+ return nil
+}
+
+func (UnimplementedUserServant) Logout() mir.Error {
+ return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented))
+}
+
+func (UnimplementedUserServant) Login(req *LoginReq) (*LoginResp, mir.Error) {
+ return nil, mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented))
+}
+
+func (UnimplementedUserServant) mustEmbedUnimplementedUserServant() {}
+
+// UnimplementedUserRender can be embedded to have forward compatible implementations.
+type UnimplementedUserRender struct {
+ RenderAny func(*gin.Context, any, mir.Error)
+}
+
+func (r *UnimplementedUserRender) RenderLogout(c *gin.Context, err mir.Error) {
+ r.RenderAny(c, nil, err)
+}
+
+func (r *UnimplementedUserRender) RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) {
+ r.RenderAny(c, data, err)
+}
+
+func (r *UnimplementedUserRender) mustEmbedUnimplementedUserRender() {}
+
+// UnimplementedUserBinding can be embedded to have forward compatible implementations.
+type UnimplementedUserBinding struct {
+ BindAny func(*gin.Context, any) mir.Error
+}
+
+func (b *UnimplementedUserBinding) BindLogin(c *gin.Context) (*LoginReq, mir.Error) {
+ obj := new(LoginReq)
+ err := b.BindAny(c, obj)
+ return obj, err
+}
+
+func (b *UnimplementedUserBinding) mustEmbedUnimplementedUserBinding() {}
diff --git a/internal/mirc/main.go b/internal/mirc/main.go
new file mode 100644
index 00000000..6213d798
--- /dev/null
+++ b/internal/mirc/main.go
@@ -0,0 +1,32 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package main
+
+import (
+ "log"
+
+ . "github.com/alimy/mir/v3/core"
+ . "github.com/alimy/mir/v3/engine"
+
+ _ "github.com/rocboss/paopao-ce/internal/mirc/routes/admin/v1"
+ _ "github.com/rocboss/paopao-ce/internal/mirc/routes/bot/v1"
+ _ "github.com/rocboss/paopao-ce/internal/mirc/routes/localoss/v1"
+ _ "github.com/rocboss/paopao-ce/internal/mirc/routes/space/v1"
+ _ "github.com/rocboss/paopao-ce/internal/mirc/routes/v1"
+)
+
+//go:generate go run main.go
+func main() {
+ log.Println("generate code start")
+ opts := Options{
+ RunMode(InSerialDebugMode),
+ GeneratorName(GeneratorGin),
+ SinkPath("auto"),
+ }
+ if err := Generate(opts); err != nil {
+ log.Fatal(err)
+ }
+ log.Println("generate code finish")
+}
diff --git a/internal/mirc/routes/README.md b/internal/mirc/routes/README.md
new file mode 100644
index 00000000..c592aa65
--- /dev/null
+++ b/internal/mirc/routes/README.md
@@ -0,0 +1,10 @@
+### RESTful API for paopao-ce
+本目录包含所有RESTful API相关定义文件
+
+|目录|系列API|备注|
+| ----- | ----- | ----- |
+|v1|/|Web v1版本RESTful API相关定义文件|
+|admin|m|Admin后台运维系列相关RESTful API相关定义文件|
+|space|x|SpaceX系列相关RESTful API相关定义文件|
+|localoss|s| LocalOSS OBS系列RESTful API相关定义文件|
+|bot|r| Bot系列相关RESTful API相关定义文件|
diff --git a/internal/mirc/routes/admin/README.md b/internal/mirc/routes/admin/README.md
new file mode 100644
index 00000000..c9fa71b9
--- /dev/null
+++ b/internal/mirc/routes/admin/README.md
@@ -0,0 +1,4 @@
+### Admin系列RESTful API相关定义文件
+本目录包含 Admin后台运维相关API定义文件。
+
+* v1 - v1版本API
diff --git a/internal/mirc/routes/admin/v1/user.go b/internal/mirc/routes/admin/v1/user.go
new file mode 100644
index 00000000..6f0dcb79
--- /dev/null
+++ b/internal/mirc/routes/admin/v1/user.go
@@ -0,0 +1,42 @@
+package v1
+
+import (
+ . "github.com/alimy/mir/v3"
+ . "github.com/alimy/mir/v3/engine"
+)
+
+func init() {
+ AddEntry(new(User))
+}
+
+type AgentInfo struct {
+ Platform string `json:"platform"`
+ UserAgent string `json:"user_agent"`
+}
+
+type ServerInfo struct {
+ ApiVer string `json:"api_ver"`
+}
+
+type UserInfo struct {
+ Name string `json:"name"`
+}
+
+type LoginReq struct {
+ AgentInfo AgentInfo `json:"agent_info"`
+ Name string `json:"name"`
+ Passwd string `json:"passwd"`
+}
+
+type LoginResp struct {
+ UserInfo
+ ServerInfo ServerInfo `json:"server_info"`
+ JwtToken string `json:"jwt_token"`
+}
+
+type User struct {
+ Chain Chain `mir:"-"`
+ Group Group `mir:"m/v1"`
+ Login func(Post, LoginReq) LoginResp `mir:"/user/login/"`
+ Logout func(Post) `mir:"/user/logout/"`
+}
diff --git a/internal/mirc/routes/bot/README.md b/internal/mirc/routes/bot/README.md
new file mode 100644
index 00000000..a1aa83ac
--- /dev/null
+++ b/internal/mirc/routes/bot/README.md
@@ -0,0 +1,4 @@
+### Bot系列RESTful API相关定义文件
+本目录包含 Bot相关API定义文件。
+
+* v1 - v1版本API
diff --git a/internal/mirc/routes/bot/v1/user.go b/internal/mirc/routes/bot/v1/user.go
new file mode 100644
index 00000000..a4839673
--- /dev/null
+++ b/internal/mirc/routes/bot/v1/user.go
@@ -0,0 +1,42 @@
+package v1
+
+import (
+ . "github.com/alimy/mir/v3"
+ . "github.com/alimy/mir/v3/engine"
+)
+
+func init() {
+ AddEntry(new(User))
+}
+
+type AgentInfo struct {
+ Platform string `json:"platform"`
+ UserAgent string `json:"user_agent"`
+}
+
+type ServerInfo struct {
+ ApiVer string `json:"api_ver"`
+}
+
+type UserInfo struct {
+ Name string `json:"name"`
+}
+
+type LoginReq struct {
+ AgentInfo AgentInfo `json:"agent_info"`
+ Name string `json:"name"`
+ Passwd string `json:"passwd"`
+}
+
+type LoginResp struct {
+ UserInfo
+ ServerInfo ServerInfo `json:"server_info"`
+ JwtToken string `json:"jwt_token"`
+}
+
+type User struct {
+ Chain Chain `mir:"-"`
+ Group Group `mir:"r/v1"`
+ Login func(Post, LoginReq) LoginResp `mir:"/user/login/"`
+ Logout func(Post) `mir:"/user/logout/"`
+}
diff --git a/internal/mirc/routes/localoss/README.md b/internal/mirc/routes/localoss/README.md
new file mode 100644
index 00000000..e1769bf5
--- /dev/null
+++ b/internal/mirc/routes/localoss/README.md
@@ -0,0 +1,4 @@
+### LocalOSS OBS系列RESTful API相关定义文件
+本目录包含 LocalOSS OBS 系列相关API定义文件。
+
+* v1 - v1版本API
diff --git a/internal/mirc/routes/localoss/v1/user.go b/internal/mirc/routes/localoss/v1/user.go
new file mode 100644
index 00000000..555ff6d7
--- /dev/null
+++ b/internal/mirc/routes/localoss/v1/user.go
@@ -0,0 +1,42 @@
+package v1
+
+import (
+ . "github.com/alimy/mir/v3"
+ . "github.com/alimy/mir/v3/engine"
+)
+
+func init() {
+ AddEntry(new(User))
+}
+
+type AgentInfo struct {
+ Platform string `json:"platform"`
+ UserAgent string `json:"user_agent"`
+}
+
+type ServerInfo struct {
+ ApiVer string `json:"api_ver"`
+}
+
+type UserInfo struct {
+ Name string `json:"name"`
+}
+
+type LoginReq struct {
+ AgentInfo AgentInfo `json:"agent_info"`
+ Name string `json:"name"`
+ Passwd string `json:"passwd"`
+}
+
+type LoginResp struct {
+ UserInfo
+ ServerInfo ServerInfo `json:"server_info"`
+ JwtToken string `json:"jwt_token"`
+}
+
+type User struct {
+ Group Group `mir:"s/v1"`
+ Index func(Get) `mir:"/index/"`
+ Login func(Post, LoginReq) LoginResp `mir:"/user/login/"`
+ Logout func(Post) `mir:"/user/logout/"`
+}
diff --git a/internal/mirc/routes/space/README.md b/internal/mirc/routes/space/README.md
new file mode 100644
index 00000000..a4ec3303
--- /dev/null
+++ b/internal/mirc/routes/space/README.md
@@ -0,0 +1,4 @@
+### SpaceX系列RESTful API
+本目录包含SpaceX系列RESTful API相关定义文件
+
+* v1 - v1版本API
diff --git a/internal/mirc/routes/space/v1/user.go b/internal/mirc/routes/space/v1/user.go
new file mode 100644
index 00000000..8dd49fa5
--- /dev/null
+++ b/internal/mirc/routes/space/v1/user.go
@@ -0,0 +1,42 @@
+package v1
+
+import (
+ . "github.com/alimy/mir/v3"
+ . "github.com/alimy/mir/v3/engine"
+)
+
+func init() {
+ AddEntry(new(User))
+}
+
+type AgentInfo struct {
+ Platform string `json:"platform"`
+ UserAgent string `json:"user_agent"`
+}
+
+type ServerInfo struct {
+ ApiVer string `json:"api_ver"`
+}
+
+type UserInfo struct {
+ Name string `json:"name"`
+}
+
+type LoginReq struct {
+ AgentInfo AgentInfo `json:"agent_info"`
+ Name string `json:"name"`
+ Passwd string `json:"passwd"`
+}
+
+type LoginResp struct {
+ UserInfo
+ ServerInfo ServerInfo `json:"server_info"`
+ JwtToken string `json:"jwt_token"`
+}
+
+type User struct {
+ Chain Chain `mir:"-"`
+ Group Group `mir:"x/v1"`
+ Login func(Post, LoginReq) LoginResp `mir:"/user/login/"`
+ Logout func(Post) `mir:"/user/logout/"`
+}
diff --git a/internal/mirc/routes/v1/localoss.go b/internal/mirc/routes/v1/localoss.go
new file mode 100644
index 00000000..bf2d09d8
--- /dev/null
+++ b/internal/mirc/routes/v1/localoss.go
@@ -0,0 +1,15 @@
+package v1
+
+import (
+ . "github.com/alimy/mir/v3"
+ . "github.com/alimy/mir/v3/engine"
+)
+
+func init() {
+ AddEntry(new(LocalOSS))
+}
+
+type LocalOSS struct {
+ Chain Chain `mir:"-"`
+ Group Group `mir:"v1"`
+}
diff --git a/internal/mirc/routes/v1/web_admin.go b/internal/mirc/routes/v1/web_admin.go
new file mode 100644
index 00000000..db95fc86
--- /dev/null
+++ b/internal/mirc/routes/v1/web_admin.go
@@ -0,0 +1,15 @@
+package v1
+
+import (
+ . "github.com/alimy/mir/v3"
+ . "github.com/alimy/mir/v3/engine"
+)
+
+func init() {
+ AddEntry(new(WebAdmin))
+}
+
+type WebAdmin struct {
+ Chain Chain `mir:"-"`
+ Group Group `mir:"v1"`
+}
diff --git a/internal/mirc/routes/v1/web_alipay.go b/internal/mirc/routes/v1/web_alipay.go
new file mode 100644
index 00000000..61de0906
--- /dev/null
+++ b/internal/mirc/routes/v1/web_alipay.go
@@ -0,0 +1,15 @@
+package v1
+
+import (
+ . "github.com/alimy/mir/v3"
+ . "github.com/alimy/mir/v3/engine"
+)
+
+func init() {
+ AddEntry(new(WebAlipay))
+}
+
+type WebAlipay struct {
+ Chain Chain `mir:"-"`
+ Group Group `mir:"v1"`
+}
diff --git a/internal/mirc/routes/v1/web_core.go b/internal/mirc/routes/v1/web_core.go
new file mode 100644
index 00000000..83193986
--- /dev/null
+++ b/internal/mirc/routes/v1/web_core.go
@@ -0,0 +1,44 @@
+package v1
+
+import (
+ . "github.com/alimy/mir/v3"
+ . "github.com/alimy/mir/v3/engine"
+)
+
+func init() {
+ AddEntry(new(WebCore))
+}
+
+type AgentInfo struct {
+ Platform string `json:"platform"`
+ UserAgent string `json:"user_agent"`
+}
+
+type ServerInfo struct {
+ ApiVer string `json:"api_ver"`
+}
+
+type UserInfo struct {
+ Name string `json:"name"`
+}
+
+type LoginReq struct {
+ AgentInfo AgentInfo `json:"agent_info"`
+ Name string `json:"name"`
+ Passwd string `json:"passwd"`
+}
+
+type LoginResp struct {
+ UserInfo
+ ServerInfo ServerInfo `json:"server_info"`
+ JwtToken string `json:"jwt_token"`
+}
+
+type WebCore struct {
+ Chain Chain `mir:"-"`
+ Group Group `mir:"v1"`
+ Index func(Get) `mir:"/index/"`
+ Articles func(Get, Head) `mir:"/articles/:category/"`
+ Login func(Post, LoginReq) LoginResp `mir:"/user/login/"`
+ Logout func(Post) `mir:"/user/logout/"`
+}
diff --git a/internal/mirc/routes/v1/web_followship.go b/internal/mirc/routes/v1/web_followship.go
new file mode 100644
index 00000000..1dd9de82
--- /dev/null
+++ b/internal/mirc/routes/v1/web_followship.go
@@ -0,0 +1,15 @@
+package v1
+
+import (
+ . "github.com/alimy/mir/v3"
+ . "github.com/alimy/mir/v3/engine"
+)
+
+func init() {
+ AddEntry(new(WebFollowship))
+}
+
+type WebFollowship struct {
+ Chain Chain `mir:"-"`
+ Group Group `mir:"v1"`
+}
diff --git a/internal/mirc/routes/v1/web_friendship.go b/internal/mirc/routes/v1/web_friendship.go
new file mode 100644
index 00000000..e1276e99
--- /dev/null
+++ b/internal/mirc/routes/v1/web_friendship.go
@@ -0,0 +1,15 @@
+package v1
+
+import (
+ . "github.com/alimy/mir/v3"
+ . "github.com/alimy/mir/v3/engine"
+)
+
+func init() {
+ AddEntry(new(WebFriendship))
+}
+
+type WebFriendship struct {
+ Chain Chain `mir:"-"`
+ Group Group `mir:"v1"`
+}
diff --git a/internal/mirc/routes/v1/web_loose.go b/internal/mirc/routes/v1/web_loose.go
new file mode 100644
index 00000000..7eff7d44
--- /dev/null
+++ b/internal/mirc/routes/v1/web_loose.go
@@ -0,0 +1,15 @@
+package v1
+
+import (
+ . "github.com/alimy/mir/v3"
+ . "github.com/alimy/mir/v3/engine"
+)
+
+func init() {
+ AddEntry(new(WebLoose))
+}
+
+type WebLoose struct {
+ Chain Chain `mir:"-"`
+ Group Group `mir:"v1"`
+}
diff --git a/internal/mirc/routes/v1/web_priv.go b/internal/mirc/routes/v1/web_priv.go
new file mode 100644
index 00000000..3d73eb1b
--- /dev/null
+++ b/internal/mirc/routes/v1/web_priv.go
@@ -0,0 +1,15 @@
+package v1
+
+import (
+ . "github.com/alimy/mir/v3"
+ . "github.com/alimy/mir/v3/engine"
+)
+
+func init() {
+ AddEntry(new(WebPriv))
+}
+
+type WebPriv struct {
+ Chain Chain `mir:"-"`
+ Group Group `mir:"v1"`
+}
diff --git a/internal/mirc/routes/v1/web_pub.go b/internal/mirc/routes/v1/web_pub.go
new file mode 100644
index 00000000..7bfe2e3a
--- /dev/null
+++ b/internal/mirc/routes/v1/web_pub.go
@@ -0,0 +1,15 @@
+package v1
+
+import (
+ . "github.com/alimy/mir/v3"
+ . "github.com/alimy/mir/v3/engine"
+)
+
+func init() {
+ AddEntry(new(WebPub))
+}
+
+type WebPub struct {
+ Chain Chain `mir:"-"`
+ Group Group `mir:"v1"`
+}
diff --git a/internal/model/rest/contacts.go b/internal/model/rest/contacts.go
deleted file mode 100644
index bbf31e42..00000000
--- a/internal/model/rest/contacts.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package rest
-
-type RequestingFriendReq struct {
- UserId int64 `json:"user_id" binding:"required"`
- Greetings string `json:"greetings" binding:"required"`
-}
-
-type AddFriendReq struct {
- UserId int64 `json:"user_id" binding:"required"`
-}
-
-type RejectFriendReq struct {
- UserId int64 `json:"user_id" binding:"required"`
-}
-
-type DeleteFriendReq struct {
- UserId int64 `json:"user_id"`
-}
-
-type ContactItem struct {
- UserId int64 `json:"user_id"`
- UserName string `json:"username"`
- Nickname string `json:"nickname"`
- Avatar string `json:"avatar"`
- Phone string `json:"phone"`
-}
-
-type ContactsResp struct {
- Contacts []ContactItem `json:"contacts"`
- Total int64 `json:"total"`
-}
diff --git a/internal/model/rest/tweets.go b/internal/model/rest/tweets.go
deleted file mode 100644
index de85e179..00000000
--- a/internal/model/rest/tweets.go
+++ /dev/null
@@ -1,8 +0,0 @@
-package rest
-
-import "github.com/rocboss/paopao-ce/internal/model"
-
-type IndexTweetsResp struct {
- Tweets []*model.PostFormated
- Total int64
-}
diff --git a/internal/model/rest/user.go b/internal/model/rest/user.go
deleted file mode 100644
index 60ff467d..00000000
--- a/internal/model/rest/user.go
+++ /dev/null
@@ -1,11 +0,0 @@
-package rest
-
-type UserProfileResp struct {
- ID int64 `json:"id"`
- Nickname string `json:"nickname"`
- Username string `json:"username"`
- Status int `json:"status"`
- Avatar string `json:"avatar"`
- IsAdmin bool `json:"is_admin"`
- IsFriend bool `json:"is_friend"`
-}
diff --git a/internal/proto/RADME.md b/internal/proto/RADME.md
new file mode 100644
index 00000000..05d78ece
--- /dev/null
+++ b/internal/proto/RADME.md
@@ -0,0 +1,2 @@
+### gRPC API
+This directory contain some gRPC API define files.
diff --git a/internal/proto/gen.go b/internal/proto/gen.go
new file mode 100644
index 00000000..adb9c8db
--- /dev/null
+++ b/internal/proto/gen.go
@@ -0,0 +1,5 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package proto
diff --git a/internal/proto/tweets.proto b/internal/proto/tweets.proto
new file mode 100644
index 00000000..1fcc9364
--- /dev/null
+++ b/internal/proto/tweets.proto
@@ -0,0 +1,10 @@
+syntax = "proto3";
+
+package paopao;
+
+option go_package = "proto";
+
+message Tag {
+ string name = 1;
+ int32 type = 2;
+}
diff --git a/internal/servants/admin/admin.go b/internal/servants/admin/admin.go
new file mode 100644
index 00000000..3fa2a7cf
--- /dev/null
+++ b/internal/servants/admin/admin.go
@@ -0,0 +1,15 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package admin
+
+import (
+ "github.com/gin-gonic/gin"
+ api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/m/v1"
+)
+
+// RouteWeb register Manager route
+func RouteManager(e *gin.Engine) {
+ api.RegisterUserServant(e, newUserSrv(), newUserBinding(), newUserRender())
+}
diff --git a/internal/servants/admin/user.go b/internal/servants/admin/user.go
new file mode 100644
index 00000000..6c3f11ab
--- /dev/null
+++ b/internal/servants/admin/user.go
@@ -0,0 +1,51 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package admin
+
+import (
+ api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/m/v1"
+ "github.com/rocboss/paopao-ce/internal/servants/base"
+)
+
+var (
+ _ api.User = (*userSrv)(nil)
+ _ api.UserBinding = (*userBinding)(nil)
+ _ api.UserRender = (*userRender)(nil)
+)
+
+type userSrv struct {
+ base.BaseServant
+ api.UnimplementedUserServant
+}
+
+type userBinding struct {
+ base.BaseBinding
+ *api.UnimplementedUserBinding
+}
+
+type userRender struct {
+ base.BaseRender
+ *api.UnimplementedUserRender
+}
+
+func newUserSrv() api.User {
+ return &userSrv{}
+}
+
+func newUserBinding() api.UserBinding {
+ return &userBinding{
+ UnimplementedUserBinding: &api.UnimplementedUserBinding{
+ BindAny: base.BindAny,
+ },
+ }
+}
+
+func newUserRender() api.UserRender {
+ return &userRender{
+ UnimplementedUserRender: &api.UnimplementedUserRender{
+ RenderAny: base.RenderAny,
+ },
+ }
+}
diff --git a/internal/servants/base/base.go b/internal/servants/base/base.go
new file mode 100644
index 00000000..6c204e7e
--- /dev/null
+++ b/internal/servants/base/base.go
@@ -0,0 +1,77 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package base
+
+import (
+ "net/http"
+ "os"
+
+ "github.com/alimy/mir/v3"
+ "github.com/gin-gonic/gin"
+ "github.com/rocboss/paopao-ce/internal/core"
+ "github.com/rocboss/paopao-ce/pkg/xerror"
+)
+
+type BaseServant struct {
+ // TODO
+}
+
+type BaseBinding struct {
+ // TODO
+}
+
+type BaseRender struct {
+ // TODO
+}
+
+func (BaseServant) userFrom(c *gin.Context) (*core.User, bool) {
+ if u, exists := c.Get("USER"); exists {
+ user, ok := u.(*core.User)
+ return user, ok
+ }
+ return nil, false
+}
+
+func BindAny(c *gin.Context, obj any) mir.Error {
+ var errs xerror.ValidErrors
+ err := c.ShouldBind(obj)
+ if err != nil {
+ return mir.NewError(xerror.InvalidParams.Code(), xerror.InvalidParams.WithDetails(errs.Error()))
+ }
+ return nil
+}
+
+func RenderAny(c *gin.Context, data any, err mir.Error) {
+ if err == nil {
+ hostname, _ := os.Hostname()
+ if data == nil {
+ data = gin.H{
+ "code": 0,
+ "msg": "success",
+ "tracehost": hostname,
+ }
+ } else {
+ data = gin.H{
+ "code": 0,
+ "msg": "success",
+ "data": data,
+ "tracehost": hostname,
+ }
+ }
+ c.JSON(http.StatusOK, data)
+ } else {
+ // TODO: error process logic
+ resp := gin.H{"code": err.StatusCode(), "msg": err.Error()}
+ // xerr := &xerror.Error{}
+ // if errors.As(err, xerr) {
+ // resp["code"], resp["msg"] = xerr.Code(), xerr.Msg()
+ // details := xerr.Details()
+ // if len(details) > 0 {
+ // resp["details"] = details
+ // }
+ // }
+ c.JSON(http.StatusInternalServerError, resp)
+ }
+}
diff --git a/internal/servants/bot/bot.go b/internal/servants/bot/bot.go
new file mode 100644
index 00000000..6ddd6846
--- /dev/null
+++ b/internal/servants/bot/bot.go
@@ -0,0 +1,15 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package bot
+
+import (
+ "github.com/gin-gonic/gin"
+ api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/r/v1"
+)
+
+// RouteBot register Bot route
+func RouteBot(e *gin.Engine) {
+ api.RegisterUserServant(e, newUserSrv(), newUserBinding(), newUserRender())
+}
diff --git a/internal/servants/bot/user.go b/internal/servants/bot/user.go
new file mode 100644
index 00000000..9f17a6e8
--- /dev/null
+++ b/internal/servants/bot/user.go
@@ -0,0 +1,51 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package bot
+
+import (
+ api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/r/v1"
+ "github.com/rocboss/paopao-ce/internal/servants/base"
+)
+
+var (
+ _ api.User = (*userSrv)(nil)
+ _ api.UserBinding = (*userBinding)(nil)
+ _ api.UserRender = (*userRender)(nil)
+)
+
+type userSrv struct {
+ base.BaseServant
+ api.UnimplementedUserServant
+}
+
+type userBinding struct {
+ base.BaseBinding
+ *api.UnimplementedUserBinding
+}
+
+type userRender struct {
+ base.BaseRender
+ *api.UnimplementedUserRender
+}
+
+func newUserSrv() api.User {
+ return &userSrv{}
+}
+
+func newUserBinding() api.UserBinding {
+ return &userBinding{
+ UnimplementedUserBinding: &api.UnimplementedUserBinding{
+ BindAny: base.BindAny,
+ },
+ }
+}
+
+func newUserRender() api.UserRender {
+ return &userRender{
+ UnimplementedUserRender: &api.UnimplementedUserRender{
+ RenderAny: base.RenderAny,
+ },
+ }
+}
diff --git a/internal/middleware/admin.go b/internal/servants/chain/admin.go
similarity index 53%
rename from internal/middleware/admin.go
rename to internal/servants/chain/admin.go
index f81b00ee..35a0fbc3 100644
--- a/internal/middleware/admin.go
+++ b/internal/servants/chain/admin.go
@@ -1,8 +1,12 @@
-package middleware
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package chain
import (
"github.com/gin-gonic/gin"
- "github.com/rocboss/paopao-ce/internal/model"
+ "github.com/rocboss/paopao-ce/internal/core"
"github.com/rocboss/paopao-ce/pkg/app"
"github.com/rocboss/paopao-ce/pkg/errcode"
)
@@ -10,8 +14,8 @@ import (
func Admin() gin.HandlerFunc {
return func(c *gin.Context) {
if user, exist := c.Get("USER"); exist {
- if userModel, ok := user.(*model.User); ok {
- if userModel.Status == model.UserStatusNormal && userModel.IsAdmin {
+ if userModel, ok := user.(*core.User); ok {
+ if userModel.Status == core.UserStatusNormal && userModel.IsAdmin {
c.Next()
return
}
diff --git a/internal/middleware/jwt.go b/internal/servants/chain/jwt.go
similarity index 89%
rename from internal/middleware/jwt.go
rename to internal/servants/chain/jwt.go
index 3fab7679..a0396630 100644
--- a/internal/middleware/jwt.go
+++ b/internal/servants/chain/jwt.go
@@ -1,4 +1,8 @@
-package middleware
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package chain
import (
"strings"
@@ -6,7 +10,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v4"
"github.com/rocboss/paopao-ce/internal/conf"
- "github.com/rocboss/paopao-ce/internal/model"
+ "github.com/rocboss/paopao-ce/internal/core"
"github.com/rocboss/paopao-ce/pkg/app"
"github.com/rocboss/paopao-ce/pkg/errcode"
)
@@ -51,8 +55,8 @@ func JWT() gin.HandlerFunc {
c.Set("USERNAME", claims.Username)
// 加载用户信息
- user := &model.User{
- Model: &model.Model{
+ user := &core.User{
+ Model: &core.Model{
ID: claims.UID,
},
}
@@ -97,8 +101,8 @@ func JwtLoose() gin.HandlerFunc {
c.Set("UID", claims.UID)
c.Set("USERNAME", claims.Username)
// 加载用户信息
- user := &model.User{
- Model: &model.Model{
+ user := &core.User{
+ Model: &core.Model{
ID: claims.UID,
},
}
diff --git a/internal/middleware/priv.go b/internal/servants/chain/priv.go
similarity index 66%
rename from internal/middleware/priv.go
rename to internal/servants/chain/priv.go
index fe31b008..6c09d0a8 100644
--- a/internal/middleware/priv.go
+++ b/internal/servants/chain/priv.go
@@ -1,10 +1,14 @@
-package middleware
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package chain
import (
+ "github.com/alimy/cfg"
"github.com/gin-gonic/gin"
- "github.com/rocboss/paopao-ce/internal/model"
+ "github.com/rocboss/paopao-ce/internal/core"
"github.com/rocboss/paopao-ce/pkg/app"
- "github.com/rocboss/paopao-ce/pkg/cfg"
"github.com/rocboss/paopao-ce/pkg/errcode"
)
@@ -12,8 +16,8 @@ func Priv() gin.HandlerFunc {
if cfg.If("PhoneBind") {
return func(c *gin.Context) {
if u, exist := c.Get("USER"); exist {
- if user, ok := u.(*model.User); ok {
- if user.Status == model.UserStatusNormal {
+ if user, ok := u.(*core.User); ok {
+ if user.Status == core.UserStatusNormal {
if user.Phone == "" {
response := app.NewResponse(c)
response.ToErrorResponse(errcode.AccountNoPhoneBind)
@@ -32,7 +36,7 @@ func Priv() gin.HandlerFunc {
} else {
return func(c *gin.Context) {
if u, exist := c.Get("USER"); exist {
- if user, ok := u.(*model.User); ok && user.Status == model.UserStatusNormal {
+ if user, ok := u.(*core.User); ok && user.Status == core.UserStatusNormal {
c.Next()
return
}
diff --git a/internal/servants/docs/docs.go b/internal/servants/docs/docs.go
new file mode 100644
index 00000000..7b6c9d36
--- /dev/null
+++ b/internal/servants/docs/docs.go
@@ -0,0 +1,17 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+//go:build !docs
+// +build !docs
+
+package docs
+
+import (
+ "github.com/gin-gonic/gin"
+)
+
+// RegisterDocs stub function for register docs asset route
+func RegisterDocs(e *gin.Engine) {
+ // empty
+}
diff --git a/internal/servants/docs/docs_embed.go b/internal/servants/docs/docs_embed.go
new file mode 100644
index 00000000..8879896c
--- /dev/null
+++ b/internal/servants/docs/docs_embed.go
@@ -0,0 +1,21 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+//go:build docs
+// +build docs
+
+package docs
+
+import (
+ "github.com/alimy/cfg"
+ "github.com/gin-gonic/gin"
+ "github.com/rocboss/paopao-ce/docs/openapi"
+)
+
+// RegisterDocs register docs asset route
+func RegisterDocs(e *gin.Engine) {
+ cfg.Be("Docs:OpenAPI", func() {
+ e.StaticFS("/docs/openapi", openapi.NewFileSystem())
+ })
+}
diff --git a/internal/servants/localoss/localoss.go b/internal/servants/localoss/localoss.go
new file mode 100644
index 00000000..721f0407
--- /dev/null
+++ b/internal/servants/localoss/localoss.go
@@ -0,0 +1,30 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package localoss
+
+import (
+ "path/filepath"
+
+ "github.com/gin-gonic/gin"
+ "github.com/rocboss/paopao-ce/internal/conf"
+ api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/s/v1"
+ "github.com/sirupsen/logrus"
+)
+
+// RouteLocalOSS register LocalOSS route if needed
+func RouteLocalOSS(e *gin.Engine) {
+ savePath, err := filepath.Abs(conf.LocalOSSSetting.SavePath)
+ if err != nil {
+ logrus.Fatalf("get localOSS save path err: %v", err)
+ }
+ e.Static("/oss", savePath)
+
+ logrus.Infof("register LocalOSS route in /oss on save path: %s", savePath)
+}
+
+// RouteLocaloss register LocalOSS route if needed
+func RouteLocaloss(e *gin.Engine) {
+ api.RegisterUserServant(e, newUserSrv(), newUserBinding(), newUserRender())
+}
diff --git a/internal/servants/localoss/user.go b/internal/servants/localoss/user.go
new file mode 100644
index 00000000..b8d2309a
--- /dev/null
+++ b/internal/servants/localoss/user.go
@@ -0,0 +1,51 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package localoss
+
+import (
+ api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/s/v1"
+ "github.com/rocboss/paopao-ce/internal/servants/base"
+)
+
+var (
+ _ api.User = (*userSrv)(nil)
+ _ api.UserBinding = (*userBinding)(nil)
+ _ api.UserRender = (*userRender)(nil)
+)
+
+type userSrv struct {
+ base.BaseServant
+ api.UnimplementedUserServant
+}
+
+type userBinding struct {
+ base.BaseBinding
+ *api.UnimplementedUserBinding
+}
+
+type userRender struct {
+ base.BaseRender
+ *api.UnimplementedUserRender
+}
+
+func newUserSrv() api.User {
+ return &userSrv{}
+}
+
+func newUserBinding() api.UserBinding {
+ return &userBinding{
+ UnimplementedUserBinding: &api.UnimplementedUserBinding{
+ BindAny: base.BindAny,
+ },
+ }
+}
+
+func newUserRender() api.UserRender {
+ return &userRender{
+ UnimplementedUserRender: &api.UnimplementedUserRender{
+ RenderAny: base.RenderAny,
+ },
+ }
+}
diff --git a/internal/servants/localoss/xerror.go b/internal/servants/localoss/xerror.go
new file mode 100644
index 00000000..38132d24
--- /dev/null
+++ b/internal/servants/localoss/xerror.go
@@ -0,0 +1,15 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package localoss
+
+import (
+ "github.com/rocboss/paopao-ce/pkg/xerror"
+)
+
+var (
+ errFileUploadFailed = xerror.NewError(10200, "文件上传失败")
+ errFileInvalidExt = xerror.NewError(10201, "文件类型不合法")
+ errFileInvalidSize = xerror.NewError(10202, "文件大小超限")
+)
diff --git a/internal/servants/servants.go b/internal/servants/servants.go
new file mode 100644
index 00000000..dd03b1de
--- /dev/null
+++ b/internal/servants/servants.go
@@ -0,0 +1,49 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package servants
+
+import (
+ "github.com/alimy/cfg"
+ "github.com/gin-gonic/gin"
+ "github.com/rocboss/paopao-ce/internal/servants/admin"
+ "github.com/rocboss/paopao-ce/internal/servants/bot"
+ "github.com/rocboss/paopao-ce/internal/servants/docs"
+ "github.com/rocboss/paopao-ce/internal/servants/localoss"
+ "github.com/rocboss/paopao-ce/internal/servants/space"
+ "github.com/rocboss/paopao-ce/internal/servants/statick"
+ "github.com/rocboss/paopao-ce/internal/servants/web"
+)
+
+// RegisterWebServants register all the servants to gin.Engine
+func RegisterWebServants(e *gin.Engine) {
+ docs.RegisterDocs(e)
+ statick.RegisterStatick(e)
+
+ cfg.Be("LocalOSS", func() {
+ localoss.RouteLocalOSS(e)
+ })
+
+ web.RouteWeb(e)
+}
+
+// RegisterAdminServants register all the servants to gin.Engine
+func RegisterAdminServants(e *gin.Engine) {
+ admin.RouteManager(e)
+}
+
+// RegisterSpaceXServants register all the servants to gin.Engine
+func RegisterSpaceXServants(e *gin.Engine) {
+ space.RouteSpaceX(e)
+}
+
+// RegisterBotServants register all the servants to gin.Engine
+func RegisterBotServants(e *gin.Engine) {
+ bot.RouteBot(e)
+}
+
+// RegisterLocalossServants register all the servants to gin.Engine
+func RegisterLocalossServants(e *gin.Engine) {
+ localoss.RouteLocaloss(e)
+}
diff --git a/internal/servants/space/space.go b/internal/servants/space/space.go
new file mode 100644
index 00000000..311f76b0
--- /dev/null
+++ b/internal/servants/space/space.go
@@ -0,0 +1,15 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package space
+
+import (
+ "github.com/gin-gonic/gin"
+ api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/x/v1"
+)
+
+// RouteWeb register SpaceX route
+func RouteSpaceX(e *gin.Engine) {
+ api.RegisterUserServant(e, newUserSrv(), newUserBinding(), newUserRender())
+}
diff --git a/internal/servants/space/user.go b/internal/servants/space/user.go
new file mode 100644
index 00000000..2e6014a0
--- /dev/null
+++ b/internal/servants/space/user.go
@@ -0,0 +1,51 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package space
+
+import (
+ api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/x/v1"
+ "github.com/rocboss/paopao-ce/internal/servants/base"
+)
+
+var (
+ _ api.User = (*userSrv)(nil)
+ _ api.UserBinding = (*userBinding)(nil)
+ _ api.UserRender = (*userRender)(nil)
+)
+
+type userSrv struct {
+ base.BaseServant
+ api.UnimplementedUserServant
+}
+
+type userBinding struct {
+ base.BaseBinding
+ *api.UnimplementedUserBinding
+}
+
+type userRender struct {
+ base.BaseRender
+ *api.UnimplementedUserRender
+}
+
+func newUserSrv() api.User {
+ return &userSrv{}
+}
+
+func newUserBinding() api.UserBinding {
+ return &userBinding{
+ UnimplementedUserBinding: &api.UnimplementedUserBinding{
+ BindAny: base.BindAny,
+ },
+ }
+}
+
+func newUserRender() api.UserRender {
+ return &userRender{
+ UnimplementedUserRender: &api.UnimplementedUserRender{
+ RenderAny: base.RenderAny,
+ },
+ }
+}
diff --git a/internal/servants/statick/statick.go b/internal/servants/statick/statick.go
new file mode 100644
index 00000000..d4c2bfdc
--- /dev/null
+++ b/internal/servants/statick/statick.go
@@ -0,0 +1,17 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+//go:build !embed
+// +build !embed
+
+package statick
+
+import (
+ "github.com/gin-gonic/gin"
+)
+
+// RegisterStatick stub function for register static asset route
+func RegisterStatick(e *gin.Engine) {
+ // empty
+}
diff --git a/internal/servants/statick/statick_embed.go b/internal/servants/statick/statick_embed.go
new file mode 100644
index 00000000..32da717f
--- /dev/null
+++ b/internal/servants/statick/statick_embed.go
@@ -0,0 +1,31 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+//go:build embed
+// +build embed
+
+package statick
+
+import (
+ "net/http"
+
+ "github.com/gin-gonic/gin"
+ "github.com/rocboss/paopao-ce/web"
+)
+
+// RegisterStatick register static assets route
+func RegisterStatick(e *gin.Engine) {
+ routeStatic(e, "/", "/index.html", "/favicon.ico", "/assets/*filepath")
+}
+
+func routeStatic(e *gin.Engine, paths ...string) {
+ staticHandler := http.FileServer(web.NewFileSystem())
+ handler := func(c *gin.Context) {
+ staticHandler.ServeHTTP(c.Writer, c.Request)
+ }
+ for _, path := range paths {
+ e.GET(path, handler)
+ e.HEAD(path, handler)
+ }
+}
diff --git a/internal/servants/web/admin.go b/internal/servants/web/admin.go
new file mode 100644
index 00000000..e4f2ef6e
--- /dev/null
+++ b/internal/servants/web/admin.go
@@ -0,0 +1,9 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package web
+
+type webAdminSrv struct {
+ // TODO
+}
diff --git a/internal/servants/web/alipay.go b/internal/servants/web/alipay.go
new file mode 100644
index 00000000..80cfd7b7
--- /dev/null
+++ b/internal/servants/web/alipay.go
@@ -0,0 +1,9 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package web
+
+type webAlipaySrv struct {
+ // TODO
+}
diff --git a/internal/servants/web/broker/attachment.go b/internal/servants/web/broker/attachment.go
new file mode 100644
index 00000000..e8c69447
--- /dev/null
+++ b/internal/servants/web/broker/attachment.go
@@ -0,0 +1,13 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package broker
+
+import (
+ "github.com/rocboss/paopao-ce/internal/core"
+)
+
+func CreateAttachment(attachment *core.Attachment) (*core.Attachment, error) {
+ return ds.CreateAttachment(attachment)
+}
diff --git a/internal/service/avatar.go b/internal/servants/web/broker/avatar.go
similarity index 95%
rename from internal/service/avatar.go
rename to internal/servants/web/broker/avatar.go
index 3ac302e0..04e183f4 100644
--- a/internal/service/avatar.go
+++ b/internal/servants/web/broker/avatar.go
@@ -1,4 +1,8 @@
-package service
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package broker
import (
"math/rand"
diff --git a/internal/servants/web/broker/broker.go b/internal/servants/web/broker/broker.go
new file mode 100644
index 00000000..fcc5846d
--- /dev/null
+++ b/internal/servants/web/broker/broker.go
@@ -0,0 +1,48 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package broker
+
+import (
+ "github.com/alimy/cfg"
+ "github.com/rocboss/paopao-ce/internal/core"
+ "github.com/rocboss/paopao-ce/internal/dao"
+ "github.com/sirupsen/logrus"
+)
+
+var (
+ ds core.DataService
+ ts core.TweetSearchService
+ oss core.ObjectStorageService
+ DisablePhoneVerify bool
+)
+
+func Initialize() {
+ ds = dao.DataService()
+ ts = dao.TweetSearchService()
+ oss = dao.ObjectStorageService()
+ DisablePhoneVerify = !cfg.If("Sms")
+}
+
+// persistMediaContents 获取媒体内容并持久化
+func persistMediaContents(contents []*PostContentItem) (items []string, err error) {
+ items = make([]string, 0, len(contents))
+ for _, item := range contents {
+ switch item.Type {
+ case core.ContentTypeImage,
+ core.ContentTypeVideo,
+ core.ContentTypeAudio,
+ core.ContentTypeAttachment,
+ core.ContentTypeChargeAttachment:
+ items = append(items, item.Content)
+ if err != nil {
+ continue
+ }
+ if err = oss.PersistObject(oss.ObjectKey(item.Content)); err != nil {
+ logrus.Errorf("service.persistMediaContents failed: %s", err)
+ }
+ }
+ }
+ return
+}
diff --git a/internal/service/comment.go b/internal/servants/web/broker/comment.go
similarity index 83%
rename from internal/service/comment.go
rename to internal/servants/web/broker/comment.go
index f5165d71..7f9389dc 100644
--- a/internal/service/comment.go
+++ b/internal/servants/web/broker/comment.go
@@ -1,11 +1,15 @@
-package service
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package broker
import (
+ "github.com/rocboss/paopao-ce/internal/core"
"time"
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/internal/conf"
- "github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/pkg/errcode"
"github.com/rocboss/paopao-ce/pkg/util"
)
@@ -28,8 +32,8 @@ type ReplyDelReq struct {
ID int64 `json:"id" binding:"required"`
}
-func GetPostComments(postID int64, sort string, offset, limit int) ([]*model.CommentFormated, int64, error) {
- conditions := &model.ConditionsT{
+func GetPostComments(postID int64, sort string, offset, limit int) ([]*core.CommentFormated, int64, error) {
+ conditions := &core.ConditionsT{
"post_id": postID,
"ORDER": sort,
}
@@ -61,7 +65,7 @@ func GetPostComments(postID int64, sort string, offset, limit int) ([]*model.Com
return nil, 0, err
}
- commentsFormated := []*model.CommentFormated{}
+ commentsFormated := []*core.CommentFormated{}
for _, comment := range comments {
commentFormated := comment.Format()
for _, content := range contents {
@@ -89,7 +93,7 @@ func GetPostComments(postID int64, sort string, offset, limit int) ([]*model.Com
return commentsFormated, totalRows, nil
}
-func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq) (comment *model.Comment, err error) {
+func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq) (comment *core.Comment, err error) {
var mediaContents []string
defer func() {
@@ -113,7 +117,7 @@ func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq)
return nil, errcode.MaxCommentCount
}
ip := ctx.ClientIP()
- comment = &model.Comment{
+ comment = &core.Comment{
PostID: post.ID,
UserID: userID,
IP: ip,
@@ -126,13 +130,13 @@ func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq)
for _, item := range param.Contents {
// 检查附件是否是本站资源
- if item.Type == model.CONTENT_TYPE_IMAGE || item.Type == model.CONTENT_TYPE_VIDEO || item.Type == model.CONTENT_TYPE_ATTACHMENT {
+ if item.Type == core.ContentTypeImage || item.Type == core.ContentTypeVideo || item.Type == core.ContentTypeAttachment {
if err := ds.CheckAttachment(item.Content); err != nil {
continue
}
}
- postContent := &model.CommentContent{
+ postContent := &core.CommentContent{
CommentID: comment.ID,
UserID: userID,
Content: item.Content,
@@ -153,10 +157,10 @@ func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq)
// 创建用户消息提醒
postMaster, err := ds.GetUserByID(post.UserID)
if err == nil && postMaster.ID != userID {
- go ds.CreateMessage(&model.Message{
+ go ds.CreateMessage(&core.Message{
SenderUserID: userID,
ReceiverUserID: postMaster.ID,
- Type: model.MsgtypeComment,
+ Type: core.MsgtypeComment,
Brief: "在泡泡中评论了你",
PostID: post.ID,
CommentID: comment.ID,
@@ -169,10 +173,10 @@ func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq)
}
// 创建消息提醒
- go ds.CreateMessage(&model.Message{
+ go ds.CreateMessage(&core.Message{
SenderUserID: userID,
ReceiverUserID: user.ID,
- Type: model.MsgtypeComment,
+ Type: core.MsgtypeComment,
Brief: "在泡泡评论中@了你",
PostID: post.ID,
CommentID: comment.ID,
@@ -182,11 +186,11 @@ func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq)
return comment, nil
}
-func GetPostComment(id int64) (*model.Comment, error) {
+func GetPostComment(id int64) (*core.Comment, error) {
return ds.GetCommentByID(id)
}
-func DeletePostComment(comment *model.Comment) error {
+func DeletePostComment(comment *core.Comment) error {
// 加载post
post, err := ds.GetPostByID(comment.PostID)
if err == nil {
@@ -198,7 +202,7 @@ func DeletePostComment(comment *model.Comment) error {
return ds.DeleteComment(comment)
}
-func createPostPreHandler(commentID int64, userID, atUserID int64) (*model.Post, *model.Comment, int64,
+func createPostPreHandler(commentID int64, userID, atUserID int64) (*core.Post, *core.Comment, int64,
error) {
// 加载Comment
comment, err := ds.GetCommentByID(commentID)
@@ -231,10 +235,10 @@ func createPostPreHandler(commentID int64, userID, atUserID int64) (*model.Post,
return post, comment, atUserID, nil
}
-func CreatePostCommentReply(ctx *gin.Context, commentID int64, content string, userID, atUserID int64) (*model.CommentReply, error) {
+func CreatePostCommentReply(ctx *gin.Context, commentID int64, content string, userID, atUserID int64) (*core.CommentReply, error) {
var (
- post *model.Post
- comment *model.Comment
+ post *core.Post
+ comment *core.Comment
err error
)
if post, comment, atUserID, err = createPostPreHandler(commentID, userID, atUserID); err != nil {
@@ -243,7 +247,7 @@ func CreatePostCommentReply(ctx *gin.Context, commentID int64, content string, u
// 创建评论
ip := ctx.ClientIP()
- reply := &model.CommentReply{
+ reply := &core.CommentReply{
CommentID: commentID,
UserID: userID,
Content: content,
@@ -268,10 +272,10 @@ func CreatePostCommentReply(ctx *gin.Context, commentID int64, content string, u
// 创建用户消息提醒
commentMaster, err := ds.GetUserByID(comment.UserID)
if err == nil && commentMaster.ID != userID {
- go ds.CreateMessage(&model.Message{
+ go ds.CreateMessage(&core.Message{
SenderUserID: userID,
ReceiverUserID: commentMaster.ID,
- Type: model.MsgTypeReply,
+ Type: core.MsgTypeReply,
Brief: "在泡泡评论下回复了你",
PostID: post.ID,
CommentID: comment.ID,
@@ -280,10 +284,10 @@ func CreatePostCommentReply(ctx *gin.Context, commentID int64, content string, u
}
postMaster, err := ds.GetUserByID(post.UserID)
if err == nil && postMaster.ID != userID && commentMaster.ID != postMaster.ID {
- go ds.CreateMessage(&model.Message{
+ go ds.CreateMessage(&core.Message{
SenderUserID: userID,
ReceiverUserID: postMaster.ID,
- Type: model.MsgTypeReply,
+ Type: core.MsgTypeReply,
Brief: "在泡泡评论下发布了新回复",
PostID: post.ID,
CommentID: comment.ID,
@@ -294,10 +298,10 @@ func CreatePostCommentReply(ctx *gin.Context, commentID int64, content string, u
user, err := ds.GetUserByID(atUserID)
if err == nil && user.ID != userID && commentMaster.ID != user.ID && postMaster.ID != user.ID {
// 创建消息提醒
- go ds.CreateMessage(&model.Message{
+ go ds.CreateMessage(&core.Message{
SenderUserID: userID,
ReceiverUserID: user.ID,
- Type: model.MsgTypeReply,
+ Type: core.MsgTypeReply,
Brief: "在泡泡评论的回复中@了你",
PostID: post.ID,
CommentID: comment.ID,
@@ -309,11 +313,11 @@ func CreatePostCommentReply(ctx *gin.Context, commentID int64, content string, u
return reply, nil
}
-func GetPostCommentReply(id int64) (*model.CommentReply, error) {
+func GetPostCommentReply(id int64) (*core.CommentReply, error) {
return ds.GetCommentReplyByID(id)
}
-func DeletePostCommentReply(reply *model.CommentReply) error {
+func DeletePostCommentReply(reply *core.CommentReply) error {
err := ds.DeleteCommentReply(reply)
if err != nil {
return err
diff --git a/internal/service/message.go b/internal/servants/web/broker/message.go
similarity index 84%
rename from internal/service/message.go
rename to internal/servants/web/broker/message.go
index a025a849..6e5dd1a1 100644
--- a/internal/service/message.go
+++ b/internal/servants/web/broker/message.go
@@ -1,4 +1,8 @@
-package service
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package broker
import (
"fmt"
@@ -6,7 +10,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/internal/conf"
- "github.com/rocboss/paopao-ce/internal/model"
+ "github.com/rocboss/paopao-ce/internal/core"
"github.com/rocboss/paopao-ce/pkg/convert"
"github.com/rocboss/paopao-ce/pkg/errcode"
)
@@ -23,7 +27,7 @@ type WhisperReq struct {
}
// CreateWhisper 创建私信
-func CreateWhisper(c *gin.Context, msg *model.Message) (*model.Message, error) {
+func CreateWhisper(c *gin.Context, msg *core.Message) (*core.Message, error) {
whisperKey := fmt.Sprintf("WhisperTimes:%d", msg.SenderUserID)
// 今日频次限制
@@ -65,8 +69,8 @@ func ReadMessage(id, userID int64) error {
return ds.ReadMessage(message)
}
-func GetMessages(userID int64, offset, limit int) ([]*model.MessageFormated, int64, error) {
- conditions := &model.ConditionsT{
+func GetMessages(userID int64, offset, limit int) ([]*core.MessageFormated, int64, error) {
+ conditions := &core.ConditionsT{
"receiver_user_id": userID,
"ORDER": "id DESC",
}
@@ -83,7 +87,7 @@ func GetMessages(userID int64, offset, limit int) ([]*model.MessageFormated, int
}
// 好友申请消息不需要获取其他信息
- if mf.Type == model.MsgTypeRequestingFriend {
+ if mf.Type == core.MsgTypeRequestingFriend {
continue
}
diff --git a/internal/service/post.go b/internal/servants/web/broker/post.go
similarity index 76%
rename from internal/service/post.go
rename to internal/servants/web/broker/post.go
index c8bda6b8..9a73528b 100644
--- a/internal/service/post.go
+++ b/internal/servants/web/broker/post.go
@@ -1,4 +1,8 @@
-package service
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package broker
import (
"errors"
@@ -10,8 +14,6 @@ import (
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/core"
- "github.com/rocboss/paopao-ce/internal/model"
- "github.com/rocboss/paopao-ce/internal/model/rest"
"github.com/rocboss/paopao-ce/pkg/errcode"
"github.com/rocboss/paopao-ce/pkg/util"
"github.com/sirupsen/logrus"
@@ -23,7 +25,7 @@ const TagTypeHot TagType = "hot"
const TagTypeNew TagType = "new"
type PostListReq struct {
- Conditions *model.ConditionsT
+ Conditions *core.ConditionsT
Offset int
Limit int
}
@@ -37,7 +39,7 @@ type PostCreationReq struct {
Tags []string `json:"tags" binding:"required"`
Users []string `json:"users" binding:"required"`
AttachmentPrice int64 `json:"attachment_price"`
- Visibility model.PostVisibleT `json:"visibility"`
+ Visibility core.PostVisibleT `json:"visibility"`
}
type PostDelReq struct {
@@ -53,8 +55,8 @@ type PostStickReq struct {
}
type PostVisibilityReq struct {
- ID int64 `json:"id" binding:"required"`
- Visibility model.PostVisibleT `json:"visibility"`
+ ID int64 `json:"id" binding:"required"`
+ Visibility core.PostVisibleT `json:"visibility"`
}
type PostStarReq struct {
@@ -66,27 +68,25 @@ type PostCollectionReq struct {
}
type PostContentItem struct {
- Content string `json:"content" binding:"required"`
- Type model.PostContentT `json:"type" binding:"required"`
- Sort int64 `json:"sort" binding:"required"`
+ Content string `json:"content" binding:"required"`
+ Type core.PostContentT `json:"type" binding:"required"`
+ Sort int64 `json:"sort" binding:"required"`
}
// Check 检查PostContentItem属性
func (p *PostContentItem) Check() error {
// 检查附件是否是本站资源
- if p.Type == model.CONTENT_TYPE_IMAGE || p.Type == model.CONTENT_TYPE_VIDEO || p.Type == model.
- CONTENT_TYPE_ATTACHMENT {
+ if p.Type == core.ContentTypeImage || p.Type == core.ContentTypeVideo || p.Type == core.ContentTypeAttachment {
if err := ds.CheckAttachment(p.Content); err != nil {
return err
}
}
// 检查链接是否合法
- if p.Type == model.CONTENT_TYPE_LINK {
+ if p.Type == core.ContentTypeLink {
if strings.Index(p.Content, "http://") != 0 && strings.Index(p.Content, "https://") != 0 {
return fmt.Errorf("链接不合法")
}
}
-
return nil
}
@@ -103,7 +103,7 @@ func tagsFrom(originTags []string) []string {
// CreatePost 创建文章
// TODO: 推文+推文内容需要在一个事务中添加,后续优化
-func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (_ *model.PostFormated, err error) {
+func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (_ *core.PostFormated, err error) {
var mediaContents []string
defer func() {
@@ -118,7 +118,7 @@ func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (_ *model.P
ip := c.ClientIP()
tags := tagsFrom(param.Tags)
- post := &model.Post{
+ post := &core.Post{
UserID: userID,
Tags: strings.Join(tags, ","),
IP: ip,
@@ -138,11 +138,11 @@ func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (_ *model.P
continue
}
- if item.Type == model.CONTENT_TYPE_ATTACHMENT && param.AttachmentPrice > 0 {
- item.Type = model.CONTENT_TYPE_CHARGE_ATTACHMENT
+ if item.Type == core.ContentTypeAttachment && param.AttachmentPrice > 0 {
+ item.Type = core.ContentTypeChargeAttachment
}
- postContent := &model.PostContent{
+ postContent := &core.PostContent{
PostID: post.ID,
UserID: userID,
Content: item.Content,
@@ -155,10 +155,10 @@ func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (_ *model.P
}
// 私密推文不创建标签与用户提醒
- if post.Visibility != model.PostVisitPrivate {
+ if post.Visibility != core.PostVisitPrivate {
// 创建标签
for _, t := range tags {
- tag := &model.Tag{
+ tag := &core.Tag{
UserID: userID,
Tag: t,
}
@@ -174,10 +174,10 @@ func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (_ *model.P
// 创建消息提醒
// TODO: 优化消息提醒处理机制
- go ds.CreateMessage(&model.Message{
+ go ds.CreateMessage(&core.Message{
SenderUserID: userID,
ReceiverUserID: user.ID,
- Type: model.MsgTypePost,
+ Type: core.MsgTypePost,
Brief: "在新发布的泡泡动态中@了你",
PostID: post.ID,
})
@@ -187,14 +187,14 @@ func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (_ *model.P
// 推送Search
PushPostToSearch(post)
- formatedPosts, err := ds.RevampPosts([]*model.PostFormated{post.Format()})
+ formatedPosts, err := ds.RevampPosts([]*core.PostFormated{post.Format()})
if err != nil {
return nil, err
}
return formatedPosts[0], nil
}
-func DeletePost(user *model.User, id int64) *errcode.Error {
+func DeletePost(user *core.User, id int64) *errcode.Error {
if user == nil {
return errcode.NoPermission
}
@@ -261,8 +261,8 @@ func StickPost(id int64) error {
return nil
}
-func VisiblePost(user *model.User, postId int64, visibility model.PostVisibleT) *errcode.Error {
- if visibility >= model.PostVisitInvalid {
+func VisiblePost(user *core.User, postId int64, visibility core.PostVisibleT) *errcode.Error {
+ if visibility >= core.PostVisitInvalid {
return errcode.InvalidParams
}
@@ -287,11 +287,11 @@ func VisiblePost(user *model.User, postId int64, visibility model.PostVisibleT)
return nil
}
-func GetPostStar(postID, userID int64) (*model.PostStar, error) {
+func GetPostStar(postID, userID int64) (*core.PostStar, error) {
return ds.GetUserPostStar(postID, userID)
}
-func CreatePostStar(postID, userID int64) (*model.PostStar, error) {
+func CreatePostStar(postID, userID int64) (*core.PostStar, error) {
// 加载Post
post, err := ds.GetPostByID(postID)
if err != nil {
@@ -299,7 +299,7 @@ func CreatePostStar(postID, userID int64) (*model.PostStar, error) {
}
// 私密post不可操作
- if post.Visibility == model.PostVisitPrivate {
+ if post.Visibility == core.PostVisitPrivate {
return nil, errors.New("no permision")
}
@@ -318,7 +318,7 @@ func CreatePostStar(postID, userID int64) (*model.PostStar, error) {
return star, nil
}
-func DeletePostStar(star *model.PostStar) error {
+func DeletePostStar(star *core.PostStar) error {
err := ds.DeletePostStar(star)
if err != nil {
return err
@@ -330,7 +330,7 @@ func DeletePostStar(star *model.PostStar) error {
}
// 私密post不可操作
- if post.Visibility == model.PostVisitPrivate {
+ if post.Visibility == core.PostVisitPrivate {
return errors.New("no permision")
}
@@ -344,11 +344,11 @@ func DeletePostStar(star *model.PostStar) error {
return nil
}
-func GetPostCollection(postID, userID int64) (*model.PostCollection, error) {
+func GetPostCollection(postID, userID int64) (*core.PostCollection, error) {
return ds.GetUserPostCollection(postID, userID)
}
-func CreatePostCollection(postID, userID int64) (*model.PostCollection, error) {
+func CreatePostCollection(postID, userID int64) (*core.PostCollection, error) {
// 加载Post
post, err := ds.GetPostByID(postID)
if err != nil {
@@ -356,7 +356,7 @@ func CreatePostCollection(postID, userID int64) (*model.PostCollection, error) {
}
// 私密post不可操作
- if post.Visibility == model.PostVisitPrivate {
+ if post.Visibility == core.PostVisitPrivate {
return nil, errors.New("no permision")
}
@@ -375,7 +375,7 @@ func CreatePostCollection(postID, userID int64) (*model.PostCollection, error) {
return collection, nil
}
-func DeletePostCollection(collection *model.PostCollection) error {
+func DeletePostCollection(collection *core.PostCollection) error {
err := ds.DeletePostCollection(collection)
if err != nil {
return err
@@ -387,7 +387,7 @@ func DeletePostCollection(collection *model.PostCollection) error {
}
// 私密post不可操作
- if post.Visibility == model.PostVisitPrivate {
+ if post.Visibility == core.PostVisitPrivate {
return errors.New("no permision")
}
@@ -401,7 +401,7 @@ func DeletePostCollection(collection *model.PostCollection) error {
return nil
}
-func GetPost(id int64) (*model.PostFormated, error) {
+func GetPost(id int64) (*core.PostFormated, error) {
post, err := ds.GetPostByID(id)
if err != nil {
@@ -431,15 +431,15 @@ func GetPost(id int64) (*model.PostFormated, error) {
return postFormated, nil
}
-func GetPostContentByID(id int64) (*model.PostContent, error) {
+func GetPostContentByID(id int64) (*core.PostContent, error) {
return ds.GetPostContentByID(id)
}
-func GetIndexPosts(user *model.User, offset int, limit int) (*rest.IndexTweetsResp, error) {
+func GetIndexPosts(user *core.User, offset int, limit int) (*core.IndexTweetList, error) {
return ds.IndexPosts(user, offset, limit)
}
-func GetPostList(req *PostListReq) ([]*model.Post, []*model.PostFormated, error) {
+func GetPostList(req *PostListReq) ([]*core.Post, []*core.PostFormated, error) {
posts, err := ds.GetPosts(req.Conditions, req.Offset, req.Limit)
if err != nil {
return nil, nil, err
@@ -448,11 +448,11 @@ func GetPostList(req *PostListReq) ([]*model.Post, []*model.PostFormated, error)
return posts, postFormated, err
}
-func GetPostCount(conditions *model.ConditionsT) (int64, error) {
+func GetPostCount(conditions *core.ConditionsT) (int64, error) {
return ds.GetPostCount(conditions)
}
-func GetPostListFromSearch(user *model.User, q *core.QueryReq, offset, limit int) ([]*model.PostFormated, int64, error) {
+func GetPostListFromSearch(user *core.User, q *core.QueryReq, offset, limit int) ([]*core.PostFormated, int64, error) {
resp, err := ts.Search(user, q, offset, limit)
if err != nil {
return nil, 0, err
@@ -464,7 +464,7 @@ func GetPostListFromSearch(user *model.User, q *core.QueryReq, offset, limit int
return posts, resp.Total, nil
}
-func GetPostListFromSearchByQuery(user *model.User, query string, offset, limit int) ([]*model.PostFormated, int64, error) {
+func GetPostListFromSearchByQuery(user *core.User, query string, offset, limit int) ([]*core.PostFormated, int64, error) {
q := &core.QueryReq{
Query: query,
Type: "search",
@@ -472,9 +472,9 @@ func GetPostListFromSearchByQuery(user *model.User, query string, offset, limit
return GetPostListFromSearch(user, q, offset, limit)
}
-func PushPostToSearch(post *model.Post) {
+func PushPostToSearch(post *core.Post) {
postFormated := post.Format()
- postFormated.User = &model.UserFormated{
+ postFormated.User = &core.UserFormated{
ID: post.UserID,
}
contents, _ := ds.GetPostContentsByIDs([]int64{post.ID})
@@ -484,7 +484,7 @@ func PushPostToSearch(post *model.Post) {
contentFormated := ""
for _, content := range postFormated.Contents {
- if content.Type == model.CONTENT_TYPE_TEXT || content.Type == model.CONTENT_TYPE_TITLE {
+ if content.Type == core.ContentTypeText || content.Type == core.ContentTypeTitle {
contentFormated = contentFormated + content.Content + "\n"
}
}
@@ -496,7 +496,7 @@ func PushPostToSearch(post *model.Post) {
ts.AddDocuments(docs, fmt.Sprintf("%d", post.ID))
}
-func DeleteSearchPost(post *model.Post) error {
+func DeleteSearchPost(post *core.Post) error {
return ts.DeleteDocuments([]string{fmt.Sprintf("%d", post.ID)})
}
@@ -505,8 +505,8 @@ func PushPostsToSearch(c *gin.Context) {
defer conf.Redis.Del(c, "JOB_PUSH_TO_SEARCH")
splitNum := 1000
- totalRows, _ := GetPostCount(&model.ConditionsT{
- "visibility IN ?": []model.PostVisibleT{model.PostVisitPublic, model.PostVisitFriend},
+ totalRows, _ := GetPostCount(&core.ConditionsT{
+ "visibility IN ?": []core.PostVisibleT{core.PostVisitPublic, core.PostVisitFriend},
})
pages := math.Ceil(float64(totalRows) / float64(splitNum))
@@ -514,7 +514,7 @@ func PushPostsToSearch(c *gin.Context) {
for i := 0; i < nums; i++ {
posts, postsFormated, err := GetPostList(&PostListReq{
- Conditions: &model.ConditionsT{},
+ Conditions: &core.ConditionsT{},
Offset: i * splitNum,
Limit: splitNum,
})
@@ -524,7 +524,7 @@ func PushPostsToSearch(c *gin.Context) {
for i, pf := range postsFormated {
contentFormated := ""
for _, content := range pf.Contents {
- if content.Type == model.CONTENT_TYPE_TEXT || content.Type == model.CONTENT_TYPE_TITLE {
+ if content.Type == core.ContentTypeText || content.Type == core.ContentTypeTitle {
contentFormated = contentFormated + content.Content + "\n"
}
}
@@ -538,22 +538,22 @@ func PushPostsToSearch(c *gin.Context) {
}
}
-func GetPostTags(param *PostTagsReq) ([]*model.TagFormated, error) {
+func GetPostTags(param *PostTagsReq) ([]*core.TagFormated, error) {
num := param.Num
if num > conf.AppSetting.MaxPageSize {
num = conf.AppSetting.MaxPageSize
}
- conditions := &model.ConditionsT{}
+ conditions := &core.ConditionsT{}
if param.Type == TagTypeHot {
// 热门标签
- conditions = &model.ConditionsT{
+ conditions = &core.ConditionsT{
"ORDER": "quote_num DESC",
}
}
if param.Type == TagTypeNew {
// 热门标签
- conditions = &model.ConditionsT{
+ conditions = &core.ConditionsT{
"ORDER": "id DESC",
}
}
@@ -571,7 +571,7 @@ func GetPostTags(param *PostTagsReq) ([]*model.TagFormated, error) {
users, _ := ds.GetUsersByIDs(userIds)
- tagsFormated := []*model.TagFormated{}
+ tagsFormated := []*core.TagFormated{}
for _, tag := range tags {
tagFormated := tag.Format()
for _, user := range users {
diff --git a/internal/service/sign.go b/internal/servants/web/broker/sign.go
similarity index 79%
rename from internal/service/sign.go
rename to internal/servants/web/broker/sign.go
index d3ec373a..c8883638 100644
--- a/internal/service/sign.go
+++ b/internal/servants/web/broker/sign.go
@@ -1,4 +1,8 @@
-package service
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package broker
import (
"fmt"
diff --git a/internal/service/user.go b/internal/servants/web/broker/user.go
similarity index 76%
rename from internal/service/user.go
rename to internal/servants/web/broker/user.go
index 7289c067..66919a99 100644
--- a/internal/service/user.go
+++ b/internal/servants/web/broker/user.go
@@ -1,4 +1,8 @@
-package service
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package broker
import (
"fmt"
@@ -10,15 +14,14 @@ import (
"github.com/gin-gonic/gin"
"github.com/gofrs/uuid"
"github.com/rocboss/paopao-ce/internal/conf"
- "github.com/rocboss/paopao-ce/internal/model"
- "github.com/rocboss/paopao-ce/internal/model/rest"
+ "github.com/rocboss/paopao-ce/internal/core"
"github.com/rocboss/paopao-ce/pkg/convert"
"github.com/rocboss/paopao-ce/pkg/errcode"
"github.com/rocboss/paopao-ce/pkg/util"
"github.com/sirupsen/logrus"
)
-const MAX_CAPTCHA_TIMES = 2
+const _MaxCaptchaTimes = 2
type PhoneCaptchaReq struct {
Phone string `json:"phone" form:"phone" binding:"required"`
@@ -59,19 +62,48 @@ type ChangeUserStatusReq struct {
Status int `json:"status" form:"status" binding:"required"`
}
-const LOGIN_ERR_KEY = "PaoPaoUserLoginErr"
-const MAX_LOGIN_ERR_TIMES = 10
+type RequestingFriendReq struct {
+ UserId int64 `json:"user_id" binding:"required"`
+ Greetings string `json:"greetings" binding:"required"`
+}
+
+type AddFriendReq struct {
+ UserId int64 `json:"user_id" binding:"required"`
+}
+
+type RejectFriendReq struct {
+ UserId int64 `json:"user_id" binding:"required"`
+}
+
+type DeleteFriendReq struct {
+ UserId int64 `json:"user_id"`
+}
+
+type UserProfileResp struct {
+ ID int64 `json:"id"`
+ Nickname string `json:"nickname"`
+ Username string `json:"username"`
+ Status int `json:"status"`
+ Avatar string `json:"avatar"`
+ IsAdmin bool `json:"is_admin"`
+ IsFriend bool `json:"is_friend"`
+}
+
+const (
+ _LoginErrKey = "PaoPaoUserLoginErr"
+ _MaxLoginErrTimes = 10
+)
// DoLogin 用户认证
-func DoLogin(ctx *gin.Context, param *AuthRequest) (*model.User, error) {
+func DoLogin(ctx *gin.Context, param *AuthRequest) (*core.User, error) {
user, err := ds.GetUserByUsername(param.Username)
if err != nil {
return nil, errcode.UnauthorizedAuthNotExist
}
if user.Model != nil && user.ID > 0 {
- if errTimes, err := conf.Redis.Get(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID)).Result(); err == nil {
- if convert.StrTo(errTimes).MustInt() >= MAX_LOGIN_ERR_TIMES {
+ if errTimes, err := conf.Redis.Get(ctx, fmt.Sprintf("%s:%d", _LoginErrKey, user.ID)).Result(); err == nil {
+ if convert.StrTo(errTimes).MustInt() >= _MaxLoginErrTimes {
return nil, errcode.TooManyLoginError
}
}
@@ -79,19 +111,19 @@ func DoLogin(ctx *gin.Context, param *AuthRequest) (*model.User, error) {
// 对比密码是否正确
if ValidPassword(user.Password, param.Password, user.Salt) {
- if user.Status == model.UserStatusClosed {
+ if user.Status == core.UserStatusClosed {
return nil, errcode.UserHasBeenBanned
}
// 清空登录计数
- conf.Redis.Del(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID))
+ conf.Redis.Del(ctx, fmt.Sprintf("%s:%d", _LoginErrKey, user.ID))
return user, nil
}
// 登录错误计数
- _, err = conf.Redis.Incr(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID)).Result()
+ _, err = conf.Redis.Incr(ctx, fmt.Sprintf("%s:%d", _LoginErrKey, user.ID)).Result()
if err == nil {
- conf.Redis.Expire(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID), time.Hour).Result()
+ conf.Redis.Expire(ctx, fmt.Sprintf("%s:%d", _LoginErrKey, user.ID), time.Hour).Result()
}
return nil, errcode.UnauthorizedAuthFailed
@@ -106,8 +138,8 @@ func ValidPassword(dbPassword, password, salt string) bool {
}
// CheckStatus 检测用户权限
-func CheckStatus(user *model.User) bool {
- return user.Status == model.UserStatusNormal
+func CheckStatus(user *core.User) bool {
+ return user.Status == core.UserStatusNormal
}
// ValidUsername 验证用户
@@ -161,7 +193,7 @@ func CheckPhoneCaptcha(phone, captcha string) *errcode.Error {
return errcode.ErrorPhoneCaptcha
}
- if c.UseTimes >= MAX_CAPTCHA_TIMES {
+ if c.UseTimes >= _MaxCaptchaTimes {
return errcode.MaxPhoneCaptchaUseTimes
}
@@ -198,16 +230,16 @@ func EncryptPasswordAndSalt(password string) (string, string) {
}
// Register 用户注册
-func Register(username, password string) (*model.User, error) {
+func Register(username, password string) (*core.User, error) {
password, salt := EncryptPasswordAndSalt(password)
- user := &model.User{
+ user := &core.User{
Nickname: username,
Username: username,
Password: password,
Avatar: GetRandomAvatar(),
Salt: salt,
- Status: model.UserStatusNormal,
+ Status: core.UserStatusNormal,
}
user, err := ds.CreateUser(user)
@@ -218,40 +250,40 @@ func Register(username, password string) (*model.User, error) {
return user, nil
}
-func RequestingFriend(user *model.User, param *rest.RequestingFriendReq) error {
+func RequestingFriend(user *core.User, param *RequestingFriendReq) error {
if _, err := ds.GetUserByID(param.UserId); err != nil {
return errcode.NotExistFriendId
}
return ds.RequestingFriend(user.ID, param.UserId, param.Greetings)
}
-func AddFriend(user *model.User, param *rest.AddFriendReq) error {
+func AddFriend(user *core.User, param *AddFriendReq) error {
if _, err := ds.GetUserByID(param.UserId); err != nil {
return errcode.NotExistFriendId
}
return ds.AddFriend(user.ID, param.UserId)
}
-func RejectFriend(user *model.User, param *rest.RejectFriendReq) error {
+func RejectFriend(user *core.User, param *RejectFriendReq) error {
if _, err := ds.GetUserByID(param.UserId); err != nil {
return errcode.NotExistFriendId
}
return ds.RejectFriend(user.ID, param.UserId)
}
-func DeleteFriend(user *model.User, param *rest.DeleteFriendReq) error {
+func DeleteFriend(user *core.User, param *DeleteFriendReq) error {
if _, err := ds.GetUserByID(param.UserId); err != nil {
return errcode.NotExistFriendId
}
return ds.DeleteFriend(user.ID, param.UserId)
}
-func GetContacts(user *model.User, offset int, limit int) (*rest.ContactsResp, error) {
+func GetContacts(user *core.User, offset int, limit int) (*core.ContactList, error) {
return ds.GetContacts(user.ID, offset, limit)
}
// GetUserInfo 获取用户信息
-func GetUserInfo(param *AuthRequest) (*model.User, error) {
+func GetUserInfo(param *AuthRequest) (*core.User, error) {
user, err := ds.GetUserByUsername(param.Username)
if err != nil {
@@ -265,7 +297,7 @@ func GetUserInfo(param *AuthRequest) (*model.User, error) {
return nil, errcode.UnauthorizedAuthNotExist
}
-func GetUserByID(id int64) (*model.User, error) {
+func GetUserByID(id int64) (*core.User, error) {
user, err := ds.GetUserByID(id)
if err != nil {
@@ -279,15 +311,15 @@ func GetUserByID(id int64) (*model.User, error) {
return nil, errcode.NoExistUsername
}
-func GetUserByUsername(user *model.User, username string) (*rest.UserProfileResp, error) {
+func GetUserByUsername(user *core.User, username string) (*UserProfileResp, error) {
other, err := ds.GetUserByUsername(username)
if err != nil {
return nil, err
}
- var resp *rest.UserProfileResp
+ var resp *UserProfileResp
if other.Model != nil && other.ID > 0 {
- resp = &rest.UserProfileResp{
+ resp = &UserProfileResp{
ID: other.ID,
Nickname: other.Nickname,
Username: other.Username,
@@ -307,14 +339,14 @@ func GetUserByUsername(user *model.User, username string) (*rest.UserProfileResp
}
// UpdateUserInfo 更新用户信息
-func UpdateUserInfo(user *model.User) *errcode.Error {
+func UpdateUserInfo(user *core.User) *errcode.Error {
if err := ds.UpdateUser(user); err != nil {
return errcode.ServerError
}
return nil
}
-func ChangeUserAvatar(user *model.User, avatar string) (err *errcode.Error) {
+func ChangeUserAvatar(user *core.User, avatar string) (err *errcode.Error) {
defer func() {
if err != nil {
deleteOssObjects([]string{avatar})
@@ -336,7 +368,7 @@ func ChangeUserAvatar(user *model.User, avatar string) (err *errcode.Error) {
}
// GetUserCollections 获取用户收藏列表
-func GetUserCollections(userID int64, offset, limit int) ([]*model.PostFormated, int64, error) {
+func GetUserCollections(userID int64, offset, limit int) ([]*core.PostFormated, int64, error) {
collections, err := ds.GetUserPostCollections(userID, offset, limit)
if err != nil {
return nil, 0, err
@@ -345,7 +377,7 @@ func GetUserCollections(userID int64, offset, limit int) ([]*model.PostFormated,
if err != nil {
return nil, 0, err
}
- var posts []*model.Post
+ var posts []*core.Post
for _, collection := range collections {
posts = append(posts, collection.Post)
}
@@ -358,7 +390,7 @@ func GetUserCollections(userID int64, offset, limit int) ([]*model.PostFormated,
}
// GetUserStars 获取用户点赞列表
-func GetUserStars(userID int64, offset, limit int) ([]*model.PostFormated, int64, error) {
+func GetUserStars(userID int64, offset, limit int) ([]*core.PostFormated, int64, error) {
stars, err := ds.GetUserPostStars(userID, offset, limit)
if err != nil {
return nil, 0, err
@@ -368,7 +400,7 @@ func GetUserStars(userID int64, offset, limit int) ([]*model.PostFormated, int64
return nil, 0, err
}
- var posts []*model.Post
+ var posts []*core.Post
for _, star := range stars {
posts = append(posts, star.Post)
}
@@ -381,7 +413,7 @@ func GetUserStars(userID int64, offset, limit int) ([]*model.PostFormated, int64
}
// GetUserWalletBills 获取用户账单列表
-func GetUserWalletBills(userID int64, offset, limit int) ([]*model.WalletStatement, int64, error) {
+func GetUserWalletBills(userID int64, offset, limit int) ([]*core.WalletStatement, int64, error) {
bills, err := ds.GetUserWalletBills(userID, offset, limit)
if err != nil {
return nil, 0, err
@@ -448,7 +480,7 @@ func IsFriend(userId, friendId int64) bool {
}
// checkPermision 检查是否拥有者或管理员
-func checkPermision(user *model.User, targetUserId int64) *errcode.Error {
+func checkPermision(user *core.User, targetUserId int64) *errcode.Error {
if user == nil || (user.ID != targetUserId && !user.IsAdmin) {
return errcode.NoPermission
}
diff --git a/internal/service/wallet.go b/internal/servants/web/broker/wallet.go
similarity index 69%
rename from internal/service/wallet.go
rename to internal/servants/web/broker/wallet.go
index 0f22b23f..6f89edf8 100644
--- a/internal/service/wallet.go
+++ b/internal/servants/web/broker/wallet.go
@@ -1,11 +1,15 @@
-package service
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package broker
import (
+ "github.com/rocboss/paopao-ce/internal/core"
"time"
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/internal/conf"
- "github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/pkg/errcode"
)
@@ -13,11 +17,11 @@ type RechargeReq struct {
Amount int64 `json:"amount" form:"amount" binding:"required"`
}
-func GetRechargeByID(id int64) (*model.WalletRecharge, error) {
+func GetRechargeByID(id int64) (*core.WalletRecharge, error) {
return ds.GetRechargeByID(id)
}
-func CreateRecharge(userID, amount int64) (*model.WalletRecharge, error) {
+func CreateRecharge(userID, amount int64) (*core.WalletRecharge, error) {
return ds.CreateRecharge(userID, amount)
}
@@ -44,7 +48,7 @@ func FinishRecharge(ctx *gin.Context, id int64, tradeNo string) error {
return nil
}
-func BuyPostAttachment(post *model.Post, user *model.User) error {
+func BuyPostAttachment(post *core.Post, user *core.User) error {
if user.Balance < post.AttachmentPrice {
return errcode.InsuffientDownloadMoney
}
diff --git a/internal/servants/web/core.go b/internal/servants/web/core.go
new file mode 100644
index 00000000..085e5bcf
--- /dev/null
+++ b/internal/servants/web/core.go
@@ -0,0 +1,51 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package web
+
+import (
+ api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/v1"
+ "github.com/rocboss/paopao-ce/internal/servants/base"
+)
+
+var (
+ _ api.WebCore = (*webCoreSrv)(nil)
+ _ api.WebCoreBinding = (*webCoreBinding)(nil)
+ _ api.WebCoreRender = (*webCoreRender)(nil)
+)
+
+type webCoreSrv struct {
+ base.BaseServant
+ api.UnimplementedWebCoreServant
+}
+
+type webCoreBinding struct {
+ base.BaseBinding
+ *api.UnimplementedWebCoreBinding
+}
+
+type webCoreRender struct {
+ base.BaseRender
+ *api.UnimplementedWebCoreRender
+}
+
+func newWebCoreSrv() api.WebCore {
+ return &webCoreSrv{}
+}
+
+func newWebCoreBinding() api.WebCoreBinding {
+ return &webCoreBinding{
+ UnimplementedWebCoreBinding: &api.UnimplementedWebCoreBinding{
+ BindAny: base.BindAny,
+ },
+ }
+}
+
+func newWebCoreRender() api.WebCoreRender {
+ return &webCoreRender{
+ UnimplementedWebCoreRender: &api.UnimplementedWebCoreRender{
+ RenderAny: base.RenderAny,
+ },
+ }
+}
diff --git a/internal/servants/web/followship.go b/internal/servants/web/followship.go
new file mode 100644
index 00000000..4158de39
--- /dev/null
+++ b/internal/servants/web/followship.go
@@ -0,0 +1,9 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package web
+
+type webFollowshipSrv struct {
+ // TODO
+}
diff --git a/internal/servants/web/friendship.go b/internal/servants/web/friendship.go
new file mode 100644
index 00000000..a4fb3d59
--- /dev/null
+++ b/internal/servants/web/friendship.go
@@ -0,0 +1,9 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package web
+
+type webFriendshipSrv struct {
+ // TODO
+}
diff --git a/internal/servants/web/loose.go b/internal/servants/web/loose.go
new file mode 100644
index 00000000..51a309a1
--- /dev/null
+++ b/internal/servants/web/loose.go
@@ -0,0 +1,9 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package web
+
+type webLooseSrv struct {
+ // TODO
+}
diff --git a/internal/servants/web/priv.go b/internal/servants/web/priv.go
new file mode 100644
index 00000000..51f0f486
--- /dev/null
+++ b/internal/servants/web/priv.go
@@ -0,0 +1,9 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package web
+
+type webPrivSrv struct {
+ // TODO
+}
diff --git a/internal/servants/web/pub.go b/internal/servants/web/pub.go
new file mode 100644
index 00000000..d7c68ec5
--- /dev/null
+++ b/internal/servants/web/pub.go
@@ -0,0 +1,9 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package web
+
+type webPubSrv struct {
+ // TODO
+}
diff --git a/internal/routers/api/api.go b/internal/servants/web/routers/api/api.go
similarity index 87%
rename from internal/routers/api/api.go
rename to internal/servants/web/routers/api/api.go
index c722ac88..b2e60cb6 100644
--- a/internal/routers/api/api.go
+++ b/internal/servants/web/routers/api/api.go
@@ -1,10 +1,14 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package api
import (
+ "github.com/alimy/cfg"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/core"
"github.com/rocboss/paopao-ce/internal/dao"
- "github.com/rocboss/paopao-ce/pkg/cfg"
"github.com/sirupsen/logrus"
"github.com/smartwalle/alipay/v3"
)
diff --git a/internal/routers/api/assets/comic.ttf b/internal/servants/web/routers/api/assets/comic.ttf
similarity index 100%
rename from internal/routers/api/assets/comic.ttf
rename to internal/servants/web/routers/api/assets/comic.ttf
diff --git a/internal/routers/api/attachment.go b/internal/servants/web/routers/api/attachment.go
similarity index 79%
rename from internal/routers/api/attachment.go
rename to internal/servants/web/routers/api/attachment.go
index 905b2c03..143c0c12 100644
--- a/internal/routers/api/attachment.go
+++ b/internal/servants/web/routers/api/attachment.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package api
import (
@@ -6,19 +10,19 @@ import (
"github.com/disintegration/imaging"
"github.com/gin-gonic/gin"
"github.com/gofrs/uuid"
- "github.com/rocboss/paopao-ce/internal/model"
- "github.com/rocboss/paopao-ce/internal/service"
+ "github.com/rocboss/paopao-ce/internal/core"
+ "github.com/rocboss/paopao-ce/internal/servants/web/broker"
"github.com/rocboss/paopao-ce/pkg/app"
"github.com/rocboss/paopao-ce/pkg/convert"
"github.com/rocboss/paopao-ce/pkg/errcode"
"github.com/sirupsen/logrus"
)
-var uploadAttachmentTypeMap = map[string]model.AttachmentType{
- "public/image": model.ATTACHMENT_TYPE_IMAGE,
- "public/avatar": model.ATTACHMENT_TYPE_IMAGE,
- "public/video": model.ATTACHMENT_TYPE_VIDEO,
- "attachment": model.ATTACHMENT_TYPE_OTHER,
+var uploadAttachmentTypeMap = map[string]core.AttachmentType{
+ "public/image": core.AttachmentTypeImage,
+ "public/avatar": core.AttachmentTypeImage,
+ "public/video": core.AttachmentTypeVideo,
+ "attachment": core.AttachmentTypeOther,
}
func GeneratePath(s string) string {
@@ -110,7 +114,7 @@ func UploadAttachment(c *gin.Context) {
}
// 构造附件Model
- attachment := &model.Attachment{
+ attachment := &core.Attachment{
FileSize: fileHeader.Size,
Content: objectUrl,
}
@@ -120,7 +124,7 @@ func UploadAttachment(c *gin.Context) {
}
attachment.Type = uploadAttachmentTypeMap[uploadType]
- if attachment.Type == model.ATTACHMENT_TYPE_IMAGE {
+ if attachment.Type == core.AttachmentTypeImage {
var src image.Image
src, err = imaging.Decode(file)
if err == nil {
@@ -128,7 +132,7 @@ func UploadAttachment(c *gin.Context) {
}
}
- attachment, err = service.CreateAttachment(attachment)
+ attachment, err = broker.CreateAttachment(attachment)
if err != nil {
logrus.Errorf("service.CreateAttachment err: %v", err)
response.ToErrorResponse(errcode.FileUploadFailed)
@@ -142,15 +146,15 @@ func DownloadAttachmentPrecheck(c *gin.Context) {
contentID := convert.StrTo(c.Query("id")).MustInt64()
// 加载content
- content, err := service.GetPostContentByID(contentID)
+ content, err := broker.GetPostContentByID(contentID)
if err != nil {
logrus.Errorf("service.GetPostContentByID err: %v", err)
response.ToErrorResponse(errcode.InvalidDownloadReq)
}
user, _ := c.Get("USER")
- if content.Type == model.CONTENT_TYPE_CHARGE_ATTACHMENT {
+ if content.Type == core.ContentTypeChargeAttachment {
// 加载post
- post, err := service.GetPost(content.PostID)
+ post, err := broker.GetPost(content.PostID)
if err != nil {
logrus.Errorf("service.GetPost err: %v", err)
response.ToResponse(gin.H{
@@ -160,7 +164,7 @@ func DownloadAttachmentPrecheck(c *gin.Context) {
}
// 发布者或管理员免费下载
- if post.UserID == user.(*model.User).ID || user.(*model.User).IsAdmin {
+ if post.UserID == user.(*core.User).ID || user.(*core.User).IsAdmin {
response.ToResponse(gin.H{
"paid": true,
})
@@ -169,7 +173,7 @@ func DownloadAttachmentPrecheck(c *gin.Context) {
// 检测是否有购买记录
response.ToResponse(gin.H{
- "paid": service.CheckPostAttachmentIsPaid(post.ID, user.(*model.User).ID),
+ "paid": broker.CheckPostAttachmentIsPaid(post.ID, user.(*core.User).ID),
})
return
}
@@ -184,18 +188,18 @@ func DownloadAttachment(c *gin.Context) {
contentID := convert.StrTo(c.Query("id")).MustInt64()
// 加载content
- content, err := service.GetPostContentByID(contentID)
+ content, err := broker.GetPostContentByID(contentID)
if err != nil {
logrus.Errorf("service.GetPostContentByID err: %v", err)
response.ToErrorResponse(errcode.InvalidDownloadReq)
}
// 收费附件
- if content.Type == model.CONTENT_TYPE_CHARGE_ATTACHMENT {
+ if content.Type == core.ContentTypeChargeAttachment {
user, _ := c.Get("USER")
// 加载post
- post, err := service.GetPost(content.PostID)
+ post, err := broker.GetPost(content.PostID)
if err != nil {
logrus.Errorf("service.GetPost err: %v", err)
response.ToResponse(gin.H{
@@ -207,24 +211,24 @@ func DownloadAttachment(c *gin.Context) {
paidFlag := false
// 发布者或管理员免费下载
- if post.UserID == user.(*model.User).ID || user.(*model.User).IsAdmin {
+ if post.UserID == user.(*core.User).ID || user.(*core.User).IsAdmin {
paidFlag = true
}
// 检测是否有购买记录
- if service.CheckPostAttachmentIsPaid(post.ID, user.(*model.User).ID) {
+ if broker.CheckPostAttachmentIsPaid(post.ID, user.(*core.User).ID) {
paidFlag = true
}
if !paidFlag {
// 未购买,则尝试购买
- err := service.BuyPostAttachment(&model.Post{
- Model: &model.Model{
+ err := broker.BuyPostAttachment(&core.Post{
+ Model: &core.Model{
ID: post.ID,
},
UserID: post.UserID,
AttachmentPrice: post.AttachmentPrice,
- }, user.(*model.User))
+ }, user.(*core.User))
if err != nil {
logrus.Errorf("service.BuyPostAttachment err: %v", err)
if err == errcode.InsuffientDownloadMoney {
diff --git a/internal/routers/api/comment.go b/internal/servants/web/routers/api/comment.go
similarity index 75%
rename from internal/routers/api/comment.go
rename to internal/servants/web/routers/api/comment.go
index 4b1fca36..0779eabb 100644
--- a/internal/routers/api/comment.go
+++ b/internal/servants/web/routers/api/comment.go
@@ -1,9 +1,13 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package api
import (
"github.com/gin-gonic/gin"
- "github.com/rocboss/paopao-ce/internal/model"
- "github.com/rocboss/paopao-ce/internal/service"
+ "github.com/rocboss/paopao-ce/internal/core"
+ "github.com/rocboss/paopao-ce/internal/servants/web/broker"
"github.com/rocboss/paopao-ce/pkg/app"
"github.com/rocboss/paopao-ce/pkg/convert"
"github.com/rocboss/paopao-ce/pkg/errcode"
@@ -14,7 +18,7 @@ func GetPostComments(c *gin.Context) {
postID := convert.StrTo(c.Query("id")).MustInt64()
response := app.NewResponse(c)
- contents, totalRows, err := service.GetPostComments(postID, "id ASC", 0, 0)
+ contents, totalRows, err := broker.GetPostComments(postID, "id ASC", 0, 0)
if err != nil {
logrus.Errorf("service.GetPostComments err: %v\n", err)
@@ -26,7 +30,7 @@ func GetPostComments(c *gin.Context) {
}
func CreatePostComment(c *gin.Context) {
- param := service.CommentCreationReq{}
+ param := broker.CommentCreationReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -36,7 +40,7 @@ func CreatePostComment(c *gin.Context) {
}
userID, _ := c.Get("UID")
- comment, err := service.CreatePostComment(c, userID.(int64), param)
+ comment, err := broker.CreatePostComment(c, userID.(int64), param)
if err != nil {
if err == errcode.MaxCommentCount {
@@ -52,7 +56,7 @@ func CreatePostComment(c *gin.Context) {
}
func DeletePostComment(c *gin.Context) {
- param := service.CommentDelReq{}
+ param := broker.CommentDelReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -62,20 +66,20 @@ func DeletePostComment(c *gin.Context) {
}
user, _ := c.Get("USER")
- comment, err := service.GetPostComment(param.ID)
+ comment, err := broker.GetPostComment(param.ID)
if err != nil {
logrus.Errorf("service.GetPostComment err: %v\n", err)
response.ToErrorResponse(errcode.GetCommentFailed)
return
}
- if user.(*model.User).ID != comment.UserID && !user.(*model.User).IsAdmin {
+ if user.(*core.User).ID != comment.UserID && !user.(*core.User).IsAdmin {
response.ToErrorResponse(errcode.NoPermission)
return
}
// 执行删除
- err = service.DeletePostComment(comment)
+ err = broker.DeletePostComment(comment)
if err != nil {
logrus.Errorf("service.DeletePostComment err: %v\n", err)
response.ToErrorResponse(errcode.DeleteCommentFailed)
@@ -86,7 +90,7 @@ func DeletePostComment(c *gin.Context) {
}
func CreatePostCommentReply(c *gin.Context) {
- param := service.CommentReplyCreationReq{}
+ param := broker.CommentReplyCreationReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -96,7 +100,7 @@ func CreatePostCommentReply(c *gin.Context) {
}
user, _ := c.Get("USER")
- comment, err := service.CreatePostCommentReply(c, param.CommentID, param.Content, user.(*model.User).ID, param.AtUserID)
+ comment, err := broker.CreatePostCommentReply(c, param.CommentID, param.Content, user.(*core.User).ID, param.AtUserID)
if err != nil {
logrus.Errorf("service.CreatePostCommentReply err: %v\n", err)
response.ToErrorResponse(errcode.CreateReplyFailed)
@@ -107,7 +111,7 @@ func CreatePostCommentReply(c *gin.Context) {
}
func DeletePostCommentReply(c *gin.Context) {
- param := service.ReplyDelReq{}
+ param := broker.ReplyDelReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -118,20 +122,20 @@ func DeletePostCommentReply(c *gin.Context) {
user, _ := c.Get("USER")
- reply, err := service.GetPostCommentReply(param.ID)
+ reply, err := broker.GetPostCommentReply(param.ID)
if err != nil {
logrus.Errorf("service.GetPostCommentReply err: %v\n", err)
response.ToErrorResponse(errcode.GetReplyFailed)
return
}
- if user.(*model.User).ID != reply.UserID && !user.(*model.User).IsAdmin {
+ if user.(*core.User).ID != reply.UserID && !user.(*core.User).IsAdmin {
response.ToErrorResponse(errcode.NoPermission)
return
}
// 执行删除
- err = service.DeletePostCommentReply(reply)
+ err = broker.DeletePostCommentReply(reply)
if err != nil {
logrus.Errorf("service.DeletePostCommentReply err: %v\n", err)
response.ToErrorResponse(errcode.DeleteCommentFailed)
diff --git a/internal/routers/api/home.go b/internal/servants/web/routers/api/home.go
similarity index 86%
rename from internal/routers/api/home.go
rename to internal/servants/web/routers/api/home.go
index 80489978..b863b712 100644
--- a/internal/routers/api/home.go
+++ b/internal/servants/web/routers/api/home.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package api
import (
@@ -12,8 +16,8 @@ import (
"github.com/gin-gonic/gin"
"github.com/gofrs/uuid"
"github.com/rocboss/paopao-ce/internal/conf"
- "github.com/rocboss/paopao-ce/internal/model"
- "github.com/rocboss/paopao-ce/internal/service"
+ "github.com/rocboss/paopao-ce/internal/core"
+ "github.com/rocboss/paopao-ce/internal/servants/web/broker"
"github.com/rocboss/paopao-ce/pkg/app"
"github.com/rocboss/paopao-ce/pkg/convert"
"github.com/rocboss/paopao-ce/pkg/debug"
@@ -39,8 +43,8 @@ func SyncSearchIndex(c *gin.Context) {
user, _ := c.Get("USER")
- if user.(*model.User).IsAdmin {
- go service.PushPostsToSearch(c)
+ if user.(*core.User).IsAdmin {
+ go broker.PushPostsToSearch(c)
}
response.ToResponse(nil)
@@ -74,7 +78,7 @@ func GetCaptcha(c *gin.Context) {
}
func PostCaptcha(c *gin.Context) {
- param := service.PhoneCaptchaReq{}
+ param := broker.PhoneCaptchaReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -96,7 +100,7 @@ func PostCaptcha(c *gin.Context) {
return
}
- err := service.SendPhoneCaptcha(c, param.Phone)
+ err := broker.SendPhoneCaptcha(c, param.Phone)
if err != nil {
logrus.Errorf("app.SendPhoneCaptcha errs: %v", errs)
response.ToErrorResponse(errcode.GetPhoneCaptchaError)
diff --git a/internal/routers/api/message.go b/internal/servants/web/routers/api/message.go
similarity index 74%
rename from internal/routers/api/message.go
rename to internal/servants/web/routers/api/message.go
index 8c24cbd2..9cc72ffd 100644
--- a/internal/routers/api/message.go
+++ b/internal/servants/web/routers/api/message.go
@@ -1,9 +1,13 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package api
import (
"github.com/gin-gonic/gin"
- "github.com/rocboss/paopao-ce/internal/model"
- "github.com/rocboss/paopao-ce/internal/service"
+ "github.com/rocboss/paopao-ce/internal/core"
+ "github.com/rocboss/paopao-ce/internal/servants/web/broker"
"github.com/rocboss/paopao-ce/pkg/app"
"github.com/rocboss/paopao-ce/pkg/errcode"
"github.com/sirupsen/logrus"
@@ -12,12 +16,12 @@ import (
func GetUnreadMsgCount(c *gin.Context) {
response := app.NewResponse(c)
- user := &model.User{}
+ user := &core.User{}
if u, exists := c.Get("USER"); exists {
- user = u.(*model.User)
+ user = u.(*core.User)
}
- count, _ := service.GetUnreadCount(user.ID)
+ count, _ := broker.GetUnreadCount(user.ID)
response.ToResponse(gin.H{
"count": count,
@@ -28,7 +32,7 @@ func GetMessages(c *gin.Context) {
response := app.NewResponse(c)
userID, _ := c.Get("UID")
- messages, totalRows, err := service.GetMessages(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
+ messages, totalRows, err := broker.GetMessages(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
if err != nil {
logrus.Errorf("service.GetMessages err: %v\n", err)
@@ -40,7 +44,7 @@ func GetMessages(c *gin.Context) {
}
func ReadMessage(c *gin.Context) {
- param := service.ReadMessageReq{}
+ param := broker.ReadMessageReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -50,7 +54,7 @@ func ReadMessage(c *gin.Context) {
}
userID, _ := c.Get("UID")
- err := service.ReadMessage(param.ID, userID.(int64))
+ err := broker.ReadMessage(param.ID, userID.(int64))
if err != nil {
logrus.Errorf("service.ReadMessage err: %v\n", err)
response.ToErrorResponse(errcode.ReadMessageFailed)
@@ -61,7 +65,7 @@ func ReadMessage(c *gin.Context) {
}
func SendUserWhisper(c *gin.Context) {
- param := service.WhisperReq{}
+ param := broker.WhisperReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -78,10 +82,10 @@ func SendUserWhisper(c *gin.Context) {
return
}
- _, err := service.CreateWhisper(c, &model.Message{
+ _, err := broker.CreateWhisper(c, &core.Message{
SenderUserID: userID.(int64),
ReceiverUserID: param.UserID,
- Type: model.MsgTypeWhisper,
+ Type: core.MsgTypeWhisper,
Brief: "给你发送新私信了",
Content: param.Content,
})
diff --git a/internal/routers/api/post.go b/internal/servants/web/routers/api/post.go
similarity index 79%
rename from internal/routers/api/post.go
rename to internal/servants/web/routers/api/post.go
index f580428f..9ca19f3f 100644
--- a/internal/routers/api/post.go
+++ b/internal/servants/web/routers/api/post.go
@@ -1,10 +1,13 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package api
import (
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/internal/core"
- "github.com/rocboss/paopao-ce/internal/model"
- "github.com/rocboss/paopao-ce/internal/service"
+ "github.com/rocboss/paopao-ce/internal/servants/web/broker"
"github.com/rocboss/paopao-ce/pkg/app"
"github.com/rocboss/paopao-ce/pkg/convert"
"github.com/rocboss/paopao-ce/pkg/errcode"
@@ -25,7 +28,7 @@ func GetPostList(c *gin.Context) {
user, _ := userFrom(c)
offset, limit := app.GetPageOffset(c)
if q.Query == "" && q.Type == "search" {
- resp, err := service.GetIndexPosts(user, offset, limit)
+ resp, err := broker.GetIndexPosts(user, offset, limit)
if err != nil {
logrus.Errorf("service.GetPostList err: %v\n", err)
response.ToErrorResponse(errcode.GetPostsFailed)
@@ -34,7 +37,7 @@ func GetPostList(c *gin.Context) {
response.ToResponseList(resp.Tweets, resp.Total)
} else {
- posts, totalRows, err := service.GetPostListFromSearch(user, q, offset, limit)
+ posts, totalRows, err := broker.GetPostListFromSearch(user, q, offset, limit)
if err != nil {
logrus.Errorf("service.GetPostListFromSearch err: %v\n", err)
@@ -49,7 +52,7 @@ func GetPost(c *gin.Context) {
postID := convert.StrTo(c.Query("id")).MustInt64()
response := app.NewResponse(c)
- postFormated, err := service.GetPost(postID)
+ postFormated, err := broker.GetPost(postID)
if err != nil {
logrus.Errorf("service.GetPost err: %v\n", err)
@@ -61,7 +64,7 @@ func GetPost(c *gin.Context) {
}
func CreatePost(c *gin.Context) {
- param := service.PostCreationReq{}
+ param := broker.PostCreationReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -71,7 +74,7 @@ func CreatePost(c *gin.Context) {
}
userID, _ := c.Get("UID")
- post, err := service.CreatePost(c, userID.(int64), param)
+ post, err := broker.CreatePost(c, userID.(int64), param)
if err != nil {
logrus.Errorf("service.CreatePost err: %v\n", err)
@@ -83,7 +86,7 @@ func CreatePost(c *gin.Context) {
}
func DeletePost(c *gin.Context) {
- param := service.PostDelReq{}
+ param := broker.PostDelReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -98,7 +101,7 @@ func DeletePost(c *gin.Context) {
return
}
- err := service.DeletePost(user, param.ID)
+ err := broker.DeletePost(user, param.ID)
if err != nil {
logrus.Errorf("service.DeletePost err: %v\n", err)
response.ToErrorResponse(err)
@@ -114,7 +117,7 @@ func GetPostStar(c *gin.Context) {
userID, _ := c.Get("UID")
- _, err := service.GetPostStar(postID, userID.(int64))
+ _, err := broker.GetPostStar(postID, userID.(int64))
if err != nil {
response.ToResponse(gin.H{
"status": false,
@@ -129,7 +132,7 @@ func GetPostStar(c *gin.Context) {
}
func PostStar(c *gin.Context) {
- param := service.PostStarReq{}
+ param := broker.PostStarReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -141,14 +144,14 @@ func PostStar(c *gin.Context) {
userID, _ := c.Get("UID")
status := false
- star, err := service.GetPostStar(param.ID, userID.(int64))
+ star, err := broker.GetPostStar(param.ID, userID.(int64))
if err != nil {
// 创建Star
- _, err = service.CreatePostStar(param.ID, userID.(int64))
+ _, err = broker.CreatePostStar(param.ID, userID.(int64))
status = true
} else {
// 取消Star
- err = service.DeletePostStar(star)
+ err = broker.DeletePostStar(star)
}
if err != nil {
@@ -167,7 +170,7 @@ func GetPostCollection(c *gin.Context) {
userID, _ := c.Get("UID")
- _, err := service.GetPostCollection(postID, userID.(int64))
+ _, err := broker.GetPostCollection(postID, userID.(int64))
if err != nil {
response.ToResponse(gin.H{
"status": false,
@@ -182,7 +185,7 @@ func GetPostCollection(c *gin.Context) {
}
func PostCollection(c *gin.Context) {
- param := service.PostCollectionReq{}
+ param := broker.PostCollectionReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -194,14 +197,14 @@ func PostCollection(c *gin.Context) {
userID, _ := c.Get("UID")
status := false
- collection, err := service.GetPostCollection(param.ID, userID.(int64))
+ collection, err := broker.GetPostCollection(param.ID, userID.(int64))
if err != nil {
// 创建collection
- _, err = service.CreatePostCollection(param.ID, userID.(int64))
+ _, err = broker.CreatePostCollection(param.ID, userID.(int64))
status = true
} else {
// 取消Star
- err = service.DeletePostCollection(collection)
+ err = broker.DeletePostCollection(collection)
}
if err != nil {
@@ -215,7 +218,7 @@ func PostCollection(c *gin.Context) {
}
func LockPost(c *gin.Context) {
- param := service.PostLockReq{}
+ param := broker.PostLockReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -227,18 +230,18 @@ func LockPost(c *gin.Context) {
user, _ := c.Get("USER")
// 获取Post
- postFormated, err := service.GetPost(param.ID)
+ postFormated, err := broker.GetPost(param.ID)
if err != nil {
logrus.Errorf("service.GetPost err: %v\n", err)
response.ToErrorResponse(errcode.GetPostFailed)
return
}
- if postFormated.UserID != user.(*model.User).ID && !user.(*model.User).IsAdmin {
+ if postFormated.UserID != user.(*core.User).ID && !user.(*core.User).IsAdmin {
response.ToErrorResponse(errcode.NoPermission)
return
}
- err = service.LockPost(param.ID)
+ err = broker.LockPost(param.ID)
if err != nil {
logrus.Errorf("service.LockPost err: %v\n", err)
response.ToErrorResponse(errcode.LockPostFailed)
@@ -251,7 +254,7 @@ func LockPost(c *gin.Context) {
}
func StickPost(c *gin.Context) {
- param := service.PostStickReq{}
+ param := broker.PostStickReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -263,18 +266,18 @@ func StickPost(c *gin.Context) {
user, _ := c.Get("USER")
// 获取Post
- postFormated, err := service.GetPost(param.ID)
+ postFormated, err := broker.GetPost(param.ID)
if err != nil {
logrus.Errorf("service.GetPost err: %v\n", err)
response.ToErrorResponse(errcode.GetPostFailed)
return
}
- if !user.(*model.User).IsAdmin {
+ if !user.(*core.User).IsAdmin {
response.ToErrorResponse(errcode.NoPermission)
return
}
- err = service.StickPost(param.ID)
+ err = broker.StickPost(param.ID)
if err != nil {
logrus.Errorf("service.StickPost err: %v\n", err)
response.ToErrorResponse(errcode.LockPostFailed)
@@ -287,7 +290,7 @@ func StickPost(c *gin.Context) {
}
func VisiblePost(c *gin.Context) {
- param := service.PostVisibilityReq{}
+ param := broker.PostVisibilityReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -297,7 +300,7 @@ func VisiblePost(c *gin.Context) {
}
user, _ := userFrom(c)
- if err := service.VisiblePost(user, param.ID, param.Visibility); err != nil {
+ if err := broker.VisiblePost(user, param.ID, param.Visibility); err != nil {
logrus.Errorf("service.VisiblePost err: %v\n", err)
response.ToErrorResponse(err)
return
@@ -309,7 +312,7 @@ func VisiblePost(c *gin.Context) {
}
func GetPostTags(c *gin.Context) {
- param := service.PostTagsReq{}
+ param := broker.PostTagsReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -318,7 +321,7 @@ func GetPostTags(c *gin.Context) {
return
}
- tags, err := service.GetPostTags(¶m)
+ tags, err := broker.GetPostTags(¶m)
if err != nil {
logrus.Errorf("service.GetPostTags err: %v\n", err)
response.ToErrorResponse(errcode.GetPostTagsFailed)
diff --git a/internal/routers/api/user.go b/internal/servants/web/routers/api/user.go
similarity index 80%
rename from internal/routers/api/user.go
rename to internal/servants/web/routers/api/user.go
index 7541c54b..f45ff8ce 100644
--- a/internal/routers/api/user.go
+++ b/internal/servants/web/routers/api/user.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package api
import (
@@ -6,9 +10,8 @@ import (
"unicode/utf8"
"github.com/gin-gonic/gin"
- "github.com/rocboss/paopao-ce/internal/model"
- "github.com/rocboss/paopao-ce/internal/model/rest"
- "github.com/rocboss/paopao-ce/internal/service"
+ "github.com/rocboss/paopao-ce/internal/core"
+ "github.com/rocboss/paopao-ce/internal/servants/web/broker"
"github.com/rocboss/paopao-ce/pkg/app"
"github.com/rocboss/paopao-ce/pkg/convert"
"github.com/rocboss/paopao-ce/pkg/errcode"
@@ -18,7 +21,7 @@ import (
// Login 用户登录
func Login(c *gin.Context) {
- param := service.AuthRequest{}
+ param := broker.AuthRequest{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -27,7 +30,7 @@ func Login(c *gin.Context) {
return
}
- user, err := service.DoLogin(c, ¶m)
+ user, err := broker.DoLogin(c, ¶m)
if err != nil {
logrus.Errorf("service.DoLogin err: %v", err)
response.ToErrorResponse(err.(*errcode.Error))
@@ -49,7 +52,7 @@ func Login(c *gin.Context) {
// Register 用户注册
func Register(c *gin.Context) {
- param := service.RegisterRequest{}
+ param := broker.RegisterRequest{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -59,7 +62,7 @@ func Register(c *gin.Context) {
}
// 用户名检查
- err := service.ValidUsername(param.Username)
+ err := broker.ValidUsername(param.Username)
if err != nil {
logrus.Errorf("service.Register err: %v", err)
response.ToErrorResponse(err.(*errcode.Error))
@@ -67,14 +70,14 @@ func Register(c *gin.Context) {
}
// 密码检查
- err = service.CheckPassword(param.Password)
+ err = broker.CheckPassword(param.Password)
if err != nil {
logrus.Errorf("service.Register err: %v", err)
response.ToErrorResponse(err.(*errcode.Error))
return
}
- user, err := service.Register(
+ user, err := broker.Register(
param.Username,
param.Password,
)
@@ -92,7 +95,7 @@ func Register(c *gin.Context) {
}
func RequestingFriend(c *gin.Context) {
- param := rest.RequestingFriendReq{}
+ param := broker.RequestingFriendReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -110,7 +113,7 @@ func RequestingFriend(c *gin.Context) {
return
}
- if err := service.RequestingFriend(user, ¶m); err != nil {
+ if err := broker.RequestingFriend(user, ¶m); err != nil {
logrus.Errorf("service.RequestingFriend err: %v", err)
response.ToErrorResponse(errcode.SendRequestingFriendFailed)
return
@@ -120,7 +123,7 @@ func RequestingFriend(c *gin.Context) {
}
func AddFriend(c *gin.Context) {
- param := rest.AddFriendReq{}
+ param := broker.AddFriendReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -137,7 +140,7 @@ func AddFriend(c *gin.Context) {
return
}
- if err := service.AddFriend(user, ¶m); err != nil {
+ if err := broker.AddFriend(user, ¶m); err != nil {
logrus.Errorf("service.AddFriend err: %v", err)
response.ToErrorResponse(errcode.AddFriendFailed)
return
@@ -147,7 +150,7 @@ func AddFriend(c *gin.Context) {
}
func RejectFriend(c *gin.Context) {
- param := rest.RejectFriendReq{}
+ param := broker.RejectFriendReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -164,7 +167,7 @@ func RejectFriend(c *gin.Context) {
return
}
- if err := service.RejectFriend(user, ¶m); err != nil {
+ if err := broker.RejectFriend(user, ¶m); err != nil {
logrus.Errorf("service.RejectFriend err: %v", err)
response.ToErrorResponse(errcode.RejectFriendFailed)
return
@@ -174,7 +177,7 @@ func RejectFriend(c *gin.Context) {
}
func DeleteFriend(c *gin.Context) {
- param := rest.DeleteFriendReq{}
+ param := broker.DeleteFriendReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -191,7 +194,7 @@ func DeleteFriend(c *gin.Context) {
return
}
- if err := service.DeleteFriend(user, ¶m); err != nil {
+ if err := broker.DeleteFriend(user, ¶m); err != nil {
logrus.Errorf("service.DeleteFriend err: %v", err)
response.ToErrorResponse(errcode.DeleteFriendFailed)
return
@@ -208,7 +211,7 @@ func GetContacts(c *gin.Context) {
}
offset, limit := app.GetPageOffset(c)
- resp, err := service.GetContacts(user, offset, limit)
+ resp, err := broker.GetContacts(user, offset, limit)
if err != nil {
logrus.Errorf("service.DeleteFriend err: %v", err)
response.ToErrorResponse(errcode.GetContactsFailed)
@@ -219,14 +222,14 @@ func GetContacts(c *gin.Context) {
// 获取用户基本信息
func GetUserInfo(c *gin.Context) {
- param := service.AuthRequest{}
+ param := broker.AuthRequest{}
response := app.NewResponse(c)
if username, exists := c.Get("USERNAME"); exists {
param.Username = username.(string)
}
- user, err := service.GetUserInfo(¶m)
+ user, err := broker.GetUserInfo(¶m)
if err != nil {
response.ToErrorResponse(errcode.UnauthorizedAuthNotExist)
@@ -251,7 +254,7 @@ func GetUserInfo(c *gin.Context) {
// 修改密码
func ChangeUserPassword(c *gin.Context) {
- param := service.ChangePasswordReq{}
+ param := broker.ChangePasswordReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -260,13 +263,13 @@ func ChangeUserPassword(c *gin.Context) {
return
}
- user := &model.User{}
+ user := &core.User{}
if u, exists := c.Get("USER"); exists {
- user = u.(*model.User)
+ user = u.(*core.User)
}
// 密码检查
- err := service.CheckPassword(param.Password)
+ err := broker.CheckPassword(param.Password)
if err != nil {
logrus.Errorf("service.Register err: %v", err)
response.ToErrorResponse(err.(*errcode.Error))
@@ -274,21 +277,21 @@ func ChangeUserPassword(c *gin.Context) {
}
// 旧密码校验
- if !service.ValidPassword(user.Password, param.OldPassword, user.Salt) {
+ if !broker.ValidPassword(user.Password, param.OldPassword, user.Salt) {
response.ToErrorResponse(errcode.ErrorOldPassword)
return
}
// 更新入库
- user.Password, user.Salt = service.EncryptPasswordAndSalt(param.Password)
- service.UpdateUserInfo(user)
+ user.Password, user.Salt = broker.EncryptPasswordAndSalt(param.Password)
+ broker.UpdateUserInfo(user)
response.ToResponse(nil)
}
// 修改昵称
func ChangeNickname(c *gin.Context) {
- param := service.ChangeNicknameReq{}
+ param := broker.ChangeNicknameReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -297,9 +300,9 @@ func ChangeNickname(c *gin.Context) {
return
}
- user := &model.User{}
+ user := &core.User{}
if u, exists := c.Get("USER"); exists {
- user = u.(*model.User)
+ user = u.(*core.User)
}
if utf8.RuneCountInString(param.Nickname) < 2 || utf8.RuneCountInString(param.Nickname) > 12 {
@@ -309,14 +312,14 @@ func ChangeNickname(c *gin.Context) {
// 执行绑定
user.Nickname = param.Nickname
- service.UpdateUserInfo(user)
+ broker.UpdateUserInfo(user)
response.ToResponse(nil)
}
// 修改头像
func ChangeAvatar(c *gin.Context) {
- param := service.ChangeAvatarReq{}
+ param := broker.ChangeAvatarReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -331,7 +334,7 @@ func ChangeAvatar(c *gin.Context) {
return
}
- if err := service.ChangeUserAvatar(user, param.Avatar); err != nil {
+ if err := broker.ChangeUserAvatar(user, param.Avatar); err != nil {
response.ToErrorResponse(err)
return
}
@@ -340,7 +343,7 @@ func ChangeAvatar(c *gin.Context) {
// 用户绑定手机号
func BindUserPhone(c *gin.Context) {
- param := service.UserPhoneBindReq{}
+ param := broker.UserPhoneBindReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -349,18 +352,18 @@ func BindUserPhone(c *gin.Context) {
return
}
- user := &model.User{}
+ user := &core.User{}
if u, exists := c.Get("USER"); exists {
- user = u.(*model.User)
+ user = u.(*core.User)
}
// 手机重复性检查
- if service.CheckPhoneExist(user.ID, param.Phone) {
+ if broker.CheckPhoneExist(user.ID, param.Phone) {
response.ToErrorResponse(errcode.ExistedUserPhone)
return
}
- if err := service.CheckPhoneCaptcha(param.Phone, param.Captcha); err != nil {
+ if err := broker.CheckPhoneCaptcha(param.Phone, param.Captcha); err != nil {
logrus.Errorf("service.CheckPhoneCaptcha err: %v\n", err)
response.ToErrorResponse(err)
return
@@ -368,7 +371,7 @@ func BindUserPhone(c *gin.Context) {
// 执行绑定
user.Phone = param.Phone
- if err := service.UpdateUserInfo(user); err != nil {
+ if err := broker.UpdateUserInfo(user); err != nil {
response.ToErrorResponse(err)
return
}
@@ -378,7 +381,7 @@ func BindUserPhone(c *gin.Context) {
// 修改用户状态
func ChangeUserStatus(c *gin.Context) {
- param := service.ChangeUserStatusReq{}
+ param := broker.ChangeUserStatusReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -387,12 +390,12 @@ func ChangeUserStatus(c *gin.Context) {
return
}
- if param.Status != model.UserStatusNormal && param.Status != model.UserStatusClosed {
+ if param.Status != core.UserStatusNormal && param.Status != core.UserStatusClosed {
response.ToErrorResponse(errcode.InvalidParams)
return
}
- user, err := service.GetUserByID(param.ID)
+ user, err := broker.GetUserByID(param.ID)
if err != nil {
logrus.Errorf("service.GetUserByID err: %v\n", err)
response.ToErrorResponse(errcode.NoExistUsername)
@@ -401,7 +404,7 @@ func ChangeUserStatus(c *gin.Context) {
// 执行更新
user.Status = param.Status
- service.UpdateUserInfo(user)
+ broker.UpdateUserInfo(user)
response.ToResponse(nil)
}
@@ -411,7 +414,7 @@ func GetUserProfile(c *gin.Context) {
username := c.Query("username")
user, _ := userFrom(c)
- resp, err := service.GetUserByUsername(user, username)
+ resp, err := broker.GetUserByUsername(user, username)
if err != nil {
logrus.Errorf("service.GetUserByUsername err: %v\n", err)
response.ToErrorResponse(errcode.NoExistUsername)
@@ -426,28 +429,28 @@ func GetUserPosts(c *gin.Context) {
username := c.Query("username")
user, exists := userFrom(c)
- other, err := service.GetUserByUsername(user, username)
+ other, err := broker.GetUserByUsername(user, username)
if err != nil {
logrus.Errorf("service.GetUserByUsername err: %v\n", err)
response.ToErrorResponse(errcode.NoExistUsername)
return
}
- visibilities := []model.PostVisibleT{model.PostVisitPublic}
+ visibilities := []core.PostVisibleT{core.PostVisitPublic}
if exists {
if user.ID == other.ID || user.IsAdmin {
- visibilities = append(visibilities, model.PostVisitPrivate, model.PostVisitFriend)
+ visibilities = append(visibilities, core.PostVisitPrivate, core.PostVisitFriend)
} else if other.IsFriend {
- visibilities = append(visibilities, model.PostVisitFriend)
+ visibilities = append(visibilities, core.PostVisitFriend)
}
}
- conditions := model.ConditionsT{
+ conditions := core.ConditionsT{
"user_id": other.ID,
"visibility IN ?": visibilities,
"ORDER": "latest_replied_on DESC",
}
- _, posts, err := service.GetPostList(&service.PostListReq{
+ _, posts, err := broker.GetPostList(&broker.PostListReq{
Conditions: &conditions,
Offset: (app.GetPage(c) - 1) * app.GetPageSize(c),
Limit: app.GetPageSize(c),
@@ -457,7 +460,7 @@ func GetUserPosts(c *gin.Context) {
response.ToErrorResponse(errcode.GetPostsFailed)
return
}
- totalRows, _ := service.GetPostCount(&conditions)
+ totalRows, _ := broker.GetPostCount(&conditions)
response.ToResponseList(posts, totalRows)
}
@@ -466,7 +469,7 @@ func GetUserCollections(c *gin.Context) {
response := app.NewResponse(c)
userID, _ := c.Get("UID")
- posts, totalRows, err := service.GetUserCollections(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
+ posts, totalRows, err := broker.GetUserCollections(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
if err != nil {
logrus.Errorf("service.GetUserCollections err: %v\n", err)
@@ -481,7 +484,7 @@ func GetUserStars(c *gin.Context) {
response := app.NewResponse(c)
userID, _ := c.Get("UID")
- posts, totalRows, err := service.GetUserStars(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
+ posts, totalRows, err := broker.GetUserStars(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
if err != nil {
logrus.Errorf("service.GetUserStars err: %v\n", err)
response.ToErrorResponse(errcode.GetCollectionsFailed)
@@ -495,7 +498,7 @@ func GetSuggestUsers(c *gin.Context) {
keyword := c.Query("k")
response := app.NewResponse(c)
- usernames, err := service.GetSuggestUsers(keyword)
+ usernames, err := broker.GetSuggestUsers(keyword)
if err != nil {
logrus.Errorf("service.GetSuggestUsers err: %v\n", err)
response.ToErrorResponse(errcode.GetCollectionsFailed)
@@ -509,7 +512,7 @@ func GetSuggestTags(c *gin.Context) {
keyword := c.Query("k")
response := app.NewResponse(c)
- tags, err := service.GetSuggestTags(keyword)
+ tags, err := broker.GetSuggestTags(keyword)
if err != nil {
logrus.Errorf("service.GetSuggestTags err: %v\n", err)
response.ToErrorResponse(errcode.GetCollectionsFailed)
@@ -520,7 +523,7 @@ func GetSuggestTags(c *gin.Context) {
}
func GetUserRechargeLink(c *gin.Context) {
- param := service.RechargeReq{}
+ param := broker.RechargeReq{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, ¶m)
if !valid {
@@ -531,7 +534,7 @@ func GetUserRechargeLink(c *gin.Context) {
// 下单
userID, _ := c.Get("UID")
- recharge, err := service.CreateRecharge(userID.(int64), param.Amount)
+ recharge, err := broker.CreateRecharge(userID.(int64), param.Amount)
if err != nil {
logrus.Errorf("service.CreateRecharge err: %v\n", err)
response.ToErrorResponse(errcode.RechargeReqFail)
@@ -567,7 +570,7 @@ func GetUserRechargeResult(c *gin.Context) {
id := c.Query("id")
userID, _ := c.Get("UID")
- recharge, err := service.GetRechargeByID(convert.StrTo(id).MustInt64())
+ recharge, err := broker.GetRechargeByID(convert.StrTo(id).MustInt64())
if err != nil {
response.ToErrorResponse(errcode.GetRechargeFailed)
return
@@ -601,7 +604,7 @@ func AlipayNotify(c *gin.Context) {
tradeStatus := c.Request.Form.Get("trade_status")
if tradeStatus == "TRADE_SUCCESS" {
// 交易支付成功
- err = service.FinishRecharge(c, convert.StrTo(id).MustInt64(), tradeNo)
+ err = broker.FinishRecharge(c, convert.StrTo(id).MustInt64(), tradeNo)
if err != nil {
logrus.Errorf("service.FinishRecharge err: %v\n", err)
response.ToErrorResponse(errcode.RechargeNotifyError)
@@ -615,7 +618,7 @@ func GetUserWalletBills(c *gin.Context) {
response := app.NewResponse(c)
userID, _ := c.Get("UID")
- bills, totalRows, err := service.GetUserWalletBills(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
+ bills, totalRows, err := broker.GetUserWalletBills(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
if err != nil {
logrus.Errorf("service.GetUserWalletBills err: %v\n", err)
@@ -626,9 +629,9 @@ func GetUserWalletBills(c *gin.Context) {
response.ToResponseList(bills, totalRows)
}
-func userFrom(c *gin.Context) (*model.User, bool) {
+func userFrom(c *gin.Context) (*core.User, bool) {
if u, exists := c.Get("USER"); exists {
- user, ok := u.(*model.User)
+ user, ok := u.(*core.User)
return user, ok
}
return nil, false
diff --git a/internal/routers/docs.go b/internal/servants/web/routers/docs.go
similarity index 57%
rename from internal/routers/docs.go
rename to internal/servants/web/routers/docs.go
index fc054b08..bf5e0488 100644
--- a/internal/routers/docs.go
+++ b/internal/servants/web/routers/docs.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
//go:build !docs
// +build !docs
diff --git a/internal/routers/docs_embed.go b/internal/servants/web/routers/docs_embed.go
similarity index 63%
rename from internal/routers/docs_embed.go
rename to internal/servants/web/routers/docs_embed.go
index e9c0d17d..20754e1a 100644
--- a/internal/routers/docs_embed.go
+++ b/internal/servants/web/routers/docs_embed.go
@@ -1,12 +1,16 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
//go:build docs
// +build docs
package routers
import (
+ "github.com/alimy/cfg"
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/docs/openapi"
- "github.com/rocboss/paopao-ce/pkg/cfg"
)
// registerDocs register docs asset route
diff --git a/internal/routers/router.go b/internal/servants/web/routers/router.go
similarity index 75%
rename from internal/routers/router.go
rename to internal/servants/web/routers/router.go
index 1a2b57f6..80b29be3 100644
--- a/internal/routers/router.go
+++ b/internal/servants/web/routers/router.go
@@ -1,15 +1,19 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package routers
import (
"net/http"
"path/filepath"
+ "github.com/alimy/cfg"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/internal/conf"
- "github.com/rocboss/paopao-ce/internal/middleware"
- "github.com/rocboss/paopao-ce/internal/routers/api"
- "github.com/rocboss/paopao-ce/pkg/cfg"
+ "github.com/rocboss/paopao-ce/internal/servants/chain"
+ "github.com/rocboss/paopao-ce/internal/servants/web/routers/api"
"github.com/sirupsen/logrus"
)
@@ -67,7 +71,7 @@ func NewRouter() *gin.Engine {
}
// 宽松鉴权路由组
- looseApi := r.Group("/").Use(middleware.JwtLoose())
+ looseApi := r.Group("/").Use(chain.JwtLoose())
{
// 获取广场流
looseApi.GET("/posts", api.GetPostList)
@@ -80,9 +84,9 @@ func NewRouter() *gin.Engine {
}
// 鉴权路由组
- authApi := r.Group("/").Use(middleware.JWT())
- privApi := r.Group("/").Use(middleware.JWT()).Use(middleware.Priv())
- adminApi := r.Group("/").Use(middleware.JWT()).Use(middleware.Admin())
+ authApi := r.Group("/").Use(chain.JWT())
+ privApi := r.Group("/").Use(chain.JWT()).Use(chain.Priv())
+ adminApi := r.Group("/").Use(chain.JWT()).Use(chain.Admin())
// 核心路由注册
routeCore(authApi, privApi, adminApi)
@@ -114,6 +118,78 @@ func NewRouter() *gin.Engine {
return e
}
+func RegisterRoute(e *gin.Engine) {
+ // 按需注册 docs、静态资源、LocalOSS 路由
+ {
+ registerDocs(e)
+ registerStatick(e)
+
+ cfg.Be("LocalOSS", func() {
+ routeLocalOSS(e)
+ })
+ }
+
+ // v1 group api
+ r := e.Group("/v1")
+
+ // 获取version
+ r.GET("/", api.Version)
+
+ // 用户登录
+ r.POST("/auth/login", api.Login)
+
+ // 用户注册
+ r.POST("/auth/register", api.Register)
+
+ // 获取验证码
+ r.GET("/captcha", api.GetCaptcha)
+
+ // 发送验证码
+ r.POST("/captcha", api.PostCaptcha)
+
+ // 无鉴权路由组
+ noAuthApi := r.Group("/")
+ {
+ // 获取动态详情
+ noAuthApi.GET("/post", api.GetPost)
+
+ // 获取动态评论
+ noAuthApi.GET("/post/comments", api.GetPostComments)
+
+ // 获取话题列表
+ noAuthApi.GET("/tags", api.GetPostTags)
+ }
+
+ // 宽松鉴权路由组
+ looseApi := r.Group("/").Use(chain.JwtLoose())
+ {
+ // 获取广场流
+ looseApi.GET("/posts", api.GetPostList)
+
+ // 获取用户动态列表
+ looseApi.GET("/user/posts", api.GetUserPosts)
+
+ // 获取用户基本信息
+ looseApi.GET("/user/profile", api.GetUserProfile)
+ }
+
+ // 鉴权路由组
+ authApi := r.Group("/").Use(chain.JWT())
+ privApi := r.Group("/").Use(chain.JWT()).Use(chain.Priv())
+ adminApi := r.Group("/").Use(chain.JWT()).Use(chain.Admin())
+
+ // 核心路由注册
+ routeCore(authApi, privApi, adminApi)
+
+ // 支付宝路由注册
+ cfg.Be("Alipay", func() {
+ routeAlipay(r, authApi)
+ })
+
+ // Relationship相关路由注册
+ routeRelationship(authApi)
+}
+
func routeCore(authApi gin.IRoutes, privApi gin.IRoutes, adminApi gin.IRoutes) {
// 同步索引
authApi.GET("/sync/index", api.SyncSearchIndex)
diff --git a/internal/routers/statick.go b/internal/servants/web/routers/statick.go
similarity index 58%
rename from internal/routers/statick.go
rename to internal/servants/web/routers/statick.go
index c20d5059..c1f2d1cb 100644
--- a/internal/routers/statick.go
+++ b/internal/servants/web/routers/statick.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
//go:build !embed
// +build !embed
diff --git a/internal/routers/statick_embed.go b/internal/servants/web/routers/statick_embed.go
similarity index 79%
rename from internal/routers/statick_embed.go
rename to internal/servants/web/routers/statick_embed.go
index 2ea56171..dfc729f5 100644
--- a/internal/routers/statick_embed.go
+++ b/internal/servants/web/routers/statick_embed.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
//go:build embed
// +build embed
diff --git a/internal/servants/web/web.go b/internal/servants/web/web.go
new file mode 100644
index 00000000..76ac9dd3
--- /dev/null
+++ b/internal/servants/web/web.go
@@ -0,0 +1,15 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package web
+
+import (
+ "github.com/gin-gonic/gin"
+ api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/v1"
+)
+
+// RouteWeb register web route
+func RouteWeb(e *gin.Engine) {
+ api.RegisterWebCoreServant(e, newWebCoreSrv(), newWebCoreBinding(), newWebCoreRender())
+}
diff --git a/internal/servants/web/xerror.go b/internal/servants/web/xerror.go
new file mode 100644
index 00000000..ecc0355e
--- /dev/null
+++ b/internal/servants/web/xerror.go
@@ -0,0 +1,77 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package web
+
+import (
+ "github.com/rocboss/paopao-ce/pkg/xerror"
+)
+
+var (
+ errUsernameHasExisted = xerror.NewError(20001, "用户名已存在")
+ errUsernameLengthLimit = xerror.NewError(20002, "用户名长度3~12")
+ errUsernameCharLimit = xerror.NewError(20003, "用户名只能包含字母、数字")
+ errPasswordLengthLimit = xerror.NewError(20004, "密码长度6~16")
+ errUserRegisterFailed = xerror.NewError(20005, "用户注册失败")
+ errUserHasBeenBanned = xerror.NewError(20006, "该账户已被封停")
+ errNoPermission = xerror.NewError(20007, "无权限执行该请求")
+ errUserHasBindOTP = xerror.NewError(20008, "当前用户已绑定二次验证")
+ errUserOTPInvalid = xerror.NewError(20009, "二次验证码验证失败")
+ errUserNoBindOTP = xerror.NewError(20010, "当前用户未绑定二次验证")
+ errErrorOldPassword = xerror.NewError(20011, "当前用户密码验证失败")
+ errErrorCaptchaPassword = xerror.NewError(20012, "图形验证码验证失败")
+ errAccountNoPhoneBind = xerror.NewError(20013, "拒绝操作: 账户未绑定手机号")
+ errTooManyLoginError = xerror.NewError(20014, "登录失败次数过多,请稍后再试")
+ errGetPhoneCaptchaError = xerror.NewError(20015, "短信验证码获取失败")
+ errTooManyPhoneCaptchaSend = xerror.NewError(20016, "短信验证码获取次数已达今日上限")
+ errExistedUserPhone = xerror.NewError(20017, "该手机号已被绑定")
+ errErrorPhoneCaptcha = xerror.NewError(20018, "手机验证码不正确")
+ errMaxPhoneCaptchaUseTimes = xerror.NewError(20019, "手机验证码已达最大使用次数")
+ errNicknameLengthLimit = xerror.NewError(20020, "昵称长度2~12")
+ errNoExistUsername = xerror.NewError(20021, "用户不存在")
+ errNoAdminPermission = xerror.NewError(20022, "无管理权限")
+
+ errGetPostsFailed = xerror.NewError(30001, "获取动态列表失败")
+ errCreatePostFailed = xerror.NewError(30002, "动态发布失败")
+ errGetPostFailed = xerror.NewError(30003, "获取动态详情失败")
+ errDeletePostFailed = xerror.NewError(30004, "动态删除失败")
+ errLockPostFailed = xerror.NewError(30005, "动态锁定失败")
+ errGetPostTagsFailed = xerror.NewError(30006, "获取话题列表失败")
+ errInvalidDownloadReq = xerror.NewError(30007, "附件下载请求不合法")
+ errDownloadReqError = xerror.NewError(30008, "附件下载请求失败")
+ errInsuffientDownloadMoney = xerror.NewError(30009, "附件下载失败:账户资金不足")
+ errDownloadExecFail = xerror.NewError(30010, "附件下载失败:扣费失败")
+ errStickPostFailed = xerror.NewError(30011, "动态置顶失败")
+ errVisblePostFailed = xerror.NewError(30012, "更新可见性失败")
+
+ errGetCommentsFailed = xerror.NewError(40001, "获取评论列表失败")
+ errCreateCommentFailed = xerror.NewError(40002, "评论发布失败")
+ errGetCommentFailed = xerror.NewError(40003, "获取评论详情失败")
+ errDeleteCommentFailed = xerror.NewError(40004, "评论删除失败")
+ errCreateReplyFailed = xerror.NewError(40005, "评论回复失败")
+ errGetReplyFailed = xerror.NewError(40006, "获取评论详情失败")
+ errMaxCommentCount = xerror.NewError(40007, "评论数已达最大限制")
+
+ errGetMessagesFailed = xerror.NewError(50001, "获取消息列表失败")
+ errReadMessageFailed = xerror.NewError(50002, "标记消息已读失败")
+ errSendWhisperFailed = xerror.NewError(50003, "私信发送失败")
+ errNoWhisperToSelf = xerror.NewError(50004, "不允许给自己发送私信")
+ errTooManyWhisperNum = xerror.NewError(50005, "今日私信次数已达上限")
+
+ errGetCollectionsFailed = xerror.NewError(60001, "获取收藏列表失败")
+ errGetStarsFailed = xerror.NewError(60002, "获取点赞列表失败")
+
+ errRechargeReqFail = xerror.NewError(70001, "充值请求失败")
+ errRechargeNotifyError = xerror.NewError(70002, "充值回调失败")
+ errGetRechargeFailed = xerror.NewError(70003, "充值详情获取失败")
+
+ errNoRequestingFriendToSelf = xerror.NewError(80001, "不允许添加自己为好友")
+ errNotExistFriendId = xerror.NewError(80002, "好友id不存在")
+ errSendRequestingFriendFailed = xerror.NewError(80003, "申请添加朋友请求发送失败")
+ errAddFriendFailed = xerror.NewError(80004, "添加好友失败")
+ errRejectFriendFailed = xerror.NewError(80005, "拒绝好友失败")
+ errDeleteFriendFailed = xerror.NewError(80006, "删除好友失败")
+ errGetContactsFailed = xerror.NewError(80007, "获取联系人列表失败")
+ errNoActionToSelf = xerror.NewError(80008, "不允许对自己操作")
+)
diff --git a/internal/service/admin.go b/internal/service/admin.go
new file mode 100644
index 00000000..ad965e80
--- /dev/null
+++ b/internal/service/admin.go
@@ -0,0 +1,86 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package service
+
+import (
+ "fmt"
+ "net/http"
+
+ "github.com/fatih/color"
+ "github.com/gin-contrib/cors"
+ "github.com/gin-gonic/gin"
+ "github.com/rocboss/paopao-ce/internal/conf"
+ "github.com/rocboss/paopao-ce/internal/servants"
+)
+
+type adminService struct {
+ *baseHttpService
+}
+
+func (s *adminService) Name() string {
+ return "AdminService"
+}
+
+func (s *adminService) Init() error {
+ s.registerRoute(servants.RegisterAdminServants)
+ return nil
+}
+
+func (s *adminService) String() string {
+ return fmt.Sprintf("listen on %s\n", color.GreenString("http://%s:%s", conf.AdminServerSetting.HttpIp, conf.AdminServerSetting.HttpPort))
+}
+
+func newAdminEngine() *gin.Engine {
+ e := gin.New()
+ e.HandleMethodNotAllowed = true
+ e.Use(gin.Logger())
+ e.Use(gin.Recovery())
+
+ // 跨域配置
+ corsConfig := cors.DefaultConfig()
+ corsConfig.AllowAllOrigins = true
+ corsConfig.AddAllowHeaders("Authorization")
+ e.Use(cors.New(corsConfig))
+
+ // 默认404
+ e.NoRoute(func(c *gin.Context) {
+ c.JSON(http.StatusNotFound, gin.H{
+ "code": 404,
+ "msg": "Not Found",
+ })
+ })
+
+ // 默认405
+ e.NoMethod(func(c *gin.Context) {
+ c.JSON(http.StatusMethodNotAllowed, gin.H{
+ "code": 405,
+ "msg": "Method Not Allowed",
+ })
+ })
+
+ return e
+}
+
+func newAdminService() Service {
+ addr := conf.AdminServerSetting.HttpIp + ":" + conf.AdminServerSetting.HttpPort
+ server := httpServerFrom(addr, func() *httpServer {
+ engine := newAdminEngine()
+ return &httpServer{
+ e: engine,
+ server: &http.Server{
+ Addr: addr,
+ Handler: engine,
+ ReadTimeout: conf.AdminServerSetting.ReadTimeout,
+ WriteTimeout: conf.AdminServerSetting.WriteTimeout,
+ MaxHeaderBytes: 1 << 20,
+ },
+ }
+ })
+ return &adminService{
+ baseHttpService: &baseHttpService{
+ server: server,
+ },
+ }
+}
diff --git a/internal/service/attachment.go b/internal/service/attachment.go
deleted file mode 100644
index 432a1a2f..00000000
--- a/internal/service/attachment.go
+++ /dev/null
@@ -1,7 +0,0 @@
-package service
-
-import "github.com/rocboss/paopao-ce/internal/model"
-
-func CreateAttachment(attachment *model.Attachment) (*model.Attachment, error) {
- return ds.CreateAttachment(attachment)
-}
diff --git a/internal/service/bot.go b/internal/service/bot.go
new file mode 100644
index 00000000..b9c66793
--- /dev/null
+++ b/internal/service/bot.go
@@ -0,0 +1,86 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package service
+
+import (
+ "fmt"
+ "net/http"
+
+ "github.com/fatih/color"
+ "github.com/gin-contrib/cors"
+ "github.com/gin-gonic/gin"
+ "github.com/rocboss/paopao-ce/internal/conf"
+ "github.com/rocboss/paopao-ce/internal/servants"
+)
+
+type botService struct {
+ *baseHttpService
+}
+
+func (s *botService) Name() string {
+ return "BotService"
+}
+
+func (s *botService) Init() error {
+ s.registerRoute(servants.RegisterBotServants)
+ return nil
+}
+
+func (s *botService) String() string {
+ return fmt.Sprintf("listen on %s\n", color.GreenString("http://%s:%s", conf.BotServerSetting.HttpIp, conf.BotServerSetting.HttpPort))
+}
+
+func newBotEngine() *gin.Engine {
+ e := gin.New()
+ e.HandleMethodNotAllowed = true
+ e.Use(gin.Logger())
+ e.Use(gin.Recovery())
+
+ // 跨域配置
+ corsConfig := cors.DefaultConfig()
+ corsConfig.AllowAllOrigins = true
+ corsConfig.AddAllowHeaders("Authorization")
+ e.Use(cors.New(corsConfig))
+
+ // 默认404
+ e.NoRoute(func(c *gin.Context) {
+ c.JSON(http.StatusNotFound, gin.H{
+ "code": 404,
+ "msg": "Not Found",
+ })
+ })
+
+ // 默认405
+ e.NoMethod(func(c *gin.Context) {
+ c.JSON(http.StatusMethodNotAllowed, gin.H{
+ "code": 405,
+ "msg": "Method Not Allowed",
+ })
+ })
+
+ return e
+}
+
+func newBotService() Service {
+ addr := conf.BotServerSetting.HttpIp + ":" + conf.BotServerSetting.HttpPort
+ server := httpServerFrom(addr, func() *httpServer {
+ engine := newBotEngine()
+ return &httpServer{
+ e: engine,
+ server: &http.Server{
+ Addr: addr,
+ Handler: engine,
+ ReadTimeout: conf.BotServerSetting.ReadTimeout,
+ WriteTimeout: conf.BotServerSetting.WriteTimeout,
+ MaxHeaderBytes: 1 << 20,
+ },
+ }
+ })
+ return &botService{
+ baseHttpService: &baseHttpService{
+ server: server,
+ },
+ }
+}
diff --git a/internal/service/http_server.go b/internal/service/http_server.go
new file mode 100644
index 00000000..4a8fdf3b
--- /dev/null
+++ b/internal/service/http_server.go
@@ -0,0 +1,83 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package service
+
+import (
+ "context"
+ "net/http"
+ "sync"
+
+ "github.com/gin-gonic/gin"
+)
+
+var (
+ httpServers = make(map[string]*httpServer)
+)
+
+const (
+ httpServerInitilized uint8 = iota + 1
+ httpServerStarted
+ httpServerStoped
+)
+
+// httpServer wraper for gin.engine and http.Server
+type httpServer struct {
+ sync.RWMutex
+
+ e *gin.Engine
+ server *http.Server
+ serverStatus uint8
+}
+
+func (s *httpServer) status() uint8 {
+ s.RLock()
+ defer s.RUnlock()
+
+ return s.serverStatus
+}
+
+func (s *httpServer) start() error {
+ s.Lock()
+ if s.serverStatus == httpServerStarted || s.serverStatus == httpServerStoped {
+ return nil
+ }
+ oldStatus := s.serverStatus
+ s.serverStatus = httpServerStarted
+ s.Unlock()
+
+ if err := s.server.ListenAndServe(); err != nil {
+ s.Lock()
+ s.serverStatus = oldStatus
+ s.Unlock()
+
+ return err
+ }
+ return nil
+}
+
+func (s *httpServer) stop() error {
+ s.Lock()
+ defer s.Unlock()
+
+ if s.serverStatus == httpServerStoped || s.serverStatus == httpServerInitilized {
+ return nil
+ }
+ if err := s.server.Shutdown(context.Background()); err != nil {
+ return err
+ }
+ s.serverStatus = httpServerStoped
+ return nil
+}
+
+func httpServerFrom(addr string, newServer func() *httpServer) *httpServer {
+ s, exist := httpServers[addr]
+ if exist {
+ return s
+ }
+ s = newServer()
+ s.serverStatus = httpServerInitilized
+ httpServers[addr] = s
+ return s
+}
diff --git a/internal/service/http_service.go b/internal/service/http_service.go
new file mode 100644
index 00000000..fc7ce9b6
--- /dev/null
+++ b/internal/service/http_service.go
@@ -0,0 +1,32 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package service
+
+import (
+ "github.com/gin-gonic/gin"
+)
+
+type baseHttpService struct {
+ baseService
+
+ server *httpServer
+}
+
+func (s *baseHttpService) registerRoute(h func(e *gin.Engine)) {
+ if s.server.status() != httpServerStarted {
+ h(s.server.e)
+ }
+}
+
+func (s *baseHttpService) Start() error {
+ if err := s.server.start(); err != nil {
+ return err
+ }
+ return nil
+}
+
+func (s *baseHttpService) Stop() error {
+ return s.server.stop()
+}
diff --git a/internal/service/localoss.go b/internal/service/localoss.go
new file mode 100644
index 00000000..18dd79f9
--- /dev/null
+++ b/internal/service/localoss.go
@@ -0,0 +1,61 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package service
+
+import (
+ "fmt"
+ "net/http"
+
+ "github.com/fatih/color"
+ "github.com/gin-gonic/gin"
+ "github.com/rocboss/paopao-ce/internal/conf"
+ "github.com/rocboss/paopao-ce/internal/servants"
+)
+
+type localossService struct {
+ *baseHttpService
+}
+
+func (s *localossService) Name() string {
+ return "LocalossService"
+}
+
+func (s *localossService) Init() error {
+ s.registerRoute(servants.RegisterLocalossServants)
+ return nil
+}
+
+func (s *localossService) String() string {
+ return fmt.Sprintf("listen on %s\n", color.GreenString("http://%s:%s", conf.LocalossServerSetting.HttpIp, conf.LocalossServerSetting.HttpPort))
+}
+
+func newLocalossEngine() *gin.Engine {
+ e := gin.New()
+ e.Use(gin.Logger())
+ e.Use(gin.Recovery())
+ return e
+}
+
+func newLocalossService() Service {
+ addr := conf.LocalossServerSetting.HttpIp + ":" + conf.LocalossServerSetting.HttpPort
+ server := httpServerFrom(addr, func() *httpServer {
+ engine := newLocalossEngine()
+ return &httpServer{
+ e: engine,
+ server: &http.Server{
+ Addr: addr,
+ Handler: engine,
+ ReadTimeout: conf.LocalossServerSetting.ReadTimeout,
+ WriteTimeout: conf.LocalossServerSetting.WriteTimeout,
+ MaxHeaderBytes: 1 << 20,
+ },
+ }
+ })
+ return &localossService{
+ baseHttpService: &baseHttpService{
+ server: server,
+ },
+ }
+}
diff --git a/internal/service/service.go b/internal/service/service.go
index 9d7d4c01..34a04574 100644
--- a/internal/service/service.go
+++ b/internal/service/service.go
@@ -1,45 +1,65 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package service
import (
- "github.com/rocboss/paopao-ce/internal/core"
- "github.com/rocboss/paopao-ce/internal/dao"
- "github.com/rocboss/paopao-ce/internal/model"
- "github.com/rocboss/paopao-ce/pkg/cfg"
- "github.com/sirupsen/logrus"
-)
+ "log"
-var (
- ds core.DataService
- ts core.TweetSearchService
- oss core.ObjectStorageService
- DisablePhoneVerify bool
+ "github.com/alimy/cfg"
+ "github.com/rocboss/paopao-ce/pkg/types"
)
-func Initialize() {
- ds = dao.DataService()
- ts = dao.TweetSearchService()
- oss = dao.ObjectStorageService()
- DisablePhoneVerify = !cfg.If("Sms")
+type Service interface {
+ Name() string
+ Init() error
+ Start() error
+ Stop() error
+}
+
+type baseService types.Empty
+
+func (baseService) Name() string {
+ return ""
+}
+
+func (baseService) String() string {
+ return ""
}
-// persistMediaContents 获取媒体内容并持久化
-func persistMediaContents(contents []*PostContentItem) (items []string, err error) {
- items = make([]string, 0, len(contents))
- for _, item := range contents {
- switch item.Type {
- case model.CONTENT_TYPE_IMAGE,
- model.CONTENT_TYPE_VIDEO,
- model.CONTENT_TYPE_AUDIO,
- model.CONTENT_TYPE_ATTACHMENT,
- model.CONTENT_TYPE_CHARGE_ATTACHMENT:
- items = append(items, item.Content)
- if err != nil {
- continue
- }
- if err = oss.PersistObject(oss.ObjectKey(item.Content)); err != nil {
- logrus.Errorf("service.persistMediaContents failed: %s", err)
- }
+func InitService() []Service {
+ ss := newService()
+ for _, s := range ss {
+ if err := s.Init(); err != nil {
+ log.Fatalf("initial %s service error: %s", s.Name(), err)
}
}
+ return ss
+}
+
+func newService() (ss []Service) {
+ ss = append(ss, newWebService())
+
+ // add oldWebService if not depredcated OldWebService
+ cfg.Not("Deprecated:OldWeb", func() {
+ ss = append(ss, newOldWebService())
+ })
+
+ cfg.In(cfg.Actions{
+ "Admin": func() {
+ ss = append(ss, newAdminService())
+ },
+ "SpaceX": func() {
+ ss = append(ss, newSpaceXService())
+ },
+ "Bot": func() {
+ ss = append(ss, newBotService())
+ },
+ "LocalOSS": func() {
+ ss = append(ss, newLocalossService())
+ },
+ })
+
return
}
diff --git a/internal/service/space.go b/internal/service/space.go
new file mode 100644
index 00000000..3866c5ac
--- /dev/null
+++ b/internal/service/space.go
@@ -0,0 +1,86 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package service
+
+import (
+ "fmt"
+ "net/http"
+
+ "github.com/fatih/color"
+ "github.com/gin-contrib/cors"
+ "github.com/gin-gonic/gin"
+ "github.com/rocboss/paopao-ce/internal/conf"
+ "github.com/rocboss/paopao-ce/internal/servants"
+)
+
+type spaceXService struct {
+ *baseHttpService
+}
+
+func (s *spaceXService) Name() string {
+ return "WebService"
+}
+
+func (s *spaceXService) Init() error {
+ s.registerRoute(servants.RegisterSpaceXServants)
+ return nil
+}
+
+func (s *spaceXService) String() string {
+ return fmt.Sprintf("listen on %s\n", color.GreenString("http://%s:%s", conf.SpaceXServerSetting.HttpIp, conf.SpaceXServerSetting.HttpPort))
+}
+
+func newSpaceXEngine() *gin.Engine {
+ e := gin.New()
+ e.HandleMethodNotAllowed = true
+ e.Use(gin.Logger())
+ e.Use(gin.Recovery())
+
+ // 跨域配置
+ corsConfig := cors.DefaultConfig()
+ corsConfig.AllowAllOrigins = true
+ corsConfig.AddAllowHeaders("Authorization")
+ e.Use(cors.New(corsConfig))
+
+ // 默认404
+ e.NoRoute(func(c *gin.Context) {
+ c.JSON(http.StatusNotFound, gin.H{
+ "code": 404,
+ "msg": "Not Found",
+ })
+ })
+
+ // 默认405
+ e.NoMethod(func(c *gin.Context) {
+ c.JSON(http.StatusMethodNotAllowed, gin.H{
+ "code": 405,
+ "msg": "Method Not Allowed",
+ })
+ })
+
+ return e
+}
+
+func newSpaceXService() Service {
+ addr := conf.SpaceXServerSetting.HttpIp + ":" + conf.SpaceXServerSetting.HttpPort
+ server := httpServerFrom(addr, func() *httpServer {
+ engine := newSpaceXEngine()
+ return &httpServer{
+ e: engine,
+ server: &http.Server{
+ Addr: addr,
+ Handler: engine,
+ ReadTimeout: conf.SpaceXServerSetting.ReadTimeout,
+ WriteTimeout: conf.SpaceXServerSetting.WriteTimeout,
+ MaxHeaderBytes: 1 << 20,
+ },
+ }
+ })
+ return &spaceXService{
+ baseHttpService: &baseHttpService{
+ server: server,
+ },
+ }
+}
diff --git a/internal/service/web.go b/internal/service/web.go
new file mode 100644
index 00000000..c8e422a1
--- /dev/null
+++ b/internal/service/web.go
@@ -0,0 +1,86 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package service
+
+import (
+ "fmt"
+ "net/http"
+
+ "github.com/fatih/color"
+ "github.com/gin-contrib/cors"
+ "github.com/gin-gonic/gin"
+ "github.com/rocboss/paopao-ce/internal/conf"
+ "github.com/rocboss/paopao-ce/internal/servants"
+)
+
+type webService struct {
+ *baseHttpService
+}
+
+func (s *webService) Name() string {
+ return "WebService"
+}
+
+func (s *webService) Init() error {
+ s.registerRoute(servants.RegisterWebServants)
+ return nil
+}
+
+func (s *webService) String() string {
+ return fmt.Sprintf("listen on %s\n", color.GreenString("http://%s:%s", conf.WebServerSetting.HttpIp, conf.WebServerSetting.HttpPort))
+}
+
+func newWebEngine() *gin.Engine {
+ e := gin.New()
+ e.HandleMethodNotAllowed = true
+ e.Use(gin.Logger())
+ e.Use(gin.Recovery())
+
+ // 跨域配置
+ corsConfig := cors.DefaultConfig()
+ corsConfig.AllowAllOrigins = true
+ corsConfig.AddAllowHeaders("Authorization")
+ e.Use(cors.New(corsConfig))
+
+ // 默认404
+ e.NoRoute(func(c *gin.Context) {
+ c.JSON(http.StatusNotFound, gin.H{
+ "code": 404,
+ "msg": "Not Found",
+ })
+ })
+
+ // 默认405
+ e.NoMethod(func(c *gin.Context) {
+ c.JSON(http.StatusMethodNotAllowed, gin.H{
+ "code": 405,
+ "msg": "Method Not Allowed",
+ })
+ })
+
+ return e
+}
+
+func newWebService() Service {
+ addr := conf.WebServerSetting.HttpIp + ":" + conf.WebServerSetting.HttpPort
+ server := httpServerFrom(addr, func() *httpServer {
+ engine := newWebEngine()
+ return &httpServer{
+ e: engine,
+ server: &http.Server{
+ Addr: addr,
+ Handler: engine,
+ ReadTimeout: conf.WebServerSetting.ReadTimeout,
+ WriteTimeout: conf.WebServerSetting.WriteTimeout,
+ MaxHeaderBytes: 1 << 20,
+ },
+ }
+ })
+ return &webService{
+ baseHttpService: &baseHttpService{
+ server: server,
+ },
+ }
+}
diff --git a/internal/service/web_old.go b/internal/service/web_old.go
new file mode 100644
index 00000000..a3c58471
--- /dev/null
+++ b/internal/service/web_old.go
@@ -0,0 +1,53 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package service
+
+import (
+ "fmt"
+ "net/http"
+
+ "github.com/fatih/color"
+ "github.com/rocboss/paopao-ce/internal/conf"
+ "github.com/rocboss/paopao-ce/internal/servants/web/routers"
+)
+
+type oldWebService struct {
+ *baseHttpService
+}
+
+func (s *oldWebService) Name() string {
+ return "OldWebService"
+}
+
+func (s *oldWebService) Init() error {
+ s.registerRoute(routers.RegisterRoute)
+ return nil
+}
+
+func (s *oldWebService) String() string {
+ return fmt.Sprintf("listen on %s\n", color.GreenString("http://%s:%s", conf.ServerSetting.HttpIp, conf.ServerSetting.HttpPort))
+}
+
+func newOldWebService() Service {
+ addr := conf.ServerSetting.HttpIp + ":" + conf.ServerSetting.HttpPort
+ server := httpServerFrom(addr, func() *httpServer {
+ engine := newWebEngine()
+ return &httpServer{
+ e: engine,
+ server: &http.Server{
+ Addr: addr,
+ Handler: engine,
+ ReadTimeout: conf.ServerSetting.ReadTimeout,
+ WriteTimeout: conf.ServerSetting.WriteTimeout,
+ MaxHeaderBytes: 1 << 20,
+ },
+ }
+ })
+ return &oldWebService{
+ baseHttpService: &baseHttpService{
+ server: server,
+ },
+ }
+}
diff --git a/main.go b/main.go
index 1046e97d..4c639a61 100644
--- a/main.go
+++ b/main.go
@@ -1,17 +1,23 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package main
import (
"flag"
"fmt"
- "log"
- "net/http"
+ "os"
+ "os/signal"
"strings"
+ "sync"
+ "syscall"
"github.com/fatih/color"
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/internal"
"github.com/rocboss/paopao-ce/internal/conf"
- "github.com/rocboss/paopao-ce/internal/routers"
+ "github.com/rocboss/paopao-ce/internal/service"
"github.com/rocboss/paopao-ce/pkg/debug"
"github.com/rocboss/paopao-ce/pkg/util"
)
@@ -42,29 +48,56 @@ func init() {
}
func flagParse() {
- flag.BoolVar(&noDefaultFeatures, "no-default-features", false, "whether use default features")
+ flag.BoolVar(&noDefaultFeatures, "no-default-features", false, "whether not use default features")
flag.Var(&features, "features", "use special features")
flag.Parse()
}
-func main() {
- gin.SetMode(conf.ServerSetting.RunMode)
-
- router := routers.NewRouter()
- s := &http.Server{
- Addr: conf.ServerSetting.HttpIp + ":" + conf.ServerSetting.HttpPort,
- Handler: router,
- ReadTimeout: conf.ServerSetting.ReadTimeout,
- WriteTimeout: conf.ServerSetting.WriteTimeout,
- MaxHeaderBytes: 1 << 20,
+func runService(wg *sync.WaitGroup, ss []service.Service) {
+ gin.SetMode(conf.RunMode())
+
+ fmt.Fprintf(color.Output, "\nstarting run service...\n\n")
+ for _, s := range ss {
+ go func(s service.Service) {
+ fmt.Fprintf(color.Output, "%s[start] - %s", s.Name(), s)
+ if err := s.Start(); err != nil {
+ fmt.Fprintf(color.Output, "%s[start] - occurs on error: %s\n", s.Name(), err)
+ }
+ wg.Done()
+ }(s)
}
+}
+
+func runManage(wg *sync.WaitGroup, ss []service.Service) {
+ quit := make(chan os.Signal, 1)
+ // kill (no param) default send syscall.SIGTERM
+ // kill -2 is syscall.SIGINT
+ // kill -9 is syscall.SIGKILL but can't be catch, so don't need add it
+ signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
+ <-quit
+ fmt.Fprintf(color.Output, "\nshutting down server...\n\n")
+ for _, s := range ss {
+ if err := s.Stop(); err != nil {
+ fmt.Fprintf(color.Output, "%s[stop] - occurs on error: %s\n", s.Name(), err)
+ }
+ fmt.Fprintf(color.Output, "%s[stop] - finish...\n", s.Name())
+ }
+ wg.Done()
+}
+
+func main() {
util.PrintHelloBanner(debug.VersionInfo())
- fmt.Fprintf(color.Output, "PaoPao service listen on %s\n",
- color.GreenString(fmt.Sprintf("http://%s:%s", conf.ServerSetting.HttpIp, conf.ServerSetting.HttpPort)),
- )
- if err := s.ListenAndServe(); err != nil {
- log.Fatalf("run app failed: %s", err)
+ if ss := service.InitService(); len(ss) > 0 {
+ wg := &sync.WaitGroup{}
+ wg.Add(len(ss) + 1)
+
+ runService(wg, ss)
+ go runManage(wg, ss)
+
+ wg.Wait()
+ } else {
+ fmt.Fprintf(color.Output, "no service need start so just exit")
}
}
diff --git a/pkg/app/app.go b/pkg/app/app.go
index fc860d27..a98a49a2 100644
--- a/pkg/app/app.go
+++ b/pkg/app/app.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package app
import (
diff --git a/pkg/app/form.go b/pkg/app/form.go
index 7e376104..91b116a2 100644
--- a/pkg/app/form.go
+++ b/pkg/app/form.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package app
import (
diff --git a/pkg/app/jwt.go b/pkg/app/jwt.go
index 8033296f..b9759e07 100644
--- a/pkg/app/jwt.go
+++ b/pkg/app/jwt.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package app
import (
@@ -5,7 +9,7 @@ import (
"github.com/golang-jwt/jwt/v4"
"github.com/rocboss/paopao-ce/internal/conf"
- "github.com/rocboss/paopao-ce/internal/model"
+ "github.com/rocboss/paopao-ce/internal/core"
)
type Claims struct {
@@ -18,7 +22,7 @@ func GetJWTSecret() []byte {
return []byte(conf.JWTSetting.Secret)
}
-func GenerateToken(User *model.User) (string, error) {
+func GenerateToken(User *core.User) (string, error) {
expireTime := time.Now().Add(conf.JWTSetting.Expire)
claims := Claims{
UID: User.ID,
diff --git a/pkg/app/pagination.go b/pkg/app/pagination.go
index 1888efb9..699d1dd2 100644
--- a/pkg/app/pagination.go
+++ b/pkg/app/pagination.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package app
import (
diff --git a/pkg/cfg/cfg.go b/pkg/cfg/cfg.go
deleted file mode 100644
index 019deba9..00000000
--- a/pkg/cfg/cfg.go
+++ /dev/null
@@ -1,41 +0,0 @@
-package cfg
-
-var (
- _features = newEmptyFeatures()
-
- // Use alias of Features.Use func
- Use = _features.Use
-
- // UseDeafult alias of Features.UseDefault func
- UseDefault = _features.UseDefault
-
- // As alias of Features.Cfg func
- As = _features.Cfg
-
- // If alias of Features.CfgIf func
- If = _features.CfgIf
-
- // In alias of Features.CfgIn func
- In = _features.CfgIn
-
- // Be alias of Feaures.CfgBe func
- Be = _features.CfgBe
-
- // Not alias of Features.CfgNot func
- Not = _features.CfgNot
-)
-
-// Initialize initialize features in cfg pkg
-func Initialize(suites map[string][]string, kv map[string]string) {
- _features = NewFeatures(suites, kv)
- {
- // must re-assign variable below
- Use = _features.Use
- UseDefault = _features.UseDefault
- As = _features.Cfg
- If = _features.CfgIf
- In = _features.CfgIn
- Be = _features.CfgBe
- Not = _features.CfgNot
- }
-}
diff --git a/pkg/cfg/cfg_test.go b/pkg/cfg/cfg_test.go
deleted file mode 100644
index 0fccbce2..00000000
--- a/pkg/cfg/cfg_test.go
+++ /dev/null
@@ -1,78 +0,0 @@
-package cfg
-
-import (
- "testing"
-)
-
-func TestCfg(t *testing.T) {
- suites := map[string][]string{
- "default": {"Sms", "Alipay", "Zinc", "MySQL", "Redis", "AliOSS", "LogZinc"},
- "develop": {"Zinc", "MySQL", "AliOSS", "LogFile"},
- "slim": {"Zinc", "MySQL", "Redis", "AliOSS", "LogFile"},
- }
- kv := map[string]string{
- "sms": "SmsJuhe",
- }
-
- Initialize(suites, kv)
- UseDefault()
-
- if !If("Sms") {
- t.Error(`want If("Sms") == true but not`)
- }
-
- if v, exist := As("Sms"); exist && v != "SmsJuhe" {
- t.Errorf(`want As("Sms") == "SmsJuhe", true but got: "%s", "%t"`, v, exist)
- }
-
- matched := false
- Be("Alipay", func() {
- matched = true
- })
- if !matched {
- t.Error(`want Be("Alipay", ...) matched but not`)
- }
-
- matched = false
- Not("LogFile", func() {
- matched = true
- })
- if !matched {
- t.Error(`want Not("LogFile", ...) matched but not`)
- }
-
- var m1, m2, m3, m4 bool
- In(Actions{
- "Sms": func() {
- m1 = true
- },
- "Alipay": func() {
- m2 = true
- },
- "Meili": func() {
- m4 = true
- },
- }, func() {
- m3 = true
- })
- if !m1 || !m2 || m3 || m4 {
- t.Errorf(`In("Sms", "Alipay", "Meili", ...) not correct -> m1: %t m2:%t m3:%t m4:%t`, m1, m2, m3, m4)
- }
-
- m1 = false
- m2 = false
- m3 = false
- In(Actions{
- "LogFile": func() {
- m1 = true
- },
- "Meili": func() {
- m2 = true
- },
- }, func() {
- m3 = true
- })
- if m1 || m2 || !m3 {
- t.Errorf(`In("Zinc", "MySQL", ...) not correct -> m1: %t m2:%t m3:%t`, m1, m2, m3)
- }
-}
diff --git a/pkg/cfg/feature.go b/pkg/cfg/feature.go
deleted file mode 100644
index a04d07ca..00000000
--- a/pkg/cfg/feature.go
+++ /dev/null
@@ -1,149 +0,0 @@
-package cfg
-
-import (
- "strings"
-
- "github.com/rocboss/paopao-ce/pkg/types"
-)
-
-// Features fetures info struct
-type Features struct {
- kv map[string]string
- suites map[string][]string
- features map[string]string
-}
-
-// Actions feature-func map alias type
-type Actions map[string]types.Fn
-
-// NewFeatures create new Features instance
-func NewFeatures(suites map[string][]string, kv map[string]string) *Features {
- f := newEmptyFeatures()
- for k, v := range suites {
- if len(k) > 0 {
- for i := 0; i < len(v); i++ {
- // ignore empty string
- if len(v[i]) == 0 {
- lastIdx := len(v) - 1
- v[i] = v[lastIdx]
- v = v[:lastIdx]
- i--
- }
- }
- if len(v) > 0 {
- f.suites[k] = v
- }
- }
- }
- for k, v := range kv {
- if len(k) > 0 && len(v) > 0 {
- f.kv[k] = v
- }
- }
- f.UseDefault()
- return f
-}
-
-func newEmptyFeatures() *Features {
- return &Features{
- suites: make(map[string][]string),
- kv: make(map[string]string),
- features: make(map[string]string),
- }
-}
-
-// UseDefault use default suite for features
-func (f *Features) UseDefault() {
- f.Use([]string{"default"}, true)
-}
-
-// Use use custom suite for features
-func (f *Features) Use(suite []string, noDefault bool) {
- if noDefault && len(f.features) != 0 {
- f.features = make(map[string]string)
- }
- features := f.flatFeatures(suite)
- for _, feature := range features {
- if len(feature) == 0 {
- continue
- }
- f.features[feature] = f.kv[feature]
- }
-}
-
-func (f *Features) flatFeatures(suite []string) []string {
- features := make([]string, 0, len(suite)+10)
- for s := suite[:]; len(s) > 0; s = s[:len(s)-1] {
- item := strings.TrimSpace(strings.ToLower(s[0]))
- if len(item) > 0 {
- if items, exist := f.suites[item]; exist {
- s = append(s, items...)
- }
- features = append(features, item)
- }
- s[0] = s[len(s)-1]
- }
- return features
-}
-
-// Cfg get value by key if exist
-func (f *Features) Cfg(key string) (string, bool) {
- key = strings.ToLower(key)
- value, exist := f.features[key]
- return value, exist
-}
-
-// CfgIf check expression is true. if expression just have a string like
-// `Sms` is mean `Sms` whether define in suite feature settings. expression like
-// `Sms = SmsJuhe` is mean whether `Sms` define in suite feature settings and value
-// is `SmsJuhe`
-func (f *Features) CfgIf(expression string) bool {
- kv := strings.Split(expression, "=")
- key := strings.Trim(strings.ToLower(kv[0]), " ")
- v, ok := f.features[key]
- if len(kv) == 2 && ok && strings.Trim(kv[1], " ") == v {
- return true
- } else if len(kv) == 1 && ok {
- return true
- }
- return false
-}
-
-// CfgIn range actions to check item's expression is true then do the handle, defFn will handle
-// if all items are not matched,
-func (f *Features) CfgIn(actions Actions, defAct ...types.Fn) {
- itemMatched := false
- for expression, handle := range actions {
- if f.CfgIf(expression) && handle != nil {
- handle()
- itemMatched = true
- }
- }
- if !itemMatched && len(defAct) > 0 {
- for _, handle := range defAct {
- if handle != nil {
- handle()
- }
- }
- }
-}
-
-// CfgBe check expression is true then do the handle. if expression just have a string like
-// `Sms` is mean `Sms` whether defined in suite feature settings. expression like
-// `Sms = SmsJuhe` is mean whether `Sms` define in suite feature settings and value
-// is `SmsJuhe`
-func (f *Features) CfgBe(expression string, handle types.Fn) {
- if f.CfgIf(expression) && handle != nil {
- handle()
- }
-}
-
-// CfgNot check expression is not true then do the handle. if expression just have a string like
-// `Sms` is mean `Sms` whether defined in suite feature settings. expression like
-// `Sms = SmsJuhe` is mean whether `Sms` define in suite feature settings and value
-// is `SmsJuhe`
-func (f *Features) CfgNot(expression string, handle func()) {
- if !f.CfgIf(expression) {
- handle()
- }
-}
diff --git a/pkg/cfg/feature_test.go b/pkg/cfg/feature_test.go
deleted file mode 100644
index 98e01ec7..00000000
--- a/pkg/cfg/feature_test.go
+++ /dev/null
@@ -1,114 +0,0 @@
-package cfg
-
-import (
- "testing"
-)
-
-func TestUseDefault(t *testing.T) {
- suites := map[string][]string{
- "default": {"Sms", "Alipay", "Zinc", "MySQL", "Redis", "AliOSS", "LogZinc"},
- "develop": {"Zinc", "MySQL", "AliOSS", "LogFile"},
- "slim": {"Zinc", "MySQL", "Redis", "AliOSS", "LogFile"},
- }
- kv := map[string]string{
- "sms": "SmsJuhe",
- }
- f := NewFeatures(suites, kv)
- for _, data := range []struct {
- key string
- expect string
- exist bool
- }{
- {"Sms", "SmsJuhe", true},
- {"Alipay", "", true},
- {"Zinc", "", true},
- {"Redis", "", true},
- {"Database", "", false},
- } {
- if v, ok := f.Cfg(data.key); ok != data.exist || v != data.expect {
- t.Errorf("key: %s expect: %s exist: %t got v: %s ok: %t", data.key, data.expect, data.exist, v, ok)
- }
- }
- for exp, res := range map[string]bool{
- "Sms": true,
- "Sms = SmsJuhe": true,
- "SmsJuhe": false,
- "default": true,
- } {
- if ok := f.CfgIf(exp); res != ok {
- t.Errorf("CfgIf(%s) want %t got %t", exp, res, ok)
- }
- }
-}
-
-func TestUse(t *testing.T) {
- suites := map[string][]string{
- "default": {"Sms", "Alipay", "Zinc", "MySQL", "Redis", "AliOSS", "LogZinc"},
- "develop": {"Zinc", "MySQL", "AliOSS", "LogFile"},
- "slim": {"Zinc", "MySQL", "Redis", "AliOSS", "LogFile"},
- }
- kv := map[string]string{
- "sms": "SmsJuhe",
- }
- f := NewFeatures(suites, kv)
-
- f.Use([]string{"develop"}, true)
- for _, data := range []struct {
- key string
- expect string
- exist bool
- }{
- {"Sms", "", false},
- {"Alipay", "", false},
- {"Zinc", "", true},
- {"Redis", "", false},
- {"Database", "", false},
- } {
- if v, ok := f.Cfg(data.key); ok != data.exist || v != data.expect {
- t.Errorf("key: %s expect: %s exist: %t got v: %s ok: %t", data.key, data.expect, data.exist, v, ok)
- }
- }
- for exp, res := range map[string]bool{
- "Sms": false,
- "Sms = SmsJuhe": false,
- "SmsJuhe": false,
- "default": false,
- "develop": true,
- } {
- if ok := f.CfgIf(exp); res != ok {
- t.Errorf("CfgIf(%s) want %t got %t", exp, res, ok)
- }
- }
-
- f.UseDefault()
- f.Use([]string{"slim", "", "demo"}, false)
- for _, data := range []struct {
- key string
- expect string
- exist bool
- }{
- {"Sms", "SmsJuhe", true},
- {"Alipay", "", true},
- {"Zinc", "", true},
- {"Redis", "", true},
- {"Database", "", false},
- {"demo", "", true},
- } {
- if v, ok := f.Cfg(data.key); ok != data.exist || v != data.expect {
- t.Errorf("key: %s expect: %s exist: %t got v: %s ok: %t", data.key, data.expect, data.exist, v, ok)
- }
- }
- for exp, res := range map[string]bool{
- "Sms": true,
- "Sms = SmsJuhe": true,
- "SmsJuhe": false,
- "default": true,
- "develop": false,
- "slim": true,
- "demo": true,
- } {
- if ok := f.CfgIf(exp); res != ok {
- t.Errorf("CfgIf(%s) want %t got %t", exp, res, ok)
- }
- }
-}
diff --git a/pkg/convert/convert.go b/pkg/convert/convert.go
index 60dacf9b..ff3be5e5 100644
--- a/pkg/convert/convert.go
+++ b/pkg/convert/convert.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package convert
import "strconv"
diff --git a/pkg/convert/convert_test.go b/pkg/convert/convert_test.go
index a746e3e7..a31d13e6 100644
--- a/pkg/convert/convert_test.go
+++ b/pkg/convert/convert_test.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package convert
import (
diff --git a/pkg/crypto/signature.go b/pkg/crypto/signature.go
index 7f18959a..20a6deaa 100644
--- a/pkg/crypto/signature.go
+++ b/pkg/crypto/signature.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package crypto
import (
diff --git a/pkg/debug/version.go b/pkg/debug/version.go
index 485e8046..68236f05 100644
--- a/pkg/debug/version.go
+++ b/pkg/debug/version.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package debug
import (
diff --git a/pkg/errcode/common_code.go b/pkg/errcode/common_code.go
index 75b220ee..1f15f8c5 100644
--- a/pkg/errcode/common_code.go
+++ b/pkg/errcode/common_code.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package errcode
var (
diff --git a/pkg/errcode/errcode.go b/pkg/errcode/errcode.go
index 50f04868..5143aabb 100644
--- a/pkg/errcode/errcode.go
+++ b/pkg/errcode/errcode.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package errcode
import (
diff --git a/pkg/errcode/module_code.go b/pkg/errcode/module_code.go
index 1c5b7215..9543624b 100644
--- a/pkg/errcode/module_code.go
+++ b/pkg/errcode/module_code.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package errcode
var (
diff --git a/pkg/sign/sign.go b/pkg/sign/sign.go
index 717b8e54..fc7c10e9 100644
--- a/pkg/sign/sign.go
+++ b/pkg/sign/sign.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package sign
import (
diff --git a/pkg/types/types.go b/pkg/types/types.go
index 2696f8b9..830c56c6 100644
--- a/pkg/types/types.go
+++ b/pkg/types/types.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package types
// Empty empty alias type
diff --git a/pkg/util/banner.go b/pkg/util/banner.go
index d41b5ae1..31e25ba9 100644
--- a/pkg/util/banner.go
+++ b/pkg/util/banner.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package util
import "fmt"
diff --git a/pkg/util/ip.go b/pkg/util/ip.go
index 3aaa13c1..4561d8a6 100644
--- a/pkg/util/ip.go
+++ b/pkg/util/ip.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package util
import "github.com/rocboss/paopao-ce/pkg/util/iploc"
diff --git a/pkg/util/ip_test.go b/pkg/util/ip_test.go
index 82976be8..0740ffd5 100644
--- a/pkg/util/ip_test.go
+++ b/pkg/util/ip_test.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package util
import "testing"
diff --git a/pkg/util/iploc/iploc.go b/pkg/util/iploc/iploc.go
index a05f8d7e..449e52a9 100644
--- a/pkg/util/iploc/iploc.go
+++ b/pkg/util/iploc/iploc.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package iploc
import (
diff --git a/pkg/util/iploc/iploc_test.go b/pkg/util/iploc/iploc_test.go
index 4754e86d..a38bb106 100644
--- a/pkg/util/iploc/iploc_test.go
+++ b/pkg/util/iploc/iploc_test.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package iploc
import (
diff --git a/pkg/util/md5.go b/pkg/util/md5.go
index 8a00f545..477cd5ff 100644
--- a/pkg/util/md5.go
+++ b/pkg/util/md5.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package util
import (
diff --git a/pkg/util/md5_test.go b/pkg/util/md5_test.go
index 0bab593f..12c14c86 100644
--- a/pkg/util/md5_test.go
+++ b/pkg/util/md5_test.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package util
import "testing"
diff --git a/pkg/util/str.go b/pkg/util/str.go
index 35e034ab..8b62217d 100644
--- a/pkg/util/str.go
+++ b/pkg/util/str.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package util
import (
diff --git a/pkg/xerror/common.go b/pkg/xerror/common.go
new file mode 100644
index 00000000..2852f6c2
--- /dev/null
+++ b/pkg/xerror/common.go
@@ -0,0 +1,26 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package xerror
+
+var (
+ Success = NewError(0, "成功")
+ ServerError = NewError(10000, "服务内部错误")
+ InvalidParams = NewError(10001, "入参错误")
+ NotFound = NewError(10002, "找不到")
+ UnauthorizedAuthNotExist = NewError(10003, "账户不存在")
+ UnauthorizedAuthFailed = NewError(10004, "账户密码错误")
+ UnauthorizedTokenError = NewError(10005, "鉴权失败,Token 错误或丢失")
+ UnauthorizedTokenTimeout = NewError(10006, "鉴权失败,Token 超时")
+ UnauthorizedTokenGenerate = NewError(10007, "鉴权失败,Token 生成失败")
+ TooManyRequests = NewError(10008, "请求过多")
+
+ GatewayMethodsLimit = NewError(10109, "网关仅接受GET或POST请求")
+ GatewayLostSign = NewError(10110, "网关请求缺少签名")
+ GatewayLostAppKey = NewError(10111, "网关请求缺少APP KEY")
+ GatewayAppKeyInvalid = NewError(10112, "网关请求无效APP KEY")
+ GatewayAppKeyClosed = NewError(10113, "网关请求APP KEY已停用")
+ GatewayParamSignError = NewError(10114, "网关请求参数签名错误")
+ GatewayTooManyRequests = NewError(10115, "网关请求频次超限")
+)
diff --git a/pkg/xerror/xerror.go b/pkg/xerror/xerror.go
new file mode 100644
index 00000000..f614d18e
--- /dev/null
+++ b/pkg/xerror/xerror.go
@@ -0,0 +1,104 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
+package xerror
+
+import (
+ "fmt"
+ "net/http"
+ "strings"
+)
+
+var (
+ codes = map[int]string{}
+)
+
+type Error struct {
+ code int
+ msg string
+ details []string
+}
+
+type ValidError struct {
+ Message string
+}
+
+type ValidErrors []*ValidError
+
+func (v *ValidError) Error() string {
+ return v.Message
+}
+
+func (v ValidErrors) Error() string {
+ return strings.Join(v.Errors(), ",")
+}
+
+func (v ValidErrors) Errors() []string {
+ var errs []string
+ for _, err := range v {
+ errs = append(errs, err.Error())
+ }
+ return errs
+}
+
+func NewError(code int, msg string) *Error {
+ if _, ok := codes[code]; ok {
+ panic(fmt.Sprintf("错误码 %d 已经存在,请更换一个", code))
+ }
+ codes[code] = msg
+ return &Error{code: code, msg: msg}
+}
+
+func (e *Error) Error() string {
+ return fmt.Sprintf("错误码: %d, 错误信息: %s", e.Code(), e.Msg())
+}
+
+func (e *Error) Code() int {
+ return e.code
+}
+
+func (e *Error) Msg() string {
+ return e.msg
+}
+
+func (e *Error) Msgf(args []any) string {
+ return fmt.Sprintf(e.msg, args...)
+}
+
+func (e *Error) Details() []string {
+ return e.details
+}
+
+func (e *Error) WithDetails(details ...string) *Error {
+ newError := *e
+ newError.details = []string{}
+ newError.details = append(newError.details, details...)
+
+ return &newError
+}
+
+func (e *Error) StatusCode() int {
+ switch e.Code() {
+ case Success.Code():
+ return http.StatusOK
+ case ServerError.Code():
+ return http.StatusInternalServerError
+ case InvalidParams.Code():
+ return http.StatusBadRequest
+ case UnauthorizedAuthNotExist.Code():
+ fallthrough
+ case UnauthorizedAuthFailed.Code():
+ fallthrough
+ case UnauthorizedTokenError.Code():
+ fallthrough
+ case UnauthorizedTokenGenerate.Code():
+ fallthrough
+ case UnauthorizedTokenTimeout.Code():
+ return http.StatusUnauthorized
+ case TooManyRequests.Code():
+ return http.StatusTooManyRequests
+ }
+
+ return http.StatusInternalServerError
+}
diff --git a/pkg/zinc/zinc.go b/pkg/zinc/zinc.go
index ba1fb270..cc200a55 100644
--- a/pkg/zinc/zinc.go
+++ b/pkg/zinc/zinc.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
package zinc
import (
diff --git a/scripts/migration/embed.go b/scripts/migration/embed.go
index 88e633c8..3f1eacda 100644
--- a/scripts/migration/embed.go
+++ b/scripts/migration/embed.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
//go:build migration
// +build migration
diff --git a/web/embed.go b/web/embed.go
index 4866a53a..a16df24a 100644
--- a/web/embed.go
+++ b/web/embed.go
@@ -1,3 +1,7 @@
+// Copyright 2022 ROC. All rights reserved.
+// Use of this source code is governed by a MIT style
+// license that can be found in the LICENSE file.
+
//go:build embed
// +build embed