aboutsummaryrefslogtreecommitdiffstats
path: root/lib/structure_helpers.go
blob: 7b5865a239111d51c0e665cbe1a202831768faca (plain) (blame)
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
package lib

import (
	"strings"

	"git.sr.ht/~rjarry/aerc/models"
)

// FindMIMEPart finds the first message part with the provided MIME type.
// FindMIMEPart recurses inside multipart containers.
func FindMIMEPart(mime string, bs *models.BodyStructure, path []int) []int {
	for i, part := range bs.Parts {
		cur := append(path, i+1) //nolint:gocritic // intentional append to different slice
		if part.FullMIMEType() == mime {
			return cur
		}
		if strings.ToLower(part.MIMEType) == "multipart" {
			if path := FindMIMEPart(mime, part, cur); path != nil {
				return path
			}
		}
	}
	return nil
}

func FindPlaintext(bs *models.BodyStructure, path []int) []int {
	return FindMIMEPart("text/plain", bs, path)
}

func FindCalendartext(bs *models.BodyStructure, path []int) []int {
	return FindMIMEPart("text/calendar", bs, path)
}

func FindFirstNonMultipart(bs *models.BodyStructure, path []int) []int {
	for i, part := range bs.Parts {
		cur := append(path, i+1) //nolint:gocritic // intentional append to different slice
		mimetype := strings.ToLower(part.MIMEType)
		if mimetype != "multipart" {
			return cur
		} else if mimetype == "multipart" {
			if path := FindFirstNonMultipart(part, cur); path != nil {
				return path
			}
		}
	}
	return nil
}

func FindAllNonMultipart(bs *models.BodyStructure, path []int, pathlist [][]int) [][]int {
	for i, part := range bs.Parts {
		cur := append(path, i+1) //nolint:gocritic // intentional append to different slice
		mimetype := strings.ToLower(part.MIMEType)
		if mimetype != "multipart" {
			tmp := make([]int, len(cur))
			copy(tmp, cur)
			pathlist = append(pathlist, tmp)
		} else if mimetype == "multipart" {
			if sub := FindAllNonMultipart(part, cur, nil); len(sub) > 0 {
				pathlist = append(pathlist, sub...)
			}
		}
	}
	return pathlist
}

func EqualParts(a []int, b []int) bool {
	if len(a) != len(b) {
		return false
	}
	for i := 0; i < len(a); i++ {
		if a[i] != b[i] {
			return false
		}
	}
	return true
}