2 Commits

Author SHA1 Message Date
3f7a5fb183 add additional fields for history database
Some checks failed
Luacheck / luacheck (push) Failing after 2m27s
2025-02-13 18:53:00 -08:00
68875120c5 add documentation and update get_video_info
- change to json dump and use mpv native json reader
2025-02-13 01:50:48 -08:00
3 changed files with 743 additions and 749 deletions

View File

@@ -84,7 +84,7 @@ This script requires the following software to be installed on the system
- `ytdlp_file_format - mp4`: The preferred file format for downloaded videos - `ytdlp_file_format - mp4`: The preferred file format for downloaded videos
- `ytdlp_output_template - %(uploader)s/%(title)s.%(ext)s`: The [yt-dlp output template string](https://github.com/yt-dlp/yt-dlp#output-template) - `ytdlp_output_template - %(uploader)s/%(title)s.%(ext)s`: The [yt-dlp output template string](https://github.com/yt-dlp/yt-dlp#output-template)
- Full path with the default `download_directory` is: `~/videos/YouTube/<uploader>/<title>.<ext>` - Full path with the default `download_directory` is: `~/videos/YouTube/<uploader>/<title>.<ext>`
- `use_history_db - no`: Enable watch history tracking and remote video queuing through integration with [mpv-youtube-queue-server](https://gitea.suda.codes/sudacode/mpv-youtube-queue-server) - `use_history_db - no`: Enable watch history tracking through integration with [mpv-youtube-queue-server](https://gitea.suda.codes/sudacode/mpv-youtube-queue-server)
- `backend_host`: ip or hostname of the backend server - `backend_host`: ip or hostname of the backend server
- `backend_port`: port to connect to for the backend server - `backend_port`: port to connect to for the backend server

View File

@@ -13,7 +13,7 @@ play_previous_in_queue=ctrl+p
print_current_video=ctrl+P print_current_video=ctrl+P
print_queue=ctrl+q print_queue=ctrl+q
save_queue=ctrl+s save_queue=ctrl+s
save_full_alt=ctrl+S save_full_queue=ctrl+S
remove_from_queue=ctrl+x remove_from_queue=ctrl+x
play_selected_video=ctrl+ENTER play_selected_video=ctrl+ENTER
browser=firefox browser=firefox

View File

@@ -13,10 +13,10 @@
-- GNU General Public License for more details. -- GNU General Public License for more details.
-- You should have received a copy of the GNU General Public License -- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <https://www.gnu.org/licenses/>. -- along with this program. If not, see <https://www.gnu.org/licenses/>.
local mp = require("mp") local mp = require 'mp'
mp.options = require("mp.options") mp.options = require 'mp.options'
local utils = require("mp.utils") local utils = require 'mp.utils'
local assdraw = require("mp.assdraw") local assdraw = require 'mp.assdraw'
local styleOn = mp.get_property("osd-ass-cc/0") local styleOn = mp.get_property("osd-ass-cc/0")
local styleOff = mp.get_property("osd-ass-cc/1") local styleOff = mp.get_property("osd-ass-cc/1")
local YouTubeQueue = {} local YouTubeQueue = {}
@@ -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",
@@ -66,7 +66,7 @@ local options = {
save_queue = "ctrl+s", save_queue = "ctrl+s",
save_queue_alt = "ctrl+S", save_queue_alt = "ctrl+S",
default_save_method = "unwatched", default_save_method = "unwatched",
load_queue = "ctrl+l", load_queue = "ctrl+l"
} }
mp.options.read_options(options, "mpv-youtube-queue") mp.options.read_options(options, "mpv-youtube-queue")
@@ -87,7 +87,7 @@ local colors = {
header = "8CFAF1", header = "8CFAF1",
hover = "F2F8F8", hover = "F2F8F8",
text = "BFBFBF", text = "BFBFBF",
marked = "C679FF", marked = "C679FF"
} }
local notransparent = "\\alpha&H00&" local notransparent = "\\alpha&H00&"
@@ -101,17 +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" header = "{\\fn" ..
.. options.font_name options.font_name .. "\\fs" .. options.font_size * 1.5 .. "\\u1\\b1\\c&" .. colors.header .. "&" ..
.. "\\fs" notransparent .. "}",
.. 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 .. "{" .. sortoftransparent .. "}", font = "{\\fn" .. options.font_name .. "\\fs" .. options.font_size .. "{" .. sortoftransparent .. "}"
} }
-- }}} -- }}}
@@ -128,21 +122,56 @@ local function surround_with_quotes(s)
end end
end end
--- Truncate a string to a maximum length, adding an ellipsis if truncated
--- @param str string The string to truncate
--- @param length number The maximum length
--- @param use_ellipsis? boolean Whether to add "..." (defaults to true)
--- @return string truncated The truncated string
local function truncate_string(str, length, use_ellipsis)
if use_ellipsis == nil then
use_ellipsis = true
end
if #str <= length then
return str
end
local truncated = string.sub(str, 1, length)
if use_ellipsis then
-- Remove last 3 chars to make room for ellipsis
truncated = string.sub(truncated, 1, length - 3) .. "..." .. '"'
end
return truncated
end
--- return true if the input is null, empty, or 0 --- return true if the input is null, empty, or 0
--- @param s any - 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)
-- Handle nil case
if s == nil then if s == nil then
return true return true
elseif type(s) == "string" and s:match("^%s*$") then end
return true
elseif type(s) == "number" and s == 0 then -- Handle empty string case
return true if type(s) == "string" and s:match("^%s*$") then
elseif type(s) == "table" and next(s) == nil then
return true
elseif type(s) == "boolean" and not s then
return true return true
end 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 return false
end end
@@ -234,7 +263,7 @@ local function open_channel_in_browser()
end end
-- Internal function to print the contents of the internal playlist to the console -- Internal function to print the contents of the internal playlist to the console
local function print_internal_playlist() local function _print_internal_playlist()
local count = mp.get_property_number("playlist-count") local count = mp.get_property_number("playlist-count")
print("Playlist contents:") print("Playlist contents:")
for i = 0, count - 1 do for i = 0, count - 1 do
@@ -247,19 +276,20 @@ end
--- @param prefix string - the prefix to add to the row --- @param prefix string - the prefix to add to the row
--- @param s string - the style to apply to the row --- @param s string - the style to apply to the row
--- @param i number - the index of the row --- @param i number - the index of the row
--- @param video_name string - the title of the video --- @param title string - the title of the video
--- @param channel_name string - the name of the channel --- @param channel_name string - the name of the channel
--- @return string - the OSD row --- @return string - the OSD row
local function build_osd_row(prefix, s, i, video_name, channel_name) local function _build_osd_row(prefix, s, i, title, channel_name)
return prefix .. s .. i .. ". " .. video_name .. " - (" .. channel_name .. ")" return prefix .. s .. i .. ". " .. title .. " - (" .. channel_name .. ")"
end end
--- Helper function to determine display range for queue items --- Helper function to determine display range for queue items
--- @param queue_length number Total number of items in queue --- @param queue_length number Total number of items in queue
--- @param selected number Currently selected index --- @param selected number Currently selected index
--- @param limit number Maximum items to display --- @param limit number Maximum items to display
--- @return number, number start and end indices --- @return number, number start and end indices
local function get_display_range(queue_length, selected, limit) local function _get_display_range(queue_length, selected, limit)
local half_limit = math.floor(limit / 2) local half_limit = math.floor(limit / 2)
local start_index = selected <= half_limit and 1 or selected - half_limit local start_index = selected <= half_limit and 1 or selected - half_limit
local end_index = math.min(start_index + limit - 1, queue_length) local end_index = math.min(start_index + limit - 1, queue_length)
@@ -271,7 +301,7 @@ end
--- @param current number Currently playing index --- @param current number Currently playing index
--- @param selected number Selected index --- @param selected number Selected index
--- @return string Style to apply --- @return string Style to apply
local function get_item_style(i, current, selected) local function _get_item_style(i, current, selected)
if i == current and i == selected then if i == current and i == selected then
return style.hover_selected return style.hover_selected
elseif i == current then elseif i == current then
@@ -292,13 +322,13 @@ local function toggle_print()
end end
-- Function to remove leading and trailing quotes from the first and last arguments of a command table in-place -- Function to remove leading and trailing quotes from the first and last arguments of a command table in-place
local function remove_command_quotes(s) local function _remove_command_quotes(s)
-- if the first character of the first argument is a quote, remove it -- if the first character of the first argument is a quote, remove it
if string.sub(s[1], 1, 1) == "'" or string.sub(s[1], 1, 1) == '"' then if string.sub(s[1], 1, 1) == "'" or string.sub(s[1], 1, 1) == "\"" then
s[1] = string.sub(s[1], 2) s[1] = string.sub(s[1], 2)
end end
-- if the last character of the last argument is a quote, remove it -- if the last character of the last argument is a quote, remove it
if string.sub(s[#s], -1) == "'" or string.sub(s[#s], -1) == '"' then if string.sub(s[#s], -1) == "'" or string.sub(s[#s], -1) == "\"" then
s[#s] = string.sub(s[#s], 1, -2) s[#s] = string.sub(s[#s], 1, -2)
end end
end end
@@ -306,44 +336,170 @@ end
--- Function to split the clipboard_command into it's parts and return as a table --- Function to split the clipboard_command into it's parts and return as a table
--- @param cmd string - the command to split --- @param cmd string - the command to split
--- @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 for arg in cmd:gmatch("%S+") do
table.insert(components, arg) table.insert(components, arg)
end end
remove_command_quotes(components) _remove_command_quotes(components)
return components return components
end end
--- Converts a key-value pair or a table of key-value pairs into a JSON string. --- Add a video to the history database
--- If the key is a table, it iterates over the table to construct a JSON object. --- @param v table - the video to add to the history database
--- If the key is a single value, it constructs a JSON object with the provided key and value. --- @return boolean - true if the video was added successfully, false otherwise
--- @param key any - A single key or a table of key-value pairs to convert. function YouTubeQueue._add_to_history_db(v)
--- @param val any - The value associated with the key, used only if the key is not a table. if not options.use_history_db then
--- @return string | nil - The resulting JSON string, or nil if the input is invalid. return false
local function convert_to_json(key, val)
if type(key) == "table" then
-- Handle the case where key is a table of key-value pairs
local json = "{"
local first = true
for k, v in pairs(key) do
if not first then
json = json .. ", "
end end
first = false local url = options.backend_host .. ":" .. options.backend_port .. "/add_video"
local command = { "curl", "-X", "POST", url, "-H", "Content-Type: application/json", "-d",
string.format(
'{"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.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({
name = "subprocess",
playback_only = false,
capture_stdout = true,
args = command
}, function(success, _, err)
if not success then
print_osd_message("Failed to send video data to backend: " .. err, MSG_DURATION, style.error)
return false
end
end)
return true
end
local quoted_val = string.format('"%s"', v) --- Returns a list of URLs in the queue from start_index to the end
json = json .. string.format('"%s": %s', k, quoted_val) --- @param start_index number - the index to start from
--- @return table | nil - a table of URLs
function YouTubeQueue._get_urls(start_index)
if start_index < 0 or start_index > #video_queue then
return nil
end end
json = json .. "}" local urls = {}
return json for i = start_index + 1, #video_queue do
else table.insert(urls, video_queue[i].video_url)
end
return urls
end
--- Converts key value pairs to a json string
--- @param key any - json key
--- @param val any - json value
--- @return string | nil - the json string
function YouTubeQueue._convert_to_json(key, val)
if val == nil then
return
end
if type(val) ~= "table" then
-- For non-table values, properly quote strings and format numbers
if type(val) == "string" then if type(val) == "string" then
return string.format('{"%s": "%s"}', key, val) return string.format('{"%s": "%s"}', key, val)
else else
return string.format('{"%s": %s}', key, tostring(val)) return string.format('{"%s": %s}', key, tostring(val))
end end
end end
local json = string.format('{"%s": [', key)
for i, v in ipairs(val) do
json = json .. '"' .. v .. '"'
if i < #val then
json = json .. ", "
end
end
json = json .. "]}"
return json
end
--- Saves the remainder of the videos in the queue (all videos after the currently playing video) to the history database
--- @param idx number - the index to start saving from
--- @return boolean - true if the queue was saved successfully, false otherwise
function YouTubeQueue.save_queue(idx)
if not options.use_history_db then
return false
end
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
end
if debug then
print("Data: " .. data)
end
local command = { "curl", "-X", "POST", url, "-H", "Content-Type: application/json", "-d", data }
if debug then
print("Saving queue to history")
print("Command: " .. table.concat(command, " "))
end
mp.command_native_async({
name = "subprocess",
playback_only = false,
capture_stdout = true,
args = command
}, function(success, result, err)
if not success then
print_osd_message("Failed to save queue: " .. err, MSG_DURATION, style.error)
return false
end
if debug then
print("Status: " .. result.status)
end
if result.status == 0 then
if idx > 1 then
print_osd_message("Queue saved to history from index: " .. idx, MSG_DURATION)
else
print_osd_message("Queue saved to history.", MSG_DURATION)
end
end
end)
return true
end
-- loads the queue from the backend
function YouTubeQueue.load_queue()
if not options.use_history_db then
return false
end
local url = options.backend_host .. ":" .. options.backend_port .. "/load_queue"
local command = { "curl", "-X", "GET", url }
mp.command_native_async({
name = "subprocess",
playback_only = false,
capture_stdout = true,
args = command
}, function(success, result, err)
if not success then
print_osd_message("Failed to load queue: " .. err, MSG_DURATION, style.error)
return false
else
if result.status == 0 then
-- split urls based on commas
local urls = {}
-- Remove the brackets from json list
local l = result.stdout:sub(2, -3)
local item
for turl in l:gmatch('[^,]+') do
item = turl:match("^%s*(.-)%s*$"):gsub('"', "'")
table.insert(urls, item)
end
for _, turl in ipairs(urls) do
YouTubeQueue.add_to_queue(turl, 0)
end
print_osd_message("Loaded queue from history.", MSG_DURATION)
end
end
end)
end end
-- }}} -- }}}
@@ -361,15 +517,15 @@ function YouTubeQueue.get_video_at(idx)
return video_queue[idx] return video_queue[idx]
end end
--- returns the content of the clipboard -- returns the content of the clipboard
--- @return string | nil - the content of the clipboard -- @return string - the content of the clipboard
function YouTubeQueue.get_clipboard_content() function YouTubeQueue.get_clipboard_content()
local command = split_command(options.clipboard_command) local command = _split_command(options.clipboard_command)
local res = mp.command_native({ local res = mp.command_native({
name = "subprocess", name = "subprocess",
playback_only = false, playback_only = false,
capture_stdout = true, capture_stdout = true,
args = command, args = command
}) })
if res.status ~= 0 then if res.status ~= 0 then
@@ -388,25 +544,17 @@ function YouTubeQueue.get_clipboard_content()
end end
end end
--- Function to get the video info from the URL -- Function to get the video info from the URL
--- @param url string - the URL to get the video info from -- @param url string - the URL to get the video info from
--- @return table | nil - a table containing the video information -- @return string, string, string - the channel URL, channel name, and title of the video
function YouTubeQueue.get_video_info(url) function YouTubeQueue.get_video_info(url)
print_osd_message("Getting video info...", MSG_DURATION * 2) print_osd_message("Getting video info...", MSG_DURATION * 2)
local res = mp.command_native({ local res = mp.command_native({
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", "--playlist-items", "1", url }
"--dump-single-json",
"--ignore-config",
"--no-warnings",
"--skip-download",
"--playlist-items",
"1",
url,
},
}) })
if res.status ~= 0 or isnull(res.stdout) then if res.status ~= 0 or isnull(res.stdout) then
@@ -421,25 +569,19 @@ function YouTubeQueue.get_video_info(url)
return nil return nil
end end
local category = nil
if data.categories then
category = data.categories[1]
else
category = "Unknown"
end
local info = { local info = {
channel_url = data.channel_url or "", channel_url = data.channel_url or "",
channel_name = data.uploader or "", channel_name = data.uploader or "",
video_name = 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 "",
category = category or "", category = data.categories[1] or "",
thumbnail_url = data.thumbnail or "", thumbnail_url = data.thumbnail or "",
subscribers = data.channel_follower_count or 0, subscribers = data.channel_follower_count or ""
} }
if isnull(info.channel_url) or isnull(info.channel_name) or isnull(info.video_name) then if isnull(info.channel_url) or isnull(info.channel_name) or isnull(info.title) then
print_osd_message("Missing metadata (channel_url, uploader, video_name) 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
@@ -454,7 +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.video_name .. " by " .. current.channel_name, 3) print_osd_message("Playing: " .. current.title .. ' by ' .. current.channel_name, 3)
end end
end end
end end
@@ -470,9 +612,9 @@ end
function YouTubeQueue.set_video(direction) function YouTubeQueue.set_video(direction)
local amt local amt
direction = string.upper(direction) direction = string.upper(direction)
if direction == "NEXT" or direction == nil then if (direction == "NEXT" or direction == nil) then
amt = 1 amt = 1
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, style.error) print_osd_message("Invalid direction: " .. direction, MSG_DURATION, style.error)
@@ -520,7 +662,7 @@ function YouTubeQueue.update_current_index(update_history)
---@class table ---@class table
current_video = YouTubeQueue.get_video_at(index) current_video = YouTubeQueue.get_video_at(index)
if update_history then if update_history then
YouTubeQueue.add_to_history_db(current_video) YouTubeQueue._add_to_history_db(current_video)
end end
return return
end end
@@ -583,7 +725,7 @@ function YouTubeQueue.reorder_queue(from_index, to_index)
end end
--- Prints the queue to the OSD --- Prints the queue to the OSD
--- @param duration number Optional duration to display the queue --- @param duration number? Optional duration to display the queue
function YouTubeQueue.print_queue(duration) function YouTubeQueue.print_queue(duration)
-- Reset and prepare OSD -- Reset and prepare OSD
timeout:kill() timeout:kill()
@@ -599,17 +741,21 @@ function YouTubeQueue.print_queue(duration)
local ass = assdraw.ass_new() local ass = assdraw.ass_new()
ass:append(style.header .. "MPV-YOUTUBE-QUEUE{\\u0\\b0}" .. style.reset .. style.font .. "\n") ass:append(style.header .. "MPV-YOUTUBE-QUEUE{\\u0\\b0}" .. style.reset .. style.font .. "\n")
local start_index, end_index = get_display_range(#video_queue, selected_index, options.display_limit) local start_index, end_index = _get_display_range(
#video_queue,
selected_index,
options.display_limit
)
for i = start_index, end_index do for i = start_index, end_index do
local video = video_queue[i] local video = video_queue[i]
if not video then if not video then break end
break local prefix = (i == selected_index)
end and style.cursor .. options.cursor_icon .. "\\h" .. style.reset
local prefix = (i == selected_index) and style.cursor .. options.cursor_icon .. "\\h" .. style.reset
or "\\h\\h\\h" or "\\h\\h\\h"
local item_style = get_item_style(i, index, selected_index) local item_style = _get_item_style(i, index, selected_index)
local message = build_osd_row(prefix, item_style, i, video.video_name, video.channel_name) .. style.reset local message = _build_osd_row(prefix, item_style, i, video.title, video.channel_name)
.. style.reset
if i == marked_index then if i == marked_index then
message = message .. " " .. style.marked .. options.marked_icon .. style.reset message = message .. " " .. style.marked .. options.marked_icon .. style.reset
end end
@@ -622,10 +768,8 @@ function YouTubeQueue.print_queue(duration)
destroyer = destroy destroyer = destroy
end end
--- Function to move the cursor on the OSD by a specified amount. --- Function to move the cursor on the OSD by amt
--- Adjusts the selected index and updates the display offset to ensure --- @param amt number - the number of steps to take
--- the selected item is visible within the display limits
--- @param amt number - the number of steps to move the cursor. Positive values move up, negative values move down.
function YouTubeQueue.move_cursor(amt) function YouTubeQueue.move_cursor(amt)
timeout:kill() timeout:kill()
timeout:resume() timeout:resume()
@@ -706,32 +850,32 @@ function YouTubeQueue.add_to_queue(url, update_internal_playlist)
return return
end end
local video, channel_url, video_name local video, channel_url, title
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 if info == nil then
return nil return nil
end end
video_name = info.video_name title = info.title
video = info video = info
video["video_url"] = url video["video_url"] = url
else else
channel_url, video_name = split_path(url) channel_url, title = split_path(url)
if isnull(channel_url) or isnull(video_name) then if isnull(channel_url) or isnull(title) 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,
video_name = video_name, title = title,
channel_url = channel_url, channel_url = channel_url,
channel_name = "Local file", channel_name = "Local file",
thumbnail_url = "", thumbnail_url = "",
view_count = "", view_count = "",
upload_date = "", upload_date = "",
category = "", category = "",
subscribers = "", subscribers = ""
} }
end end
@@ -743,7 +887,7 @@ function YouTubeQueue.add_to_queue(url, update_internal_playlist)
elseif update_internal_playlist == 0 then elseif update_internal_playlist == 0 then
mp.commandv("loadfile", url, "append-play") mp.commandv("loadfile", url, "append-play")
end end
print_osd_message("Added " .. video_name .. " to queue.", MSG_DURATION) print_osd_message("Added " .. title .. " to queue.", MSG_DURATION)
end end
--- Downloads the video at the specified index --- Downloads the video at the specified index
@@ -762,38 +906,21 @@ function YouTubeQueue.download_video_at(idx)
local q = o.download_quality:sub(1, -2) local q = o.download_quality:sub(1, -2)
local dl_dir = expanduser(o.download_directory) local dl_dir = expanduser(o.download_directory)
print_osd_message("Downloading " .. v.video_name .. "...", MSG_DURATION) print_osd_message("Downloading " .. v.title .. "...", MSG_DURATION)
-- Run the download command -- Run the download command
mp.command_native_async({ mp.command_native_async({
name = "subprocess", name = "subprocess",
capture_stderr = true, capture_stderr = true,
detach = true, detach = true,
args = { args = { "yt-dlp", "-f",
"yt-dlp", "bestvideo[height<=" .. q .. "][ext=" .. options.ytdlp_file_format .. "]+bestaudio/best[height<=" .. q ..
"-f", "]/bestvideo[height<=" .. q .. "]+bestaudio/best[height<=" .. q .. "]", "-o",
"bestvideo[height<=" dl_dir .. "/" .. options.ytdlp_output_template, "--downloader", o.downloader, "--", v.video_url }
.. q
.. "][ext="
.. options.ytdlp_file_format
.. "]+bestaudio/best[height<="
.. q
.. "]/bestvideo[height<="
.. q
.. "]+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.video_name .. ".", MSG_DURATION) print_osd_message("Finished downloading " .. v.title .. ".", MSG_DURATION)
else else
print_osd_message("Error downloading " .. v.video_name .. ": " .. err, MSG_DURATION, style.error) print_osd_message("Error downloading " .. v.title .. ": " .. err, MSG_DURATION, style.error)
end end
end) end)
return true return true
@@ -808,8 +935,8 @@ function YouTubeQueue.remove_from_queue()
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.video_name then if current_video and current_video.title then
print_osd_message("Deleted " .. current_video.video_name .. " from queue.", MSG_DURATION) print_osd_message("Deleted " .. current_video.title .. " from queue.", MSG_DURATION)
end end
if selected_index > 1 then if selected_index > 1 then
selected_index = selected_index - 1 selected_index = selected_index - 1
@@ -819,139 +946,6 @@ function YouTubeQueue.remove_from_queue()
return true return true
end end
--- Returns a list of URLs in the queue from start_index to the end
--- @param start_index number - the index to start from
--- @return table | nil - a table of URLs
function YouTubeQueue.get_urls(start_index)
if start_index < 0 or start_index > #video_queue then
return nil
end
local urls = {}
for i = start_index + 1, #video_queue do
table.insert(urls, video_queue[i].video_url)
end
return urls
end
-- }}}
-- {{{ HISTORY DB
--- Add a video 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
function YouTubeQueue.add_to_history_db(v)
if not options.use_history_db then
return false
end
local url = options.backend_host .. ":" .. options.backend_port .. "/add_video"
local json = convert_to_json(v)
local command = { "curl", "-X", "POST", url, "-H", "Content-Type: application/json", "-d", json }
if debug then
print("Adding video to history")
print("Command: " .. table.concat(command, " "))
end
print_osd_message("Adding video to history...", MSG_DURATION)
mp.command_native_async({
name = "subprocess",
playback_only = false,
capture_stdout = true,
args = command,
}, function(success, _, err)
if not success then
print_osd_message("Failed to send video data to backend: " .. err, MSG_DURATION, style.error)
return false
end
end)
print_osd_message("Video added to history db", MSG_DURATION)
return true
end
--- Saves the remainder of the videos in the queue
--- (all videos after the currently playing video) to the history database
--- @param idx number - the index to start saving from
--- @return boolean - true if the queue was saved successfully, false otherwise
function YouTubeQueue.save_queue(idx)
if not options.use_history_db then
return false
end
if idx == nil then
idx = index
end
local url = options.backend_host .. ":" .. options.backend_port .. "/save_queue"
local data = 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
print("Saving queue to history")
print("Command: " .. table.concat(command, " "))
end
mp.command_native_async({
name = "subprocess",
playback_only = false,
capture_stdout = true,
args = command,
}, function(success, result, err)
if not success then
print_osd_message("Failed to save queue: " .. err, MSG_DURATION, style.error)
return false
end
if debug then
print("Status: " .. result.status)
end
if result.status == 0 then
if idx > 1 then
print_osd_message("Queue saved to history from index: " .. idx, MSG_DURATION)
else
print_osd_message("Queue saved to history.", MSG_DURATION)
end
end
end)
return true
end
-- loads the queue from the backend
function YouTubeQueue.load_queue()
if not options.use_history_db then
return false
end
local url = options.backend_host .. ":" .. options.backend_port .. "/load_queue"
local command = { "curl", "-X", "GET", url }
mp.command_native_async({
name = "subprocess",
playback_only = false,
capture_stdout = true,
args = command,
}, function(success, result, err)
if not success then
print_osd_message("Failed to load queue: " .. err, MSG_DURATION, style.error)
return false
else
if result.status == 0 then
-- split urls based on commas
local urls = {}
-- Remove the brackets from json list
local l = result.stdout:sub(2, -3)
local item
for turl in l:gmatch("[^,]+") do
item = turl:match("^%s*(.-)%s*$"):gsub('"', "'")
table.insert(urls, item)
end
for _, turl in ipairs(urls) do
YouTubeQueue.add_to_queue(turl, 0)
end
print_osd_message("Loaded queue from history.", MSG_DURATION)
end
end
end)
end
-- }}} -- }}}
-- LISTENERS {{{ -- LISTENERS {{{
@@ -991,7 +985,7 @@ local function on_playback_restart()
local url = mp.get_property("path") local url = mp.get_property("path")
YouTubeQueue.add_to_queue(url) YouTubeQueue.add_to_queue(url)
---@diagnostic disable-next-line: param-type-mismatch ---@diagnostic disable-next-line: param-type-mismatch
YouTubeQueue.add_to_history_db(current_video) YouTubeQueue._add_to_history_db(current_video)
end end
end end
@@ -1009,12 +1003,12 @@ mp.add_key_binding(options.print_queue, "print_queue", toggle_print)
mp.add_key_binding(options.move_cursor_up, "move_cursor_up", function() mp.add_key_binding(options.move_cursor_up, "move_cursor_up", function()
YouTubeQueue.move_cursor(1) YouTubeQueue.move_cursor(1)
end, { end, {
repeatable = true, repeatable = true
}) })
mp.add_key_binding(options.move_cursor_down, "move_cursor_down", function() mp.add_key_binding(options.move_cursor_down, "move_cursor_down", function()
YouTubeQueue.move_cursor(-1) YouTubeQueue.move_cursor(-1)
end, { end, {
repeatable = true, repeatable = true
}) })
mp.add_key_binding(options.play_selected_video, "play_selected_video", function() mp.add_key_binding(options.play_selected_video, "play_selected_video", function()
YouTubeQueue.play_video_at(selected_index) YouTubeQueue.play_video_at(selected_index)
@@ -1057,6 +1051,6 @@ mp.register_script_message("print_queue", YouTubeQueue.print_queue)
mp.register_script_message("add_to_youtube_queue", YouTubeQueue.add_to_queue) mp.register_script_message("add_to_youtube_queue", YouTubeQueue.add_to_queue)
mp.register_script_message("toggle_youtube_queue", toggle_print) mp.register_script_message("toggle_youtube_queue", toggle_print)
mp.register_script_message("print_internal_playlist", print_internal_playlist) mp.register_script_message("print_internal_playlist", _print_internal_playlist)
mp.register_script_message("reorder_youtube_queue", YouTubeQueue.reorder_queue) mp.register_script_message("reorder_youtube_queue", YouTubeQueue.reorder_queue)
-- }}} -- }}}