|
- package wechat
-
- import (
- "code.gitea.io/gitea/models"
- "code.gitea.io/gitea/modules/log"
- "code.gitea.io/gitea/modules/setting"
- "encoding/json"
- "github.com/patrickmn/go-cache"
- "strings"
- "time"
- )
-
- var WechatReplyCache = cache.New(2*time.Minute, 1*time.Minute)
-
- const (
- WECHAT_REPLY_CACHE_KEY = "wechat_response"
- )
-
- const (
- ReplyTypeText = "text"
- ReplyTypeImage = "image"
- ReplyTypeVoice = "voice"
- ReplyTypeVideo = "video"
- ReplyTypeMusic = "music"
- ReplyTypeNews = "news"
- )
-
- type AutomaticResponseContent struct {
- Reply *ReplyContent
- ReplyType string
- KeyWords []string
- IsFullMatch int
- }
-
- type ReplyContent struct {
- Content string
- MediaId string
- Title string
- Description string
- MusicUrl string
- HQMusicUrl string
- ThumbMediaId string
- Articles []ArticlesContent
- }
-
- func GetAutomaticReply(msg string) *AutomaticResponseContent {
- r, err := LoadAutomaticReplyFromCacheAndDisk()
- if err != nil {
- return nil
- }
- if r == nil || len(r) == 0 {
- return nil
- }
- for i := 0; i < len(r); i++ {
- if r[i].IsFullMatch == 0 {
- for _, v := range r[i].KeyWords {
- if strings.Contains(msg, v) {
- return r[i]
- }
- }
- } else if r[i].IsFullMatch > 0 {
- for _, v := range r[i].KeyWords {
- if msg == v {
- return r[i]
- }
- }
- }
- }
- return nil
-
- }
-
- func loadAutomaticReplyFromDisk() ([]*AutomaticResponseContent, error) {
- log.Info("LoadAutomaticResponseMap from disk")
- repo, err := models.GetRepositoryByOwnerAndAlias(setting.UserNameOfAutoReply, setting.RepoNameOfAutoReply)
- if err != nil {
- log.Error("get AutomaticReply repo failed, error=%v", err)
- return nil, err
- }
- repoFile, err := models.ReadLatestFileInRepo(setting.UserNameOfAutoReply, repo.Name, setting.RefNameOfAutoReply, setting.TreePathOfAutoReply)
- if err != nil {
- log.Error("get AutomaticReply failed, error=%v", err)
- return nil, err
- }
- res := make([]*AutomaticResponseContent, 0)
- json.Unmarshal(repoFile.Content, &res)
- if res == nil || len(res) == 0 {
- return nil, err
- }
- return res, nil
- }
-
- func LoadAutomaticReplyFromCacheAndDisk() ([]*AutomaticResponseContent, error) {
- v, success := WechatReplyCache.Get(WECHAT_REPLY_CACHE_KEY)
- if success {
- log.Info("LoadAutomaticResponse from cache,value = %v", v)
- if v == nil {
- return nil, nil
- }
- n := v.([]*AutomaticResponseContent)
- return n, nil
- }
-
- content, err := loadAutomaticReplyFromDisk()
- if err != nil {
- log.Error("GetNewestNotice failed, error=%v", err)
- WechatReplyCache.Set(WECHAT_REPLY_CACHE_KEY, nil, 30*time.Second)
- return nil, err
- }
- WechatReplyCache.Set(WECHAT_REPLY_CACHE_KEY, content, 60*time.Second)
- return content, nil
- }
|