Content:MirLua/Examples/database

From Miranda NG
< Content:MirLua/Examples
Revision as of 00:41, 27 September 2017 by Unsane (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

An Message 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