-- This is a proprietary plugin, property of Andreas Bielawski, (c) 2015 <andi (dot) b (at) outlook (dot) de>
-- DO NOT USE WITHOUT PERMISSION

do

local BASE_URL = 'https://upload.gfycat.com/transcode'

function get_videotogif_data (vidtogif_code)
  local url = BASE_URL..'?fetchUrl='..vidtogif_code
  local res,code  = https.request(url)
  if code ~= 200 then return "HTTP-FEHLER" end
  local data = json:decode(res)
  return data
end

function send_videotogif(data, receiver)
  if data.gifUrl == nil then
    local error_desc = data.error
	local text = 'Ein Fehler ist aufgetreten: '..error_desc
	send_msg(receiver, text, ok_cb, false)
  else
    local gif_url = data.gifUrl
    local file = download_to_file(gif_url)
    local cb_extra = {file_path=file}
    send_document(receiver, file, rmtmp_cb, cb_extra)
  end
end

function run(msg, matches)
  local vidtogif_code = matches[1]
  local data = get_videotogif_data(vidtogif_code)
  local receiver = get_receiver(msg)
  send_videotogif(data, receiver)
end

return {
  description = "Konvertiert Video in GIF", 
  usage = "/vidtogif [URL]: Konvertiert Video in GIF",
  patterns = {"^/vidtogif (.*)$"},
  run = run 
}

end