gotify通知
Some checks failed
代码更新通知 / update-server (push) Failing after 2s

This commit is contained in:
2024-12-18 16:10:39 +08:00
parent a9ce145256
commit 0e8b02a9b1
6 changed files with 280 additions and 271 deletions

View File

@@ -8,16 +8,14 @@ jobs:
steps: steps:
- name: 输出当前目录环境 - name: 输出当前目录环境
run: pwd && ls -ahl run: pwd && ls -ahl
- name: 输出github环境变量
run: echo 'github相关 ${{ toJSON(github) }}'
- name: 拷贝文件
run: cd ../ && cp -r . /root/runner/
- name: 发送通知 - name: 发送通知
id: use-go-action id: use-go-action
uses: https://git.aweoo.com/action/gotify@latest uses: https://git.aweoo.com/action/gotify@latest
with: with:
username: foo url: https://gotify.aweoo.com
- name: Print Output token: test_token
title: GotifyAction版本更新
- name: 打印上一步的输出
run: echo 'output time is ${{ steps.use-go-action.outputs.time }}' run: echo 'output time is ${{ steps.use-go-action.outputs.time }}'
- name: 错误处理 - name: 错误处理
if: ${{ failure() }} if: ${{ failure() }}

View File

@@ -10,7 +10,4 @@ tasks:
- git push origin --tags - git push origin --tags
- git push - git push
cp:
cmds:
- cp -r ${GITHUB_WORKSPACE}../ /root/runner/

View File

@@ -1,12 +1,29 @@
name: 'Gotify通知' name: 'Gotify通知'
description: '发送Gotify通知' description: '发送Gotify通知'
inputs: inputs:
username: url:
description: 'The username to print' description: '地址 不需要/message'
required: true required: true
token:
description: "token"
required: true
title:
description: "标题"
required: true
msgText:
description: "消息内容"
contentType:
description: "消息格式"
default: "text/markdown"
priority:
description: "优先级"
clickUrl:
description: "点击跳转地址"
bigImageUrl:
description: "大图地址"
outputs: outputs:
time: time:
description: 'The time when the action was called' description: '结束时间(无用)'
runs: runs:
using: 'go' using: 'go'
main: 'main.go' main: 'main.go'

1
go.mod
View File

@@ -22,6 +22,7 @@ require (
github.com/go-openapi/strfmt v0.17.0 // indirect github.com/go-openapi/strfmt v0.17.0 // indirect
github.com/go-openapi/swag v0.17.0 // indirect github.com/go-openapi/swag v0.17.0 // indirect
github.com/go-openapi/validate v0.17.0 // indirect github.com/go-openapi/validate v0.17.0 // indirect
github.com/golang-cz/devslog v0.0.11 // indirect
github.com/mailru/easyjson v0.0.0-20180823135443-60711f1a8329 // indirect github.com/mailru/easyjson v0.0.0-20180823135443-60711f1a8329 // indirect
github.com/mitchellh/mapstructure v1.1.2 // indirect github.com/mitchellh/mapstructure v1.1.2 // indirect
github.com/spf13/cast v1.7.0 // indirect github.com/spf13/cast v1.7.0 // indirect

2
go.sum
View File

@@ -32,6 +32,8 @@ github.com/go-openapi/swag v0.17.0 h1:iqrgMg7Q7SvtbWLlltPrkMs0UBJI6oTSs79JFRUi88
github.com/go-openapi/swag v0.17.0/go.mod h1:AByQ+nYG6gQg71GINrmuDXCPWdL640yX49/kXLo40Tg= github.com/go-openapi/swag v0.17.0/go.mod h1:AByQ+nYG6gQg71GINrmuDXCPWdL640yX49/kXLo40Tg=
github.com/go-openapi/validate v0.17.0 h1:pqoViQz3YLOGIhAmD0N4Lt6pa/3Gnj3ymKqQwq8iS6U= github.com/go-openapi/validate v0.17.0 h1:pqoViQz3YLOGIhAmD0N4Lt6pa/3Gnj3ymKqQwq8iS6U=
github.com/go-openapi/validate v0.17.0/go.mod h1:Uh4HdOzKt19xGIGm1qHf/ofbX1YQ4Y+MYsct2VUrAJ4= github.com/go-openapi/validate v0.17.0/go.mod h1:Uh4HdOzKt19xGIGm1qHf/ofbX1YQ4Y+MYsct2VUrAJ4=
github.com/golang-cz/devslog v0.0.11 h1:v4Yb9o0ZpuZ/D8ZrtVw1f9q5XrjnkxwHF1XmWwO8IHg=
github.com/golang-cz/devslog v0.0.11/go.mod h1:bSe5bm0A7Nyfqtijf1OMNgVJHlWEuVSXnkuASiE1vV8=
github.com/google/uuid v1.0.0 h1:b4Gk+7WdP/d3HZH8EJsZpvV7EtDOgaZLtnaNGIu1adA= github.com/google/uuid v1.0.0 h1:b4Gk+7WdP/d3HZH8EJsZpvV7EtDOgaZLtnaNGIu1adA=
github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gotify/go-api-client/v2 v2.0.4 h1:0w8skCr8aLBDKaQDg31LKKHUGF7rt7zdRpR+6cqIAlE= github.com/gotify/go-api-client/v2 v2.0.4 h1:0w8skCr8aLBDKaQDg31LKKHUGF7rt7zdRpR+6cqIAlE=

138
main.go
View File

@@ -3,57 +3,57 @@ package main
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/golang-cz/devslog"
"github.com/gotify/go-api-client/v2/auth" "github.com/gotify/go-api-client/v2/auth"
"github.com/gotify/go-api-client/v2/client/message" "github.com/gotify/go-api-client/v2/client/message"
"github.com/gotify/go-api-client/v2/gotify" "github.com/gotify/go-api-client/v2/gotify"
"github.com/gotify/go-api-client/v2/models" "github.com/gotify/go-api-client/v2/models"
"github.com/sethvargo/go-githubactions" "github.com/sethvargo/go-githubactions"
"github.com/spf13/cast" "github.com/spf13/cast"
"io/fs" "log"
"log/slog"
"net/http" "net/http"
"net/url" "net/url"
"os" "os"
"path/filepath" "strings"
"time" "time"
) )
func init() {
slogOpts := &slog.HandlerOptions{
AddSource: false,
Level: slog.LevelDebug,
}
opts := &devslog.Options{
HandlerOptions: slogOpts,
MaxSlicePrintSize: 5,
SortKeys: true,
TimeFormat: "[15:04:05]",
StringerFormatter: true,
}
logger := slog.New(devslog.NewHandler(os.Stdout, opts))
slog.SetDefault(logger)
}
func main() { func main() {
//doPush() if err := doPush(); err != nil {
//return slog.Error("推送失败", slog.Any("err", err))
log.Fatalln(err)
ctx, err := githubactions.Context()
if err != nil {
panic(err)
} }
slog.Info("推送成功")
body, err := json.Marshal(ctx)
if err != nil {
panic(err)
}
fmt.Printf("context: %s\n", string(body))
username := githubactions.GetInput("username")
fmt.Printf("username is %s\n", username)
dir, _ := os.Getwd()
root := filepath.Join(dir, "../")
filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if d.IsDir() {
if d.Name() == ".git" {
return filepath.SkipDir
}
return nil
}
//body, _ = os.ReadFile(path)
fmt.Printf("path: %s\n", path)
//fmt.Printf("path: %s\n%s\n\n", path, string(body))
return nil
})
githubactions.SetOutput("time", time.Now().Format("2006-01-02 15:04:05")) githubactions.SetOutput("time", time.Now().Format("2006-01-02 15:04:05"))
} }
func doPush() { func doPush() error {
ctx, err := githubactions.Context()
if err != nil {
slog.Error("获取上下文失败", slog.Any("err", err))
return err
}
priority := githubactions.GetInput("priority") priority := githubactions.GetInput("priority")
title := githubactions.GetInput("title") title := githubactions.GetInput("title")
@@ -64,6 +64,8 @@ func doPush() {
msgText := githubactions.GetInput("msgText") msgText := githubactions.GetInput("msgText")
stringURL := githubactions.GetInput("url") stringURL := githubactions.GetInput("url")
msgText += "\n\n" + getExtraMsg(ctx)
msg := &models.MessageExternal{ msg := &models.MessageExternal{
Message: msgText, Message: msgText,
Title: title, Title: title,
@@ -91,13 +93,13 @@ func doPush() {
parsedURL, err := url.Parse(stringURL) parsedURL, err := url.Parse(stringURL)
if err != nil { if err != nil {
panic(err) return err
} }
pushMessage(parsedURL, token, msg) return pushMessage(parsedURL, token, msg)
} }
func pushMessage(parsedURL *url.URL, token string, msg *models.MessageExternal) { func pushMessage(parsedURL *url.URL, token string, msg *models.MessageExternal) error {
client := gotify.NewClient(parsedURL, &http.Client{}) client := gotify.NewClient(parsedURL, &http.Client{})
@@ -105,17 +107,38 @@ func pushMessage(parsedURL *url.URL, token string, msg *models.MessageExternal)
params.SetBody(msg) params.SetBody(msg)
res, err := client.Message.CreateMessage(params, auth.TokenAuth(token)) res, err := client.Message.CreateMessage(params, auth.TokenAuth(token))
if err == nil { if err == nil {
// todo成功 slog.Info("推送结果", slog.Any("result", res))
response, _ := json.Marshal(res) return nil
fmt.Println(string(response))
} else { } else {
panic(err) return err
// todo 错误处理
} }
} }
type GithubEnv struct { func getExtraMsg(ctx *githubactions.GitHubContext) (result string) {
Event struct { body, err := os.ReadFile(ctx.EventPath)
if err != nil {
slog.Error("读取文件失败", slog.Any("err", err), slog.String("path", ctx.EventPath))
return
}
event := new(Event)
if err = json.Unmarshal(body, &event); err != nil {
slog.Error("解析json失败", slog.Any("err", err), slog.String("path", ctx.EventPath), slog.String("body", string(body)))
return
}
result = "**更新内容:**\n%s\n\n[查看更新](%s)\t[查看Action](%s)"
var commits []string
for _, v := range event.Commits {
commits = append(commits, fmt.Sprintf("- %s [%s](%s)", v.Message, v.Id, v.Url))
}
action := fmt.Sprintf("%s/%s/actions/runs/%d", ctx.ServerURL, ctx.Repository, ctx.RunNumber)
result = fmt.Sprintf(result, strings.Join(commits, "\n"), event.CompareUrl, action)
return
}
type Event struct {
After string `json:"after"` After string `json:"after"`
Before string `json:"before"` Before string `json:"before"`
Commits []struct { Commits []struct {
@@ -303,33 +326,4 @@ type GithubEnv struct {
Website string `json:"website"` Website string `json:"website"`
} `json:"sender"` } `json:"sender"`
TotalCommits int `json:"total_commits"` TotalCommits int `json:"total_commits"`
} `json:"event"`
EventPath string `json:"event_path"`
Workflow string `json:"workflow"`
RunId string `json:"run_id"`
RunNumber string `json:"run_number"`
Actor string `json:"actor"`
Repository string `json:"repository"`
EventName string `json:"event_name"`
Sha string `json:"sha"`
Ref string `json:"ref"`
RefName string `json:"ref_name"`
RefType string `json:"ref_type"`
HeadRef string `json:"head_ref"`
BaseRef string `json:"base_ref"`
Token string `json:"token"`
Workspace string `json:"workspace"`
Action string `json:"action"`
ActionPath string `json:"action_path"`
ActionRef string `json:"action_ref"`
ActionRepository string `json:"action_repository"`
Job string `json:"job"`
JobName string `json:"job_name"`
RepositoryOwner string `json:"repository_owner"`
RetentionDays string `json:"retention_days"`
RunnerPerflog string `json:"runner_perflog"`
RunnerTrackingId string `json:"runner_tracking_id"`
ServerUrl string `json:"server_url"`
ApiUrl string `json:"api_url"`
GraphqlUrl string `json:"graphql_url"`
} }