Completed
Push — master ( 967c56...3d8753 )
by kota
07:11
created

report.TelegramWriter.Write   C

Complexity

Conditions 10

Size

Total Lines 35
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

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