Debian Codegraph @

lualib/lua_content/init.lua

raw
1 --[[
2 Copyright (c) 2022, Vsevolod Stakhov <[email protected]>
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 ]]--
16
17 --[[[
18 -- @module lua_content
19 -- This module contains content processing logic
20 --]]
21
22
23 local exports = {}
24 local N = "lua_content"
25 local lua_util = require "lua_util"
26
27 local content_modules = {
28 ical = {
29 mime_type = { "text/calendar", "application/calendar" },
30 module = require "lua_content/ical",
31 extensions = { 'ics' },
32 output = "text"
33 },
34 vcf = {
35 mime_type = { "text/vcard", "application/vcard" },
36 module = require "lua_content/vcard",
37 extensions = { 'vcf' },
38 output = "text"
39 },
40 pdf = {
41 mime_type = "application/pdf",
42 module = require "lua_content/pdf",
43 extensions = { 'pdf' },
44 output = "table"
45 },
46 }
47
48 local modules_by_mime_type
49 local modules_by_extension
50
51 local function init()
52 modules_by_mime_type = {}
53 modules_by_extension = {}
54 for k, v in pairs(content_modules) do
55 if v.mime_type then
56 if type(v.mime_type) == 'table' then
57 for _, mt in ipairs(v.mime_type) do
58 modules_by_mime_type[mt] = { k, v }
59 end
60 else
61 modules_by_mime_type[v.mime_type] = { k, v }
62 end
63
64 end
65 if v.extensions then
66 for _, ext in ipairs(v.extensions) do
67 modules_by_extension[ext] = { k, v }
68 end
69 end
70 end
71 end
72
73 exports.maybe_process_mime_part = function(part, task)
74 if not modules_by_mime_type then
75 init()
76 end
77
78 local ctype, csubtype = part:get_type()
79 local mt = string.format("%s/%s", ctype or 'application',
80 csubtype or 'octet-stream')
81 local pair = modules_by_mime_type[mt]
82
83 if not pair then
84 local ext = part:get_detected_ext()
85
86 if ext then
87 pair = modules_by_extension[ext]
88 end
89 end
90
91 if pair then
92 lua_util.debugm(N, task, "found known content of type %s: %s",
93 mt, pair[1])
94
95 local data = pair[2].module.process(part:get_content(), part, task)
96
97 if data then
98 lua_util.debugm(N, task, "extracted content from %s: %s type",
99 pair[1], type(data))
100 part:set_specific(data)
101 else
102 lua_util.debugm(N, task, "failed to extract anything from %s",
103 pair[1])
104 end
105 end
106
107 end
108
109 return exports