~dricottone/digestion

ref: 8cc83015e2289b611448002a194f23cfaaa253b5 digestion/message/format.go -rw-r--r-- 2.4 KiB
8cc83015Dominic Ricottone Makefile updates 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package message

import (
	"fmt"
	"strings"

	textwrap "git.dominic-ricottone.com/~dricottone/textwrap/common"

	"git.dominic-ricottone.com/~dricottone/digestion/decoder"
)

func (m *Message) determine_best_part() int {
	// Handle cases with obvious best part
	number_parts := len(m.Parts)
	if number_parts == 0 {
		return -1
	} else if number_parts == 1 {
		return 0
	}

	// Evaluate each part--lower is better
	evaluations := []int{}
	for i := 0; i < number_parts; i++ {
		value := m.Parts[i].evaluate_type()
		value += m.Parts[i].evaluate_encoding()
		evaluations = append(evaluations, value)
	}

	// Find minimum value and return that part index
	best_part_index := 0
	for i := 1; i < number_parts; i++ {
		if evaluations[i] < evaluations[best_part_index] {
			best_part_index = i
		}
	}
	return best_part_index
}

func (m *Message) format_header() []string {
	buffer := []string{}
	if m.Header.Subject != "" {
		buffer = append(buffer, fmt.Sprintf("Subject: %s", m.Header.Subject))
	}
	if m.Header.Date != "" {
		buffer = append(buffer, fmt.Sprintf("Date: %s", m.Header.Date))
	}
	if m.Header.From != "" {
		buffer = append(buffer, fmt.Sprintf("From: %s", m.Header.From))
	}
	if m.Header.To != "" {
		buffer = append(buffer, fmt.Sprintf("To: %s", m.Header.To))
	}
	if m.Header.Cc != "" {
		buffer = append(buffer, fmt.Sprintf("Cc: %s", m.Header.Cc))
	}
	//if m.Header.MessageID != "" {
	//	buffer = append(buffer, fmt.Sprintf("MessageID: %s", m.Header.MessageID))
	//}
	//if m.Header.ContentType != "" {
	//	buffer = append(buffer, fmt.Sprintf("ContentType: %s", m.Header.ContentType))
	//}
	return buffer
}

func (m *Message) format_content(length int) ([]string, error) {
	best_part := m.determine_best_part()
	buffer := []string{}

	// Handle messages with no content
	if best_part == -1 {
		return buffer, nil
	}

	// Decode best part's content
	decoded, err := decoder.DecodeArray(m.Parts[best_part].Content, m.Parts[best_part].Header.ContentEncoding)
	if err != nil {
		return buffer, err
	}

	// Wrap text content
	wrapped, err := textwrap.WrapArray(decoded, length)
	if err != nil {
		return decoded, err
	}

	return wrapped, nil
}

func (m *Message) Dump(length int) {
	header := m.format_header()
	content, err := m.format_content(length)
	if err != nil {
		fmt.Printf("error: %s", err)
	}

	for _, line := range append(header, content...) {
		fmt.Printf("%s\n", line)
	}
	fmt.Printf("%s\n\n", strings.Repeat("-", length))
}