mime.lua 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. -----------------------------------------------------------------------------
  2. -- MIME support for the Lua language.
  3. -- Author: Diego Nehab
  4. -- Conforming to RFCs 2045-2049
  5. -----------------------------------------------------------------------------
  6. -----------------------------------------------------------------------------
  7. -- Declare module and import dependencies
  8. -----------------------------------------------------------------------------
  9. local base = _G
  10. local ltn12 = require("ltn12")
  11. local mime = require("mime.core")
  12. local string = require("string")
  13. local _M = mime
  14. -- encode, decode and wrap algorithm tables
  15. local encodet, decodet, wrapt = {},{},{}
  16. _M.encodet = encodet
  17. _M.decodet = decodet
  18. _M.wrapt = wrapt
  19. -- creates a function that chooses a filter by name from a given table
  20. local function choose(table)
  21. return function(name, opt1, opt2)
  22. if base.type(name) ~= "string" then
  23. name, opt1, opt2 = "default", name, opt1
  24. end
  25. local f = table[name or "nil"]
  26. if not f then
  27. base.error("unknown key (" .. base.tostring(name) .. ")", 3)
  28. else return f(opt1, opt2) end
  29. end
  30. end
  31. -- define the encoding filters
  32. encodet['base64'] = function()
  33. return ltn12.filter.cycle(_M.b64, "")
  34. end
  35. encodet['quoted-printable'] = function(mode)
  36. return ltn12.filter.cycle(_M.qp, "",
  37. (mode == "binary") and "=0D=0A" or "\r\n")
  38. end
  39. -- define the decoding filters
  40. decodet['base64'] = function()
  41. return ltn12.filter.cycle(_M.unb64, "")
  42. end
  43. decodet['quoted-printable'] = function()
  44. return ltn12.filter.cycle(_M.unqp, "")
  45. end
  46. local function format(chunk)
  47. if chunk then
  48. if chunk == "" then return "''"
  49. else return string.len(chunk) end
  50. else return "nil" end
  51. end
  52. -- define the line-wrap filters
  53. wrapt['text'] = function(length)
  54. length = length or 76
  55. return ltn12.filter.cycle(_M.wrp, length, length)
  56. end
  57. wrapt['base64'] = wrapt['text']
  58. wrapt['default'] = wrapt['text']
  59. wrapt['quoted-printable'] = function()
  60. return ltn12.filter.cycle(_M.qpwrp, 76, 76)
  61. end
  62. -- function that choose the encoding, decoding or wrap algorithm
  63. _M.encode = choose(encodet)
  64. _M.decode = choose(decodet)
  65. _M.wrap = choose(wrapt)
  66. -- define the end-of-line normalization filter
  67. function _M.normalize(marker)
  68. return ltn12.filter.cycle(_M.eol, 0, marker)
  69. end
  70. -- high level stuffing filter
  71. function _M.stuff()
  72. return ltn12.filter.cycle(_M.dot, 2)
  73. end
  74. return _M