-------------------------------------------------------------------------------- -- Title: MIME.lua -- Description: Like a square peg in a round hole -- Author: Raphaël Szwarc http://alt.textdrive.com/lua/ -- Creation Date: February 1, 2005 -- Legal: Copyright (C) 2005 Raphaël Szwarc -------------------------------------------------------------------------------- -- import dependencies require( "LUObject" ) require( "LUMap" ) -- extend the super class local thisClass, superClass = LUObject.extend( LUObject ) -- factory class method, this is where all the instance methods are implemented as closures thisClass.new = function() return nil end -- class method thisClass.trim = function( aValue ) return string.gsub( aValue, "^%s*(.-)%s*$", "%1" ) end -- class method -- as per http://lua-users.org/wiki/MailBoxParsing thisClass.mimeHeaders = function( aContent ) if ( ( aContent ~= nil ) and ( string.len( aContent ) > 1 ) ) then local someHeaders = {} local startIndex, endIndex = 1, 1 aContent = "\r\n" .. aContent .. "$$$:\r\n" while true do endIndex = string.find( aContent, "\r\n%S-:", startIndex + 1 ) if ( endIndex ~= nil ) then local _, _, aKey, aValue = string.find( string.sub( aContent, startIndex + 1, endIndex - 1 ), "(%S-):(.*)" ) if ( ( aKey ~= nil ) and ( aValue ~= nil ) ) then aValue = string.gsub( aValue or "", "\r\n", "\n" ) aValue = string.gsub( aValue, "\n%s*", " " ) aKey = string.lower( aKey ) aValue = thisClass.trim( aValue ) aKey = thisClass.trim( aKey ) if ( someHeaders[ aKey ] ~= nil ) then someHeaders[ aKey ] = someHeaders[ aKey ] .. ", " .. aValue else someHeaders[ aKey ] = aValue end end else break end startIndex, endIndex = endIndex, startIndex end someHeaders[ "$$$" ] = nil return LUMap.new().putAll( someHeaders ) end return LUMap.new() end -- class method -- as per http://lua-users.org/wiki/MailBoxParsing thisClass.toMIME = function( aContent ) if ( ( aContent ~= nil ) and ( string.len( aContent ) > 1 ) ) then do local _, _, anHeaderContent, aBodyContent = string.find( aContent, "^(.-\r\n)\r\n(.*)" ) aBodyContent = aBodyContent or aContent aBodyContent = thisClass.trim( aBodyContent ) return thisClass.mimeHeaders( anHeaderContent ), aBodyContent end end return LUMap.new(), "" end -- class method thisClass.toString = function( someHeaders, aContent ) local aSeparator = "\r\n" local aBuffer = {} if ( ( someHeaders ~= nil ) and ( someHeaders.size() > 0 ) ) then for aKey, aValue in someHeaders.content() do aKey = thisClass.trim( string.lower( aKey ) ) aValue = thisClass.trim( aValue ) table.insert( aBuffer, aKey .. ": " .. aValue ) end end table.insert( aBuffer, "" ) table.insert( aBuffer, aContent or "" ) return table.concat( aBuffer, aSeparator ) end -- define the class name MIME = thisClass return MIME