This repository was archived by the owner on Jan 11, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathyoucube.lua
578 lines (486 loc) · 15.5 KB
/
youcube.lua
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
--[[
_ _ ____ _ _ ____ _ _ ___ ____
\_/ | | | | | | | |__] |___
| |__| |__| |___ |__| |__] |___
Github Repository: https://github.com/Commandcracker/YouCube
License: GPL-3.0
]]
local _VERSION = "0.0.0-poc.1.0.0"
-- Libraries - OpenLibrarieLoader v1.0.0 --
--TODO: Optional libs
-- For something like a JSON lib that is only needed for older CC Versions or
-- optional logging.lua support
local function is_lib(Table, Item)
for key, value in ipairs(Table) do
if value == Item or value .. ".lua" == Item then
return true, value
end
end
return false
end
local libs = { "youcubeapi", "numberformatter", "semver", "argparse", "string_pack" }
local lib_paths = { ".", "./lib", "./apis", "./modules", "/", "/lib", "/apis", "/modules" }
if _G.lOS then
table.insert(lib_paths, "/Program_Files/YouCube/lib")
end
for i, path in pairs(lib_paths) do
if fs.exists(path) then
for _i, file_name in pairs(fs.list(path)) do
local found, lib = is_lib(libs, file_name)
if found and libs[lib] == nil then
if require then
libs[lib] = require(path .. "/" .. file_name:gsub(".lua", ""))
else
libs[lib] = dofile(path .. "/" .. file_name)
end
end
end
end
end
for key, lib in ipairs(libs) do
if libs[lib] == nil then
error("Library \"" .. lib .. "\" not found")
end
end
-- args --
local program_name
if arg then
program_name = arg[0]
else
program_name = fs.getName(shell.getRunningProgram()):gsub("[\\.].*$", "")
end
local parser = libs.argparse {
help_max_width = ({ term.getSize() })[1],
help_usage_margin = 1,
help_description_margin = 23,
name = program_name
}
:description "Official YouCube client for accessing media from services like YouTube"
parser:argument "URL"
:args "*"
:description "URL or search term."
parser:flag "-v" "--verbose"
:description "Enables verbose output."
:target "verbose"
:action "store_true"
parser:option "-V" "--volume"
:description "Sets the volume of the audio. A value from 0-100"
:target "volume"
parser:option "-s" "--server"
:description "The server that YC should use."
:target "server"
:args(1)
parser:flag "--nv" "--no-video"
:description "Disables video."
:target "no_video"
:action "store_true"
parser:flag "--na" "--no-audio"
:description "Disables audio."
:target "no_audio"
:action "store_true"
parser:flag "--sh" "--shuffle"
:description "Shuffles audio before playing"
:target "shuffle"
:action "store_true"
parser:flag "-l" "--loop"
:description "Loops the media."
:target "loop"
:action "store_true"
parser:flag "--lp" "--loop-playlist"
:description "Loops the playlist."
:target "loop_playlist"
:action "store_true"
local args = parser:parse { ... }
if args.volume then
args.volume = tonumber(args.volume)
if args.volume == nil then
parser:error("Volume must be a number")
end
if args.volume > 100 then
parser:error("Volume cant be over 100")
end
if args.volume < 0 then
parser:error("Volume cant be below 0")
end
args.volume = args.volume / 100
end
if #args.URL > 0 then
args.URL = table.concat(args.URL, " ")
else
args.URL = nil
end
if args.no_video and args.no_audio then
parser:error("Nothing will happen, when audio and video is disabled!")
end
-- CraftOS-PC support --
if periphemu then
periphemu.create("top", "speaker")
-- Fuck the max websocket message police
config.set("http_max_websocket_message", 2 ^ 30)
end
-- main --
local speakers = { peripheral.find("speaker") }
local tapes = { peripheral.find("tape_drive") }
if #speakers == 0 and #tapes == 0 then
error("You need a tapedrive or speaker in order to use YouCube!")
end
local youcubeapi = libs.youcubeapi.API.new()
local audiodevices = {}
for _, speaker in pairs(speakers) do
table.insert(audiodevices, libs.youcubeapi.Speaker.new(speaker))
end
for _, tape in pairs(tapes) do
table.insert(audiodevices, libs.youcubeapi.Tape.new(tape))
end
local last_error
local valid_audiodevices = {}
for i, audiodevice in pairs(audiodevices) do
local _error = audiodevice:validate()
if _error ~= nil then
last_error = _error
else
table.insert(valid_audiodevices, audiodevice)
end
end
if #valid_audiodevices == 0 then
error(last_error)
end
-- update check --
local function get_versions()
local url = "https://raw.githubusercontent.com/Commandcracker/YouCube/main/versions.json"
-- Check if the URL is valid
local ok, err = http.checkURL(url)
if not ok then
printError("Invalid Update URL.", "\"" .. url .. "\" ", err)
return
end
local response, http_err = http.get(url, nil, true)
if not response then
printError("Failed to retreat data from update URL. \"" .. url .. "\" (" .. http_err .. ")")
return
end
local sResponse = response.readAll()
response.close()
return textutils.unserialiseJSON(sResponse)
end
local function write_outdated(current, latest)
if libs.semver(current) ^ libs.semver(latest) then
term.setTextColor(colors.yellow)
else
term.setTextColor(colors.red)
end
term.write(current)
term.setTextColor(colors.lightGray)
term.write(" -> ")
term.setTextColor(colors.lime)
term.write(latest)
term.setTextColor(colors.white)
end
local function can_update(name, current, latest)
if libs.semver(current) < libs.semver(latest) then
term.write(name .. " ")
write_outdated(current, latest)
print()
end
end
local function update_checker()
local versions = get_versions()
if versions == nil then return end
can_update(
"youcube",
_VERSION,
versions.client.version
)
can_update(
"youcubeapi",
libs.youcubeapi._VERSION,
versions.client.libraries.youcubeapi.version
)
can_update(
"numberformatter",
libs.numberformatter._VERSION,
versions.client.libraries.numberformatter.version
)
can_update(
"semver",
tostring(libs.semver._VERSION),
versions.client.libraries.semver.version
)
can_update(
"argparse",
libs.argparse.version,
versions.client.libraries.argparse.version
)
local handshake = youcubeapi:handshake()
if libs.semver(handshake.server.version) < libs.semver(versions.server.version) then
print("Tell the server owner to update their server!")
write_outdated(handshake.server.version, versions.server.version)
print()
end
if not libs.semver(libs.youcubeapi._API_VERSION) ^ libs.semver(handshake.api.version) then
print("Client is not compatible with server")
term.setTextColor(colors.red)
term.write(libs.youcubeapi._API_VERSION)
term.setTextColor(colors.lightGray)
term.write(" ^ ")
term.setTextColor(colors.red)
term.write(handshake.api.version)
term.setTextColor(colors.white)
print()
end
if libs.semver(libs.youcubeapi._API_VERSION) < libs.semver(versions.api.version) then
print("Your client is using an outdated API version")
write_outdated(libs.youcubeapi._API_VERSION, versions.api.version)
print()
end
if libs.semver(handshake.api.version) < libs.semver(versions.api.version) then
print("The server is using an outdated API version")
write_outdated(libs.youcubeapi._API_VERSION, versions.api.version)
print()
end
end
local function play_audio(buffer, title)
for _, audiodevice in pairs(valid_audiodevices) do
audiodevice:reset()
audiodevice:setLabel(title)
audiodevice:setVolume(args.volume)
end
while true do
local chunk = buffer:next()
-- Adjust buffer size on first chunk
if buffer.filler.chunkindex == 1 then
buffer.size = math.ceil(1024 / (#chunk / 16))
end
if chunk == "" then
local play_functions = {}
for _, audiodevice in pairs(valid_audiodevices) do
table.insert(play_functions, function()
audiodevice:play()
end)
end
parallel.waitForAll(table.unpack(play_functions))
return
end
local write_functions = {}
for _, audiodevice in pairs(valid_audiodevices) do
table.insert(write_functions, function()
audiodevice:write(chunk)
end)
end
parallel.waitForAll(table.unpack(write_functions))
end
end
-- #region playback controll vars
local back_buffer = {}
local max_back = settings.get("youcube.max_back") or 32
local queue = {}
local restart = false
-- #endregion
local function play(url)
restart = false
print("Requesting media ...")
if not args.no_video then
youcubeapi:request_media(url, term.getSize())
else
youcubeapi:request_media(url)
end
local data
local x, y = term.getCursorPos()
repeat
data = youcubeapi:receive()
if data.action == "status" then
term.setCursorPos(x, y)
term.clearLine()
term.write("Status: ")
term.setTextColor(colors.green)
os.queueEvent("youcube:status", data)
term.write(data.message)
term.setTextColor(colors.white)
else
print()
end
until data.action == "media"
if data.action == "error" then
error(data.message)
end
term.write("Playing: ")
term.setTextColor(colors.lime)
print(data.title)
term.setTextColor(colors.white)
if data.like_count then
print("Likes: " .. libs.numberformatter.compact(data.like_count))
end
if data.view_count then
print("Views: " .. libs.numberformatter.compact(data.view_count))
end
if not args.no_video then
-- wait, that the user can see the video info
sleep(2)
end
local video_buffer = libs.youcubeapi.Buffer.new(
libs.youcubeapi.VideoFiller.new(
youcubeapi,
data.id,
term.getSize()
),
--[[
Most videos run on 30 fps, so we store 2s of video.
]]
60
)
local audio_buffer = libs.youcubeapi.Buffer.new(
libs.youcubeapi.AudioFiller.new(
youcubeapi,
data.id
),
--[[
We want to buffer 1024 chunks.
One chunks is 16 bits.
The server (with default settings) sends 32 chunks at once.
]]
32
)
if args.verbose then
term.clear()
term.setCursorPos(1, 1)
term.write("[DEBUG MODE]")
end
parallel.waitForAny(
function()
-- Fill Buffers
while true do
os.queueEvent("youcube:fill_buffers")
os.pullEvent()
if not args.no_audio then
audio_buffer:fill()
end
if args.verbose then
term.setCursorPos(1, ({ term.getSize() })[2])
term.clearLine()
term.write("Audio_Buffer: " .. #audio_buffer.buffer)
end
if not args.no_video then
video_buffer:fill()
end
end
end,
function()
os.queueEvent("youcube:playing")
parallel.waitForAll(
function()
if not args.no_video then
local string_unpack
if not string.unpack then
string_unpack = libs.string_pack.unpack
end
os.queueEvent("youcube:vid_playing", data)
libs.youcubeapi.play_vid(video_buffer, string_unpack)
os.queueEvent("youcube:vid_eof", data)
end
end,
function()
if not args.no_audio then
os.queueEvent("youcube:audio_playing", data)
play_audio(audio_buffer, data.title)
os.queueEvent("youcube:audio_eof", data)
end
end
)
end,
function()
while true do
local _, key = os.pullEvent("key")
if key == (settings.get("youcube.keys.skip") or keys.d) then
table.insert(back_buffer, url) --finished playing, push the value to the back buffer
if #back_buffer > max_back then
table.remove(back_buffer, 1) --remove it from the front of the buffer
end
if not args.no_video then
libs.youcubeapi.reset_term()
end
break
elseif key == (settings.get("youcube.keys.restart") or keys.r) then
table.insert(queue, url) --add the current song to upcoming
if not args.no_video then
libs.youcubeapi.reset_term()
end
restart = true
break
end
end
end
)
if data.playlist_videos then
return data.playlist_videos
end
end
local function play_playlist(playlist)
queue = playlist
if args.shuffle then
local shuffled = {}
for i, v in pairs(queue) do
local pos = math.random(1, #shuffled + 1)
table.insert(shuffled, pos, v)
end
queue = shuffled
end
while #queue ~= 0 do
local pl = table.remove(queue)
parallel.waitForAny(
function()
while true do
local _, key = os.pullEvent("key")
if key == (settings.get("youcube.keys.back") or keys.a) then
table.insert(queue, pl) --add the current song to upcoming
local prev = table.remove(back_buffer)
if prev then --nil/false check
table.insert(queue, prev) --add previous song to upcoming
end
if not args.no_video then
libs.youcubeapi.reset_term()
end
break
end
end
end,
function()
play(pl) --play the url
end
)
end
end
local function main()
youcubeapi:detect_bestest_server(args.server, args.verbose)
pcall(update_checker)
if not args.URL then
print("Enter Url or Search Term:")
term.setTextColor(colors.lightGray)
args.URL = read()
term.setTextColor(colors.white)
end
local playlist_videos = play(args.URL)
if args.loop == true then
while true do
play(args.URL)
end
end
if playlist_videos then
if args.loop_playlist == true then
while true do
if playlist_videos then
play_playlist(playlist_videos)
end
end
end
play_playlist(playlist_videos)
end
while restart do
play(args.URL)
end
youcubeapi.websocket.close()
if not args.no_video then
libs.youcubeapi.reset_term()
end
os.queueEvent("youcube:playback_ended")
end
main()