summaryrefslogtreecommitdiff
path: root/mac/.config/mpv/scripts/youtube-search.lua
blob: 898944718854561ca6ea7e7d7e24f7c46d70fbdd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
--[[
    This script allows users to search and open youtube results from within mpv.
    Available at: https://github.com/CogentRedTester/mpv-scripts

    Users can open the search page with Y, and use Y again to open a search.
    Alternatively, Ctrl+y can be used at any time to open a search.
    Esc can be used to close the page.
    Enter will open the selected item, Shift+Enter will append the item to the playlist.

    This script requires that my other scripts `scroll-list` and `user-input` be installed.
    scroll-list.lua and user-input-module.lua must be in the ~~/script-modules/ directory,
    while user-input.lua should be loaded by mpv normally.

    https://github.com/CogentRedTester/mpv-scroll-list
    https://github.com/CogentRedTester/mpv-user-input

    This script also requires a youtube API key to be entered.
    The API key must be passed to the `API_key` script-opt.
    A personal API key is free and can be created from:
    https://console.developers.google.com/apis/api/youtube.googleapis.com/

    The script also requires that curl be in the system path.

    An alternative to using the official youtube API is to use Invidious.
    This script has experimental support for Invidious searches using the 'invidious',
    'API_path', and 'frontend' options. API_path refers to the url of the API the
    script uses, Invidious API paths are usually in the form:
        https://domain.name/api/v1/
    The frontend option is the url to actualy try to load videos from. This
    can probably be the same as the above url:
        https://domain.name
    Since the url syntax seems to be identical between Youtube and Invidious,
    it should be possible to mix these options, a.k.a. using the Google
    API to get videos from an Invidious frontend, or to use an Invidious
    API to get videos from Youtube.
    The 'invidious' option tells the script that the API_path is for an
    Invidious path. This is to support other possible API options in the future.
]]
--

local mp = require("mp")
local msg = require("mp.msg")
local utils = require("mp.utils")
local opts = require("mp.options")

package.path = mp.command_native({ "expand-path", "~~/script-modules/?.lua;" }) .. package.path
local ui = require("user-input-module")
local list = require("scroll-list")

local o = {
	API_key = io.popen("pass show api/google-cloud/youtube-search"):read("*a"):gsub("%s+", ""),

	--number of search results to show in the list
	num_results = 40,

	--the url to send API calls to
	API_path = "https://www.googleapis.com/youtube/v3/",

	--attempt this API if the default fails
	fallback_API_path = "",

	--the url to load videos from
	frontend = "https://www.youtube.com",

	--use invidious API calls
	invidious = false,

	--whether the fallback uses invidious as well
	fallback_invidious = false,
}

opts.read_options(o)

--ensure the URL options are properly formatted
local function format_options()
	if o.API_path:sub(-1) ~= "/" then
		o.API_path = o.API_path .. "/"
	end
	if o.fallback_API_path:sub(-1) ~= "/" then
		o.fallback_API_path = o.fallback_API_path .. "/"
	end
	if o.frontend:sub(-1) == "/" then
		o.frontend = o.frontend:sub(1, -2)
	end
end

format_options()

list.header = ("%s Search: \\N-------------------------------------------------"):format(
	o.invidious and "Invidious" or "Youtube"
)
list.num_entries = 17
list.list_style = [[{\fs10}\N{\q2\fs25\c&Hffffff&}]]
list.empty_text = "enter search query"

local ass_escape = list.ass_escape

--encodes a string so that it uses url percent encoding
--this function is based on code taken from here: https://rosettacode.org/wiki/URL_encoding#Lua
local function encode_string(str)
	if type(str) ~= "string" then
		return str
	end
	local output, t = str:gsub("[^%w]", function(char)
		return string.format("%%%X", string.byte(char))
	end)
	return output
end

--convert HTML character codes to the correct characters
local function html_decode(str)
	if type(str) ~= "string" then
		return str
	end

	return str:gsub("&(#?)(%w-);", function(is_ascii, code)
		if is_ascii == "#" then
			return string.char(tonumber(code))
		end
		if code == "amp" then
			return "&"
		end
		if code == "quot" then
			return '"'
		end
		if code == "apos" then
			return "'"
		end
		if code == "lt" then
			return "<"
		end
		if code == "gt" then
			return ">"
		end
		return nil
	end)
end

--creates a formatted results table from an invidious API call
local function format_invidious_results(response)
	if not response then
		return nil
	end
	local results = {}

	for i, item in ipairs(response) do
		if i > o.num_results then
			break
		end

		local t = {}
		table.insert(results, t)

		t.title = html_decode(item.title)
		t.channelTitle = html_decode(item.author)
		if item.type == "video" then
			t.type = "video"
			t.id = item.videoId
		elseif item.type == "playlist" then
			t.type = "playlist"
			t.id = item.playlistId
		elseif item.type == "channel" then
			t.type = "channel"
			t.id = item.authorId
			t.title = t.channelTitle
		end
	end

	return results
end

--creates a formatted results table from a youtube API call
function format_youtube_results(response)
	if not response or not response.items then
		return nil
	end
	local results = {}

	for _, item in ipairs(response.items) do
		local t = {}
		table.insert(results, t)

		t.title = html_decode(item.snippet.title)
		t.channelTitle = html_decode(item.snippet.channelTitle)

		if item.id.kind == "youtube#video" then
			t.type = "video"
			t.id = item.id.videoId
		elseif item.id.kind == "youtube#playlist" then
			t.type = "playlist"
			t.id = item.id.playlistId
		elseif item.id.kind == "youtube#channel" then
			t.type = "channel"
			t.id = item.id.channelId
		end
	end

	return results
end

--sends an API request
local function send_request(type, queries, API_path)
	local url = (API_path or o.API_path) .. type
	url = url .. "?"

	for key, value in pairs(queries) do
		msg.verbose(key, value)
		url = url .. "&" .. key .. "=" .. encode_string(value)
	end

	msg.debug(url)
	local request = mp.command_native({
		name = "subprocess",
		capture_stdout = true,
		capture_stderr = true,
		playback_only = false,
		args = { "curl", url },
	})

	local response = utils.parse_json(request.stdout)
	msg.trace(utils.to_string(request))

	if request.status ~= 0 then
		msg.error(request.stderr)
		return nil
	end
	if not response then
		msg.error("Could not parse response:")
		msg.error(request.stdout)
		return nil
	end
	if response.error then
		msg.error(request.stdout)
		return nil
	end

	return response
end

--sends a search API request - handles Google/Invidious API differences
local function search_request(queries, API_path, invidious)
	list.header = ("%s Search: %s\\N-------------------------------------------------"):format(
		invidious and "Invidious" or "Youtube",
		ass_escape(queries.q, true)
	)
	list.list = {}
	list.empty_text = "~"
	list:update()
	local results = {}

	--we need to modify the returned results so that the rest of the script can read it
	if invidious then
		--Invidious searches are done with pages rather than a max result number
		local page = 1
		while #results < o.num_results do
			queries.page = page

			local response = send_request("search", queries, API_path)
			response = format_invidious_results(response)
			if not response then
				msg.warn("Search did not return a results list")
				return
			end
			if #response == 0 then
				break
			end

			for _, item in ipairs(response) do
				table.insert(results, item)
			end

			page = page + 1
		end
	else
		local response = send_request("search", queries, API_path)
		results = format_youtube_results(response)
	end

	--print error messages to console if the API request fails
	if not results then
		msg.warn("Search did not return a results list")
		return
	end

	list.empty_text = "no results"
	return results
end

local function insert_video(item)
	list:insert({
		ass = ("%s   {\\c&aaaaaa&}%s"):format(ass_escape(item.title), ass_escape(item.channelTitle)),
		url = ("%s/watch?v=%s"):format(o.frontend, item.id),
	})
end

local function insert_playlist(item)
	list:insert({
		ass = ("🖿 %s   {\\c&aaaaaa&}%s"):format(ass_escape(item.title), ass_escape(item.channelTitle)),
		url = ("%s/playlist?list=%s"):format(o.frontend, item.id),
	})
end

local function insert_channel(item)
	list:insert({
		ass = ("👤 %s"):format(ass_escape(item.title)),
		url = ("%s/channel/%s"):format(o.frontend, item.id),
	})
end

local function reset_list()
	list.selected = 1
	list:clear()
end

--creates the search request queries depending on what API we're using
local function get_search_queries(query, invidious)
	if invidious then
		return {
			q = query,
			type = "all",
			page = 1,
		}
	else
		return {
			key = o.API_key,
			q = query,
			part = "id,snippet",
			maxResults = o.num_results,
		}
	end
end

local function search(query)
	local response = search_request(get_search_queries(query, o.invidious), o.API_path, o.invidious)
	if not response and o.fallback_API_path ~= "/" then
		msg.info("search failed - attempting fallback")
		response =
			search_request(get_search_queries(query, o.fallback_invidious), o.fallback_API_path, o.fallback_invidious)
	end

	if not response then
		return
	end
	reset_list()

	for _, item in ipairs(response) do
		if item.type == "video" then
			insert_video(item)
		elseif item.type == "playlist" then
			insert_playlist(item)
		elseif item.type == "channel" then
			insert_channel(item)
		end
	end
	list:update()
	list:open()
end

local function play_result(flag)
	if not list[list.selected] then
		return
	end
	if flag == "new_window" then
		mp.commandv("run", "mpv", list[list.selected].url)
		return
	end

	mp.commandv("loadfile", list[list.selected].url, flag)
	if flag == "replace" then
		list:close()
	end
end

table.insert(list.keybinds, {
	"ENTER",
	"play",
	function()
		play_result("replace")
	end,
	{},
})
table.insert(list.keybinds, {
	"Shift+ENTER",
	"play_append",
	function()
		play_result("append-play")
	end,
	{},
})
table.insert(list.keybinds, {
	"Ctrl+ENTER",
	"play_new_window",
	function()
		play_result("new_window")
	end,
	{},
})

local function open_search_input()
	ui.get_user_input(function(input)
		if not input then
			return
		end
		search(input)
	end, { request_text = "Enter Query:" })
end

mp.add_key_binding("", "yt", open_search_input)

mp.add_key_binding("", "youtube-search", function()
	if not list.hidden then
		open_search_input()
	else
		list:open()
		if #list.list == 0 then
			open_search_input()
		end
	end
end)