Skip to content

Commit

Permalink
Merge pull request #148 from hibare/dev
Browse files Browse the repository at this point in the history
Refactor notifiers, use GoCommon
  • Loading branch information
hibare authored Aug 19, 2023
2 parents 2bd5726 + 0969224 commit 28a9ee3
Show file tree
Hide file tree
Showing 6 changed files with 115 additions and 136 deletions.
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ go 1.20

require (
github.com/go-co-op/gocron v1.31.1
github.com/hibare/GoCommon/v2 v2.1.1
github.com/hibare/GoCommon/v2 v2.2.0
github.com/jedib0t/go-pretty/v6 v6.4.6
github.com/sirupsen/logrus v1.9.3
github.com/spf13/cobra v1.7.0
Expand Down Expand Up @@ -35,4 +35,4 @@ require (
gopkg.in/yaml.v3 v3.0.1 // indirect
)

// replace github.com/hibare/GoCommon => ../GoCommon
// replace github.com/hibare/GoCommon/v2 => ../GoCommon
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,8 @@ github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/hibare/GoCommon/v2 v2.1.1 h1:LeMv8nQFTAeEwzqh6hQHobbgkfOzv5c8XWtyAgF8TCU=
github.com/hibare/GoCommon/v2 v2.1.1/go.mod h1:azkJtd0og4/HDZ47NydL/zEc3ALukwF0mPbmghNRrSQ=
github.com/hibare/GoCommon/v2 v2.2.0 h1:aQd/MvgONakXzNQlLTzFtCea7as1XtuBvv1eNk6y99U=
github.com/hibare/GoCommon/v2 v2.2.0/go.mod h1:azkJtd0og4/HDZ47NydL/zEc3ALukwF0mPbmghNRrSQ=
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
Expand Down
27 changes: 15 additions & 12 deletions internal/backup/backup.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package backup

import (
"fmt"
"errors"
"os"
"path/filepath"

Expand All @@ -15,6 +15,11 @@ import (
"github.com/hibare/GoS3Backup/internal/notifiers"
)

var (
ErrArchiving = errors.New("error archiving")
ErrNoProcessableFiles = errors.New("no processable files")
)

func Backup() {
s3 := commonS3.S3{
Endpoint: config.Current.S3.Endpoint,
Expand All @@ -40,28 +45,26 @@ func Backup() {
zipPath, totalFiles, totalDirs, successFiles, err := commonFiles.ArchiveDir(dir)
if err != nil {
log.Warnf("Archiving failed %s", dir)
notifiers.BackupFailedNotification("", dir, totalDirs, totalFiles)
notifiers.NotifyBackupFailure(dir, totalDirs, totalFiles, err)
continue
}

if successFiles <= 0 {
err := fmt.Errorf("Failed to archive")
log.Warnf("Uploading failed %s: %s", dir, err)
notifiers.BackupFailedNotification(err.Error(), dir, totalDirs, totalFiles)
notifiers.NotifyBackupFailure(dir, totalDirs, totalFiles, ErrNoProcessableFiles)
continue
}

log.Infof("Uploading files %d/%d", successFiles, totalFiles)
key, err := s3.UploadFile(zipPath)

if err != nil {
log.Warnf("Uploading failed %s: %s", dir, err)
notifiers.BackupFailedNotification(err.Error(), dir, totalDirs, totalFiles)
notifiers.NotifyBackupFailure(dir, totalDirs, totalFiles, err)
continue
}

log.Warnf("Uploaded files %d/%d at %s", successFiles, totalFiles, key)
notifiers.BackupSuccessfulNotification(dir, totalDirs, totalFiles, successFiles, key)
log.Infof("Uploaded files %d/%d at %s", successFiles, totalFiles, key)
notifiers.NotifyBackupSuccess(dir, totalDirs, totalFiles, successFiles, key)
os.Remove(zipPath)

} else {
Expand All @@ -70,12 +73,12 @@ func Backup() {

if successFiles <= 0 {
log.Warnf("Uploading failed %s", dir)
notifiers.BackupFailedNotification("", dir, totalDirs, totalFiles)
notifiers.NotifyBackupFailure(dir, totalDirs, totalFiles, ErrNoProcessableFiles)
continue
}

log.Warnf("Uploaded files %d/%d at %s", successFiles, totalFiles, s3.Prefix)
notifiers.BackupSuccessfulNotification(dir, totalDirs, totalFiles, successFiles, key)
notifiers.NotifyBackupSuccess(dir, totalDirs, totalFiles, successFiles, key)
}

}
Expand Down Expand Up @@ -141,7 +144,7 @@ func PurgeOldBackups() {

backups, err := ListBackups()
if err != nil {
notifiers.BackupDeletionFailureNotification(err.Error(), constants.NotAvailable)
notifiers.NotifyBackupDeleteFailure(constants.NotAvailable, err)
return
}

Expand All @@ -160,7 +163,7 @@ func PurgeOldBackups() {

if err := s3.DeleteObjects(key, true); err != nil {
log.Errorf("Error deleting backup %s: %v", key, err)
notifiers.BackupDeletionFailureNotification(err.Error(), key)
notifiers.NotifyBackupDeleteFailure(key, err)
continue
}
}
Expand Down
5 changes: 5 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,11 @@ func LoadConfig() {
Current.Backup.Cron = constants.DefaultCron
}

// If notifier webhook is empty, set status to disable
if Current.Notifiers.Discord.Webhook == "" {
Current.Notifiers.Discord.Enabled = false
}

Current.Backup.Hostname = commonUtils.GetHostname()
}

Expand Down
153 changes: 66 additions & 87 deletions internal/notifiers/discord.go
Original file line number Diff line number Diff line change
@@ -1,63 +1,36 @@
package notifiers

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strconv"

"github.com/hibare/GoCommon/v2/pkg/notifiers/discord"
"github.com/hibare/GoS3Backup/internal/config"
"github.com/hibare/GoS3Backup/internal/constants"
"github.com/hibare/GoS3Backup/internal/version"
log "github.com/sirupsen/logrus"
)

type DiscordWebhookMessage struct {
Embeds []DiscordEmbed `json:"embeds"`
Components []DiscordComponent `json:"components"`
Username string `json:"username"`
Content string `json:"content"`
}

type DiscordEmbed struct {
Title string `json:"title"`
Description string `json:"description"`
Color int `json:"color"`
Footer DiscordEmbedFooter `json:"footer"`
Fields []DiscordEmbedField `json:"fields"`
}

type DiscordEmbedField struct {
Name string `json:"name"`
Value string `json:"value"`
Inline bool `json:"inline,omitempty"`
}

type DiscordEmbedFooter struct {
Text string `json:"text"`
}

type DiscordComponent struct {
// Define struct for Discord components if needed
func runDiscordPrechecks() error {
if !config.Current.Notifiers.Discord.Enabled {
return ErrNotifierDisabled
}
return nil
}

func (d *DiscordWebhookMessage) AddFooter() {
if version.V.NewVersionAvailable {
footer := DiscordEmbedFooter{
Text: version.V.GetUpdateNotification(),
}
d.Embeds[0].Footer = footer
func discordNotifyBackupSuccess(directory string, totalDirs, totalFiles, successFiles int, key string) {
if err := runDiscordPrechecks(); err != nil {
log.Error(err)
return
}
}

func DiscordBackupSuccessfulNotification(webhookUrl string, hostname, directory string, totalDirs, totalFiles, successFiles int, key string) error {
webhookMessage := DiscordWebhookMessage{
Embeds: []DiscordEmbed{
message := discord.Message{
Embeds: []discord.Embed{
{
Title: "Directory",
Description: directory,
Color: 1498748,
Fields: []DiscordEmbedField{
Fields: []discord.EmbedField{
{
Name: "Key",
Value: key,
Expand All @@ -76,24 +49,35 @@ func DiscordBackupSuccessfulNotification(webhookUrl string, hostname, directory
},
},
},
Components: []DiscordComponent{},
Username: "Backup Job",
Content: fmt.Sprintf("**Backup Successful** - *%s*", hostname),
Components: []discord.Component{},
Username: constants.ProgramIdentifier,
Content: fmt.Sprintf("**Backup Successful** - *%s*", config.Current.Backup.Hostname),
}
webhookMessage.AddFooter()

return SendMessage(webhookUrl, webhookMessage)
if version.V.NewVersionAvailable {
if err := message.AddFooter(version.V.GetUpdateNotification()); err != nil {
log.Warn(err)
}
}

if err := message.Send(config.Current.Notifiers.Discord.Webhook); err != nil {
log.Error(err)
}
}

func DiscordBackupFailedNotification(webhookUrl string, hostname, err, directory string, totalDirs, totalFiles int) error {
webhookMessage := DiscordWebhookMessage{
Embeds: []DiscordEmbed{
func discordNotifyBackupFailure(directory string, totalDirs, totalFiles int, err error) {
if err := runDiscordPrechecks(); err != nil {
log.Error(err)
return
}

message := discord.Message{
Embeds: []discord.Embed{
{
Title: "Error",
Description: err,
Description: err.Error(),
Color: 14554702,
Fields: []DiscordEmbedField{
Fields: []discord.EmbedField{
{
Name: "Directory",
Value: directory,
Expand All @@ -112,23 +96,35 @@ func DiscordBackupFailedNotification(webhookUrl string, hostname, err, directory
},
},
},
Components: []DiscordComponent{},
Username: "Backup Job",
Content: fmt.Sprintf("**Backup Failed** - *%s*", hostname),
Components: []discord.Component{},
Username: constants.ProgramIdentifier,
Content: fmt.Sprintf("**Backup Failed** - *%s*", config.Current.Backup.Hostname),
}

if version.V.NewVersionAvailable {
if err := message.AddFooter(version.V.GetUpdateNotification()); err != nil {
log.Warn(err)
}
}
webhookMessage.AddFooter()

return SendMessage(webhookUrl, webhookMessage)
if err := message.Send(config.Current.Notifiers.Discord.Webhook); err != nil {
log.Error(err)
}
}

func DiscordBackupDeletionFailureNotification(webhookUrl string, hostname, err, key string) error {
webhookMessage := DiscordWebhookMessage{
Embeds: []DiscordEmbed{
func discordNotifyBackupDeleteFailure(key string, err error) {
if err := runDiscordPrechecks(); err != nil {
log.Error(err)
return
}

message := discord.Message{
Embeds: []discord.Embed{
{
Title: "Error",
Description: err,
Description: err.Error(),
Color: 14590998,
Fields: []DiscordEmbedField{
Fields: []discord.EmbedField{
{
Name: "Key",
Value: key,
Expand All @@ -137,35 +133,18 @@ func DiscordBackupDeletionFailureNotification(webhookUrl string, hostname, err,
},
},
},
Components: []DiscordComponent{},
Username: "Backup Job",
Content: fmt.Sprintf("**Backup Deletion Failed** - *%s*", hostname),
}
webhookMessage.AddFooter()

return SendMessage(webhookUrl, webhookMessage)
}

func SendMessage(webhookUrl string, message DiscordWebhookMessage) error {
if config.Current.Notifiers.Discord.Webhook != "" && !config.Current.Notifiers.Discord.Enabled {
log.Warning("Discord notifier not enabled")
return nil
}

payload, err := json.Marshal(message)
if err != nil {
return &json.SyntaxError{}
Components: []discord.Component{},
Username: constants.ProgramIdentifier,
Content: fmt.Sprintf("**Backup Deletion Failed** - *%s*", config.Current.Backup.Hostname),
}

resp, err := http.Post(webhookUrl, "application/json", bytes.NewBuffer(payload))
if err != nil {
return err
if version.V.NewVersionAvailable {
if err := message.AddFooter(version.V.GetUpdateNotification()); err != nil {
log.Warn(err)
}
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return err
if err := message.Send(config.Current.Notifiers.Discord.Webhook); err != nil {
log.Error(err)
}

return nil
}
Loading

0 comments on commit 28a9ee3

Please sign in to comment.