-
Notifications
You must be signed in to change notification settings - Fork 351
/
ytfzf
executable file
·3787 lines (3202 loc) · 119 KB
/
ytfzf
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env sh
# state variables
: "${__is_submenu:=0}" "${__is_fzf_preview:=0}"
# versioning system:
# major.minor.bugs
YTFZF_VERSION="git-2051.a67ba26"
#ENVIRONMENT VARIABLES {{{
: "${YTFZF_CONFIG_DIR:=${XDG_CONFIG_HOME:-$HOME/.config}/ytfzf}"
: "${YTFZF_CONFIG_FILE:=$YTFZF_CONFIG_DIR/conf.sh}"
: "${YTFZF_SUBSCRIPTIONS_FILE:=$YTFZF_CONFIG_DIR/subscriptions}"
: "${YTFZF_THUMBNAIL_VIEWERS_DIR:=$YTFZF_CONFIG_DIR/thumbnail-viewers}"
: "${YTFZF_SORT_NAMES_DIR:=$YTFZF_CONFIG_DIR/sort-names}"
: "${YTFZF_CUSTOM_INTERFACES_DIR:=$YTFZF_CONFIG_DIR/interfaces}"
: "${YTFZF_URL_HANDLERS_DIR:=$YTFZF_CONFIG_DIR/url-handlers}"
: "${YTFZF_CUSTOM_THUMBNAILS_DIR:=$YTFZF_CONFIG_DIR/thumbnails}"
: "${YTFZF_EXTENSIONS_DIR:=$YTFZF_CONFIG_DIR/extensions}"
: "${YTFZF_CUSTOM_SCRAPERS_DIR:=$YTFZF_CONFIG_DIR/scrapers}"
: "${YTFZF_SYSTEM_ADDON_DIR:=/usr/local/share/ytfzf/addons}"
: "${YTFZF_TEMP_DIR:="${TMPDIR:-/tmp}"/ytfzf-$(id -u)}"
: "${YTFZF_LOGFILE:=}"
if [ "$YTFZF_LOGFILE" ] && { [ "$__is_fzf_preview" -eq 1 ] || [ "$__is_submenu" -eq 1 ]; }; then
printf "[%s]\n==============\nSubmenu: %d\nFzf Preview: %d\n==============\n" "$(date)" "$__is_submenu" "$__is_fzf_preview" >>"${YTFZF_LOGFILE}"
elif [ "${YTFZF_LOGFILE}" ]; then
: >"${YTFZF_LOGFILE}"
fi
! [ -d "$YTFZF_TEMP_DIR" ] && mkdir -p "${YTFZF_TEMP_DIR}"
export YTFZF_PID=$$
#}}}
############################
# DEBUGGING #
############################
# There are only a couple tooling methods that I know of for debugging (other than printing stuff everywhere)
# set log_level to 3, and set YTFZF_LOGFILE=./some-file.log
# set -x may also be used.
############################
# CODE STYLE #
############################
##################
# VARIABLE NAMES #
##################
# Starts with __ if it is a state variable thatt is allowed to be accessed globally.
# for example: __is_submenu is a state variable that keeps track of whether or not itt is a submenu
# another example: __scrape_count is the current scrape number
# Environment variables should be all caps, do not use full caps for constansts
# Const variable should start with c_ or const_
# Configuration variables should not start with any prefix, and should have a --long-opt equivelent with as close of a name as posisble to the variable
# example: the search_source variable has the long opt equivelent of --search-source
# Private variables should start with an _
# A major exception to this is the _search variable, which is global, and should not be used as a local variable.
##################
# FUNCTION NAMES #
##################
# Private functions should start with an _
# All other functions that should be accessed globally should not start with an _
# A major exception to this is _get_request which is a global function
# interface functions MUST start with interface_ in order to work properly
# scraper functions MUST start with scrape_ in order to work properly
############################
# ERRORS #
############################
# 0: success
# 1: general error
# 2: invalid -opt or command argument, invalid argument for opt, configuration error
# eg: ytfzf -c terminal (invalid scrape)
# 3: missing dependency
# 4: scraping error
# 5: empty search
# *: Likely a curl error
############################
# CODE #
############################
# colors {{{
c_red="\033[1;31m"
c_green="\033[1;32m"
c_yellow="\033[1;33m"
c_blue="\033[1;34m"
c_magenta="\033[1;35m"
c_cyan="\033[1;36m"
c_reset="\033[0m"
c_bold="\033[1m"
#}}}
: "${check_vars_exists:=${YTFZF_CHECK_VARS_EXISTS:-1}}"
# __ytfzf__ extension {{{
print_help___ytfzf__() {
#the [2A will clear the \n---__ytfzf__--- garbage (in supported terminals)
printf "\033[2A%s" \
"Usage: ytfzf [OPTIONS...] <search-query>
The search-query can also be read from stdin
GENERAL OPTIONS:
-h Show this help text
--version Get the current version
--version-all Get the current version of ytfzf,
and required dependencies
UTILITY OPTIONS:
--channel-link=<link> Gets the uuid of a youtube channel from a link.
PLAYING OPTIONS:
-d Download the selected video(s)
-m Only play audio
-f Select a video format before playing
--format-selection=<type>
Type can either be normal, or simple
--format-sort=<sort> The sort used in ytdl for -f.
--video-pref=<pref> The ytdl video preference.
--audio-pref=<pref> The ytdl audio preference.
--ytdl-pref=<pref> The combined ytdl video and audio preference.
-u <url handler> The program to use for handling urls
(deafult: multimedia_player)
-L Show the link of selected video(s)
-I <info> Instead of playing the selected video(s),
get information about them.
Options can be separated with a comma,
eg: L,R
Options for info:
L: print the link of the video
VJ: print the json of the video
J: print the json of all videos
shown in the search
R: print the data
of the selected videos,
as appears in the menu
F: print the selected video format
--info-wait When -I or -L is used,
wait for user input before continuing
--info-action=<action>
The action to do when --info-wait is 1.
action can be one of
q: exit
Q: exit (bypass -l)
'': play video
--detach Detach the url handler from the terminal
--notify-playing Sends a notification when a video is selected.
--url-handler-opts=<opts>
Pass the given opts to the url handler.
--ytdl-opts=<opts> Pass the opts to ytdl when downloading
--ytdl-path=<path> The path to youtube-dl
MENU OPTIONS:
-l Reopen the menu when the video stops playing
-t Show thumbnails
-T <viewer> The program to use for displaying thumbnails.
see ytfzf(1) for a list of viewers.
--async-thumbnails Download thumbnails asynchronously.
--skip-thumb-download Skips the process of downloading thumbnails
--thumbnail-quality=<quality>
Select quality of thumbnails,
can be:
maxres
maxresdefault
sddefault
high (default)
medium
default
start
middle
end
-i <interface> The interface to use (default: text)
-D Alias for -i ext
-a Automatically select the first video
-r Automatically select a random video
-A Select all videos
-S <sed address> Automatically selects a specific video
based on a given sed address
-n <video count> The amount of videos to select with -a and -r
--preview-side=<side> The side to show the preview on in fzf:
left
right
up
down
--fancy-subs Adds a divider between each subscription
when scraping subscriptions
--sort Sorts video results by a sort name,
The default sort name is upload-date
To change sort names use --sort=<name>
--sort-name=<name> Load a different sorting algorithm for --sort
To see usable sort-names, use --list-addons
--disable-submenus Whether or not to disable submenus,
which are menus for results like:
playlists and channels
--disable-back Disables the back button in submenus
--disable-actions Disables actions such as submenus, and the back button.
--keep-vars Options passed to ytfzf are kept in submenus.
--submenu-opts=<opts> ytfzf options to pass to submenus.
SEARCH OPTIONS:
-s After closing fzf make another search
-q Use a search query from search history
see ytfzf(1) for more info.
--search-source=<source>
The place to get the search from
see ytfzf(1) for more information
--multi-search Allow multiple searches seperated by ,
--pages The amount of pages to scrape
does not work with some scrapers.
--pages-start=<page> The page number to start on
--odysee-video-count The amount of videos to scrape from odysee
--nsfw Enable nsfw videos (odysee only)
--sort-by=<sort> Searches for videos sorted by:
relevance
rating (youtube only)
upload_date
oldest_first (odysee only)
view_count (youtube only)
--upload-date=<time> Searches for videos that were uploaded:
hour
today
week
month
year
--video-duration=<time> Searches for videos that are:
short
medium
long
--type=<type> Searches for uploads of type:
video
playlist
channel
all
--features=<features> Searches for videos with features:
hd
subtitles
creative_commons
3d
live
4k
360
location
hdr
--region=<country-code> The region to search.
-c <scraper> The scraper to use,
See ytfzf(1) for a list of builtin scrapers
you can use multiple scrapers
by separating each with a comma, eg:
youtube,odysee
--scrape+=<scraper> Use another scraper
--scrape-=<scraper> Dont use a scraper.
-H alias for -c H
--ii=<instance> The invidious instance to use for scraping.
--force-youtube Converts invidious links to youtube links
before playing (enabled by default)
--force-invidious Uses the chosen invidious instance
instead of converting to a youtube link
ADDON OPTIONS:
-e <extention> Load an extention
--list-addons Show available addons
MISC OPTIONS:
-x Clear search and watch history
--history-clear=<type> Clear either search, or watch history.
--max-threads=<count> The amount of threads that should be spawned
at any given time.
--single-threaded Same as --max-threads=1
--rii Refreseh invidious instance cache
--available-inv-instances
Shows the invidious instances
that ytfzf may pick from
--keep-cache Do not delete the cache files.
--thumbnail-log Write thumbnail errors to this file.
See ytfzf(1) and ytfzf(5) for more information.
"
}
handle_playing_notifications() {
# if no notify-send push error to /dev/null
if [ "$#" -le 1 ]; then
unset IFS
while read -r id title; do
notify-send -c ytfzf -i "$thumb_dir/${id}.jpg" "Ytfzf Info" "Opening: $title" 2>/dev/null
done <<-EOF
$(jq -r '.[]|select(.url=="'"$*"'")|"\(.ID)\t\(.title)"' <"$ytfzf_video_json_file")
EOF
else
notify-send -c ytfzf "ytfzf info" "Opening: $# videos" 2>/dev/null
fi
}
on_open_url_handler___ytfzf__() {
[ "$notify_playing" -eq 1 ] && handle_playing_notifications "$@"
}
on_clean_up___ytfzf__() {
# print_info "cleaning up\n"
# clean up only as parent process
# kill ytfzf sub process{{{
# I think this needs to be written to a file because of sub-shells
jobs_file="${YTFZF_TEMP_DIR}/the-jobs-need-to-be-written-to-a-file-$$.list"
jobs -p >"$jobs_file"
while read -r line; do
[ "$line" ] && kill "$line" 2>/dev/null
done <"$jobs_file"
rm -f "$jobs_file"
#}}}
if [ "$__is_fzf_preview" -eq 0 ]; then
[ "$keep_cache" -eq 1 ] && print_debug "[CLEAN UP]: copying cache dir" && cp -r "${session_cache_dir}" "${cache_dir}"
[ -d "$session_cache_dir" ] && rm -rf "$session_cache_dir"
fi
}
on_load_fake_extension___ytfzf__() {
#these need to be here, because it modifies stuff for _getopts
#also no harm done because enable_hist cannot be set to true with an --option
#do not check if hist is enabled, because on_load_fake_extension___ytfzf_history__ does that
load_fake_extension "__ytfzf_history__" "1"
load_fake_extension "__ytfzf_search_history__" "1"
}
on_post_set_vars___ytfzf__() {
[ -z "$ytdl_path" ] && { command_exists "yt-dlp" && ytdl_path="yt-dlp" || ytdl_path="youtube-dl"; }
: "${ytdl_pref:=$video_pref+$audio_pref/best/$video_pref/$audio_pref}"
: "${shortcut_binds="Enter,double-click,${download_shortcut},${video_shortcut},${audio_shortcut},${detach_shortcut},${print_link_shortcut},${show_formats_shortcut},${info_shortcut},${search_again_shortcut},${custom_shortcut_binds},${custom_shortcut_binds}"}"
[ ! -d "$cache_dir" ] && mkdir -p "$cache_dir"
# If file doesn't already exist (or if force-refresh is requested), cURL and cache it.
# CHECK: implement check for force-request
# CHECK: added --refresh-inv-instances to optargs
[ ! -f "$instances_file" ] && refresh_inv_instances
: "${invidious_instance:=$(get_random_invidious_instance)}"
#if there is no domain, use the chosen invidious instance
[ -z "${yt_video_link_domain}" ] && yt_video_link_domain="${invidious_instance}"
export FZF_DEFAULT_OPTS="--margin=0,3,0,0 $FZF_DEFAULT_OPTS"
[ "$multi_search" -eq 1 ] && load_fake_extension "__ytfzf_multisearch__"
scrape_search_exclude="${scrape_search_exclude}${custom_scrape_search_exclude} "
source_scrapers
print_debug "${new_line}=============${new_line}VARIABLE DUMP${new_line}============="
print_debug "$(set)"
print_debug "${new_line}============${new_line}END VAR DUMP${new_line}============"
}
#}}}
# __ytfzf_multisearch__ extension {{{
on_init_search___ytfzf_multisearch__() {
prepare_for_set_args ","
# shellcheck disable=SC2086
set -- $1
end_of_set_args
__total_search_count="$#"
printf "%s\n" "$@" >"${session_cache_dir}/searches.list"
# if we get rid of everything up to the first comma, and it's empty or equal to the original, there is 1 scrape
if [ "$__total_scrape_count" -lt "$__total_search_count" ]; then
scrape=$(mul_str "${scrape}," "$(($(wc -l <"${session_cache_dir}/searches.list") / __total_scrape_count))")
set_scrape_count
fi
}
ext_on_search___ytfzf_multisearch__() {
get_search_from_source "next"
}
get_search_from_next() {
_search=$(head -n "$__scrape_count" "${session_cache_dir}/searches.list" | tail -n 1)
}
# }}}
# __ytfzf_history_management__ {{{
on_load_fake_extension___ytfzf_history_management__() {
on_opt_parse_x() {
clear_hist "${1:-all}"
exit 0
}
on_opt_parse_hist_clear() { on_opt_parse_x "$@"; }
clear_hist() {
case "$1" in
search)
: >"$search_hist_file"
print_info "Search history cleared"
;;
watch)
: >"$hist_file"
print_info "Watch history cleared"
;;
*)
: >"$search_hist_file"
: >"$hist_file"
print_info "History cleared"
;;
esac
}
}
# }}}
# __ytfzf_history__ extension {{{
on_load_fake_extension___ytfzf_history__() {
! extension_is_loaded "__ytfzf_history_management__" && load_fake_extension "__ytfzf_history_management__"
: "${hist_file:="$cache_dir/watch_hist"}"
on_opt_parse_history() {
if [ "$enable_hist" -eq 0 ]; then
die 1 "enable_hist must be set to 1 for -H/--history"
fi
scrape=history
}
on_opt_parse_H() {
on_opt_parse_history "$@"
}
}
on_open_url_handler___ytfzf_history__() {
add_to_hist "$ytfzf_video_json_file" <"$ytfzf_selected_urls"
}
add_to_hist() {
[ "$enable_hist" -eq 1 ] || return
print_debug "[WATCH HIST]: adding to file $hist_file"
# id of the video to add to hist will be passed through stdin
# if multiple videos are selected, multiple ids will be present on multiple lines
json_file="$1"
urls="$(printf '"%s",' $(cat))"
urls="[${urls%,}]"
jq -r '[ .[]|select(.url as $url | '"$urls"' | index($url) >= 0)]' <"$json_file" | sed "/\[\]/d" | sed "2s/$/\n \"viewed\": \"$(date +'%m\/%d\/%y\ %H\:%M\:%S\ %z')\",/" >>"$hist_file"
unset url urls json_file
}
scrape_history() {
enable_hist=0 # enabling history while scrape is history causes issues
scrape_json_file "$hist_file" "$2"
cp "$2" "$2.tmp"
jq -s '[.[]|.[]+{scraper: "watch_history"}]' <"$2.tmp" >"$2"
rm "$2.tmp"
}
scrape_H() { scrape_history "$@"; }
video_info_text_watch_history() {
viewed_len=19
[ "${views#"|"}" -eq "${views#"|"}" ] 2>/dev/null && views="|$(printf "%s" "${views#"|"}" | add_commas)"
printf "%-${title_len}.${title_len}s\t" "$title"
printf "%-${channel_len}.${channel_len}s\t" "$channel"
printf "%-${dur_len}.${dur_len}s\t" "$duration"
printf "%-${view_len}.${view_len}s\t" "$views"
printf "%-${date_len}.${date_len}s\t" "$date"
printf "%-${viewed_len}.${viewed_len}s\t" "$viewed"
printf "%s" "$url"
printf "\n"
}
# }}}
# __ytfzf_search_history__ extension {{{
on_load_fake_extension___ytfzf_search_history__() {
! extension_is_loaded "__ytfzf_history_management__" && load_fake_extension "__ytfzf_history_management__"
: "${search_hist_file:="$cache_dir/search_hist"}"
on_opt_parse_q() {
if [ "$enable_search_hist" -eq 0 ]; then
die 1 "In order to use this search history must be enabled"
fi
[ ! -s "$search_hist_file" ] && die 1 "You have no search history"
search_source="hist"
}
on_opt_parse_search_hist() {
on_opt_parse_q "$@"
}
}
on_post_set_vars___ytfzf_search_history__() {
[ "${use_search_hist:-0}" -eq 1 ] && print_warning "use_search_hist is deprecated, please use search_source=hist instead" && search_source=hist
}
on_init_search___ytfzf_history__() {
[ "$enable_search_hist" -eq 1 ] && [ -n "$_search" ] && [ "$__is_submenu" -eq 0 ] && [ "$__is_fzf_preview" -eq 0 ] && handle_search_history "$_search" "$search_hist_file"
}
get_search_from_hist() {
_search="$(parse_search_hist_file <"$search_hist_file" | quick_menu_wrapper)"
}
parse_search_hist_file() {
awk -F"${tab_space}" '{ if ($2 == "") {print $1} else {print $2} }'
}
handle_search_history() {
printf "%s${tab_space}%s\n" "$(date +'%D %H:%M:%S %z')" "${1}" >>"$2"
}
# }}}
# Utility functions {{{
############################
# UTILITY FUNCTIONS #
############################
# In order to be a utility function it must meet the following requirements:
# Does not have side effects
# Can be redefined by the user in an extension or config file
## Jq util{{{
jq_pad_left='
def pad_left(n; num):
num | tostring |
if (n > length) then ((n - length) * "0") + (.) else . end
'
# }}}
# Invidious{{{
refresh_inv_instances() {
print_info "Fetching list of healthy invidious instances ..." &&
# The pipeline does the following:
# - Fetches the avaiable invidious instances
# - Gets the one where the api is public
# - Puts them in a list
curl -X GET -sSf "$instances_url" | jq -r '[.[]|select(.[1].api==true)|.[1].uri]|join("\n")' >"$instances_file"
}
get_invidious_instances() {
cat "$instances_file"
}
get_random_invidious_instance() {
shuf "$instances_file" | head -n 1
}
# }}}
# General Scraping{{{
_get_request() {
_base_url=$1
shift 1
# Get search query from youtube
curl -f "$_base_url" -s -L \
"$@" \
-H "User-Agent: $useragent" \
-H 'Accept-Language: en-US,en;q=0.9' \
--compressed
}
create_sorted_video_data() {
jq -c -r 'select(.!=[])|.[]' <"$ytfzf_video_json_file" | sort_video_data_fn
}
download_thumbnails() {
[ "$skip_thumb_download" -eq 1 ] && {
print_info "Skipping thumbnail download"
return 0
}
[ "$async_thumbnails" -eq 0 ] && print_info "Fetching thumbnails...${new_line}"
curl_config_file="${session_temp_dir}/curl_config"
[ -z "$*" ] && return 0
: >"$curl_config_file"
for line in "$@"; do
printf "url=\"%s\"\noutput=\"$thumb_dir/%s.jpg\"\n" "${line%%';'*}" "${line##*';'}"
done >>"$curl_config_file"
curl -fLZ -K "$curl_config_file"
[ $? -eq 2 ] && curl -fL -K "$curl_config_file"
}
get_missing_thumbnails() {
# this function could be done in a more pure-shell way, however it is extremely slow
_tmp_id_list_file="${session_temp_dir}/all-ids.list"
_downloaded_ids_file="${session_temp_dir}/downloaded-ids.list"
# gets all ids and writes them to file
jq -r '.[]|select(.thumbs!=null)|.ID' <"$ytfzf_video_json_file" | sort | uniq >"$_tmp_id_list_file"
# gets thumb urls, and ids, and concatinates them such as: <thumbnail>;<id>
# essencially gets all downloaded thumbnail ids, by checking $thumb_dir and substituting out the \.jpg at the end
find "$thumb_dir" -type f | sed -n 's/^.*\///; s/\.jpg$//; /^[^\/]*$/p' | sort >"$_downloaded_ids_file"
# Finds ids that appear in _tmp_id_list_file only
# shellcheck disable=SC2089
missing_ids="\"$(diff "$_downloaded_ids_file" "$_tmp_id_list_file" | sed -n 's/^[>+] *\(.*\)$/\1/p')\""
# formats missing ids into the format: <thumb-url>;<id>
jq --arg ids "$missing_ids" -r '.[]|select(.thumbs!=null)|select(.ID as $id | $ids | contains($id))|.thumbs + ";" + .ID' <"$ytfzf_video_json_file"
unset _tmp_id_list_file _downloaded_ids_file missing_ids
}
# }}}
#arg/ifs manipulation{{{
prepare_for_set_args() {
OLD_IFS=$IFS
[ "$1" = "" ] && unset IFS || IFS=$1
set -f
}
end_of_set_args() {
IFS=$OLD_IFS
}
modify_ifs() {
OLD_IFS=$IFS
IFS=${1:-" ${tab_space}${new_line}"}
}
end_modify_ifs() {
IFS=$OLD_IFS
}
# }}}
#general util{{{
_get_real_channel_link() {
_input_link=$(trim_blank "$1")
case "$1" in
http?://*/@*)
domain=${_input_link#https://}
domain=${domain%%/*}
url=$(printf "https://www.youtube.com/channel/%s\n" "$(_get_request "$_input_link" | sed -n 's/.*"channelId":"\([^"]\+\).*/\1/p')")
_get_real_channel_link_handle_empty_real_path() {
printf "$url"
}
;;
http?://*/c/* | http?://*/user/* | *\.*)
domain=${_input_link#https://}
domain=${domain%%/*}
url=$(printf "%s" "$_input_link" | sed 's_\(https://\)*\(www\.\)*youtube\.com_'"${invidious_instance}"'_')
_get_real_channel_link_handle_empty_real_path() {
printf "https://%s\n" "${1#https://}"
}
;;
[Uu][Cc]??????????????????????/videos | [Uu][Cc]?????????????????????? | *channel/[Uu][Cc]?????????????????????? | *channel/[Uu][Cc]??????????????????????/videos)
id="${_input_link%/videos}"
id="${id%/playlists}"
id="${id%/streams}"
id="${id##*channel/}"
print_warning "$_input_link appears to be a youtube id, which is hard to detect, please use a full channel url next time"
domain="youtube.com"
url=$(printf "https://youtube.com/channel/%s/videos" "$id" | sed 's_\(https://\)*\(www\.\)*youtube\.com_'"${invidious_instance}"'_')
_get_real_channel_link_handle_empty_real_path() {
printf "%s\n" "https://${domain}/channel/${id}/videos"
}
;;
"@"*)
for link in "https://www.youtube.com/user/${1#"@"}" "https://www.youtube.com/c/${1#"@"}"; do
_real_link="$(_get_real_channel_link "$link")"
if [ "$_real_link" != "$link" ]; then
printf "%s\n" "$_real_link"
return 0
fi
done
return 1
;;
*)
_get_real_channel_link_handle_empty_real_path() {
printf "$1\n"
}
;;
esac
real_path="$(curl -is "$url" | sed -n 's/^[Ll]ocation: //p' | sed 's/[\n\r]$//g')"
# prints the origional url because it was correct
if [ -z "$real_path" ]; then
_get_real_channel_link_handle_empty_real_path "$_input_link"
return 0
fi
printf "%s\n" "https://${domain}${real_path}"
}
trim_url() {
while IFS= read -r _line; do
printf '%s\n' "${_line##*"|"}"
done
}
trim_blank() {
sed -e 's/^[[:blank:]]*//g' -e 's/[[:blank:]]*$//g' <<EOF
$1
EOF
}
command_exists() {
command -v "$1" >/dev/null 2>&1
}
is_relative_dir() {
case "$1" in
../* | ./* | ~/* | /*) return 0 ;;
esac
return 1
}
get_key_value() {
sep="${3:- }"
value="${1##*"${sep}""${2}"=}"
# this can be used similarly to how you use $REPLY in bash
KEY_VALUE="${value%%"${sep}"*}"
printf "%s" "$KEY_VALUE"
unset value
[ "$KEY_VALUE" ]
return "$?"
}
# capitalizes the first letter of a string
title_str() {
awk '{printf "%s%s\n", toupper(substr($1,0,1)), substr($1,2)}' <<-EOF
$1
EOF
}
# backup shuf function, as shuf is not posix
command_exists "shuf" || shuf() {
#make awk read from fd 3, fd 3 will read $1 if exists, or stdin
[ "$1" ] && exec 3<"$1" || exec 3<&0
awk -F'\n' 'BEGIN{srand()} {print rand() " " $0}' <&3 | sort -n | sed 's/[^ ]* //'
exec 3<&-
}
add_commas() {
awk '
{
for(i=0; i<length($1); i++){
if(i % 3 == 0 && i!=0){
printf ","
}
printf "%s", substr($1, length($1) - i, 1)
}
}
END{
print ""
}' |
awk '
{
for (i=length($1); i>0; i--){
printf "%s", substr($1, i, 1)
}
}
'
}
mul_str() {
str=$1
by=$2
new_str="$str"
mul_str_i=1
while [ "$mul_str_i" -lt "$by" ]; do
new_str="${new_str}${str}"
mul_str_i=$((mul_str_i + 1))
done
printf "%s" "$new_str"
unset mul_str_i new_str by str
}
detach_cmd() {
nohup "$@" >"/dev/null" 2>&1 &
}
remove_ansi_escapes() {
sed -e 's/[[:cntrl:]]\[\([[:digit:]][[:digit:]]*\(;\|m\)\)*//g'
}
# }}}
#Menu stuff{{{
quick_menu() {
fzf --ansi --reverse --prompt="$1"
}
quick_menu_ext() {
external_menu "$1"
}
info_wait_prompt() {
printf "%s\n" "quit [q]" "quit (override -l) [Q]" "open menu [c]" "play [enter]"
read -r info_wait_action
}
info_wait_prompt_ext() {
info_wait_action=$(printf "%s\n" "quit: q" "quit (override -l): Q" "open menu: c" "play: enter" | quick_menu_wrapper "Choose action" | sed -e 's/enter//' -e 's/^.*: \(.*\)$/\1/p' | tr -d '[:space:]')
}
display_text() {
printf "%s\n" "$@"
}
display_text_ext() {
display_text "$@"
}
display_text_wrapper() {
generic_wrapper "display_text" "$@"
}
info_wait_prompt_wrapper() {
generic_wrapper "info_wait_prompt" "$@"
}
search_prompt_menu_wrapper() {
generic_wrapper "search_prompt_menu" "$@"
}
quick_menu_wrapper() {
generic_wrapper "quick_menu" "$1"
}
generic_wrapper() {
base_name=$1
shift
fn_name="$base_name""$(printf "%s" "${interface:+_$interface}" | sed 's/-/_/g')"
if command_exists "$fn_name"; then
print_debug "[INTERFACE]: Running menu function: $fn_name"
$fn_name "$@"
else
print_debug "[INTERFACE]: Menu function $fn_name did not exist, falling back to ${base_name}_ext"
"$base_name"_ext "$@"
fi
unset fn_name
}
# The menu to use instead of fzf when -D is specified
external_menu() {
# dmenu extremely laggy when showing tabs
tr -d '\t' | remove_ansi_escapes | dmenu -i -l 30 -p "$1"
}
search_prompt_menu() {
printf "Search\n> " >/dev/stderr
read -r _search
printf "\033[1A\033[K\r%s\n" "> $_search" >/dev/stderr
}
search_prompt_menu_ext() {
_search="$(printf '' | external_menu "Search: ")"
}
run_interface() {
if [ "$show_thumbnails" -eq 1 ]; then
prepare_for_set_args
case "$async_thumbnails" in
0) download_thumbnails $(get_missing_thumbnails) ;;
1) download_thumbnails $(get_missing_thumbnails) >/dev/null 2>&1 & ;;
esac
end_of_set_args
fi
_interface="interface_${interface:-text}"
print_debug "[INTERFACE]: Running interface: $_interface"
$(printf "%s" "$_interface" | sed 's/-/_/g') "$ytfzf_video_json_file" "$ytfzf_selected_urls"
unset _interface
}
_init_video_info_text() {
TTY_COLS=$1
command_exists "column" && use_column=1 || {
use_column=0
print_warning "command \"column\" not found, the menu may look very bad"
}
title_len=$((TTY_COLS / 2))
channel_len=$((TTY_COLS / 5))
dur_len=7
view_len=10
date_len=14
}
_post_video_info_text() {
if [ "$use_column" = "1" ]; then
column -t -s "$tab_space"
else
cat
fi
}
_video_info_text() {
[ "${views#"|"}" -eq "${views#"|"}" ] 2>/dev/null && views="|$(printf "%s" "${views#"|"}" | add_commas)"
printf "%-${title_len}.${title_len}s\t" "$title"
printf "%-${channel_len}.${channel_len}s\t" "$channel"
printf "%-${dur_len}.${dur_len}s\t" "$duration"
printf "%-${view_len}.${view_len}s\t" "$views"
printf "%-${date_len}.${date_len}s\t" "$date"
printf "%s" "$url"
printf "\n"
}
#This function generates a series of lines that will be displayed in fzf, or some other interface
#takes in a series of jsonl lines, each jsonl should follow the VIDEO JSON FORMAT
video_info_text() {
jq -r '[.title, .channel, .duration, .views, .date, .viewed, .url, .scraper]|join("\t|")' | while IFS="$tab_space" read -r title channel duration views date viewed url scraper; do
scraper="${scraper#"|"}"
fn_name=video_info_text_"${scraper}"
if command_exists "$fn_name"; then
"$fn_name" "$title" "$channel" "$duration" "$views" "$date" "$viewed" "$url" "$scraper"
else
_video_info_text "$title" "$channel" "$duration" "$views" "$date" "$viewed" "$url" "$scraper"
fi
done
unset title channel duration views date viewed url scraper
}
# This is completely unrelated to video_info_text
# It is used in preview_img for when text should appear in the preview in fzf
thumbnail_video_info_text() {
[ "$views" -eq "$views" ] 2>/dev/null && views="$(printf "%s" "$views" | add_commas)"
[ -n "$title" ] && printf "\n ${c_cyan}%s" "$title"
[ -n "$channel" ] && printf "\n ${c_blue}Channel ${c_green}%s" "$channel"
[ -n "$duration" ] && printf "\n ${c_blue}Duration ${c_yellow}%s" "$duration"
[ -n "$views" ] && printf "\n ${c_blue}Views ${c_magenta}%s" "$views"
[ -n "$date" ] && printf "\n ${c_blue}Date ${c_cyan}%s" "$date"
[ -n "$viewed" ] && printf "\n ${c_blue}Viewed ${c_cyan}%s" "$viewed"
[ -n "$description" ] && printf "\n ${c_blue}Description ${c_reset}: %s" "$(printf "%s" "$description" | sed 's/\\n/\n/g')"
}