summaryrefslogtreecommitdiffstats
path: root/lua/inbox/indexers/notmuch.lua
blob: a05c112fce2e364704ecbf837c1e4f8c2ebaf8cf (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
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: inbox.Entry
---@field filename string[]
---@field date_relative string?
---@field duplicate integer
---@field body inbox.EntryPart[]
---@field crypto table

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

---@private
---@param id string
---@return inbox.Notmuch.Entry | nil
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 job = Job:new({
		command = "notmuch",
		args = { "search", "--format=json" },
		on_exit = vim.schedule_wrap(function(j)
			---@type inbox.Notmuch.SearchResult[]
			local results = utils.json_decode(table.concat(j:result(), "\n"))

			---@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", "--include-html", ("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 = {}
	for _, part in pairs(M.flatten_parts(entry.body[1])) do
		entry.parts[part["content-type"]] = part
	end

	return entry
end

function M.get_entry(id)
	return M.cache(id)
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

---@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