add additional fields for history database
Some checks failed
Luacheck / luacheck (push) Failing after 2m27s

This commit is contained in:
sudacode 2025-02-13 18:53:00 -08:00
parent 68875120c5
commit 3f7a5fb183
Signed by: sudacode
SSH Key Fingerprint: SHA256:lT5C2bB398DcX6daCF/gYFNSTK3y+Du3oTGUnYzfTEw

View File

@ -29,7 +29,7 @@ local marked_index = nil
local current_video = nil local current_video = nil
local destroyer = nil local destroyer = nil
local timeout local timeout
local debug = false local debug = true
local options = { local options = {
add_to_queue = "ctrl+a", add_to_queue = "ctrl+a",
@ -101,11 +101,11 @@ local style = {
cursor = "{\\c&" .. colors.cursor .. "&" .. notransparent .. "}", cursor = "{\\c&" .. colors.cursor .. "&" .. notransparent .. "}",
marked = "{\\c&" .. colors.marked .. "&" .. notransparent .. "}", marked = "{\\c&" .. colors.marked .. "&" .. notransparent .. "}",
reset = "{\\c&" .. colors.text .. "&" .. sortoftransparent .. "}", reset = "{\\c&" .. colors.text .. "&" .. sortoftransparent .. "}",
header = "{\\fn" .. options.font_name .. "\\fs" .. options.font_size * 1.5 .. header = "{\\fn" ..
"\\u1\\b1\\c&" .. colors.header .. "&" .. notransparent .. "}", options.font_name .. "\\fs" .. options.font_size * 1.5 .. "\\u1\\b1\\c&" .. colors.header .. "&" ..
notransparent .. "}",
hover = "{\\c&" .. colors.hover .. "&" .. semitransparent .. "}", hover = "{\\c&" .. colors.hover .. "&" .. semitransparent .. "}",
font = "{\\fn" .. options.font_name .. "\\fs" .. options.font_size .. "{" .. font = "{\\fn" .. options.font_name .. "\\fs" .. options.font_size .. "{" .. sortoftransparent .. "}"
sortoftransparent .. "}"
} }
-- }}} -- }}}
@ -128,42 +128,74 @@ end
--- @param use_ellipsis? boolean Whether to add "..." (defaults to true) --- @param use_ellipsis? boolean Whether to add "..." (defaults to true)
--- @return string truncated The truncated string --- @return string truncated The truncated string
local function truncate_string(str, length, use_ellipsis) local function truncate_string(str, length, use_ellipsis)
if use_ellipsis == nil then use_ellipsis = true end if use_ellipsis == nil then
if #str <= length then return str end use_ellipsis = true
end
if #str <= length then
return str
end
local truncated = string.sub(str, 1, length) local truncated = string.sub(str, 1, length)
if use_ellipsis then if use_ellipsis then
-- Remove last 3 chars to make room for ellipsis -- Remove last 3 chars to make room for ellipsis
truncated = string.sub(truncated, 1, length - 3) .. "..." truncated = string.sub(truncated, 1, length - 3) .. "..." .. '"'
end end
return truncated return truncated
end end
--- return true if the input is false, nil, empty, or 0 --- return true if the input is null, empty, or 0
--- @param s string - the input to check for nullity --- @param s any - the input to check for nullity
--- @return boolean - true if the input is null, false otherwise --- @return boolean - true if the input is null, false otherwise
local function isnull(s) local function isnull(s)
if not s or s == nil or s == "" or s == 0 or s == {} then -- Handle nil case
if s == nil then
return true return true
else
return false
end end
-- Handle empty string case
if type(s) == "string" and s:match("^%s*$") then
return true
end
-- Handle numeric zero case
if type(s) == "number" and s == 0 then
return true
end
-- Handle empty table case
if type(s) == "table" and next(s) == nil then
return true
end
-- Handle false boolean case
if type(s) == "boolean" and not s then
return true
end
return false
end end
-- remove single quotes, newlines, and carriage returns from a string -- remove single quotes, newlines, and carriage returns from a string
local function strip(s) return string.gsub(s, "['\n\r]", "") end local function strip(s)
return string.gsub(s, "['\n\r]", "")
end
-- print a message to the OSD -- print a message to the OSD
---@param message string - the message to print ---@param message string - the message to print
---@param duration number - the duration to display the message ---@param duration number - the duration to display the message
---@param s string - the style to use for the message ---@param s string - the style to use for the message
local function print_osd_message(message, duration, s) local function print_osd_message(message, duration, s)
if s == style.error and not options.show_errors then return end if s == style.error and not options.show_errors then
return
end
destroy() destroy()
if s == nil then s = style.font .. "{" .. notransparent .. "}" end if s == nil then
if duration == nil then duration = MSG_DURATION end s = style.font .. "{" .. notransparent .. "}"
mp.osd_message(styleOn .. s .. message .. style.reset .. styleOff .. "\n", end
duration) if duration == nil then
duration = MSG_DURATION
end
mp.osd_message(styleOn .. s .. message .. style.reset .. styleOff .. "\n", duration)
end end
---returns true if the provided path exists and is a file ---returns true if the provided path exists and is a file
@ -174,7 +206,9 @@ local function is_file(filepath)
if debug and type(result) == "table" then if debug and type(result) == "table" then
print("IS_FILE() check: " .. tostring(result.is_file)) print("IS_FILE() check: " .. tostring(result.is_file))
end end
if result == nil or type(result) ~= "table" then return false end if result == nil or type(result) ~= "table" then
return false
end
return true return true
end end
@ -182,7 +216,9 @@ end
---@param filepath string - the path to extract the filename from ---@param filepath string - the path to extract the filename from
---@return string | nil - the filename ---@return string | nil - the filename
local function split_path(filepath) local function split_path(filepath)
if is_file(filepath) then return utils.split_path(filepath) end if is_file(filepath) then
return utils.split_path(filepath)
end
end end
--- returns the expanded path of a file. eg. ~/file.txt -> /home/user/file.txt --- returns the expanded path of a file. eg. ~/file.txt -> /home/user/file.txt
@ -190,7 +226,9 @@ end
--- @return string - the expanded path --- @return string - the expanded path
local function expanduser(path) local function expanduser(path)
-- remove trailing slash if it exists -- remove trailing slash if it exists
if string.sub(path, -1) == "/" then path = string.sub(path, 1, -2) end if string.sub(path, -1) == "/" then
path = string.sub(path, 1, -2)
end
if path:sub(1, 1) == "~" then if path:sub(1, 1) == "~" then
local home = os.getenv("HOME") local home = os.getenv("HOME")
if home then if home then
@ -235,10 +273,45 @@ local function _print_internal_playlist()
end end
--- Helper function to build the OSD row for the queue --- Helper function to build the OSD row for the queue
--- @param prefix string - the prefix to add to the row
--- @param s string - the style to apply to the row
--- @param i number - the index of the row
--- @param title string - the title of the video
--- @param channel_name string - the name of the channel
--- @return string - the OSD row
local function _build_osd_row(prefix, s, i, title, channel_name) local function _build_osd_row(prefix, s, i, title, channel_name)
return prefix .. s .. i .. ". " .. title .. " - (" .. channel_name .. ")" return prefix .. s .. i .. ". " .. title .. " - (" .. channel_name .. ")"
end end
--- Helper function to determine display range for queue items
--- @param queue_length number Total number of items in queue
--- @param selected number Currently selected index
--- @param limit number Maximum items to display
--- @return number, number start and end indices
local function _get_display_range(queue_length, selected, limit)
local half_limit = math.floor(limit / 2)
local start_index = selected <= half_limit and 1 or selected - half_limit
local end_index = math.min(start_index + limit - 1, queue_length)
return start_index, end_index
end
--- Helper function to get the style for a queue item
--- @param i number Current item index
--- @param current number Currently playing index
--- @param selected number Selected index
--- @return string Style to apply
local function _get_item_style(i, current, selected)
if i == current and i == selected then
return style.hover_selected
elseif i == current then
return style.selected
elseif i == selected then
return style.hover
end
return style.reset
end
--- Toggle queue visibility --- Toggle queue visibility
local function toggle_print() local function toggle_print()
if destroyer ~= nil then if destroyer ~= nil then
@ -265,7 +338,9 @@ end
--- @return table - the split command as a table --- @return table - the split command as a table
local function _split_command(cmd) local function _split_command(cmd)
local components = {} local components = {}
for arg in cmd:gmatch("%S+") do table.insert(components, arg) end for arg in cmd:gmatch("%S+") do
table.insert(components, arg)
end
_remove_command_quotes(components) _remove_command_quotes(components)
return components return components
end end
@ -274,16 +349,19 @@ end
--- @param v table - the video to add to the history database --- @param v table - the video to add to the history database
--- @return boolean - true if the video was added successfully, false otherwise --- @return boolean - true if the video was added successfully, false otherwise
function YouTubeQueue._add_to_history_db(v) function YouTubeQueue._add_to_history_db(v)
if not options.use_history_db then return false end if not options.use_history_db then
local url = options.backend_host .. ":" .. options.backend_port .. return false
"/add_video" end
local command = { local url = options.backend_host .. ":" .. options.backend_port .. "/add_video"
"curl", "-X", "POST", url, "-H", "Content-Type: application/json", "-d", local command = { "curl", "-X", "POST", url, "-H", "Content-Type: application/json", "-d",
string.format( string.format(
'{"video_url": "%s", "title": "%s", "channel_url": "%s", "channel_name": "%s"}', '{"video_url": "%s", "video_name": "%s", "channel_url": "%s", "channel_name": "%s", "category": "%s", "view_count": "%s", "upload_date": "%s", "thumbnail_url": "%s", "subscribers": "%s"}',
v.video_url, v.title, v.channel_url, v.channel_name v.video_url, v.title, v.channel_url, v.channel_name, v.category, v.view_count, v.upload_date, v
) .thumbnail_url, v.subscribers) }
} if debug then
print("Adding video to history")
-- print("Command: " .. table.concat(command, " "))
end
mp.command_native_async({ mp.command_native_async({
name = "subprocess", name = "subprocess",
playback_only = false, playback_only = false,
@ -291,8 +369,7 @@ function YouTubeQueue._add_to_history_db(v)
args = command args = command
}, function(success, _, err) }, function(success, _, err)
if not success then if not success then
print_osd_message("Failed to send video data to backend: " .. err, print_osd_message("Failed to send video data to backend: " .. err, MSG_DURATION, style.error)
MSG_DURATION, style.error)
return false return false
end end
end) end)
@ -303,7 +380,9 @@ end
--- @param start_index number - the index to start from --- @param start_index number - the index to start from
--- @return table | nil - a table of URLs --- @return table | nil - a table of URLs
function YouTubeQueue._get_urls(start_index) function YouTubeQueue._get_urls(start_index)
if start_index < 0 or start_index > #video_queue then return nil end if start_index < 0 or start_index > #video_queue then
return nil
end
local urls = {} local urls = {}
for i = start_index + 1, #video_queue do for i = start_index + 1, #video_queue do
table.insert(urls, video_queue[i].video_url) table.insert(urls, video_queue[i].video_url)
@ -316,12 +395,23 @@ end
--- @param val any - json value --- @param val any - json value
--- @return string | nil - the json string --- @return string | nil - the json string
function YouTubeQueue._convert_to_json(key, val) function YouTubeQueue._convert_to_json(key, val)
if val == nil then return end if val == nil then
if type(val) ~= "table" then return "{" .. key .. ":" .. val .. "}" end return
end
if type(val) ~= "table" then
-- For non-table values, properly quote strings and format numbers
if type(val) == "string" then
return string.format('{"%s": "%s"}', key, val)
else
return string.format('{"%s": %s}', key, tostring(val))
end
end
local json = string.format('{"%s": [', key) local json = string.format('{"%s": [', key)
for i, v in ipairs(val) do for i, v in ipairs(val) do
json = json .. '"' .. v .. '"' json = json .. '"' .. v .. '"'
if i < #val then json = json .. ", " end if i < #val then
json = json .. ", "
end
end end
json = json .. "]}" json = json .. "]}"
return json return json
@ -331,22 +421,22 @@ end
--- @param idx number - the index to start saving from --- @param idx number - the index to start saving from
--- @return boolean - true if the queue was saved successfully, false otherwise --- @return boolean - true if the queue was saved successfully, false otherwise
function YouTubeQueue.save_queue(idx) function YouTubeQueue.save_queue(idx)
if not options.use_history_db then return false end if not options.use_history_db then
if idx == nil then idx = index end
local url = options.backend_host .. ":" .. options.backend_port ..
"/save_queue"
local data = YouTubeQueue._convert_to_json("urls",
YouTubeQueue._get_urls(idx + 1))
if data == nil or data == '{"urls": []}' then
print_osd_message("Failed to save queue: No videos remaining in queue",
MSG_DURATION, style.error)
return false return false
end end
if debug then print("Data: " .. data) end if idx == nil then
local command = { idx = index
"curl", "-X", "POST", url, "-H", "Content-Type: application/json", "-d", end
data local url = options.backend_host .. ":" .. options.backend_port .. "/save_queue"
} local data = YouTubeQueue._convert_to_json("urls", YouTubeQueue._get_urls(idx + 1))
if data == nil or data == '{"urls": []}' then
print_osd_message("Failed to save queue: No videos remaining in queue", MSG_DURATION, style.error)
return false
end
if debug then
print("Data: " .. data)
end
local command = { "curl", "-X", "POST", url, "-H", "Content-Type: application/json", "-d", data }
if debug then if debug then
print("Saving queue to history") print("Saving queue to history")
print("Command: " .. table.concat(command, " ")) print("Command: " .. table.concat(command, " "))
@ -358,15 +448,15 @@ function YouTubeQueue.save_queue(idx)
args = command args = command
}, function(success, result, err) }, function(success, result, err)
if not success then if not success then
print_osd_message("Failed to save queue: " .. err, MSG_DURATION, print_osd_message("Failed to save queue: " .. err, MSG_DURATION, style.error)
style.error)
return false return false
end end
if debug then print("Status: " .. result.status) end if debug then
print("Status: " .. result.status)
end
if result.status == 0 then if result.status == 0 then
if idx > 1 then if idx > 1 then
print_osd_message("Queue saved to history from index: " .. idx, print_osd_message("Queue saved to history from index: " .. idx, MSG_DURATION)
MSG_DURATION)
else else
print_osd_message("Queue saved to history.", MSG_DURATION) print_osd_message("Queue saved to history.", MSG_DURATION)
end end
@ -377,9 +467,10 @@ end
-- loads the queue from the backend -- loads the queue from the backend
function YouTubeQueue.load_queue() function YouTubeQueue.load_queue()
if not options.use_history_db then return false end if not options.use_history_db then
local url = options.backend_host .. ":" .. options.backend_port .. return false
"/load_queue" end
local url = options.backend_host .. ":" .. options.backend_port .. "/load_queue"
local command = { "curl", "-X", "GET", url } local command = { "curl", "-X", "GET", url }
mp.command_native_async({ mp.command_native_async({
@ -389,8 +480,7 @@ function YouTubeQueue.load_queue()
args = command args = command
}, function(success, result, err) }, function(success, result, err)
if not success then if not success then
print_osd_message("Failed to load queue: " .. err, MSG_DURATION, print_osd_message("Failed to load queue: " .. err, MSG_DURATION, style.error)
style.error)
return false return false
else else
if result.status == 0 then if result.status == 0 then
@ -439,8 +529,7 @@ function YouTubeQueue.get_clipboard_content()
}) })
if res.status ~= 0 then if res.status ~= 0 then
print_osd_message("Failed to get clipboard content", MSG_DURATION, print_osd_message("Failed to get clipboard content", MSG_DURATION, style.error)
style.error)
return nil return nil
end end
@ -450,8 +539,7 @@ function YouTubeQueue.get_clipboard_content()
elseif content:match("^file://") or utils.file_info(content) then elseif content:match("^file://") or utils.file_info(content) then
return content return content
else else
print_osd_message("Clipboard content is not a valid URL or file path", print_osd_message("Clipboard content is not a valid URL or file path", MSG_DURATION, style.error)
MSG_DURATION, style.error)
return nil return nil
end end
end end
@ -465,23 +553,19 @@ function YouTubeQueue.get_video_info(url)
name = "subprocess", name = "subprocess",
playback_only = false, playback_only = false,
capture_stdout = true, capture_stdout = true,
args = { args = { "yt-dlp", "--dump-single-json", "--ignore-config", "--no-warnings", "--skip-download",
"yt-dlp", "--dump-single-json", "--ignore-config", "--no-warnings", "--playlist-items", "1", url }
"--skip-download", "--playlist-items", "1", url
}
}) })
if res.status ~= 0 or isnull(res.stdout) then if res.status ~= 0 or isnull(res.stdout) then
print_osd_message("Failed to get video info (yt-dlp error)", print_osd_message("Failed to get video info (yt-dlp error)", MSG_DURATION, style.error)
MSG_DURATION, style.error)
print("yt-dlp status: " .. res.status) print("yt-dlp status: " .. res.status)
return nil return nil
end end
local data = utils.parse_json(res.stdout) local data = utils.parse_json(res.stdout)
if isnull(data) then if isnull(data) then
print_osd_message("Failed to parse JSON from yt-dlp", MSG_DURATION, print_osd_message("Failed to parse JSON from yt-dlp", MSG_DURATION, style.error)
style.error)
return nil return nil
end end
@ -491,14 +575,13 @@ function YouTubeQueue.get_video_info(url)
title = data.title or "", title = data.title or "",
view_count = data.view_count or "", view_count = data.view_count or "",
upload_date = data.upload_date or "", upload_date = data.upload_date or "",
description = data.description or "" category = data.categories[1] or "",
thumbnail_url = data.thumbnail or "",
subscribers = data.channel_follower_count or ""
} }
if isnull(info.channel_url) or isnull(info.channel_name) or if isnull(info.channel_url) or isnull(info.channel_name) or isnull(info.title) then
isnull(info.title) then print_osd_message("Missing metadata (channel_url, uploader, title) in JSON", MSG_DURATION, style.error)
print_osd_message(
"Missing metadata (channel_url, uploader, title) in JSON",
MSG_DURATION, style.error)
return nil return nil
end end
@ -513,8 +596,7 @@ function YouTubeQueue.print_current_video()
print_osd_message("Playing: " .. current.video_url, 3) print_osd_message("Playing: " .. current.video_url, 3)
else else
if current and current.video_url then if current and current.video_url then
print_osd_message("Playing: " .. current.title .. ' by ' .. print_osd_message("Playing: " .. current.title .. ' by ' .. current.channel_name, 3)
current.channel_name, 3)
end end
end end
end end
@ -535,11 +617,12 @@ function YouTubeQueue.set_video(direction)
elseif (direction == "PREV" or direction == "PREVIOUS") then elseif (direction == "PREV" or direction == "PREVIOUS") then
amt = -1 amt = -1
else else
print_osd_message("Invalid direction: " .. direction, MSG_DURATION, print_osd_message("Invalid direction: " .. direction, MSG_DURATION, style.error)
style.error) return nil
end
if index + amt > #video_queue or index + amt == 0 then
return nil return nil
end end
if index + amt > #video_queue or index + amt == 0 then return nil end
index = index + amt index = index + amt
selected_index = index selected_index = index
current_video = video_queue[index] current_video = video_queue[index]
@ -551,7 +634,9 @@ end
--- @return boolean - true if the video is in the queue, false otherwise --- @return boolean - true if the video is in the queue, false otherwise
function YouTubeQueue.is_in_queue(url) function YouTubeQueue.is_in_queue(url)
for _, v in ipairs(video_queue) do for _, v in ipairs(video_queue) do
if v.video_url == url then return true end if v.video_url == url then
return true
end
end end
return false return false
end end
@ -560,9 +645,15 @@ end
--- @param update_history boolean - whether to update the history database --- @param update_history boolean - whether to update the history database
--- @return number | nil - the index of the currently playing video --- @return number | nil - the index of the currently playing video
function YouTubeQueue.update_current_index(update_history) function YouTubeQueue.update_current_index(update_history)
if debug then print("Updating current index") end if debug then
if #video_queue == 0 then return end print("Updating current index")
if update_history == nil then update_history = false end end
if #video_queue == 0 then
return
end
if update_history == nil then
update_history = false
end
local current_url = mp.get_property("path") local current_url = mp.get_property("path")
for i, v in ipairs(video_queue) do for i, v in ipairs(video_queue) do
if v.video_url == current_url then if v.video_url == current_url then
@ -607,16 +698,19 @@ function YouTubeQueue.reorder_queue(from_index, to_index)
return return
end end
-- Check if the provided indices are within the bounds of the video_queue -- Check if the provided indices are within the bounds of the video_queue
if from_index > 0 and from_index <= #video_queue and to_index > 0 and if from_index > 0 and from_index <= #video_queue and to_index > 0 and to_index <= #video_queue then
to_index <= #video_queue then
-- move the video from the from_index to to_index in the internal playlist. -- move the video from the from_index to to_index in the internal playlist.
-- playlist-move is 0-indexed -- playlist-move is 0-indexed
if from_index < to_index and to_index == #video_queue then if from_index < to_index and to_index == #video_queue then
mp.commandv("playlist-move", from_index - 1, to_index) mp.commandv("playlist-move", from_index - 1, to_index)
if to_index > index then index = index - 1 end if to_index > index then
index = index - 1
end
elseif from_index < to_index then elseif from_index < to_index then
mp.commandv("playlist-move", from_index - 1, to_index) mp.commandv("playlist-move", from_index - 1, to_index)
if to_index > index then index = index - 1 end if to_index > index then
index = index - 1
end
else else
mp.commandv("playlist-move", from_index - 1, to_index - 1) mp.commandv("playlist-move", from_index - 1, to_index - 1)
end end
@ -626,73 +720,50 @@ function YouTubeQueue.reorder_queue(from_index, to_index)
table.remove(video_queue, from_index) table.remove(video_queue, from_index)
table.insert(video_queue, to_index, temp_video) table.insert(video_queue, to_index, temp_video)
else else
print_osd_message("Invalid indices for reordering. No changes made.", print_osd_message("Invalid indices for reordering. No changes made.", MSG_DURATION, style.error)
MSG_DURATION, style.error)
end end
end end
--- Prints the queue to the OSD --- Prints the queue to the OSD
--- @param duration number? Optional duration to display the queue
function YouTubeQueue.print_queue(duration) function YouTubeQueue.print_queue(duration)
-- Reset and prepare OSD
timeout:kill() timeout:kill()
mp.set_osd_ass(0, 0, "") mp.set_osd_ass(0, 0, "")
timeout:resume() timeout:resume()
if #video_queue == 0 then
print_osd_message("No videos in the queue or history.", duration, style.error)
destroyer = destroy
return
end
local ass = assdraw.ass_new() local ass = assdraw.ass_new()
local current_index = index ass:append(style.header .. "MPV-YOUTUBE-QUEUE{\\u0\\b0}" .. style.reset .. style.font .. "\n")
if #video_queue > 0 then
local half_limit = math.floor(options.display_limit / 2)
local start_index, end_index
if selected_index <= half_limit then local start_index, end_index = _get_display_range(
start_index = 1 #video_queue,
else selected_index,
start_index = selected_index - half_limit options.display_limit
end )
end_index = start_index + options.display_limit - 1 for i = start_index, end_index do
if end_index > #video_queue then end_index = #video_queue end local video = video_queue[i]
if not video then break end
ass:append( local prefix = (i == selected_index)
style.header .. "MPV-YOUTUBE-QUEUE{\\u0\\b0}" .. style.reset .. and style.cursor .. options.cursor_icon .. "\\h" .. style.reset
style.font .. "\n") or "\\h\\h\\h"
local message local item_style = _get_item_style(i, index, selected_index)
for i = start_index, end_index do local message = _build_osd_row(prefix, item_style, i, video.title, video.channel_name)
local prefix = (i == selected_index) and style.cursor .. .. style.reset
options.cursor_icon .. "\\h" .. style.reset or if i == marked_index then
"\\h\\h\\h" message = message .. " " .. style.marked .. options.marked_icon .. style.reset
if i == current_index and i == selected_index then
message = _build_osd_row(prefix, style.hover_selected, i,
video_queue[i].title,
video_queue[i].channel_name)
elseif i == current_index then
message = _build_osd_row(prefix, style.selected, i,
video_queue[i].title,
video_queue[i].channel_name)
elseif i == selected_index then
message = _build_osd_row(prefix, style.hover, i,
video_queue[i].title,
video_queue[i].channel_name)
else
message = _build_osd_row(prefix, style.reset, i,
video_queue[i].title,
video_queue[i].channel_name)
end
message = message .. style.reset
if i == marked_index then
message =
message .. " " .. style.marked .. options.marked_icon ..
style.reset .. "\n"
else
message = message .. "\n"
end
ass:append(style.font .. message)
end end
mp.set_osd_ass(0, 0, ass.text) ass:append(style.font .. message .. "\n")
if duration ~= nil then end
mp.add_timeout(duration, function() destroy() end) mp.set_osd_ass(0, 0, ass.text)
end if duration then
else mp.add_timeout(duration, destroy)
print_osd_message("No videos in the queue or history.", duration,
style.error)
end end
destroyer = destroy destroyer = destroy
end end
@ -710,8 +781,7 @@ function YouTubeQueue.move_cursor(amt)
end end
if amt == 1 and selected_index > 1 and selected_index < display_offset + 1 then if amt == 1 and selected_index > 1 and selected_index < display_offset + 1 then
display_offset = display_offset - math.abs(selected_index - amt) display_offset = display_offset - math.abs(selected_index - amt)
elseif amt == -1 and selected_index < #video_queue and selected_index > elseif amt == -1 and selected_index < #video_queue and selected_index > display_offset + options.display_limit then
display_offset + options.display_limit then
display_offset = display_offset + math.abs(selected_index - amt) display_offset = display_offset + math.abs(selected_index - amt)
end end
YouTubeQueue.print_queue() YouTubeQueue.print_queue()
@ -765,11 +835,15 @@ end
--- @param update_internal_playlist number - whether to update the internal playlist --- @param update_internal_playlist number - whether to update the internal playlist
--- @return table | nil - the video added to the queue --- @return table | nil - the video added to the queue
function YouTubeQueue.add_to_queue(url, update_internal_playlist) function YouTubeQueue.add_to_queue(url, update_internal_playlist)
if update_internal_playlist == nil then update_internal_playlist = 0 end if update_internal_playlist == nil then
if url == nil or url == "" then update_internal_playlist = 0
end
if isnull(url) then
--- @class string --- @class string
url = YouTubeQueue.get_clipboard_content() url = YouTubeQueue.get_clipboard_content()
if url == nil then return end if url == nil then
return
end
end end
if YouTubeQueue.is_in_queue(url) then if YouTubeQueue.is_in_queue(url) then
print_osd_message("Video already in queue.", MSG_DURATION, style.error) print_osd_message("Video already in queue.", MSG_DURATION, style.error)
@ -780,23 +854,28 @@ function YouTubeQueue.add_to_queue(url, update_internal_playlist)
url = strip(url) url = strip(url)
if not is_file(url) then if not is_file(url) then
local info = YouTubeQueue.get_video_info(url) local info = YouTubeQueue.get_video_info(url)
if info == nil then return nil end if info == nil then
return nil
end
title = info.title title = info.title
video = info video = info
video["video_url"] = url video["video_url"] = url
else else
channel_url, title = split_path(url) channel_url, title = split_path(url)
if channel_url == nil or title == nil or channel_url == "" or title == if isnull(channel_url) or isnull(title) then
"" then print_osd_message("Error getting video info.", MSG_DURATION, style.error)
print_osd_message("Error getting video info.", MSG_DURATION,
style.error)
return return
end end
video = { video = {
video_url = url, video_url = url,
title = title, title = title,
channel_url = channel_url, channel_url = channel_url,
channel_name = "Local file" channel_name = "Local file",
thumbnail_url = "",
view_count = "",
upload_date = "",
category = "",
subscribers = ""
} }
end end
@ -815,11 +894,12 @@ end
--- @param idx number - the index of the video to download --- @param idx number - the index of the video to download
--- @return boolean - true if the video was downloaded successfully, false otherwise --- @return boolean - true if the video was downloaded successfully, false otherwise
function YouTubeQueue.download_video_at(idx) function YouTubeQueue.download_video_at(idx)
if idx < 0 or idx > #video_queue then return false end if idx < 0 or idx > #video_queue then
return false
end
local v = video_queue[idx] local v = video_queue[idx]
if is_file(v.video_url) then if is_file(v.video_url) then
print_osd_message("Current video is a local file... doing nothing.", print_osd_message("Current video is a local file... doing nothing.", MSG_DURATION, style.error)
MSG_DURATION, style.error)
return false return false
end end
local o = options local o = options
@ -832,21 +912,15 @@ function YouTubeQueue.download_video_at(idx)
name = "subprocess", name = "subprocess",
capture_stderr = true, capture_stderr = true,
detach = true, detach = true,
args = { args = { "yt-dlp", "-f",
"yt-dlp", "-f", "bestvideo[height<=" .. q .. "][ext=" .. options.ytdlp_file_format .. "]+bestaudio/best[height<=" .. q ..
"bestvideo[height<=" .. q .. "][ext=" .. options.ytdlp_file_format .. "]/bestvideo[height<=" .. q .. "]+bestaudio/best[height<=" .. q .. "]", "-o",
"]+bestaudio/best[height<=" .. q .. "]/bestvideo[height<=" .. q .. dl_dir .. "/" .. options.ytdlp_output_template, "--downloader", o.downloader, "--", v.video_url }
"]+bestaudio/best[height<=" .. q .. "]", "-o",
dl_dir .. "/" .. options.ytdlp_output_template, "--downloader",
o.downloader, "--", v.video_url
}
}, function(success, _, err) }, function(success, _, err)
if success then if success then
print_osd_message("Finished downloading " .. v.title .. ".", print_osd_message("Finished downloading " .. v.title .. ".", MSG_DURATION)
MSG_DURATION)
else else
print_osd_message("Error downloading " .. v.title .. ": " .. err, print_osd_message("Error downloading " .. v.title .. ": " .. err, MSG_DURATION, style.error)
MSG_DURATION, style.error)
end end
end) end)
return true return true
@ -856,17 +930,17 @@ end
--- @return boolean - true if the video was removed successfully, false otherwise --- @return boolean - true if the video was removed successfully, false otherwise
function YouTubeQueue.remove_from_queue() function YouTubeQueue.remove_from_queue()
if index == selected_index then if index == selected_index then
print_osd_message("Cannot remove current video", MSG_DURATION, print_osd_message("Cannot remove current video", MSG_DURATION, style.error)
style.error)
return false return false
end end
table.remove(video_queue, selected_index) table.remove(video_queue, selected_index)
mp.commandv("playlist-remove", selected_index - 1) mp.commandv("playlist-remove", selected_index - 1)
if current_video and current_video.title then if current_video and current_video.title then
print_osd_message("Deleted " .. current_video.title .. " from queue.", print_osd_message("Deleted " .. current_video.title .. " from queue.", MSG_DURATION)
MSG_DURATION) end
if selected_index > 1 then
selected_index = selected_index - 1
end end
if selected_index > 1 then selected_index = selected_index - 1 end
index = index - 1 index = index - 1
YouTubeQueue.print_queue() YouTubeQueue.print_queue()
return true return true
@ -879,7 +953,9 @@ end
-- This function is called when the current file ends or when moving to the -- This function is called when the current file ends or when moving to the
-- next or previous item in the internal playlist -- next or previous item in the internal playlist
local function on_end_file(event) local function on_end_file(event)
if debug then print("End file event triggered: " .. event.reason) end if debug then
print("End file event triggered: " .. event.reason)
end
if event.reason == "eof" then -- The file ended normally if event.reason == "eof" then -- The file ended normally
YouTubeQueue.update_current_index(true) YouTubeQueue.update_current_index(true)
end end
@ -887,18 +963,24 @@ end
-- Function to be called when the track-changed event is triggered -- Function to be called when the track-changed event is triggered
local function on_track_changed() local function on_track_changed()
if debug then print("Track changed event triggered.") end if debug then
print("Track changed event triggered.")
end
YouTubeQueue.update_current_index() YouTubeQueue.update_current_index()
end end
local function on_file_loaded() local function on_file_loaded()
if debug then print("Load file event triggered.") end if debug then
print("Load file event triggered.")
end
YouTubeQueue.update_current_index(true) YouTubeQueue.update_current_index(true)
end end
-- Function to be called when the playback-restart event is triggered -- Function to be called when the playback-restart event is triggered
local function on_playback_restart() local function on_playback_restart()
if debug then print("Playback restart event triggered.") end if debug then
print("Playback restart event triggered.")
end
if current_video == nil then if current_video == nil then
local url = mp.get_property("path") local url = mp.get_property("path")
YouTubeQueue.add_to_queue(url) YouTubeQueue.add_to_queue(url)
@ -910,35 +992,38 @@ end
-- }}} -- }}}
-- KEY BINDINGS {{{ -- KEY BINDINGS {{{
mp.add_key_binding(options.add_to_queue, "add_to_queue", mp.add_key_binding(options.add_to_queue, "add_to_queue", YouTubeQueue.add_to_queue)
YouTubeQueue.add_to_queue) mp.add_key_binding(options.play_next_in_queue, "play_next_in_queue", function()
mp.add_key_binding(options.play_next_in_queue, "play_next_in_queue", YouTubeQueue.play_video("NEXT")
function() YouTubeQueue.play_video("NEXT") end) end)
mp.add_key_binding(options.play_previous_in_queue, "play_prev_in_queue", mp.add_key_binding(options.play_previous_in_queue, "play_prev_in_queue", function()
function() YouTubeQueue.play_video("PREV") end) YouTubeQueue.play_video("PREV")
end)
mp.add_key_binding(options.print_queue, "print_queue", toggle_print) mp.add_key_binding(options.print_queue, "print_queue", toggle_print)
mp.add_key_binding(options.move_cursor_up, "move_cursor_up", mp.add_key_binding(options.move_cursor_up, "move_cursor_up", function()
function() YouTubeQueue.move_cursor(1) end, YouTubeQueue.move_cursor(1)
{ repeatable = true }) end, {
mp.add_key_binding(options.move_cursor_down, "move_cursor_down", repeatable = true
function() YouTubeQueue.move_cursor(-1) end, })
{ repeatable = true }) mp.add_key_binding(options.move_cursor_down, "move_cursor_down", function()
mp.add_key_binding(options.play_selected_video, "play_selected_video", YouTubeQueue.move_cursor(-1)
function() YouTubeQueue.play_video_at(selected_index) end) end, {
mp.add_key_binding(options.open_video_in_browser, "open_video_in_browser", repeatable = true
open_video_in_browser) })
mp.add_key_binding(options.print_current_video, "print_current_video", mp.add_key_binding(options.play_selected_video, "play_selected_video", function()
YouTubeQueue.print_current_video) YouTubeQueue.play_video_at(selected_index)
mp.add_key_binding(options.open_channel_in_browser, "open_channel_in_browser", end)
open_channel_in_browser) mp.add_key_binding(options.open_video_in_browser, "open_video_in_browser", open_video_in_browser)
mp.add_key_binding(options.download_current_video, "download_current_video", mp.add_key_binding(options.print_current_video, "print_current_video", YouTubeQueue.print_current_video)
function() YouTubeQueue.download_video_at(index) end) mp.add_key_binding(options.open_channel_in_browser, "open_channel_in_browser", open_channel_in_browser)
mp.add_key_binding(options.download_selected_video, "download_selected_video", mp.add_key_binding(options.download_current_video, "download_current_video", function()
function() YouTubeQueue.download_video_at(selected_index) end) YouTubeQueue.download_video_at(index)
mp.add_key_binding(options.move_video, "move_video", end)
YouTubeQueue.mark_and_move_video) mp.add_key_binding(options.download_selected_video, "download_selected_video", function()
mp.add_key_binding(options.remove_from_queue, "delete_video", YouTubeQueue.download_video_at(selected_index)
YouTubeQueue.remove_from_queue) end)
mp.add_key_binding(options.move_video, "move_video", YouTubeQueue.mark_and_move_video)
mp.add_key_binding(options.remove_from_queue, "delete_video", YouTubeQueue.remove_from_queue)
mp.add_key_binding(options.save_queue, "save_queue", function() mp.add_key_binding(options.save_queue, "save_queue", function()
if options.default_save_method == "unwatched" then if options.default_save_method == "unwatched" then
YouTubeQueue.save_queue(index) YouTubeQueue.save_queue(index)