Content:MirLua/Examples/database

From Miranda NG
Jump to: navigation, search

An Msg_Export analogue: local db = require('m_database')

m.HookEvent("DB/Event/Added", function(w, l)

 local hContact = tonumber(w)
 -- note that path to file should be exists
 local path = m.Parse('%miranda_userdata%\\History\\')
   .. db.GetContactInfo(hContact, 'Uid')
   .. '.log'
 local contactName = db.GetContactInfo(hContact, 'DisplayName')
 local message = GetMessage(tonumber(l), contactName)
 print(message)
 if message then
   local file = io.open(path, 'a+')
   if file then
     file:write(message)
     file:close()
     print('ok')
   end
 end

end)

function GetMessage(hDbEvent, contactName)

 local event = DBEVENTINFO(hDbEvent)
 if event.Type == 0 then
   local isSent = event.Flags & 2 == 2
   local nick = isSent and 'me' or contactName
   local date = os.date("%d.%m.%Y %H:%M:%S", event.Timestamp)
   local text = toutf8(event.Blob)
   return string.interpolate('{1} {2}:\t{3}\n', nick, date, text)
 end
 return nil

end

function toutf8(bytes)

 local bytearr = {}
 for i = 1, #bytes do
   local v = bytes[i]
   local utf8byte = v < 0 and (0xff + v + 1) or v
   table.insert(bytearr, string.char(utf8byte))
 end
 return table.concat(bytearr)

end