summaryrefslogtreecommitdiffstats
path: root/lua/inbox/indexers/notmuch.lua
blob: 5b3e48c2968e03235354dff8c0da913b3bf38bb4 (plain)
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
local Job = require("plenary.job")
local Path = require("plenary.path")
local utils = require("inbox.utils")

---@class inbox.Indexer.Notmuch.Config
local default_config = {
	database_dir = Path:new(vim.env.XDG_DATA_HOME, "mail").filename,
	map_tag_signs = {},
}

---@class inbox.Indexer.Notmuch: inbox.Indexer, inbox.Indexer.Notmuch.Config
---@field _cache table<string, inbox.Notmuch.Entry>
---@field cache? fun(id: string): inbox.Notmuch.Entry?
---@field flatten_parts? fun(part: inbox.EntryPart, parts: inbox.EntryPart[]?): inbox.EntryPart[]
---@field show_id? fun(id: string): inbox.Notmuch.Entry
---@field parse_tags? fun(tags: string[]): string[]
---@field summarize? fun(item: inbox.Notmuch.SearchResult): inbox.Summary

---@class inbox.Notmuch.SearchResult
---@field authors string | string[]
---@field date_relative string
---@field matched integer
---@field query string[]
---@field subject string | string[]
---@field tags string[]
---@field thread integer
---@field timestamp integer
---@field total integer

---@class inbox.Notmuch.Entry
---@field id string
---@field filename string[]
---@field timestamp integer
---@field date_relative string?
---@field tags string[]
---@field duplicate integer
---@field body inbox.EntryPart[]
---@field crypto table
---@field headers inbox.Headers
---@field parts  inbox.EntryPart

---@type inbox.Indexer.Notmuch
local M = {
	_cache = {},
}

function M.cache(id)
	if M._cache[id] == nil then
		M._cache[id] = M.show_id(id)
	end

	return M._cache[id]
end

function M.available()
	return vim.fn.executable("notmuch") == 1
end

function M.index(maildir, callback, opts)
	opts = opts or {}

	local json = ""
	local job = Job:new({
		command = "notmuch",
		args = { "search", "--format=json" },
		on_stdout = vim.schedule_wrap(function(_, stdout)
			json = json .. stdout
		end),
		on_exit = vim.schedule_wrap(function()
			---@type inbox.Notmuch.SearchResult[]
			local results = utils.json_decode(json)

			---@type inbox.Summary[]
			local entries = {}
			local ids = {}
			local signs = {}

			for lnum, result in ipairs(results) do
				ids[lnum] = (result.query[1]:gsub("^id:", ""))
				entries[lnum] = M.summarize(result)
				for _, sign in pairs(M.parse_tags(result.tags)) do
					table.insert(signs, { sign, lnum })
				end
			end

			callback(ids, entries, signs)
		end),
	})

	local folder = Path:new(maildir):make_relative(M.database_dir)
	table.insert(job.args, ("folder:%s"):format(folder))

	-- TODO: handle different operators i.e. "not", "or", etc.
	for name, value in pairs(opts) do
		table.insert(job.args, "and")
		table.insert(job.args, ("%s:%s"):format(name, value))
	end

	job:start()
end

---@private
---@param tags string[]
---@return string[] parsed tags
function M.parse_tags(tags)
	local signs = {}
	for _, tag in ipairs(tags) do
		if M.map_tag_signs[tag] ~= nil then
			table.insert(signs, M.map_tag_signs[tag])
		else
			table.insert(signs, tag)
		end
	end
	return signs
end

---@private
---@param item inbox.Notmuch.SearchResult
---@return inbox.Summary summary
function M.summarize(item)
	local date = item.date_relative

	local from
	if type(item.authors) == "table" then
		from = item.authors[1] --[[@as string]]
	else
		from = item.authors --[[@as string]]
	end

	local subject
	if type(item.subject) == "table" then
		subject = item.subject[1] --[[@as string]]
	else
		subject = item.subject --[[@as string]]
	end
	subject = subject:gsub("\r?\n", " ")

	return {
		date,
		from,
		subject,
	}
end

---@private
---@param id string
---@return inbox.Notmuch.Entry?
function M.show_id(id)
	if id == nil then
		vim.notify(("Failed to find entry with id: '%s'"):format(id), vim.log.levels.ERROR)
		return nil
	end

	local job = Job:new({
		command = "notmuch",
		args = { "show", "--format=json", ("id:%s"):format(id) },
	})

	local stdout = job:sync()

	local entry = utils.json_decode(table.concat(stdout, "\n"))
	while not vim.tbl_isempty(entry) and vim.tbl_islist(entry) do
		entry = entry[1] --[[@as inbox.Notmuch.Entry]]
	end

	entry.tags = M.parse_tags(entry.tags)
	entry.parts = M.flatten_parts(entry.body[1])

	return entry
end

---@param id string
---@return inbox.Entry?
function M.get_entry(id)
	local entry = M.cache(id)
	if entry == nil then
		return nil
	end

	local parts = vim.tbl_map(function(part)
		return part["content-type"]
	end, entry.parts)

	---@type inbox.Entry
	return {
		id = entry.id,
		timestamp = entry.timestamp,
		filename = entry.filename[1],
		tags = entry.tags,
		parts = parts,
		headers = entry.headers,
	}
end

function M.flatten_parts(part, parts)
	if parts == nil then
		parts = {}
	end

	if type(part.content) == "table" then
		for _, p in
			pairs(part.content --[[@as inbox.EntryPart[] ]])
		do
			parts = M.flatten_parts(p, parts)
		end
	else
		table.insert(parts, part)
	end

	return parts
end

function M.get_part(id, content_type, callback)
	local entry = M.cache(id)

	if entry == nil then
		vim.notify(("Failed to get entry with id: %s"):format(id), vim.log.levels.ERROR)
		return nil
	end

	---@type inbox.EntryPart?
	local part
	if content_type == nil then
		for _, p in pairs(entry.parts) do
			if part == nil or p.id < part.id then
				part = p
			end
		end
	else
		for _, p in pairs(entry.parts) do
			if p["content-type"] ~= content_type then
				part = p
				break
			end
		end
	end

	if part == nil then
		vim.notify(("Failed to find message part for entry id: %s"):format(id), vim.log.levels.ERROR)
		return nil
	end

	local stdout = {}
	local job = Job:new({
		command = "notmuch",
		args = { "show", ("--part=%s"):format(part.id), ("id:%s"):format(entry.id) },
		on_stdout = vim.schedule_wrap(function(_, data)
			table.insert(stdout, data)
		end),
		on_exit = vim.schedule_wrap(function()
			callback(part["content-type"], stdout)
		end),
	})

	job:start()
end

---@param opts inbox.Indexer.Notmuch.Config
function M.setup(opts)
	local config = vim.tbl_deep_extend("keep", opts or {}, default_config)

	for k, v in pairs(config) do
		M[k] = v
	end
end

return M