Merge branch 'feat-channel'

This commit is contained in:
JustSong
2023-05-06 10:18:48 +08:00
32 changed files with 1657 additions and 412 deletions
+2 -5
View File
@@ -20,11 +20,8 @@ type barkMessageResponse struct {
Message string `json:"message"`
}
func SendBarkMessage(message *model.Message, user *model.User) error {
if user.BarkServer == "" || user.BarkSecret == "" {
return errors.New("未配置 Bark 消息推送方式")
}
url := fmt.Sprintf("%s/%s", user.BarkServer, user.BarkSecret)
func SendBarkMessage(message *model.Message, user *model.User, channel_ *model.Channel) error {
url := fmt.Sprintf("%s/%s", channel_.URL, channel_.Secret)
req := barkMessageRequest{
Title: message.Title,
Body: message.Content,
+14 -14
View File
@@ -2,6 +2,7 @@ package channel
import (
"errors"
"fmt"
"github.com/gorilla/websocket"
"message-pusher/common"
"message-pusher/model"
@@ -17,7 +18,7 @@ const (
)
type webSocketClient struct {
userId int
key string
conn *websocket.Conn
message chan *model.Message
pong chan bool
@@ -55,10 +56,10 @@ func (c *webSocketClient) handleDataWriting() {
defer func() {
pingTicker.Stop()
clientConnMapMutex.Lock()
client, ok := clientMap[c.userId]
client, ok := clientMap[c.key]
// otherwise we may delete the new added client!
if ok && client.timestamp == c.timestamp {
delete(clientMap, c.userId)
delete(clientMap, c.key)
}
clientConnMapMutex.Unlock()
err := c.conn.Close()
@@ -108,18 +109,19 @@ func (c *webSocketClient) close() {
// the defer function in handleDataWriting will do the cleanup
}
var clientMap map[int]*webSocketClient
var clientMap map[string]*webSocketClient
var clientConnMapMutex sync.Mutex
func init() {
clientConnMapMutex.Lock()
clientMap = make(map[int]*webSocketClient)
clientMap = make(map[string]*webSocketClient)
clientConnMapMutex.Unlock()
}
func RegisterClient(userId int, conn *websocket.Conn) {
func RegisterClient(channelName string, userId int, conn *websocket.Conn) {
key := fmt.Sprintf("%s:%d", channelName, userId)
clientConnMapMutex.Lock()
oldClient, existed := clientMap[userId]
oldClient, existed := clientMap[key]
clientConnMapMutex.Unlock()
if existed {
byeMessage := &model.Message{
@@ -134,7 +136,7 @@ func RegisterClient(userId int, conn *websocket.Conn) {
Description: "客户端连接成功!",
}
newClient := &webSocketClient{
userId: userId,
key: key,
conn: conn,
message: make(chan *model.Message),
pong: make(chan bool),
@@ -145,16 +147,14 @@ func RegisterClient(userId int, conn *websocket.Conn) {
go newClient.handleDataReading()
defer newClient.sendMessage(helloMessage)
clientConnMapMutex.Lock()
clientMap[userId] = newClient
clientMap[key] = newClient
clientConnMapMutex.Unlock()
}
func SendClientMessage(message *model.Message, user *model.User) error {
if user.ClientSecret == "" {
return errors.New("未配置 WebSocket 客户端消息推送方式")
}
func SendClientMessage(message *model.Message, user *model.User, channel_ *model.Channel) error {
key := fmt.Sprintf("%s:%d", channel_.Name, user.Id)
clientConnMapMutex.Lock()
client, existed := clientMap[user.Id]
client, existed := clientMap[key]
clientConnMapMutex.Unlock()
if !existed {
return errors.New("客户端未连接")
+2 -5
View File
@@ -26,11 +26,8 @@ type corpMessageResponse struct {
Message string `json:"errmsg"`
}
func SendCorpMessage(message *model.Message, user *model.User) error {
func SendCorpMessage(message *model.Message, user *model.User, channel_ *model.Channel) error {
// https://developer.work.weixin.qq.com/document/path/91770
if user.CorpWebhookURL == "" {
return errors.New("未配置企业微信群机器人消息推送方式")
}
messageRequest := corpMessageRequest{
MessageType: "text",
}
@@ -48,7 +45,7 @@ func SendCorpMessage(message *model.Message, user *model.User) error {
if err != nil {
return err
}
resp, err := http.Post(fmt.Sprintf("%s", user.CorpWebhookURL), "application/json",
resp, err := http.Post(fmt.Sprintf("%s", channel_.URL), "application/json",
bytes.NewBuffer(jsonData))
if err != nil {
return err
+3 -6
View File
@@ -35,11 +35,8 @@ type dingMessageResponse struct {
Message string `json:"errmsg"`
}
func SendDingMessage(message *model.Message, user *model.User) error {
func SendDingMessage(message *model.Message, user *model.User, channel_ *model.Channel) error {
// https://open.dingtalk.com/document/robots/custom-robot-access#title-72m-8ag-pqw
if user.DingWebhookURL == "" {
return errors.New("未配置钉钉群机器人消息推送方式")
}
messageRequest := dingMessageRequest{
MessageType: "text",
}
@@ -60,7 +57,7 @@ func SendDingMessage(message *model.Message, user *model.User) error {
}
timestamp := time.Now().UnixMilli()
sign, err := dingSign(user.DingWebhookSecret, timestamp)
sign, err := dingSign(channel_.Secret, timestamp)
if err != nil {
return err
}
@@ -68,7 +65,7 @@ func SendDingMessage(message *model.Message, user *model.User) error {
if err != nil {
return err
}
resp, err := http.Post(fmt.Sprintf("%s&timestamp=%d&sign=%s", user.DingWebhookURL, timestamp, sign), "application/json",
resp, err := http.Post(fmt.Sprintf("%s&timestamp=%d&sign=%s", channel_.URL, timestamp, sign), "application/json",
bytes.NewBuffer(jsonData))
if err != nil {
return err
+2 -5
View File
@@ -18,10 +18,7 @@ type discordMessageResponse struct {
Message string `json:"message"`
}
func SendDiscordMessage(message *model.Message, user *model.User) error {
if user.DiscordWebhookURL == "" {
return errors.New("未配置 Discord 群机器人消息推送方式")
}
func SendDiscordMessage(message *model.Message, user *model.User, channel_ *model.Channel) error {
if message.Content == "" {
message.Content = message.Description
}
@@ -42,7 +39,7 @@ func SendDiscordMessage(message *model.Message, user *model.User) error {
if err != nil {
return err
}
resp, err := http.Post(user.DiscordWebhookURL, "application/json", bytes.NewBuffer(jsonData))
resp, err := http.Post(channel_.URL, "application/json", bytes.NewBuffer(jsonData))
if err != nil {
return err
}
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"message-pusher/model"
)
func SendEmailMessage(message *model.Message, user *model.User) error {
func SendEmailMessage(message *model.Message, user *model.User, channel_ *model.Channel) error {
if message.To != "" {
if user.SendEmailToOthers != common.SendEmailToOthersAllowed && user.Role < common.RoleAdminUser {
return errors.New("没有权限发送邮件给其他人,请联系管理员为你添加该权限")
+3 -6
View File
@@ -46,11 +46,8 @@ type larkMessageResponse struct {
Message string `json:"msg"`
}
func SendLarkMessage(message *model.Message, user *model.User) error {
func SendLarkMessage(message *model.Message, user *model.User, channel_ *model.Channel) error {
// https://open.feishu.cn/document/ukTMukTMukTM/ucTM5YjL3ETO24yNxkjN#e1cdee9f
if user.LarkWebhookURL == "" {
return errors.New("未配置飞书群机器人消息推送方式")
}
messageRequest := larkMessageRequest{
MessageType: "text",
}
@@ -83,7 +80,7 @@ func SendLarkMessage(message *model.Message, user *model.User) error {
now := time.Now()
timestamp := now.Unix()
sign, err := larkSign(user.LarkWebhookSecret, timestamp)
sign, err := larkSign(channel_.Secret, timestamp)
if err != nil {
return err
}
@@ -93,7 +90,7 @@ func SendLarkMessage(message *model.Message, user *model.User) error {
if err != nil {
return err
}
resp, err := http.Post(user.LarkWebhookURL, "application/json",
resp, err := http.Post(channel_.URL, "application/json",
bytes.NewBuffer(jsonData))
if err != nil {
return err
+24 -38
View File
@@ -5,45 +5,31 @@ import (
"message-pusher/model"
)
const (
TypeEmail = "email"
TypeWeChatTestAccount = "test"
TypeWeChatCorpAccount = "corp_app"
TypeCorp = "corp"
TypeLark = "lark"
TypeDing = "ding"
TypeTelegram = "telegram"
TypeDiscord = "discord"
TypeBark = "bark"
TypeClient = "client"
TypeNone = "none"
)
func SendMessage(message *model.Message, user *model.User) error {
switch message.Channel {
case TypeEmail:
return SendEmailMessage(message, user)
case TypeWeChatTestAccount:
return SendWeChatTestMessage(message, user)
case TypeWeChatCorpAccount:
return SendWeChatCorpMessage(message, user)
case TypeCorp:
return SendCorpMessage(message, user)
case TypeLark:
return SendLarkMessage(message, user)
case TypeDing:
return SendDingMessage(message, user)
case TypeBark:
return SendBarkMessage(message, user)
case TypeClient:
return SendClientMessage(message, user)
case TypeTelegram:
return SendTelegramMessage(message, user)
case TypeDiscord:
return SendDiscordMessage(message, user)
case TypeNone:
func SendMessage(message *model.Message, user *model.User, channel_ *model.Channel) error {
switch channel_.Type {
case model.TypeEmail:
return SendEmailMessage(message, user, channel_)
case model.TypeWeChatTestAccount:
return SendWeChatTestMessage(message, user, channel_)
case model.TypeWeChatCorpAccount:
return SendWeChatCorpMessage(message, user, channel_)
case model.TypeCorp:
return SendCorpMessage(message, user, channel_)
case model.TypeLark:
return SendLarkMessage(message, user, channel_)
case model.TypeDing:
return SendDingMessage(message, user, channel_)
case model.TypeBark:
return SendBarkMessage(message, user, channel_)
case model.TypeClient:
return SendClientMessage(message, user, channel_)
case model.TypeTelegram:
return SendTelegramMessage(message, user, channel_)
case model.TypeDiscord:
return SendDiscordMessage(message, user, channel_)
case model.TypeNone:
return nil
default:
return errors.New("不支持的消息通道:" + message.Channel)
return errors.New("不支持的消息通道:" + channel_.Type)
}
}
+6 -6
View File
@@ -20,16 +20,16 @@ type telegramMessageResponse struct {
Description string `json:"description"`
}
func SendTelegramMessage(message *model.Message, user *model.User) error {
func SendTelegramMessage(message *model.Message, user *model.User, channel_ *model.Channel) error {
// https://core.telegram.org/bots/api#sendmessage
if user.TelegramBotToken == "" || user.TelegramChatId == "" {
return errors.New("未配置 Telegram 机器人消息推送方式")
}
messageRequest := telegramMessageRequest{
ChatId: user.TelegramChatId,
ChatId: channel_.AccountId,
Text: message.Content,
ParseMode: "markdown",
}
if message.To != "" {
messageRequest.ChatId = message.To
}
if messageRequest.Text == "" {
messageRequest.Text = message.Description
}
@@ -37,7 +37,7 @@ func SendTelegramMessage(message *model.Message, user *model.User) error {
if err != nil {
return err
}
resp, err := http.Post(fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", user.TelegramBotToken), "application/json",
resp, err := http.Post(fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", channel_.Secret), "application/json",
bytes.NewBuffer(jsonData))
if err != nil {
return err
+144 -101
View File
@@ -12,6 +12,7 @@ type TokenStoreItem interface {
Token() string
Refresh()
IsFilled() bool
IsShared() bool
}
type tokenStore struct {
@@ -22,34 +23,51 @@ type tokenStore struct {
var s tokenStore
func channel2item(channel_ *model.Channel) TokenStoreItem {
if channel_.Type == model.TypeWeChatTestAccount {
item := &WeChatTestAccountTokenStoreItem{
AppID: channel_.AppId,
AppSecret: channel_.Secret,
}
return item
} else if channel_.Type == model.TypeWeChatCorpAccount {
corpId, agentId, err := parseWechatCorpAccountAppId(channel_.AppId)
if err != nil {
common.SysError(err.Error())
return nil
}
item := &WeChatCorpAccountTokenStoreItem{
CorpId: corpId,
AgentSecret: channel_.Secret,
AgentId: agentId,
}
return item
}
return nil
}
func channels2items(channels []*model.Channel) []TokenStoreItem {
var items []TokenStoreItem
for _, channel_ := range channels {
item := channel2item(channel_)
if item != nil {
items = append(items, item)
}
}
return items
}
func TokenStoreInit() {
s.Map = make(map[string]*TokenStoreItem)
// https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html
// https://developer.work.weixin.qq.com/document/path/91039
s.ExpirationSeconds = 2 * 55 * 60 // 2 hours - 5 minutes
go func() {
users, err := model.GetAllUsersWithSecrets()
channels, err := model.GetTokenStoreChannels()
if err != nil {
common.FatalLog(err.Error())
}
var items []TokenStoreItem
for _, user := range users {
if user.WeChatTestAccountId != "" {
item := &WeChatTestAccountTokenStoreItem{
AppID: user.WeChatTestAccountId,
AppSecret: user.WeChatTestAccountSecret,
}
items = append(items, item)
}
if user.WeChatCorpAccountId != "" {
item := &WeChatCorpAccountTokenStoreItem{
CorpId: user.WeChatCorpAccountId,
AgentSecret: user.WeChatCorpAccountAgentSecret,
AgentId: user.WeChatCorpAccountAgentId,
}
items = append(items, item)
}
}
items := channels2items(channels)
s.Mutex.RLock()
for i := range items {
// s.Map[item.Key()] = &item // This is wrong, you are getting the address of a local variable!
@@ -99,78 +117,14 @@ func TokenStoreRemoveItem(item TokenStoreItem) {
}
func TokenStoreAddUser(user *model.User) {
testItem := WeChatTestAccountTokenStoreItem{
AppID: user.WeChatTestAccountId,
AppSecret: user.WeChatTestAccountSecret,
channels, err := model.GetTokenStoreChannelsByUserId(user.Id)
if err != nil {
common.SysError(err.Error())
return
}
TokenStoreAddItem(&testItem)
corpItem := WeChatCorpAccountTokenStoreItem{
CorpId: user.WeChatCorpAccountId,
AgentSecret: user.WeChatCorpAccountAgentSecret,
AgentId: user.WeChatCorpAccountAgentId,
}
TokenStoreAddItem(&corpItem)
}
func TokenStoreUpdateUser(cleanUser *model.User, originUser *model.User) {
// WeChat Test Account
// The fields of cleanUser may be incomplete!
if cleanUser.WeChatTestAccountId == originUser.WeChatTestAccountId {
cleanUser.WeChatTestAccountId = ""
}
if cleanUser.WeChatTestAccountSecret == originUser.WeChatTestAccountSecret {
cleanUser.WeChatTestAccountSecret = ""
}
// This means the user updated those fields.
if cleanUser.WeChatTestAccountId != "" || cleanUser.WeChatTestAccountSecret != "" {
oldWeChatTestAccountTokenStoreItem := WeChatTestAccountTokenStoreItem{
AppID: originUser.WeChatTestAccountId,
AppSecret: originUser.WeChatTestAccountSecret,
}
// Yeah, it's a deep copy.
newWeChatTestAccountTokenStoreItem := oldWeChatTestAccountTokenStoreItem
if cleanUser.WeChatTestAccountId != "" {
newWeChatTestAccountTokenStoreItem.AppID = cleanUser.WeChatTestAccountId
}
if cleanUser.WeChatTestAccountSecret != "" {
newWeChatTestAccountTokenStoreItem.AppSecret = cleanUser.WeChatTestAccountSecret
}
if !oldWeChatTestAccountTokenStoreItem.IsShared() {
TokenStoreRemoveItem(&oldWeChatTestAccountTokenStoreItem)
}
TokenStoreAddItem(&newWeChatTestAccountTokenStoreItem)
}
// WeChat Corp Account
if cleanUser.WeChatCorpAccountId == originUser.WeChatCorpAccountId {
cleanUser.WeChatCorpAccountId = ""
}
if cleanUser.WeChatCorpAccountAgentId == originUser.WeChatCorpAccountAgentId {
cleanUser.WeChatCorpAccountAgentId = ""
}
if cleanUser.WeChatCorpAccountAgentSecret == originUser.WeChatCorpAccountAgentSecret {
cleanUser.WeChatCorpAccountAgentSecret = ""
}
if cleanUser.WeChatCorpAccountId != "" || cleanUser.WeChatCorpAccountAgentId != "" || cleanUser.WeChatCorpAccountAgentSecret != "" {
oldWeChatCorpAccountTokenStoreItem := WeChatCorpAccountTokenStoreItem{
CorpId: originUser.WeChatCorpAccountId,
AgentSecret: originUser.WeChatCorpAccountAgentSecret,
AgentId: originUser.WeChatCorpAccountAgentId,
}
newWeChatCorpAccountTokenStoreItem := oldWeChatCorpAccountTokenStoreItem
if cleanUser.WeChatCorpAccountId != "" {
newWeChatCorpAccountTokenStoreItem.CorpId = cleanUser.WeChatCorpAccountId
}
if cleanUser.WeChatCorpAccountAgentSecret != "" {
newWeChatCorpAccountTokenStoreItem.AgentSecret = cleanUser.WeChatCorpAccountAgentSecret
}
if cleanUser.WeChatCorpAccountAgentId != "" {
newWeChatCorpAccountTokenStoreItem.AgentId = cleanUser.WeChatCorpAccountAgentId
}
if !oldWeChatCorpAccountTokenStoreItem.IsShared() {
TokenStoreRemoveItem(&oldWeChatCorpAccountTokenStoreItem)
}
TokenStoreAddItem(&newWeChatCorpAccountTokenStoreItem)
items := channels2items(channels)
for i := range items {
TokenStoreAddItem(items[i])
}
}
@@ -178,20 +132,109 @@ func TokenStoreUpdateUser(cleanUser *model.User, originUser *model.User) {
// user must be filled.
// It's okay to delete a user that don't have an item here.
func TokenStoreRemoveUser(user *model.User) {
testAccountTokenStoreItem := WeChatTestAccountTokenStoreItem{
AppID: user.WeChatTestAccountId,
AppSecret: user.WeChatTestAccountSecret,
channels, err := model.GetTokenStoreChannelsByUserId(user.Id)
if err != nil {
common.SysError(err.Error())
return
}
if !testAccountTokenStoreItem.IsShared() {
TokenStoreRemoveItem(&testAccountTokenStoreItem)
items := channels2items(channels)
for i := range items {
if items[i].IsShared() {
continue
}
TokenStoreRemoveItem(items[i])
}
corpAccountTokenStoreItem := WeChatCorpAccountTokenStoreItem{
CorpId: user.WeChatCorpAccountId,
AgentSecret: user.WeChatCorpAccountAgentSecret,
AgentId: user.WeChatCorpAccountAgentId,
}
func TokenStoreAddChannel(channel *model.Channel) {
if channel.Type != model.TypeWeChatTestAccount && channel.Type != model.TypeWeChatCorpAccount {
return
}
if !corpAccountTokenStoreItem.IsShared() {
TokenStoreRemoveItem(&corpAccountTokenStoreItem)
item := channel2item(channel)
if item != nil {
TokenStoreAddItem(item)
}
}
func TokenStoreRemoveChannel(channel *model.Channel) {
if channel.Type != model.TypeWeChatTestAccount && channel.Type != model.TypeWeChatCorpAccount {
return
}
item := channel2item(channel)
if item != nil {
TokenStoreRemoveItem(item)
}
}
func TokenStoreUpdateChannel(newChannel *model.Channel, oldChannel *model.Channel) {
if oldChannel.Type != model.TypeWeChatTestAccount && oldChannel.Type != model.TypeWeChatCorpAccount {
return
}
if oldChannel.Type == model.TypeWeChatTestAccount {
// Only keep changed parts
if newChannel.AppId == oldChannel.AppId {
newChannel.AppId = ""
}
if newChannel.Secret == oldChannel.Secret {
newChannel.Secret = ""
}
oldItem := WeChatTestAccountTokenStoreItem{
AppID: oldChannel.AppId,
AppSecret: oldChannel.Secret,
}
// Yeah, it's a deep copy.
newItem := oldItem
// This means the user updated those fields.
if newChannel.AppId != "" {
newItem.AppID = newChannel.AppId
}
if newChannel.Secret != "" {
newItem.AppSecret = newChannel.Secret
}
if !oldItem.IsShared() {
TokenStoreRemoveItem(&oldItem)
}
TokenStoreAddItem(&newItem)
return
}
if oldChannel.Type == model.TypeWeChatCorpAccount {
// Only keep changed parts
if newChannel.AppId == oldChannel.AppId {
newChannel.AppId = ""
}
if newChannel.Secret == oldChannel.Secret {
newChannel.Secret = ""
}
corpId, agentId, err := parseWechatCorpAccountAppId(oldChannel.AppId)
if err != nil {
common.SysError(err.Error())
return
}
oldItem := WeChatCorpAccountTokenStoreItem{
CorpId: corpId,
AgentSecret: oldChannel.Secret,
AgentId: agentId,
}
// Yeah, it's a deep copy.
newItem := oldItem
// This means the user updated those fields.
if newChannel.AppId != "" {
corpId, agentId, err := parseWechatCorpAccountAppId(oldChannel.AppId)
if err != nil {
common.SysError(err.Error())
return
}
newItem.CorpId = corpId
newItem.AgentId = agentId
}
if newChannel.Secret != "" {
newItem.AgentSecret = newChannel.Secret
}
if !oldItem.IsShared() {
TokenStoreRemoveItem(&oldItem)
}
TokenStoreAddItem(&newItem)
return
}
}
+23 -9
View File
@@ -8,6 +8,7 @@ import (
"message-pusher/common"
"message-pusher/model"
"net/http"
"strings"
"time"
)
@@ -30,8 +31,9 @@ func (i *WeChatCorpAccountTokenStoreItem) Key() string {
}
func (i *WeChatCorpAccountTokenStoreItem) IsShared() bool {
return model.DB.Where("wechat_corp_account_id = ? and wechat_corp_account_agent_secret = ? and wechat_corp_account_agent_id = ?",
i.CorpId, i.AgentSecret, i.AgentId).Find(&model.User{}).RowsAffected != 1
appId := fmt.Sprintf("%s|%s", i.CorpId, i.AgentId)
return model.DB.Where("type = ? and app_id = ? and secret = ?",
model.TypeWeChatCorpAccount, appId, i.AgentSecret).Find(&model.Channel{}).RowsAffected != 1
}
func (i *WeChatCorpAccountTokenStoreItem) IsFilled() bool {
@@ -95,14 +97,26 @@ type wechatCorpMessageResponse struct {
ErrorMessage string `json:"errmsg"`
}
func SendWeChatCorpMessage(message *model.Message, user *model.User) error {
if user.WeChatCorpAccountId == "" {
return errors.New("未配置微信企业号消息推送方式")
func parseWechatCorpAccountAppId(appId string) (string, string, error) {
parts := strings.Split(appId, "|")
if len(parts) != 2 {
return "", "", errors.New("无效的微信企业号配置")
}
return parts[0], parts[1], nil
}
func SendWeChatCorpMessage(message *model.Message, user *model.User, channel_ *model.Channel) error {
// https://developer.work.weixin.qq.com/document/path/90236
corpId, agentId, err := parseWechatCorpAccountAppId(channel_.AppId)
if err != nil {
return err
}
userId := channel_.AccountId
clientType := channel_.Other
agentSecret := channel_.Secret
messageRequest := wechatCorpMessageRequest{
ToUser: user.WeChatCorpAccountUserId,
AgentId: user.WeChatCorpAccountAgentId,
ToUser: userId,
AgentId: agentId,
}
if message.To != "" {
messageRequest.ToUser = message.To
@@ -118,7 +132,7 @@ func SendWeChatCorpMessage(message *model.Message, user *model.User) error {
messageRequest.TextCard.URL = common.ServerAddress
}
} else {
if user.WeChatCorpAccountClientType == "plugin" {
if clientType == "plugin" {
messageRequest.MessageType = "textcard"
messageRequest.TextCard.Title = message.Title
messageRequest.TextCard.Description = message.Description
@@ -132,7 +146,7 @@ func SendWeChatCorpMessage(message *model.Message, user *model.User) error {
if err != nil {
return err
}
key := fmt.Sprintf("%s%s%s", user.WeChatCorpAccountId, user.WeChatCorpAccountAgentId, user.WeChatCorpAccountAgentSecret)
key := fmt.Sprintf("%s%s%s", corpId, agentId, agentSecret)
accessToken := TokenStoreGetToken(key)
resp, err := http.Post(fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s", accessToken), "application/json",
bytes.NewBuffer(jsonData))
+6 -9
View File
@@ -29,8 +29,8 @@ func (i *WeChatTestAccountTokenStoreItem) Key() string {
}
func (i *WeChatTestAccountTokenStoreItem) IsShared() bool {
return model.DB.Where("wechat_test_account_id = ? and wechat_test_account_secret = ?",
i.AppID, i.AppSecret).Find(&model.User{}).RowsAffected != 1
return model.DB.Where("type = ? and app_id = ? and secret = ?",
model.TypeWeChatTestAccount, i.AppID, i.AppSecret).Find(&model.Channel{}).RowsAffected != 1
}
func (i *WeChatTestAccountTokenStoreItem) IsFilled() bool {
@@ -88,13 +88,10 @@ type wechatTestMessageResponse struct {
ErrorMessage string `json:"errmsg"`
}
func SendWeChatTestMessage(message *model.Message, user *model.User) error {
if user.WeChatTestAccountId == "" {
return errors.New("未配置微信测试号消息推送方式")
}
func SendWeChatTestMessage(message *model.Message, user *model.User, channel_ *model.Channel) error {
values := wechatTestMessageRequest{
ToUser: user.WeChatTestAccountOpenId,
TemplateId: user.WeChatTestAccountTemplateId,
ToUser: channel_.AccountId,
TemplateId: channel_.Other,
URL: "",
}
values.Data.Text.Value = message.Description
@@ -103,7 +100,7 @@ func SendWeChatTestMessage(message *model.Message, user *model.User) error {
if err != nil {
return err
}
key := fmt.Sprintf("%s%s", user.WeChatTestAccountId, user.WeChatTestAccountSecret)
key := fmt.Sprintf("%s%s", channel_.AppId, channel_.Secret)
accessToken := TokenStoreGetToken(key)
resp, err := http.Post(fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s", accessToken), "application/json",
bytes.NewBuffer(jsonData))
+6
View File
@@ -106,3 +106,9 @@ const (
MessageSendStatusSent = 2
MessageSendStatusFailed = 3
)
const (
ChannelStatusUnknown = 0
ChannelStatusEnabled = 1
ChannelStatusDisabled = 2
)
+5
View File
@@ -12,6 +12,7 @@ import (
"runtime"
"strconv"
"strings"
"time"
)
func OpenBrowser(url string) {
@@ -151,3 +152,7 @@ func Markdown2HTML(markdown string) (HTML string, err error) {
HTML = buf.String()
return
}
func GetTimestamp() int64 {
return time.Now().Unix()
}
+193
View File
@@ -0,0 +1,193 @@
package controller
import (
"github.com/gin-gonic/gin"
"message-pusher/channel"
"message-pusher/common"
"message-pusher/model"
"net/http"
"strconv"
)
func GetAllChannels(c *gin.Context) {
userId := c.GetInt("id")
p, _ := strconv.Atoi(c.Query("p"))
if p < 0 {
p = 0
}
channels, err := model.GetChannelsByUserId(userId, p*common.ItemsPerPage, common.ItemsPerPage)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "",
"data": channels,
})
return
}
func SearchChannels(c *gin.Context) {
userId := c.GetInt("id")
keyword := c.Query("keyword")
channels, err := model.SearchChannels(userId, keyword)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "",
"data": channels,
})
return
}
func GetChannel(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
userId := c.GetInt("id")
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
})
return
}
channel_, err := model.GetChannelById(id, userId)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "",
"data": channel_,
})
return
}
func AddChannel(c *gin.Context) {
channel_ := model.Channel{}
err := c.ShouldBindJSON(&channel_)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
})
return
}
if len(channel_.Name) == 0 || len(channel_.Name) > 20 {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": "通道名称长度必须在1-20之间",
})
return
}
cleanChannel := model.Channel{
Type: channel_.Type,
UserId: c.GetInt("id"),
Name: channel_.Name,
Description: channel_.Description,
Status: common.ChannelStatusEnabled,
Secret: channel_.Secret,
AppId: channel_.AppId,
AccountId: channel_.AccountId,
URL: channel_.URL,
Other: channel_.Other,
CreatedTime: common.GetTimestamp(),
}
err = cleanChannel.Insert()
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
})
return
}
channel.TokenStoreAddChannel(&cleanChannel)
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "",
})
return
}
func DeleteChannel(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
userId := c.GetInt("id")
channel_, err := model.DeleteChannelById(id, userId)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
})
return
}
channel.TokenStoreRemoveChannel(channel_)
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "",
})
return
}
func UpdateChannel(c *gin.Context) {
userId := c.GetInt("id")
statusOnly := c.Query("status_only")
channel_ := model.Channel{}
err := c.ShouldBindJSON(&channel_)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
})
return
}
oldChannel, err := model.GetChannelById(channel_.Id, userId)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
})
return
}
cleanChannel := oldChannel
if statusOnly != "" {
cleanChannel.Status = channel_.Status
} else {
// If you add more fields, please also update channel_.Update()
cleanChannel.Type = channel_.Type
cleanChannel.Name = channel_.Name
cleanChannel.Description = channel_.Description
cleanChannel.Secret = channel_.Secret
cleanChannel.AppId = channel_.AppId
cleanChannel.AccountId = channel_.AccountId
cleanChannel.URL = channel_.URL
cleanChannel.Other = channel_.Other
}
err = cleanChannel.Update()
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
})
return
}
channel.TokenStoreUpdateChannel(cleanChannel, oldChannel)
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "",
"data": cleanChannel,
})
return
}
+26 -10
View File
@@ -2,6 +2,7 @@ package controller
import (
"encoding/json"
"errors"
"fmt"
"github.com/gin-gonic/gin"
"message-pusher/channel"
@@ -65,21 +66,21 @@ func pushMessageHelper(c *gin.Context, message *model.Message) {
user := model.User{Username: c.Param("username")}
err := user.FillUserByUsername()
if err != nil {
c.JSON(http.StatusForbidden, gin.H{
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
})
return
}
if user.Status == common.UserStatusNonExisted {
c.JSON(http.StatusForbidden, gin.H{
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": "用户不存在",
})
return
}
if user.Status == common.UserStatusDisabled {
c.JSON(http.StatusForbidden, gin.H{
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": "用户已被封禁",
})
@@ -89,7 +90,7 @@ func pushMessageHelper(c *gin.Context, message *model.Message) {
if message.Token == "" {
message.Token = c.Request.Header.Get("Authorization")
if message.Token == "" {
c.JSON(http.StatusForbidden, gin.H{
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": "token 为空",
})
@@ -97,7 +98,7 @@ func pushMessageHelper(c *gin.Context, message *model.Message) {
}
}
if user.Token != message.Token {
c.JSON(http.StatusForbidden, gin.H{
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": "无效的 token",
})
@@ -110,10 +111,18 @@ func pushMessageHelper(c *gin.Context, message *model.Message) {
if message.Channel == "" {
message.Channel = user.Channel
if message.Channel == "" {
message.Channel = channel.TypeEmail
message.Channel = model.TypeEmail
}
}
err = saveAndSendMessage(&user, message)
channel_, err := model.GetChannelByName(message.Channel, user.Id)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": "无效的渠道的名称",
})
return
}
err = saveAndSendMessage(&user, message, channel_)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
@@ -127,7 +136,10 @@ func pushMessageHelper(c *gin.Context, message *model.Message) {
})
}
func saveAndSendMessage(user *model.User, message *model.Message) error {
func saveAndSendMessage(user *model.User, message *model.Message, channel_ *model.Channel) error {
if channel_.Status != common.ChannelStatusEnabled {
return errors.New("该渠道已被禁用")
}
message.Link = common.GetUUID()
if message.URL == "" {
message.URL = fmt.Sprintf("%s/message/%s", common.ServerAddress, message.Link)
@@ -152,7 +164,7 @@ func saveAndSendMessage(user *model.User, message *model.Message) error {
} else {
message.Link = "unsaved" // This is for user to identify whether the message is saved
}
err := channel.SendMessage(message, user)
err := channel.SendMessage(message, user, channel_)
common.MessageCount += 1 // We don't need to use atomic here because it's not a critical value
if err != nil {
return err
@@ -284,7 +296,11 @@ func ResendMessage(c *gin.Context) {
if err != nil {
return err
}
err = saveAndSendMessage(user, message)
channel_, err := model.GetChannelByName(message.Channel, user.Id)
if err != nil {
return err
}
err = saveAndSendMessage(user, message, channel_)
if err != nil {
return err
}
+6 -36
View File
@@ -389,45 +389,15 @@ func UpdateSelf(c *gin.Context) {
})
return
}
originUser, err := model.GetUserById(c.GetInt("id"), true)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
})
return
}
// White list mode. For safe :)
cleanUser := model.User{
Id: c.GetInt("id"),
Username: user.Username,
Password: user.Password,
DisplayName: user.DisplayName,
Token: user.Token,
Channel: user.Channel,
WeChatTestAccountId: user.WeChatTestAccountId,
WeChatTestAccountSecret: user.WeChatTestAccountSecret,
WeChatTestAccountTemplateId: user.WeChatTestAccountTemplateId,
WeChatTestAccountOpenId: user.WeChatTestAccountOpenId,
WeChatTestAccountVerificationToken: user.WeChatTestAccountVerificationToken,
WeChatCorpAccountId: user.WeChatCorpAccountId,
WeChatCorpAccountAgentSecret: user.WeChatCorpAccountAgentSecret,
WeChatCorpAccountAgentId: user.WeChatCorpAccountAgentId,
WeChatCorpAccountUserId: user.WeChatCorpAccountUserId,
WeChatCorpAccountClientType: user.WeChatCorpAccountClientType,
CorpWebhookURL: user.CorpWebhookURL,
LarkWebhookURL: user.LarkWebhookURL,
LarkWebhookSecret: user.LarkWebhookSecret,
DingWebhookURL: user.DingWebhookURL,
DingWebhookSecret: user.DingWebhookSecret,
BarkServer: user.BarkServer,
BarkSecret: user.BarkSecret,
ClientSecret: user.ClientSecret,
TelegramBotToken: user.TelegramBotToken,
TelegramChatId: user.TelegramChatId,
DiscordWebhookURL: user.DiscordWebhookURL,
Id: c.GetInt("id"),
Username: user.Username,
Password: user.Password,
DisplayName: user.DisplayName,
Token: user.Token,
Channel: user.Channel,
}
channel.TokenStoreUpdateUser(&cleanUser, originUser)
if user.Password == "$I_LOVE_U" {
user.Password = "" // rollback to what it should be
+22 -3
View File
@@ -27,10 +27,29 @@ func RegisterClient(c *gin.Context) {
}
user := model.User{Username: c.Param("username")}
err := user.FillUserByUsername()
if secret != user.ClientSecret {
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": "用户名与密钥不匹配",
"message": "无效的用户名",
})
return
}
channelName := c.Query("channel")
if channelName == "" {
channelName = "client"
}
channel_, err := model.GetChannelByName(channelName, user.Id)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": "无效的通道名称",
})
return
}
if secret != channel_.Secret {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": "通道名称与密钥不匹配",
})
return
}
@@ -42,6 +61,6 @@ func RegisterClient(c *gin.Context) {
})
return
}
channel.RegisterClient(user.Id, conn)
channel.RegisterClient(channelName, user.Id, conn)
return
}
+108
View File
@@ -0,0 +1,108 @@
package model
import (
"errors"
)
const (
TypeEmail = "email"
TypeWeChatTestAccount = "test"
TypeWeChatCorpAccount = "corp_app"
TypeCorp = "corp"
TypeLark = "lark"
TypeDing = "ding"
TypeTelegram = "telegram"
TypeDiscord = "discord"
TypeBark = "bark"
TypeClient = "client"
TypeNone = "none"
)
type Channel struct {
Id int `json:"id"`
Type string `json:"type" gorm:"type:varchar(32)"`
UserId int `json:"user_id" gorm:"uniqueIndex:name_user_id"`
Name string `json:"name" gorm:"type:varchar(32);uniqueIndex:name_user_id"`
Description string `json:"description"`
Status int `json:"status" gorm:"default:1"` // enabled, disabled
Secret string `json:"secret"`
AppId string `json:"app_id"`
AccountId string `json:"account_id"`
URL string `json:"url" gorm:"column:url"`
Other string `json:"other"`
CreatedTime int64 `json:"created_time" gorm:"bigint"`
}
func GetChannelById(id int, userId int) (*Channel, error) {
if id == 0 || userId == 0 {
return nil, errors.New("id 或 userId 为空!")
}
c := Channel{Id: id, UserId: userId}
err := DB.Where(c).First(&c).Error
return &c, err
}
func GetChannelByName(name string, userId int) (*Channel, error) {
if name == "" || userId == 0 {
return nil, errors.New("name 或 userId 为空!")
}
c := Channel{Name: name, UserId: userId}
err := DB.Where(c).First(&c).Error
return &c, err
}
func GetTokenStoreChannels() (channels []*Channel, err error) {
err = DB.Where("type = ? or type = ?", TypeWeChatCorpAccount, TypeWeChatTestAccount).Find(&channels).Error
return channels, err
}
func GetTokenStoreChannelsByUserId(userId int) (channels []*Channel, err error) {
err = DB.Where("user_id = ?", userId).Where("type = ? or type = ?", TypeWeChatCorpAccount, TypeWeChatTestAccount).Find(&channels).Error
return channels, err
}
func GetChannelsByUserId(userId int, startIdx int, num int) (channels []*Channel, err error) {
err = DB.Omit("secret").Where("user_id = ?", userId).Order("id desc").Limit(num).Offset(startIdx).Find(&channels).Error
return channels, err
}
func SearchChannels(userId int, keyword string) (channels []*Channel, err error) {
err = DB.Omit("secret").Where("user_id = ?", userId).Where("id = ? or name LIKE ?", keyword, keyword+"%").Find(&channels).Error
return channels, err
}
func DeleteChannelById(id int, userId int) (c *Channel, err error) {
// Why we need userId here? In case user want to delete other's c.
if id == 0 || userId == 0 {
return nil, errors.New("id 或 userId 为空!")
}
c = &Channel{Id: id, UserId: userId}
err = DB.Where(c).First(&c).Error
if err != nil {
return nil, err
}
return c, c.Delete()
}
func (channel *Channel) Insert() error {
var err error
err = DB.Create(channel).Error
return err
}
func (channel *Channel) UpdateStatus(status int) error {
err := DB.Model(channel).Update("status", status).Error
return err
}
// Update Make sure your token's fields is completed, because this will update non-zero values
func (channel *Channel) Update() error {
var err error
err = DB.Model(channel).Select("type", "name", "description", "secret", "app_id", "account_id", "url", "other", "status").Updates(channel).Error
return err
}
func (channel *Channel) Delete() error {
err := DB.Delete(channel).Error
return err
}
+4
View File
@@ -64,6 +64,10 @@ func InitDB() (err error) {
if err != nil {
return err
}
err = db.AutoMigrate(&Channel{})
if err != nil {
return err
}
err = createRootAccountIfNeed()
return err
} else {
+15 -44
View File
@@ -9,41 +9,20 @@ import (
// User if you add sensitive fields, don't forget to clean them in setupLogin function.
// Otherwise, the sensitive information will be saved on local storage in plain text!
type User struct {
Id int `json:"id"`
Username string `json:"username" gorm:"unique;index" validate:"max=12"`
Password string `json:"password" gorm:"not null;" validate:"min=8,max=20"`
DisplayName string `json:"display_name" gorm:"index" validate:"max=20"`
Role int `json:"role" gorm:"type:int;default:1"` // admin, common
Status int `json:"status" gorm:"type:int;default:1"` // enabled, disabled
Token string `json:"token"`
Email string `json:"email" gorm:"index" validate:"max=50"`
GitHubId string `json:"github_id" gorm:"column:github_id;index"`
WeChatId string `json:"wechat_id" gorm:"column:wechat_id;index"`
VerificationCode string `json:"verification_code" gorm:"-:all"` // this field is only for Email verification, don't save it to database!
Channel string `json:"channel"`
WeChatTestAccountId string `json:"wechat_test_account_id" gorm:"column:wechat_test_account_id"`
WeChatTestAccountSecret string `json:"wechat_test_account_secret" gorm:"column:wechat_test_account_secret"`
WeChatTestAccountTemplateId string `json:"wechat_test_account_template_id" gorm:"column:wechat_test_account_template_id"`
WeChatTestAccountOpenId string `json:"wechat_test_account_open_id" gorm:"column:wechat_test_account_open_id"`
WeChatTestAccountVerificationToken string `json:"wechat_test_account_verification_token" gorm:"column:wechat_test_account_verification_token"`
WeChatCorpAccountId string `json:"wechat_corp_account_id" gorm:"column:wechat_corp_account_id"`
WeChatCorpAccountAgentSecret string `json:"wechat_corp_account_agent_secret" gorm:"column:wechat_corp_account_agent_secret"`
WeChatCorpAccountAgentId string `json:"wechat_corp_account_agent_id" gorm:"column:wechat_corp_account_agent_id"`
WeChatCorpAccountUserId string `json:"wechat_corp_account_user_id" gorm:"column:wechat_corp_account_user_id"`
WeChatCorpAccountClientType string `json:"wechat_corp_account_client_type" gorm:"column:wechat_corp_account_client_type;default=plugin"`
CorpWebhookURL string `json:"corp_webhook_url" gorm:"corp_webhook_url"`
LarkWebhookURL string `json:"lark_webhook_url"`
LarkWebhookSecret string `json:"lark_webhook_secret"`
DingWebhookURL string `json:"ding_webhook_url"`
DingWebhookSecret string `json:"ding_webhook_secret"`
BarkServer string `json:"bark_server"`
BarkSecret string `json:"bark_secret"`
ClientSecret string `json:"client_secret"`
TelegramBotToken string `json:"telegram_bot_token"`
TelegramChatId string `json:"telegram_chat_id"`
DiscordWebhookURL string `json:"discord_webhook_url"`
SendEmailToOthers int `json:"send_email_to_others" gorm:"type:int;default:0"`
SaveMessageToDatabase int `json:"save_message_to_database" gorm:"type:int;default:0"`
Id int `json:"id"`
Username string `json:"username" gorm:"unique;index" validate:"max=12"`
Password string `json:"password" gorm:"not null;" validate:"min=8,max=20"`
DisplayName string `json:"display_name" gorm:"index" validate:"max=20"`
Role int `json:"role" gorm:"type:int;default:1"` // admin, common
Status int `json:"status" gorm:"type:int;default:1"` // enabled, disabled
Token string `json:"token"`
Email string `json:"email" gorm:"index" validate:"max=50"`
GitHubId string `json:"github_id" gorm:"column:github_id;index"`
WeChatId string `json:"wechat_id" gorm:"column:wechat_id;index"`
VerificationCode string `json:"verification_code" gorm:"-:all"` // this field is only for Email verification, don't save it to database!
Channel string `json:"channel"`
SendEmailToOthers int `json:"send_email_to_others" gorm:"type:int;default:0"`
SaveMessageToDatabase int `json:"save_message_to_database" gorm:"type:int;default:0"`
}
func GetMaxUserId() int {
@@ -57,11 +36,6 @@ func GetAllUsers(startIdx int, num int) (users []*User, err error) {
return users, err
}
func GetAllUsersWithSecrets() (users []*User, err error) {
err = DB.Where("status = ?", common.UserStatusEnabled).Where("wechat_test_account_id != '' or wechat_corp_account_id != ''").Find(&users).Error
return users, err
}
func SearchUsers(keyword string) (users []*User, err error) {
err = DB.Select([]string{"id", "username", "display_name", "role", "status", "email"}).Where("id = ? or username LIKE ? or email LIKE ? or display_name LIKE ?", keyword, keyword+"%", keyword+"%", keyword+"%").Find(&users).Error
return users, err
@@ -77,10 +51,7 @@ func GetUserById(id int, selectAll bool) (*User, error) {
err = DB.First(&user, "id = ?", id).Error
} else {
err = DB.Select([]string{"id", "username", "display_name", "role", "status", "email", "wechat_id", "github_id",
"channel", "token",
"wechat_test_account_id", "wechat_test_account_template_id", "wechat_test_account_open_id",
"wechat_corp_account_id", "wechat_corp_account_agent_id", "wechat_corp_account_user_id", "wechat_corp_account_client_type",
"bark_server", "telegram_chat_id", "save_message_to_database",
"channel", "token", "save_message_to_database",
}).First(&user, "id = ?", id).Error
}
return &user, err
+10
View File
@@ -64,6 +64,16 @@ func SetApiRouter(router *gin.Engine) {
messageRoute.DELETE("/", middleware.RootAuth(), controller.DeleteAllMessages)
messageRoute.DELETE("/:id", middleware.UserAuth(), controller.DeleteMessage)
}
channelRoute := apiRouter.Group("/channel")
channelRoute.Use(middleware.UserAuth())
{
channelRoute.GET("/", controller.GetAllChannels)
channelRoute.GET("/search", controller.SearchChannels)
channelRoute.GET("/:id", controller.GetChannel)
channelRoute.POST("/", controller.AddChannel)
channelRoute.PUT("/", controller.UpdateChannel)
channelRoute.DELETE("/:id", controller.DeleteChannel)
}
}
pushRouter := router.Group("/push")
pushRouter.Use(middleware.GlobalAPIRateLimit())
+26
View File
@@ -16,6 +16,8 @@ import PasswordResetConfirm from './components/PasswordResetConfirm';
import { UserContext } from './context/User';
import { StatusContext } from './context/Status';
import Message from './pages/Message';
import Channel from './pages/Channel';
import EditChannel from './pages/Channel/EditChannel';
const Home = lazy(() => import('./pages/Home'));
const About = lazy(() => import('./pages/About'));
@@ -107,6 +109,30 @@ function App() {
</Suspense>
}
/>
<Route
path='/channel'
element={
<PrivateRoute>
<Channel />
</PrivateRoute>
}
/>
<Route
path='/channel/edit/:id'
element={
<Suspense fallback={<Loading></Loading>}>
<EditChannel />
</Suspense>
}
/>
<Route
path='/channel/add'
element={
<Suspense fallback={<Loading></Loading>}>
<EditChannel />
</Suspense>
}
/>
<Route
path='/message'
element={
+333
View File
@@ -0,0 +1,333 @@
import React, { useEffect, useState } from 'react';
import { Button, Form, Label, Pagination, Table } from 'semantic-ui-react';
import { Link } from 'react-router-dom';
import { API, showError, showSuccess } from '../helpers';
import { ITEMS_PER_PAGE } from '../constants';
import { renderChannel, renderTimestamp } from '../helpers/render';
const ChannelsTable = () => {
const [channels, setChannels] = useState([]);
const [loading, setLoading] = useState(true);
const [activePage, setActivePage] = useState(1);
const [searchKeyword, setSearchKeyword] = useState('');
const [searching, setSearching] = useState(false);
const [user, setUser] = useState({ username: '', token: '' });
const loadChannels = async (startIdx) => {
const res = await API.get(`/api/channel/?p=${startIdx}`);
const { success, message, data } = res.data;
if (success) {
if (startIdx === 0) {
setChannels(data);
} else {
let newChannels = channels;
newChannels.push(...data);
setChannels(newChannels);
}
} else {
showError(message);
}
setLoading(false);
};
const onPaginationChange = (e, { activePage }) => {
(async () => {
if (activePage === Math.ceil(channels.length / ITEMS_PER_PAGE) + 1) {
// In this case we have to load more data and then append them.
await loadChannels(activePage - 1);
}
setActivePage(activePage);
})();
};
useEffect(() => {
loadChannels(0)
.then()
.catch((reason) => {
showError(reason);
});
loadUser()
.then()
.catch((reason) => {
showError(reason);
});
}, []);
const manageChannel = async (id, action, idx) => {
let data = { id };
let res;
switch (action) {
case 'delete':
res = await API.delete(`/api/channel/${id}/`);
break;
case 'enable':
data.status = 1;
res = await API.put('/api/channel/?status_only=true', data);
break;
case 'disable':
data.status = 2;
res = await API.put('/api/channel/?status_only=true', data);
break;
}
const { success, message } = res.data;
if (success) {
showSuccess('操作成功完成!');
let channel = res.data.data;
let newChannels = [...channels];
let realIdx = (activePage - 1) * ITEMS_PER_PAGE + idx;
if (action === 'delete') {
newChannels[realIdx].deleted = true;
} else {
newChannels[realIdx].status = channel.status;
}
setChannels(newChannels);
} else {
showError(message);
}
};
const renderStatus = (status) => {
switch (status) {
case 1:
return <Label basic>已启用</Label>;
case 2:
return (
<Label basic color='red'>
已禁用
</Label>
);
default:
return (
<Label basic color='grey'>
未知状态
</Label>
);
}
};
const searchChannels = async () => {
if (searchKeyword === '') {
// if keyword is blank, load files instead.
await loadChannels(0);
setActivePage(1);
return;
}
setSearching(true);
const res = await API.get(`/api/channel/search?keyword=${searchKeyword}`);
const { success, message, data } = res.data;
if (success) {
setChannels(data);
setActivePage(1);
} else {
showError(message);
}
setSearching(false);
};
const handleKeywordChange = async (e, { value }) => {
setSearchKeyword(value.trim());
};
const sortChannel = (key) => {
if (channels.length === 0) return;
setLoading(true);
let sortedChannels = [...channels];
sortedChannels.sort((a, b) => {
return ('' + a[key]).localeCompare(b[key]);
});
if (sortedChannels[0].id === channels[0].id) {
sortedChannels.reverse();
}
setChannels(sortedChannels);
setLoading(false);
};
const loadUser = async () => {
let res = await API.get(`/api/user/self`);
const { success, message, data } = res.data;
if (success) {
setUser(data);
} else {
showError(message);
}
setLoading(false);
};
const test = async (channel) => {
let res = await API.get(
`/push/${user.username}?token=${user.token}&channel=${channel}&title=消息推送服务&description=配置成功!`
);
const { success, message } = res.data;
if (success) {
showSuccess('测试消息已发送');
} else {
showError(message);
}
};
return (
<>
<Form onSubmit={searchChannels}>
<Form.Input
icon='search'
fluid
iconPosition='left'
placeholder='搜索通道的 ID 或名称 ...'
value={searchKeyword}
loading={searching}
onChange={handleKeywordChange}
/>
</Form>
<Table basic>
<Table.Header>
<Table.Row>
<Table.HeaderCell
style={{ cursor: 'pointer' }}
onClick={() => {
sortChannel('id');
}}
>
ID
</Table.HeaderCell>
<Table.HeaderCell
style={{ cursor: 'pointer' }}
onClick={() => {
sortChannel('name');
}}
>
名称
</Table.HeaderCell>
<Table.HeaderCell
style={{ cursor: 'pointer' }}
onClick={() => {
sortChannel('description');
}}
>
备注
</Table.HeaderCell>
<Table.HeaderCell
style={{ cursor: 'pointer' }}
onClick={() => {
sortChannel('type');
}}
>
类型
</Table.HeaderCell>
<Table.HeaderCell
style={{ cursor: 'pointer' }}
onClick={() => {
sortChannel('status');
}}
>
状态
</Table.HeaderCell>
<Table.HeaderCell
style={{ cursor: 'pointer' }}
onClick={() => {
sortChannel('created_time');
}}
>
创建时间
</Table.HeaderCell>
<Table.HeaderCell>操作</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{channels
.slice(
(activePage - 1) * ITEMS_PER_PAGE,
activePage * ITEMS_PER_PAGE
)
.map((channel, idx) => {
if (channel.deleted) return <></>;
return (
<Table.Row key={channel.id}>
<Table.Cell>{channel.id}</Table.Cell>
<Table.Cell>{channel.name}</Table.Cell>
<Table.Cell>
{channel.description ? channel.description : '无备注信息'}
</Table.Cell>
<Table.Cell>{renderChannel(channel.type)}</Table.Cell>
<Table.Cell>{renderStatus(channel.status)}</Table.Cell>
<Table.Cell>
{renderTimestamp(channel.created_time)}
</Table.Cell>
<Table.Cell>
<div>
<Button
size={'small'}
negative
onClick={() => {
manageChannel(channel.id, 'delete', idx).then();
}}
>
删除
</Button>
<Button
size={'small'}
onClick={() => {
test(channel.name).then();
}}
>
测试
</Button>
<Button
size={'small'}
onClick={() => {
manageChannel(
channel.id,
channel.status === 1 ? 'disable' : 'enable',
idx
).then();
}}
>
{channel.status === 1 ? '禁用' : '启用'}
</Button>
<Button
size={'small'}
as={Link}
to={'/channel/edit/' + channel.id}
>
编辑
</Button>
</div>
</Table.Cell>
</Table.Row>
);
})}
</Table.Body>
<Table.Footer>
<Table.Row>
<Table.HeaderCell colSpan='7'>
<Button
size='small'
as={Link}
to='/channel/add'
loading={loading}
>
添加新的通道
</Button>
<Pagination
floated='right'
activePage={activePage}
onPageChange={onPaginationChange}
size='small'
siblingRange={1}
totalPages={
Math.ceil(channels.length / ITEMS_PER_PAGE) +
(channels.length % ITEMS_PER_PAGE === 0 ? 1 : 0)
}
/>
</Table.HeaderCell>
</Table.Row>
</Table.Footer>
</Table>
</>
);
};
export default ChannelsTable;
+5
View File
@@ -18,6 +18,11 @@ const headerButtons = [
to: '/message',
icon: 'mail',
},
{
name: '通道',
to: '/channel',
icon: 'sitemap',
},
{
name: '用户',
to: '/user',
+51 -102
View File
@@ -1,81 +1,16 @@
import React, { useEffect, useRef, useState } from 'react';
import { Button, Form, Label, Modal, Pagination, Table } from 'semantic-ui-react';
import { API, openPage, showError, showSuccess, showWarning, timestamp2string } from '../helpers';
import {
Button,
Form,
Label,
Modal,
Pagination,
Table,
} from 'semantic-ui-react';
import { API, openPage, showError, showSuccess, showWarning } from '../helpers';
import { ITEMS_PER_PAGE } from '../constants';
function renderChannel(channel) {
switch (channel) {
case 'email':
return <Label color='green'>邮件</Label>;
case 'test':
return (
<Label style={{ backgroundColor: '#2cbb00', color: 'white' }}>
微信测试号
</Label>
);
case 'corp_app':
return (
<Label style={{ backgroundColor: '#5fc9ec', color: 'white' }}>
企业微信应用号
</Label>
);
case 'corp':
return (
<Label style={{ backgroundColor: '#019d82', color: 'white' }}>
企业微信群机器人
</Label>
);
case 'lark':
return (
<Label style={{ backgroundColor: '#00d6b9', color: 'white' }}>
飞书群机器人
</Label>
);
case 'ding':
return (
<Label style={{ backgroundColor: '#007fff', color: 'white' }}>
钉钉群机器人
</Label>
);
case 'bark':
return (
<Label style={{ backgroundColor: '#ff3b30', color: 'white' }}>
Bark App
</Label>
);
case 'client':
return (
<Label style={{ backgroundColor: '#121212', color: 'white' }}>
WebSocket 客户端
</Label>
);
case 'telegram':
return (
<Label style={{ backgroundColor: '#29a9ea', color: 'white' }}>
Telegram 机器人
</Label>
);
case 'discord':
return (
<Label style={{ backgroundColor: '#404eed', color: 'white' }}>
Discord 群机器人
</Label>
);
case 'none':
return <Label></Label>;
default:
return <Label color='grey'>未知通道</Label>;
}
}
function renderTimestamp(timestamp) {
return (
<>
{timestamp2string(timestamp)}
</>
);
}
import { renderChannel, renderTimestamp } from '../helpers/render';
function renderStatus(status) {
switch (status) {
@@ -119,8 +54,8 @@ const MessagesTable = () => {
title: '消息标题',
description: '消息描述',
content: '消息内容',
link: ''
}); // Message to be viewed
link: '',
}); // Message to be viewed
const [viewModalOpen, setViewModalOpen] = useState(false);
const loadMessages = async (startIdx) => {
@@ -277,7 +212,7 @@ const MessagesTable = () => {
autoRefreshSecondsRef.current = 10;
} else {
autoRefreshSecondsRef.current -= 1;
setAutoRefreshSeconds(autoRefreshSeconds => autoRefreshSeconds - 1); // Important!
setAutoRefreshSeconds((autoRefreshSeconds) => autoRefreshSeconds - 1); // Important!
}
}, 1000);
}
@@ -285,7 +220,6 @@ const MessagesTable = () => {
return () => clearInterval(intervalId);
}, [autoRefresh]);
return (
<>
<Form onSubmit={searchMessages}>
@@ -405,16 +339,26 @@ const MessagesTable = () => {
<Table.Footer>
<Table.Row>
<Table.HeaderCell colSpan='6'>
<Button size='small' loading={loading} onClick={() => {
refresh().then();
}}>
<Button
size='small'
loading={loading}
onClick={() => {
refresh().then();
}}
>
手动刷新
</Button>
<Button size='small' loading={loading} onClick={() => {
setAutoRefresh(!autoRefresh);
setAutoRefreshSeconds(10);
}}>
{autoRefresh ? `自动刷新中(${autoRefreshSeconds} 秒后刷新)` : '自动刷新'}
<Button
size='small'
loading={loading}
onClick={() => {
setAutoRefresh(!autoRefresh);
setAutoRefreshSeconds(10);
}}
>
{autoRefresh
? `自动刷新中(${autoRefreshSeconds} 秒后刷新)`
: '自动刷新'}
</Button>
<Pagination
floated='right'
@@ -431,28 +375,33 @@ const MessagesTable = () => {
</Table.Row>
</Table.Footer>
</Table>
<Modal
size='tiny'
open={viewModalOpen}
>
<Modal size='tiny' open={viewModalOpen}>
<Modal.Header>{message.title ? message.title : '无标题'}</Modal.Header>
<Modal.Content>
{message.description ? <p className={'quote'}>{message.description}</p> : ''}
{message.description ? (
<p className={'quote'}>{message.description}</p>
) : (
''
)}
{message.content ? <p>{message.content}</p> : ''}
</Modal.Content>
<Modal.Actions>
<Button onClick={() => {
if (message.URL) {
openPage(message.URL);
} else {
openPage(`/message/${message.link}`);
}
}}>
<Button
onClick={() => {
if (message.URL) {
openPage(message.URL);
} else {
openPage(`/message/${message.link}`);
}
}}
>
打开
</Button>
<Button onClick={() => {
setViewModalOpen(false);
}}>
<Button
onClick={() => {
setViewModalOpen(false);
}}
>
关闭
</Button>
</Modal.Actions>
+38
View File
@@ -0,0 +1,38 @@
export const CHANNEL_OPTIONS = [
{ key: 'email', text: '邮件', value: 'email', color: '#4285f4' },
{ key: 'test', text: '微信测试号', value: 'test', color: '#2cbb00' },
{
key: 'corp_app',
text: '企业微信应用号',
value: 'corp_app',
color: '#5fc9ec',
},
{ key: 'corp', text: '企业微信群机器人', value: 'corp', color: '#019d82' },
{ key: 'lark', text: '飞书群机器人', value: 'lark', color: '#00d6b9' },
{ key: 'ding', text: '钉钉群机器人', value: 'ding', color: '#007fff' },
{ key: 'bark', text: 'Bark App', value: 'bark', color: '#ff3b30' },
{
key: 'client',
text: 'WebSocket 客户端',
value: 'client',
color: '#121212',
},
{
key: 'telegram',
text: 'Telegram 机器人',
value: 'telegram',
color: '#29a9ea',
},
{
key: 'discord',
text: 'Discord 群机器人',
value: 'discord',
color: '#404eed',
},
{
key: 'none',
text: '不推送',
value: 'none',
color: '#808080',
},
];
+2 -1
View File
@@ -1,3 +1,4 @@
export * from './toast.constants';
export * from './user.constants';
export * from './common.constant';
export * from './common.constant';
export * from './channel.constants';
+32
View File
@@ -0,0 +1,32 @@
import { Label } from 'semantic-ui-react';
import { timestamp2string } from './utils';
import React from 'react';
import { CHANNEL_OPTIONS } from '../constants';
let channelMap = undefined;
export function renderChannel(key) {
if (channelMap === undefined) {
channelMap = new Map();
CHANNEL_OPTIONS.forEach((option) => {
channelMap[option.key] = option;
});
}
let channel = channelMap[key];
if (channel) {
return (
<Label basic style={{ backgroundColor: channel.color, color: 'white' }}>
{channel.text}
</Label>
);
}
return (
<Label basic color='red'>
未知通道
</Label>
);
}
export function renderTimestamp(timestamp) {
return <>{timestamp2string(timestamp)}</>;
}
+520
View File
@@ -0,0 +1,520 @@
import React, { useEffect, useState } from 'react';
import { Button, Form, Header, Message, Segment } from 'semantic-ui-react';
import { useParams } from 'react-router-dom';
import { API, showError, showSuccess } from '../../helpers';
import { CHANNEL_OPTIONS } from '../../constants';
import axios from 'axios';
const EditChannel = () => {
const params = useParams();
const channelId = params.id;
const isEditing = channelId !== undefined;
const [loading, setLoading] = useState(isEditing);
const originInputs = {
type: 'none',
name: '',
description: '',
secret: '',
app_id: '',
account_id: '',
url: '',
other: '',
corp_id: '', // only for corp_app
agent_id: '', // only for corp_app
};
const [inputs, setInputs] = useState(originInputs);
const { type, name, description, secret, app_id, account_id, url, other } =
inputs;
const handleInputChange = (e, { name, value }) => {
setInputs((inputs) => ({ ...inputs, [name]: value }));
};
const loadChannel = async () => {
let res = await API.get(`/api/channel/${channelId}`);
const { success, message, data } = res.data;
if (success) {
if (data.type === 'corp_app') {
const [corp_id, agent_id] = data.app_id.split('|');
data.corp_id = corp_id;
data.agent_id = agent_id;
}
setInputs(data);
} else {
showError(message);
}
setLoading(false);
};
useEffect(() => {
if (isEditing) {
loadChannel().then();
}
}, []);
const submit = async () => {
if (!name) return;
let res = undefined;
let localInputs = { ...inputs };
switch (inputs.type) {
case 'corp_app':
localInputs.app_id = `${inputs.corp_id}|${inputs.agent_id}`;
break;
case 'bark':
localInputs.url = 'https://api.day.app';
}
if (isEditing) {
res = await API.put(`/api/channel/`, {
...localInputs,
id: parseInt(channelId),
});
} else {
res = await API.post(`/api/channel`, localInputs);
}
const { success, message } = res.data;
if (success) {
if (isEditing) {
showSuccess('通道信息更新成功!');
} else {
showSuccess('通道创建成功!');
setInputs(originInputs);
}
} else {
showError(message);
}
};
const getTelegramChatId = async () => {
if (inputs.telegram_bot_token === '') {
showError('请先输入 Telegram 机器人令牌!');
return;
}
let res = await axios.get(
`https://api.telegram.org/bot${inputs.secret}/getUpdates`
);
const { ok } = res.data;
if (ok) {
let result = res.data.result;
if (result.length === 0) {
showError(`请先向你的机器人发送一条任意消息!`);
} else {
let id = result[0]?.message?.chat?.id;
id = id.toString();
setInputs((inputs) => ({ ...inputs, account_id: id }));
showSuccess('会话 ID 获取成功!');
}
} else {
showError(`发生错误:${res.description}`);
}
};
const renderChannelForm = () => {
switch (type) {
case 'email':
return (
<>
<Message>
邮件推送方式email需要设置邮箱请前往个人设置页面绑定邮箱地址之后系统将自动为你创建邮箱推送通道
</Message>
</>
);
case 'test':
return (
<>
<Message>
通过微信测试号进行推送点击前往配置
<a
target='_blank'
href='https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index'
>
微信公众平台接口测试帐号
</a>
<br />
<br />
需要新增测试模板模板标题推荐填写为消息推送模板内容必须填写为
{' {{'}text.DATA{'}}'}
</Message>
<Form.Group widths={3}>
<Form.Input
label='测试号 ID'
name='app_id'
onChange={handleInputChange}
autoComplete='new-password'
value={inputs.app_id}
placeholder='测试号信息 -> appID'
/>
<Form.Input
label='测试号密钥'
name='secret'
type='password'
onChange={handleInputChange}
autoComplete='new-password'
value={inputs.secret}
placeholder='测试号信息 -> appsecret'
/>
<Form.Input
label='测试模板 ID'
name='other'
onChange={handleInputChange}
autoComplete='new-password'
value={inputs.other}
placeholder='模板消息接口 -> 模板 ID'
/>
</Form.Group>
<Form.Group widths={3}>
<Form.Input
label='用户 Open ID'
name='account_id'
onChange={handleInputChange}
autoComplete='new-password'
value={inputs.account_id}
placeholder='扫描测试号二维码 -> 用户列表 -> 微信号'
/>
</Form.Group>
</>
);
case 'corp_app':
return (
<>
<Message>
通过企业微信应用号进行推送点击前往配置
<a
target='_blank'
href='https://work.weixin.qq.com/wework_admin/frame#apps'
>
企业微信应用管理
</a>
<br />
<br />
注意企业微信要求配置可信 IP步骤应用管理 -> 自建 -> 创建应用
-> 应用设置页面下拉中找到企业可信 IP点击配置 -> 设置可信域名
-> 可调用
JS-SDK跳转小程序的可信域名下面填写一个域名然后点击申请校验域名根据提示完成校验
-> 之后填写服务器 IP 地址 IP
地址是消息推送服务所部署在的服务器的 IP
地址未必是上面校验域名中记录的 IP 地址
</Message>
<Form.Group widths={3}>
<Form.Input
label='企业 ID'
name='corp_id'
onChange={handleInputChange}
autoComplete='new-password'
value={inputs.corp_id}
placeholder='我的企业 -> 企业信息 -> 企业 ID'
/>
<Form.Input
label='应用 AgentId'
name='agent_id'
onChange={handleInputChange}
autoComplete='new-password'
value={inputs.agent_id}
placeholder='应用管理 -> 自建 -> 创建应用 -> AgentId'
/>
<Form.Input
label='应用 Secret'
name='secret'
type='password'
onChange={handleInputChange}
autoComplete='new-password'
value={inputs.secret}
placeholder='应用管理 -> 自建 -> 创建应用 -> Secret'
/>
</Form.Group>
<Form.Group widths={3}>
<Form.Input
label='用户账号'
name='account_id'
onChange={handleInputChange}
autoComplete='new-password'
value={inputs.account_id}
placeholder='通讯录 -> 点击姓名 -> 账号'
/>
<Form.Select
label='微信企业号客户端类型'
name='other'
options={[
{
key: 'plugin',
text: '微信中的企业微信插件',
value: 'plugin',
},
{ key: 'app', text: '企业微信 APP', value: 'app' },
]}
value={inputs.other}
onChange={handleInputChange}
/>
</Form.Group>
</>
);
case 'corp':
return (
<>
<Message>
通过企业微信群机器人进行推送配置流程选择一个群聊 -> 设置 ->
群机器人 -> 添加 -> 新建 -> 输入名字点击添加 -> 点击复制 Webhook
地址
</Message>
<Form.Group widths={2}>
<Form.Input
label='Webhook 地址'
name='url'
onChange={handleInputChange}
autoComplete='new-password'
value={inputs.url}
placeholder='在此填写企业微信提供的 Webhook 地址'
/>
</Form.Group>
</>
);
case 'lark':
return (
<>
<Message>
通过飞书群机器人进行推送飞书桌面客户端的配置流程选择一个群聊
-> 设置 -> 群机器人 -> 添加机器人 -> 自定义机器人 -> 添加
<strong>注意选中签名校验</strong>
<a
target='_blank'
href='https://open.feishu.cn/document/ukTMukTMukTM/ucTM5YjL3ETO24yNxkjN'
>
飞书开放文档
</a>
</Message>
<Form.Group widths={2}>
<Form.Input
label='Webhook 地址'
name='url'
onChange={handleInputChange}
autoComplete='new-password'
value={inputs.url}
placeholder='在此填写飞书提供的 Webhook 地址'
/>
<Form.Input
label='签名校验密钥'
name='secret'
type='password'
onChange={handleInputChange}
autoComplete='new-password'
value={inputs.secret}
placeholder='在此填写飞书提供的签名校验密钥'
/>
</Form.Group>
</>
);
case 'ding':
return (
<>
<Message>
通过钉钉群机器人进行推送钉钉桌面客户端的配置流程选择一个群聊
-> 群设置 -> 智能群助手 -> 添加机器人点击右侧齿轮图标 ->
自定义 -> 添加
<strong>注意选中加密</strong>
<a
target='_blank'
href='https://open.dingtalk.com/document/robots/custom-robot-access'
>
钉钉开放文档
</a>
</Message>
<Form.Group widths={2}>
<Form.Input
label='Webhook 地址'
name='url'
onChange={handleInputChange}
autoComplete='new-password'
value={inputs.url}
placeholder='在此填写钉钉提供的 Webhook 地址'
/>
<Form.Input
label='签名校验密钥'
name='secret'
type='password'
onChange={handleInputChange}
autoComplete='new-password'
value={inputs.secret}
placeholder='在此填写钉钉提供的签名校验密钥'
/>
</Form.Group>
</>
);
case 'bark':
return (
<>
<Message>
通过 Bark 进行推送下载 Bark 后按提示注册设备之后会看到一个
URL例如 <code>https://api.day.app/wrsVSDRANDOM/Body Text</code>
其中 <code>wrsVSDRANDOM</code> key
</Message>
<Form.Group widths={2}>
<Form.Input
label='服务器地址'
name='url'
onChange={handleInputChange}
autoComplete='new-password'
value={inputs.url}
placeholder='在此填写 Bark 服务器地址,不填则使用默认值'
/>
<Form.Input
label='推送 key'
name='secret'
type='password'
onChange={handleInputChange}
autoComplete='new-password'
value={inputs.secret}
placeholder='在此填写 Bark 推送 key'
/>
</Form.Group>
</>
);
case 'client':
return (
<>
<Message>
通过 WebSocket
客户端进行推送可以使用官方客户端实现或者根据协议自行实现官方客户端
<a
target='_blank'
href='https://github.com/songquanpeng/personal-assistant'
>
详见此处
</a>
</Message>
<Form.Group widths={2}>
<Form.Input
label='客户端连接密钥'
name='secret'
type='password'
onChange={handleInputChange}
autoComplete='new-password'
value={inputs.secret}
placeholder='在此设置客户端连接密钥'
/>
</Form.Group>
</>
);
case 'telegram':
return (
<>
<Message>
通过 Telegram 机器人进行消息推送首先向
<a href='https://t.me/botfather' target='_blank'>
{' '}
Bot Father{' '}
</a>
申请创建一个新的机器人之后在下方输入获取到的令牌然后点击你的机器人随便发送一条消息之后点击下方的获取会话
ID按钮系统将自动为你填写会话
ID最后点击保存按钮保存设置即可
</Message>
<Form.Group widths={2}>
<Form.Input
label='Telegram 机器人令牌'
name='secret'
type='password'
onChange={handleInputChange}
autoComplete='new-password'
value={inputs.secret}
placeholder='在此设置 Telegram 机器人令牌'
/>
<Form.Input
label='Telegram 会话 ID'
name='account_id'
type='text'
onChange={handleInputChange}
autoComplete='new-password'
value={inputs.account_id}
placeholder='在此设置 Telegram 会话 ID'
/>
</Form.Group>
<Button onClick={getTelegramChatId} loading={loading}>
获取会话 ID
</Button>
</>
);
case 'discord':
return (
<>
<Message>
通过 Discord 群机器人进行推送配置流程选择一个 channel -> 设置
-> 整合 -> 创建 Webhook -> 点击复制 Webhook URL
</Message>
<Form.Group widths={2}>
<Form.Input
label='Webhook 地址'
name='url'
onChange={handleInputChange}
autoComplete='new-password'
value={inputs.url}
placeholder='在此填写 Discord 提供的 Webhook 地址'
/>
</Form.Group>
</>
);
case 'none':
return (
<>
<Message>
仅保存消息不做推送可以在 Web
端查看需要用户具有消息持久化的权限
</Message>
</>
);
default:
return (
<>
<Message>未知通道类型</Message>
</>
);
}
};
return (
<>
<Segment loading={loading}>
<Header as='h3'>{isEditing ? '更新通道配置' : '新建消息通道'}</Header>
<Form autoComplete='new-password'>
<Form.Field>
<Form.Input
label='名称'
name='name'
placeholder={
'请输入通道名称,请仅使用英文字母和下划线,该名称必须唯一'
}
onChange={handleInputChange}
value={name}
autoComplete='new-password'
required
/>
</Form.Field>
<Form.Field>
<Form.Input
label='备注'
name='description'
type={'text'}
placeholder={'请输入备注信息'}
onChange={handleInputChange}
value={description}
autoComplete='new-password'
/>
</Form.Field>
<Form.Select
label='通道类型'
name='type'
options={CHANNEL_OPTIONS}
value={type}
onChange={handleInputChange}
/>
{renderChannelForm()}
<Button disabled={type === 'email'} onClick={submit}>
提交
</Button>
</Form>
</Segment>
</>
);
};
export default EditChannel;
+14
View File
@@ -0,0 +1,14 @@
import React from 'react';
import { Header, Segment } from 'semantic-ui-react';
import ChannelsTable from '../../components/ChannelsTable';
const Channel = () => (
<>
<Segment>
<Header as='h3'>我的通道</Header>
<ChannelsTable />
</Segment>
</>
);
export default Channel;
+11 -11
View File
@@ -30,38 +30,38 @@ const AddUser = () => {
return (
<>
<Segment>
<Header as="h3">创建新用户账户</Header>
<Form autoComplete="off">
<Header as='h3'>创建新用户账户</Header>
<Form autoComplete='new-password'>
<Form.Field>
<Form.Input
label="用户名"
name="username"
label='用户名'
name='username'
placeholder={'请输入用户名'}
onChange={handleInputChange}
value={username}
autoComplete="off"
autoComplete='new-password'
required
/>
</Form.Field>
<Form.Field>
<Form.Input
label="显示名称"
name="display_name"
label='显示名称'
name='display_name'
placeholder={'请输入显示名称'}
onChange={handleInputChange}
value={display_name}
autoComplete="off"
autoComplete='new-password'
/>
</Form.Field>
<Form.Field>
<Form.Input
label="密码"
name="password"
label='密码'
name='password'
type={'password'}
placeholder={'请输入密码'}
onChange={handleInputChange}
value={password}
autoComplete="off"
autoComplete='new-password'
required
/>
</Form.Field>