/
eml.py
182 lines (136 loc) · 4.93 KB
/
eml.py
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import datetime
from io import BytesIO
from typing import Any
import dateparser
from eml_parser import EmlParser
from ioc_finder import parse_domain_names, parse_email_addresses, parse_ipv4_addresses
from returns.functions import raise_exception
from returns.maybe import Maybe
from returns.pipeline import flow
from returns.pointfree import bind
from returns.result import ResultE, safe
from backend import schemas
from backend.outlookmsgfile import Message
from backend.utils import parse_urls_from_body
from backend.validator import is_eml_file
from .abstract import AbstractFactory
def is_inline_forward_attachment(attachment: dict) -> bool:
content_header = attachment.get("content_header", {})
content_types: list[str] = content_header.get("content-type", [])
content_dispositions: list[str] = content_header.get("content-disposition", [])
is_rfc822 = False
for content_type in content_types:
if content_type.startswith("message/rfc822;"):
is_rfc822 = True
break
is_inline = False
for content_disposition in content_dispositions:
if content_disposition.startswith("inline;"):
is_inline = True
break
return is_rfc822 and is_inline
@safe
def to_eml(data: bytes) -> bytes:
if is_eml_file(data):
return data
# assume data is a msg file
file = BytesIO(data)
message = Message(file)
email = message.to_email()
return email.as_bytes()
@safe
def parse(data: bytes) -> dict:
parser = EmlParser(include_raw_body=True, include_attachment_data=True)
return parser.decode_email_bytes(data)
def parse_datetime(dt: str | datetime.datetime | None) -> datetime.datetime | None:
if isinstance(dt, str):
return dateparser.parse(dt)
if isinstance(dt, datetime.datetime):
return dt
return None
def _normalize_received_date(received: dict):
src = received.get("src", "")
parts: list[str] = src.split(";")
last_part = parts[-1].strip()
received["date"] = (
Maybe.from_optional(received.get("date"))
.bind_optional(parse_datetime)
.value_or(parse_datetime(last_part))
)
return received
def _normalize_received(received: list[dict]) -> list[dict]:
if len(received) == 0:
return []
received = [_normalize_received_date(r) for r in received]
received.reverse()
first = received[0]
optional_base_datetime = (
Maybe.from_optional(first.get("date"))
.bind_optional(parse_datetime)
.value_or(None)
)
for r in received:
optional_datetime = (
Maybe.from_optional(r.get("date"))
.bind_optional(parse_datetime)
.value_or(None)
)
if optional_base_datetime is None or optional_datetime is None:
continue
delay = (optional_datetime - optional_base_datetime).seconds
r["delay"] = delay
optional_base_datetime = optional_datetime
return received
@safe
def normalize_header(parsed: dict) -> dict:
header = parsed.get("header", {})
# set message-id as a top-level attribute
message_id = header.get("header", {}).get("message-id", [])
if len(message_id) > 0:
header["message_id"] = message_id[0]
received = header.get("received", [])
header["received"] = _normalize_received(received)
parsed["header"] = header
return parsed
def _normalize_body(body: dict[str, Any]) -> dict[str, Any]:
content = body.get("content", "")
content_type = body.get("content_type", "")
body["urls"] = parse_urls_from_body(content, content_type)
body["emails"] = parse_email_addresses(content)
body["domains"] = parse_domain_names(content)
body["ip_addresses"] = parse_ipv4_addresses(content)
for key in ["uri", "email", "domain", "ip"]:
body.pop(key, None)
return body
@safe
def normalize_bodies(parsed: dict) -> dict:
bodies = parsed.get("body", [])
parsed["bodies"] = [_normalize_body(body) for body in bodies]
parsed.pop("body", None)
return parsed
@safe
def normalize_attachments(parsed: dict) -> dict:
# change "attachment" to "attachments"
attachments = parsed.get("attachment", [])
non_inline_forward_attachments = []
for attachment in attachments:
if not is_inline_forward_attachment(attachment):
non_inline_forward_attachments.append(attachment)
parsed["attachments"] = non_inline_forward_attachments
parsed.pop("attachment", None)
return parsed
@safe
def transform(parsed: dict) -> schemas.Eml:
return schemas.Eml.model_validate(parsed)
class EmlFactory(AbstractFactory):
@classmethod
def call(cls, data: bytes) -> schemas.Eml:
result: ResultE[schemas.Eml] = flow(
to_eml(data),
bind(parse),
bind(normalize_attachments),
bind(normalize_bodies),
bind(normalize_header),
bind(transform),
)
return result.alt(raise_exception).unwrap()