feat(im): support Yunzhijia image messages
This commit is contained in:
@@ -7,8 +7,12 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
@@ -27,17 +31,31 @@ const markdownFormatType = "markdown"
|
||||
|
||||
// Compile-time check.
|
||||
var _ im.Adapter = (*Adapter)(nil)
|
||||
var _ im.FileDownloader = (*Adapter)(nil)
|
||||
|
||||
var yunzhijiaAuthURL = "https://yunzhijia.com/api/oauth2_v12/auth/getAppAccessToken"
|
||||
var yunzhijiaDownloadFileBaseURL = "https://yunzhijia.com/gateway/docrest/doc/file/downloadfileOpen"
|
||||
|
||||
var validateDownloadFileURL = func(rawURL string) error {
|
||||
_, err := validateEndpointURL(rawURL, "https", "yunzhijia.com")
|
||||
return err
|
||||
}
|
||||
|
||||
// Adapter implements im.Adapter for Yunzhijia (云之家).
|
||||
type Adapter struct {
|
||||
sendMsgURL string
|
||||
secret string
|
||||
appID string
|
||||
appSecret string
|
||||
httpClient *http.Client
|
||||
allowedWebhookHostSuffix string
|
||||
tokenMu sync.Mutex
|
||||
accessToken string
|
||||
accessTokenExpiresAt time.Time
|
||||
}
|
||||
|
||||
// NewAdapter creates a Yunzhijia adapter.
|
||||
func NewAdapter(sendMsgURL, secret string, timeoutSeconds int, allowedHostSuffix string) *Adapter {
|
||||
func NewAdapter(sendMsgURL, secret, appID, appSecret string, timeoutSeconds int, allowedHostSuffix string) *Adapter {
|
||||
if timeoutSeconds <= 0 {
|
||||
timeoutSeconds = 10
|
||||
}
|
||||
@@ -46,7 +64,9 @@ func NewAdapter(sendMsgURL, secret string, timeoutSeconds int, allowedHostSuffix
|
||||
transport.DialContext = safeDialContext
|
||||
return &Adapter{
|
||||
sendMsgURL: strings.TrimSpace(sendMsgURL),
|
||||
secret: secret,
|
||||
secret: strings.TrimSpace(secret),
|
||||
appID: strings.TrimSpace(appID),
|
||||
appSecret: strings.TrimSpace(appSecret),
|
||||
allowedWebhookHostSuffix: strings.TrimSpace(allowedHostSuffix),
|
||||
httpClient: &http.Client{
|
||||
Timeout: time.Duration(timeoutSeconds) * time.Second,
|
||||
@@ -128,8 +148,14 @@ func toIncomingMessage(ctx context.Context, msg *callbackMessage) *im.IncomingMe
|
||||
return nil
|
||||
}
|
||||
|
||||
param, err := parseMessageParam(msg.MsgParam)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[Yunzhijia] Failed to parse msgParam: msgId=%s err=%v", msg.MsgID, err)
|
||||
}
|
||||
image, hasImage := param.firstImage()
|
||||
|
||||
content := strings.TrimSpace(msg.Content)
|
||||
if content == "" {
|
||||
if content == "" && !hasImage {
|
||||
logger.Infof(ctx,
|
||||
"[Yunzhijia] Skip empty content: msgId=%s", msg.MsgID)
|
||||
return nil
|
||||
@@ -138,25 +164,30 @@ func toIncomingMessage(ctx context.Context, msg *callbackMessage) *im.IncomingMe
|
||||
// Conversation bots should only receive messages explicitly addressed to them.
|
||||
var mentioned bool
|
||||
content, mentioned = cleanAtMention(content, msg.RobotName)
|
||||
if !mentioned {
|
||||
mentioned = messageParamMentionsRobot(param, msg.RobotID)
|
||||
}
|
||||
if !mentioned {
|
||||
logger.Infof(ctx, "[Yunzhijia] Skip message without robot mention: msgId=%s", msg.MsgID)
|
||||
return nil
|
||||
}
|
||||
|
||||
if content == "" {
|
||||
if content == "" && !hasImage {
|
||||
logger.Infof(ctx,
|
||||
"[Yunzhijia] Skip after cleaning @mention: msgId=%s", msg.MsgID)
|
||||
return nil
|
||||
}
|
||||
|
||||
userID := firstNonEmpty(msg.OperatorOpenid, msg.OperatorOID, msg.OpenID, msg.SenderID, msg.OperatorID, msg.OperatorUserID)
|
||||
userName := firstNonEmpty(msg.OperatorName, msg.SenderName)
|
||||
chatType := im.ChatTypeGroup
|
||||
chatID := msg.RobotID
|
||||
chatID := firstNonEmpty(msg.GroupID, msg.RobotID)
|
||||
|
||||
return &im.IncomingMessage{
|
||||
incoming := &im.IncomingMessage{
|
||||
Platform: im.PlatformYunzhijia,
|
||||
MessageType: im.MessageTypeText,
|
||||
UserID: msg.OperatorOpenid,
|
||||
UserName: msg.OperatorName,
|
||||
UserID: userID,
|
||||
UserName: userName,
|
||||
ChatID: chatID,
|
||||
ChatType: chatType,
|
||||
Content: content,
|
||||
@@ -164,11 +195,53 @@ func toIncomingMessage(ctx context.Context, msg *callbackMessage) *im.IncomingMe
|
||||
Extra: map[string]string{
|
||||
"robot_id": msg.RobotID,
|
||||
"robot_name": msg.RobotName,
|
||||
"group_id": msg.GroupID,
|
||||
"group_type": fmt.Sprintf("%d", msg.GroupType),
|
||||
"operator_name": msg.OperatorName,
|
||||
"operator_name": userName,
|
||||
"time": fmt.Sprintf("%d", msg.Time),
|
||||
},
|
||||
}
|
||||
if hasImage {
|
||||
incoming.MessageType = im.MessageTypeImage
|
||||
incoming.FileKey = image.Data
|
||||
incoming.FileName = defaultImageFileName(msg.MsgID)
|
||||
incoming.Extra["yunzhijia_image_width"] = fmt.Sprintf("%d", image.Width)
|
||||
incoming.Extra["yunzhijia_image_height"] = fmt.Sprintf("%d", image.Height)
|
||||
}
|
||||
return incoming
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
if trimmed := strings.TrimSpace(value); trimmed != "" {
|
||||
return trimmed
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func messageParamMentionsRobot(param *messageParam, robotID string) bool {
|
||||
if param == nil || robotID == "" {
|
||||
return false
|
||||
}
|
||||
for _, notifyTo := range param.NotifyTo {
|
||||
if notifyTo == robotID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, desc := range param.Desc {
|
||||
if desc.Type == "at" && desc.Data == robotID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func defaultImageFileName(msgID string) string {
|
||||
if msgID == "" {
|
||||
return "yunzhijia-image.png"
|
||||
}
|
||||
return msgID + ".png"
|
||||
}
|
||||
|
||||
// cleanAtMention removes @RobotName from the beginning of user content.
|
||||
@@ -262,6 +335,163 @@ func (a *Adapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, r
|
||||
return nil
|
||||
}
|
||||
|
||||
// DownloadFile downloads a file/image resource sent by Yunzhijia.
|
||||
func (a *Adapter) DownloadFile(ctx context.Context, msg *im.IncomingMessage) (io.ReadCloser, string, error) {
|
||||
if msg.FileKey == "" {
|
||||
return nil, "", fmt.Errorf("yunzhijia file id is required")
|
||||
}
|
||||
fileID := strings.TrimSpace(msg.FileKey)
|
||||
if err := validateFileID(fileID); err != nil {
|
||||
return nil, "", fmt.Errorf("invalid yunzhijia file id: %w", err)
|
||||
}
|
||||
|
||||
accessToken, err := a.getAppAccessToken(ctx)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
downloadURL := buildDownloadFileURL(fileID)
|
||||
if err := validateDownloadFileURL(downloadURL); err != nil {
|
||||
return nil, "", fmt.Errorf("download url rejected: %w", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, downloadURL, nil)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("create download request: %w", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
resp, err := a.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("download file: %w", err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
return nil, "", fmt.Errorf("download file returned %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
fileName := msg.FileName
|
||||
if fileName == "" {
|
||||
fileName = fileID
|
||||
}
|
||||
fileName = resolveDownloadFileName(fileName, resp)
|
||||
return resp.Body, fileName, nil
|
||||
}
|
||||
|
||||
func buildDownloadFileURL(fileID string) string {
|
||||
u, _ := url.Parse(yunzhijiaDownloadFileBaseURL)
|
||||
query := url.Values{}
|
||||
query.Set("fileId", fileID)
|
||||
u.RawQuery = query.Encode()
|
||||
return u.String()
|
||||
}
|
||||
|
||||
func validateFileID(fileID string) error {
|
||||
if fileID == "" {
|
||||
return fmt.Errorf("empty")
|
||||
}
|
||||
if len(fileID) > 256 {
|
||||
return fmt.Errorf("too long")
|
||||
}
|
||||
if strings.ContainsAny(fileID, `/\?#&`) {
|
||||
return fmt.Errorf("contains path or query separators")
|
||||
}
|
||||
for _, r := range fileID {
|
||||
if unicode.IsControl(r) || unicode.IsSpace(r) {
|
||||
return fmt.Errorf("contains whitespace or control character")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Adapter) getAppAccessToken(ctx context.Context) (string, error) {
|
||||
if a.appID == "" || a.appSecret == "" {
|
||||
return "", fmt.Errorf("yunzhijia app_id and app_secret are required to download files")
|
||||
}
|
||||
|
||||
a.tokenMu.Lock()
|
||||
if a.accessToken != "" && time.Now().Before(a.accessTokenExpiresAt) {
|
||||
token := a.accessToken
|
||||
a.tokenMu.Unlock()
|
||||
return token, nil
|
||||
}
|
||||
a.tokenMu.Unlock()
|
||||
|
||||
payload := map[string]any{
|
||||
"appId": a.appID,
|
||||
"secret": a.appSecret,
|
||||
"timestamp": time.Now().UnixMilli(),
|
||||
}
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("marshal yunzhijia token request: %w", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, yunzhijiaAuthURL, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("create yunzhijia token request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := a.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("request yunzhijia app access token: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
respBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read yunzhijia token response: %w", err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("yunzhijia token endpoint returned %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
var tokenResp appAccessTokenResponse
|
||||
if err := json.Unmarshal(respBody, &tokenResp); err != nil {
|
||||
return "", fmt.Errorf("parse yunzhijia token response: %w", err)
|
||||
}
|
||||
if !tokenResp.Success || tokenResp.ErrorCode != 0 || tokenResp.Data.AccessToken == "" {
|
||||
return "", fmt.Errorf("yunzhijia token response failed: errorCode=%d error=%v", tokenResp.ErrorCode, tokenResp.Error)
|
||||
}
|
||||
|
||||
expiresIn := tokenResp.Data.ExpireIn
|
||||
if expiresIn <= 0 {
|
||||
expiresIn = 3600
|
||||
}
|
||||
expiresAt := time.Now().Add(time.Duration(expiresIn) * time.Second)
|
||||
if expiresIn > 120 {
|
||||
expiresAt = expiresAt.Add(-60 * time.Second)
|
||||
}
|
||||
|
||||
a.tokenMu.Lock()
|
||||
a.accessToken = tokenResp.Data.AccessToken
|
||||
a.accessTokenExpiresAt = expiresAt
|
||||
a.tokenMu.Unlock()
|
||||
return tokenResp.Data.AccessToken, nil
|
||||
}
|
||||
|
||||
func resolveDownloadFileName(fallback string, resp *http.Response) string {
|
||||
fileName := fallback
|
||||
if cd := resp.Header.Get("Content-Disposition"); cd != "" {
|
||||
if _, params, err := mime.ParseMediaType(cd); err == nil {
|
||||
if name := strings.TrimSpace(params["filename"]); name != "" {
|
||||
fileName = name
|
||||
}
|
||||
}
|
||||
}
|
||||
if filepath.Ext(fileName) == "" {
|
||||
switch strings.ToLower(strings.TrimSpace(strings.Split(resp.Header.Get("Content-Type"), ";")[0])) {
|
||||
case "image/jpeg":
|
||||
fileName += ".jpg"
|
||||
case "image/png":
|
||||
fileName += ".png"
|
||||
case "image/gif":
|
||||
fileName += ".gif"
|
||||
}
|
||||
}
|
||||
return fileName
|
||||
}
|
||||
|
||||
// validateSendURL checks that sendMsgUrl is safe to call (HTTPS, no internal IPs, allowed host).
|
||||
func (a *Adapter) validateSendURL() error {
|
||||
_, err := validateEndpointURL(a.sendMsgURL, "https", a.allowedWebhookHostSuffix)
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -36,7 +37,7 @@ func TestVerifyCallbackSignature(t *testing.T) {
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = req
|
||||
|
||||
adapter := NewAdapter("https://www.yunzhijia.com/send", "secret", 10, "yunzhijia.com")
|
||||
adapter := NewAdapter("https://www.yunzhijia.com/send", "secret", "", "", 10, "yunzhijia.com")
|
||||
if err := adapter.VerifyCallback(c); err != nil {
|
||||
t.Fatalf("VerifyCallback() error = %v", err)
|
||||
}
|
||||
@@ -68,8 +69,94 @@ func TestCleanAtMentionRequiresNameBoundary(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestToIncomingMessageParsesMsgParamImage(t *testing.T) {
|
||||
msg := &callbackMessage{
|
||||
Type: 2,
|
||||
MsgType: 23,
|
||||
RobotID: "BOT-1",
|
||||
RobotName: "Websocket",
|
||||
GroupID: "group-1",
|
||||
OperatorOpenid: "user",
|
||||
OperatorName: "User",
|
||||
Time: 123,
|
||||
MsgID: "message",
|
||||
Content: "@Websocket 图片测试一下看看[图片]",
|
||||
GroupType: 2,
|
||||
MsgParam: `{"desc":[{"data":"BOT-1","length":10,"start":0,"type":"at"},` +
|
||||
`{"data":"file-1","h":1032,"length":4,"start":19,"type":"image","w":1920}],` +
|
||||
`"notifyTo":["BOT-1"],"notifyType":1}`,
|
||||
}
|
||||
|
||||
got := toIncomingMessage(t.Context(), msg)
|
||||
if got == nil {
|
||||
t.Fatal("toIncomingMessage() returned nil")
|
||||
}
|
||||
if got.MessageType != im.MessageTypeImage {
|
||||
t.Fatalf("MessageType = %q, want image", got.MessageType)
|
||||
}
|
||||
if got.FileKey != "file-1" {
|
||||
t.Fatalf("FileKey = %q, want file-1", got.FileKey)
|
||||
}
|
||||
if got.FileName != "message.png" {
|
||||
t.Fatalf("FileName = %q, want message.png", got.FileName)
|
||||
}
|
||||
if got.ChatID != "group-1" {
|
||||
t.Fatalf("ChatID = %q, want group-1", got.ChatID)
|
||||
}
|
||||
if got.Content != "图片测试一下看看[图片]" {
|
||||
t.Fatalf("Content = %q", got.Content)
|
||||
}
|
||||
if got.Extra["yunzhijia_image_width"] != "1920" || got.Extra["yunzhijia_image_height"] != "1032" {
|
||||
t.Fatalf("image dimensions extra = %#v", got.Extra)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToIncomingMessageAcceptsMsgParamMention(t *testing.T) {
|
||||
msg := &callbackMessage{
|
||||
Type: 2,
|
||||
RobotID: "BOT-1",
|
||||
RobotName: "Websocket",
|
||||
OperatorOpenid: "user",
|
||||
OperatorName: "User",
|
||||
Time: 123,
|
||||
MsgID: "message",
|
||||
Content: "图片测试一下看看[图片]",
|
||||
MsgParam: `{"desc":[{"data":"BOT-1","type":"at"},{"data":"file-1","type":"image"}]}`,
|
||||
}
|
||||
|
||||
got := toIncomingMessage(t.Context(), msg)
|
||||
if got == nil {
|
||||
t.Fatal("toIncomingMessage() returned nil")
|
||||
}
|
||||
if got.FileKey != "file-1" {
|
||||
t.Fatalf("FileKey = %q, want file-1", got.FileKey)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToIncomingMessageAcceptsImageWithoutText(t *testing.T) {
|
||||
msg := &callbackMessage{
|
||||
Type: 2,
|
||||
RobotID: "BOT-1",
|
||||
RobotName: "Websocket",
|
||||
OperatorOpenid: "user",
|
||||
OperatorName: "User",
|
||||
Time: 123,
|
||||
MsgID: "message",
|
||||
Content: "",
|
||||
MsgParam: `{"desc":[{"data":"BOT-1","type":"at"},{"data":"file-1","type":"image"}]}`,
|
||||
}
|
||||
|
||||
got := toIncomingMessage(t.Context(), msg)
|
||||
if got == nil {
|
||||
t.Fatal("toIncomingMessage() returned nil")
|
||||
}
|
||||
if got.MessageType != im.MessageTypeImage || got.FileKey != "file-1" || got.Content != "" {
|
||||
t.Fatalf("incoming = %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendReplyAcceptsAny2xxAndBuildsPayload(t *testing.T) {
|
||||
adapter := NewAdapter("https://www.yunzhijia.com/send", "", 10, "yunzhijia.com")
|
||||
adapter := NewAdapter("https://www.yunzhijia.com/send", "", "", "", 10, "yunzhijia.com")
|
||||
var payload sendMessagePayload
|
||||
adapter.httpClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
if err := json.NewDecoder(req.Body).Decode(&payload); err != nil {
|
||||
@@ -98,7 +185,7 @@ func TestSendReplyAcceptsAny2xxAndBuildsPayload(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestSendReplyFormatTypeOverride(t *testing.T) {
|
||||
adapter := NewAdapter("https://www.yunzhijia.com/send", "", 10, "yunzhijia.com")
|
||||
adapter := NewAdapter("https://www.yunzhijia.com/send", "", "", "", 10, "yunzhijia.com")
|
||||
var payload sendMessagePayload
|
||||
adapter.httpClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
if err := json.NewDecoder(req.Body).Decode(&payload); err != nil {
|
||||
@@ -135,3 +222,91 @@ func TestSendReplyFormatTypeOverride(t *testing.T) {
|
||||
t.Fatalf("expected overridden format type 'text', got %#v", payload.Param)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildDownloadFileURL(t *testing.T) {
|
||||
got := buildDownloadFileURL("file-1")
|
||||
if got != "https://yunzhijia.com/gateway/docrest/doc/file/downloadfileOpen?fileId=file-1" {
|
||||
t.Fatalf("download URL = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadFile(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/api/oauth2_v12/auth/getAppAccessToken":
|
||||
if r.Method != http.MethodPost {
|
||||
t.Fatalf("token method = %s", r.Method)
|
||||
}
|
||||
var tokenReq map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&tokenReq); err != nil {
|
||||
t.Fatalf("decode token request: %v", err)
|
||||
}
|
||||
if tokenReq["appId"] != "app-id" || tokenReq["secret"] != "app-secret" {
|
||||
t.Fatalf("token request = %#v", tokenReq)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"data":{"accessToken":"token-1","expireIn":7136},"error":null,"errorCode":0,"success":true}`))
|
||||
case "/gateway/docrest/doc/file/downloadfileOpen":
|
||||
if r.Header.Get("Authorization") != "Bearer token-1" {
|
||||
t.Fatalf("Authorization = %q", r.Header.Get("Authorization"))
|
||||
}
|
||||
if r.URL.Query().Get("fileId") != "file-1" {
|
||||
t.Fatalf("query = %q", r.URL.RawQuery)
|
||||
}
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
_, _ = w.Write([]byte("image-bytes"))
|
||||
default:
|
||||
t.Fatalf("path = %q", r.URL.Path)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
oldAuthURL := yunzhijiaAuthURL
|
||||
oldBaseURL := yunzhijiaDownloadFileBaseURL
|
||||
oldValidator := validateDownloadFileURL
|
||||
yunzhijiaAuthURL = server.URL + "/api/oauth2_v12/auth/getAppAccessToken"
|
||||
yunzhijiaDownloadFileBaseURL = server.URL + "/gateway/docrest/doc/file/downloadfileOpen"
|
||||
validateDownloadFileURL = func(string) error { return nil }
|
||||
defer func() {
|
||||
yunzhijiaAuthURL = oldAuthURL
|
||||
yunzhijiaDownloadFileBaseURL = oldBaseURL
|
||||
validateDownloadFileURL = oldValidator
|
||||
}()
|
||||
|
||||
adapter := NewAdapter("https://www.yunzhijia.com/send", "", "app-id", "app-secret", 10, "yunzhijia.com")
|
||||
adapter.httpClient = server.Client()
|
||||
reader, fileName, err := adapter.DownloadFile(context.Background(), &im.IncomingMessage{
|
||||
FileKey: "file-1",
|
||||
FileName: "message.png",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("DownloadFile() error = %v", err)
|
||||
}
|
||||
defer reader.Close()
|
||||
body, err := io.ReadAll(reader)
|
||||
if err != nil {
|
||||
t.Fatalf("read body: %v", err)
|
||||
}
|
||||
if string(body) != "image-bytes" || fileName != "message.png" {
|
||||
t.Fatalf("body=%q fileName=%q", string(body), fileName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadFileRequiresAppCredentials(t *testing.T) {
|
||||
adapter := NewAdapter("https://www.yunzhijia.com/send", "", "", "", 10, "yunzhijia.com")
|
||||
_, _, err := adapter.DownloadFile(context.Background(), &im.IncomingMessage{FileKey: "file-1"})
|
||||
if err == nil || !strings.Contains(err.Error(), "app_id and app_secret") {
|
||||
t.Fatalf("DownloadFile() error = %v, want app credential error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateFileIDRejectsURLishValues(t *testing.T) {
|
||||
for _, fileID := range []string{"", "a/b", "a?b", "a&b", "a b"} {
|
||||
if err := validateFileID(fileID); err == nil {
|
||||
t.Fatalf("validateFileID(%q) = nil, want error", fileID)
|
||||
}
|
||||
}
|
||||
if err := validateFileID("6a605afe5dda8e000121fcea"); err != nil {
|
||||
t.Fatalf("validateFileID(valid) error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,11 +24,13 @@ func NewFactory() im.AdapterFactory {
|
||||
}
|
||||
|
||||
secret := im.GetString(creds, "secret")
|
||||
appID := im.GetString(creds, "app_id")
|
||||
appSecret := im.GetString(creds, "app_secret")
|
||||
allowedHostSuffix := im.GetString(creds, "allowed_webhook_host_suffix")
|
||||
|
||||
timeoutSeconds := positiveIntCredential(creds, "timeout_seconds", 10)
|
||||
|
||||
adapter := NewAdapter(sendMsgURL, secret, timeoutSeconds, allowedHostSuffix)
|
||||
adapter := NewAdapter(sendMsgURL, secret, appID, appSecret, timeoutSeconds, allowedHostSuffix)
|
||||
if err := adapter.validateSendURL(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
@@ -1,16 +1,44 @@
|
||||
package yunzhijia
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// callbackMessage is the JSON structure that Yunzhijia posts to the webhook.
|
||||
type callbackMessage struct {
|
||||
Type int `json:"type"`
|
||||
MsgType int `json:"msgType"`
|
||||
EID string `json:"eid"`
|
||||
ClientID string `json:"clientId"`
|
||||
RobotID string `json:"robotId"`
|
||||
RobotName string `json:"robotName"`
|
||||
OpenID string `json:"openId"`
|
||||
GroupID string `json:"groupId"`
|
||||
OperatorOpenid string `json:"operatorOpenid"`
|
||||
OperatorOID string `json:"operatorOid"`
|
||||
OperatorID string `json:"operatorId"`
|
||||
OperatorUserID string `json:"operatorUserId"`
|
||||
OperatorName string `json:"operatorName"`
|
||||
SenderID string `json:"senderId"`
|
||||
SenderName string `json:"senderName"`
|
||||
Time int64 `json:"time"`
|
||||
MsgID string `json:"msgId"`
|
||||
Content string `json:"content"`
|
||||
GroupType int `json:"groupType"`
|
||||
MsgParam string `json:"msgParam"`
|
||||
}
|
||||
|
||||
type messageParam struct {
|
||||
Desc []messageParamDesc `json:"desc"`
|
||||
NotifyTo []string `json:"notifyTo"`
|
||||
NotifyType int `json:"notifyType"`
|
||||
}
|
||||
|
||||
type messageParamDesc struct {
|
||||
Type string `json:"type"`
|
||||
Data string `json:"data"`
|
||||
Start int `json:"start"`
|
||||
Length int `json:"length"`
|
||||
Width int `json:"w"`
|
||||
Height int `json:"h"`
|
||||
}
|
||||
|
||||
// sendMessagePayload is the JSON body POSTed to sendMsgUrl to reply.
|
||||
@@ -32,3 +60,39 @@ type notifyParam struct {
|
||||
type sendMessageParam struct {
|
||||
FormatType string `json:"formatType,omitempty"`
|
||||
}
|
||||
|
||||
type appAccessTokenResponse struct {
|
||||
Data appAccessTokenData `json:"data"`
|
||||
Error any `json:"error"`
|
||||
ErrorCode int `json:"errorCode"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
type appAccessTokenData struct {
|
||||
AccessToken string `json:"accessToken"`
|
||||
ExpireIn int64 `json:"expireIn"`
|
||||
RefreshToken string `json:"refreshToken"`
|
||||
}
|
||||
|
||||
func (m *messageParam) firstImage() (messageParamDesc, bool) {
|
||||
if m == nil {
|
||||
return messageParamDesc{}, false
|
||||
}
|
||||
for _, desc := range m.Desc {
|
||||
if desc.Type == "image" && desc.Data != "" {
|
||||
return desc, true
|
||||
}
|
||||
}
|
||||
return messageParamDesc{}, false
|
||||
}
|
||||
|
||||
func parseMessageParam(raw string) (*messageParam, error) {
|
||||
if raw == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var param messageParam
|
||||
if err := json.Unmarshal([]byte(raw), ¶m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ¶m, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user