Completed
Pull Request — master (#762)
by
unknown
06:48
created

report.TelegramWriter.Write   C

Complexity

Conditions 10

Size

Total Lines 38
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 28
dl 0
loc 38
rs 5.9999
c 0
b 0
f 0
nop 1

How to fix   Complexity   

Complexity

Complex classes like report.TelegramWriter.Write often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
package report
2
3
import (
4
	"bytes"
5
	"fmt"
6
	"net/http"
7
	"strconv"
8
	"strings"
9
10
	"github.com/future-architect/vuls/config"
11
	"github.com/future-architect/vuls/models"
12
)
13
14
// TelegramWriter sends report to Telegram
15
type TelegramWriter struct{}
16
17
func (w TelegramWriter) Write(rs ...models.ScanResult) (err error) {
18
	conf := config.Conf.Telegram
19
20
	for _, r := range rs {
21
		msgs := []string{fmt.Sprintf("*%s*\n%s\n%s\n%s",
22
			r.ServerInfo(),
23
			r.ScannedCves.FormatCveSummary(),
24
			r.ScannedCves.FormatFixedStatus(r.Packages),
25
			r.FormatUpdatablePacksSummary())}
26
		for _, vinfo := range r.ScannedCves {
27
			maxCvss := vinfo.MaxCvssScore()
28
			severity := strings.ToUpper(maxCvss.Value.Severity)
29
			if severity == "" {
30
				severity = "?"
31
			}
32
33
			msgs = append(msgs, fmt.Sprintf(`[%s](https://nvd.nist.gov/vuln/detail/%s) _%s %s %s_\n%s`,
34
				vinfo.CveID,
35
				vinfo.CveID,
36
				strconv.FormatFloat(maxCvss.Value.Score, 'f', 1, 64),
37
				severity,
38
				maxCvss.Value.Vector,
39
				vinfo.Summaries(config.Conf.Lang, r.Family)[0].Value))
40
			if len(msgs) == 5 {
41
				if err = sendMessage(conf.ChatID, conf.Token, strings.Join(msgs, "\n\n")); err != nil {
42
					return err
43
				}
44
				msgs = []string{}
45
			}
46
		}
47
		if len(msgs) != 0 {
48
			if err = sendMessage(conf.ChatID, conf.Token, strings.Join(msgs, "\n\n")); err != nil {
49
				return err
50
			}
51
		}
52
53
	}
54
	return nil
55
}
56
57
func sendMessage(chatID, token, message string) error {
58
	uri := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", token)
59
	payload := `{"text": "` + strings.Replace(message, `"`, `\"`, -1) + `", "chat_id": "` + chatID + `", "parse_mode": "Markdown" }`
60
	req, err := http.NewRequest("POST", uri, bytes.NewBuffer([]byte(payload)))
61
	req.Header.Add("Content-Type", "application/json")
62
	if err != nil {
63
		return err
64
	}
65
	client := &http.Client{}
66
	resp, err := client.Do(req)
67
	if checkResponse(resp) != nil && err != nil {
68
		fmt.Println(err)
69
		return err
70
	}
71
	defer resp.Body.Close()
72
	return nil
73
}
74
75
func checkResponse(r *http.Response) error {
76
	if c := r.StatusCode; 200 <= c && c <= 299 {
77
		return nil
78
	}
79
	return fmt.Errorf("API call to %s failed: %s", r.Request.URL.String(), r.Status)
80
}
81