if SERVER then
-- Pool network strings
util.AddNetworkString("PlayYouTubeAudio")
end
local function APIRequest(videoID, callback)
-- Build API URL
local url = {}
url[1] = "https://youtubeinmp3.com/fetch/?format=JSON&video="
url[2] = "https://www.youtube.com/watch?v="
url[3] = videoID
url = table.concat(url)
http.Fetch(url, function(body, len, headers, code)
if code ~= 200 then
return callback(false, "API request failed")
end
local json = util.JSONToTable(body)
if not json then
local shortenerUrl = "http://tny.im/yourls-api.php"
local shortenerParams = {
action = "shorturl",
url = url,
format = "json"
}
http.Post(shortenerUrl, shortenerParams, function(body, len, headers, code)
-- Beg that the URL shortener doesn't fail!
return callback(false, "Go to " .. util.JSONToTable(body).shorturl .. ", click \"Convert & Download MP3\" then try requesting this song again.")
end)
elseif json.error then
return callback(false, json.error)
else
return callback(true, json)
end
end)
end
if CLIENT then
-- This function plays audio from URL
local station
local function play(url)
if IsValid(station) then station:Stop() end
sound.PlayURL(url, "", function(_station)
station = _station
if IsValid(station) then
station:Play()
end
end)
end
-- Net hook
net.Receive("PlayYouTubeAudio", function()
APIRequest(net.ReadString(), function(ok, data)
if not ok then
print(data)
return false
end
play(data.link)
end)
end)
end
-- Create ULX command
local CATEGORY_NAME = "YouTube"
function ulx.youtube(calling_ply, videoID)
if string.len(videoID) ~= 11 then
ULib.tsayError(calling_ply, "Invalid video ID. Example: !youtube Y6ljFaKRTrI")
return false
end
APIRequest(videoID, function(ok, data)
if not ok then
ULib.tsayError(calling_ply, data)
return false
end
net.Start("PlayYouTubeAudio")
net.WriteString(videoID)
net.Broadcast()
ulx.fancyLogAdmin(calling_ply, "#A played song: #s", data.title)
end)
end
local youtube = ulx.command(CATEGORY_NAME, "ulx youtube", ulx.youtube, "!youtube")
youtube:addParam{type=ULib.cmds.StringArg, hint="YouTube video ID", ULib.cmds.takeRestOfLine}
youtube:defaultAccess(ULib.ACCESS_ADMIN)
youtube:help("Plays audio from a YouTube video.")