-- 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://vimeo.com/api/v2'

function get_vimeo_data (vimeo_code)
  local url = BASE_URL..'/video/'..vimeo_code..'.json'
  local res,code  = http.request(url)
  if code ~= 200 then return "HTTP FEHLER" end
  local data = json:decode(res)
  return data
end

function send_vimeo_data(data, receiver)
  local title = data[1].title
  local uploader = data[1].user_name
  local viewCount = data[1].stats_number_of_plays
  totalseconds = data[1].duration
  
  -- convert s to mm:ss
  seconds = totalseconds % 60
  minutes = math.floor(totalseconds / 60)
  minutes = minutes % 60
  local duration = string.format("%02d:%02d",  minutes, seconds)
	
  local text = title..'\n(Hochgeladen von: '..uploader..', '..duration..' Minuten, '..viewCount..' mal angesehen)\n'
  local image = download_to_file(data[1].thumbnail_large)
  if string.ends(image, ".webp") then
  send_document(receiver, image, ok_cb, false)
  else
  send_photo(receiver, image, ok_cb, false)
  end
  send_msg(receiver, text, ok_cb, false)
end

function run(msg, matches)
  local vimeo_code = matches[1]
  local data = get_vimeo_data(vimeo_code)
  local receiver = get_receiver(msg)
  send_vimeo_data(data, receiver)
end

return {
  description = "Sendet Vimeo-Info.", 
  usage = {"vimeo.com Link"},
  patterns = {"vimeo.com/([A-Za-z0-9-_-]+)"},
  run = run 
}

end
