-
Notifications
You must be signed in to change notification settings - Fork 19
/
jerry.sh
executable file
·1601 lines (1501 loc) · 86.3 KB
/
jerry.sh
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
#!/bin/sh
JERRY_VERSION=1.9.9
anilist_base="https://graphql.anilist.co"
config_file="$HOME/.config/jerry/jerry.conf"
jerry_editor=${VISUAL:-${EDITOR}}
tmp_dir="/tmp/jerry"
tmp_position="/tmp/jerry_position"
cleanup() {
# tput clear
rm -rf "$tmp_dir" 2>/dev/null
if [ "$image_preview" = true ] && [ "$use_external_menu" = false ]; then
killall ueberzugpp 2>/dev/null
rm /tmp/ueberzugpp-* 2>/dev/null
fi
}
trap cleanup EXIT INT TERM
applications="$HOME/.local/share/applications/jerry"
images_cache_dir="/tmp/jerry/jerry-images"
command -v bat >/dev/null 2>&1 && display="bat" || display="less"
case "$(uname -s)" in
MINGW* | *Msys) separator=';' && path_thing='' && sed="sed" ;;
*arwin) sed="gsed" && player="iina" ;;
*) separator=':' && path_thing="\\" && sed="sed" ;;
esac
command -v notify-send >/dev/null 2>&1 && notify="true" || notify="false"
send_notification() {
[ "$json_output" = true ] && return
if [ "$use_external_menu" = false ] || [ -z "$use_external_menu" ]; then
[ -z "$4" ] && printf "\33[2K\r\033[1;34m%s\n\033[0m" "$1" && return
[ -n "$4" ] && printf "\33[2K\r\033[1;34m%s - %s\n\033[0m" "$1" "$4" && return
fi
[ -z "$2" ] && timeout=3000 || timeout="$2"
if [ "$notify" = "true" ]; then
[ -z "$3" ] && notify-send -e "$1" "$4" -t "$timeout" -h string:x-canonical-private-synchronous:jerry
[ -n "$3" ] && notify-send -e "$1" "$4" -t "$timeout" -i "$3" -h string:x-canonical-private-synchronous:jerry
fi
}
dep_ch() {
for dep; do
command -v "$dep" >/dev/null || send_notification "Program \"$dep\" not found. Please install it."
done
}
dep_ch "grep" "$sed" "curl" "fzf" || true
if [ "$use_external_menu" = true ]; then
dep_ch "rofi" || true
fi
usage() {
printf "
Usage: %s [options] [query]
If a query is provided, it will be used to search for an anime, and will default to the 'Watch New Anime' option.
Options:
-c, --continue
Continue watching from currently watching list (using the user's anilist account)
--dub
Allows user to watch anime in dub
-e, --edit
Edit config file using an editor defined with jerry_editor in the config (\$EDITOR by default). If a config file does not exist, creates one with a default configuration
-d, --discord
Display currently watching anime in Discord Rich Presence (jerrydiscordpresence.py is required for this, check the wiki for instructions on how to install it)
-h, --help
Show this help message and exit
-i, --image-preview
Allows image preview in fzf and rofi
-j, --json
Outputs the json containing video links, subtitle links, referrers etc. to stdout
-l, --language
Specify the subtitle language
-n, --number
Specify the episode number for an anime
--rofi, --dmenu, --external-menu
Use an external menu (instead of the default fzf) to select an anime (default one is rofi, but this can be specified in the config file)
-q, --quality
Specify the video quality
-s, --syncplay
Watch anime together with friends, using Syncplay (only tested using mpv)
-u, --update
Update the script
-v, --version
Show the script version
--vlc
Use VLC as the video player
-w, --website
Choose which website to get video links from (default: allanime) (currently supported: allanime, aniwatch, yugen, hdrezka and crunchyroll)
Note:
All arguments can be specified in the config file as well.
If an argument is specified in both the config file and the command line, the command line argument will be used.
Some example usages:
${0##*/} -q 720 banana fish
${0##*/} --rofi -l russian cyberpunk edgerunners -i -n 2
${0##*/} -l spanish cyberpunk edgerunners --number 2 --json
" "${0##*/}"
}
configuration() {
[ -n "$XDG_CONFIG_HOME" ] && config_dir="$XDG_CONFIG_HOME/jerry" || config_dir="$HOME/.config/jerry"
[ -n "$XDG_DATA_HOME" ] && data_dir="$XDG_DATA_HOME/jerry" || data_dir="$HOME/.local/share/jerry"
[ ! -d "$data_dir" ] && mkdir -p "$data_dir"
#shellcheck disable=1090
[ -f "$config_file" ] && . "${config_file}"
if [ -z "$player" ]; then
case "$(uname -s)" in
MINGW* | *Msys) player="mpv.exe" ;;
*) player="mpv" ;;
esac
fi
[ -z "$provider" ] && provider="allanime"
[ -z "$download_dir" ] && download_dir="$PWD"
[ -z "$manga_dir" ] && manga_dir="$data_dir/jerry-manga"
[ -z "$manga_format" ] && manga_format="image"
[ -z "$manga_opener" ] && manga_opener="feh"
[ -z "$history_file" ] && history_file="$data_dir/jerry_history.txt"
[ -z "$subs_language" ] && subs_language="english"
subs_language="$(printf "%s" "$subs_language" | cut -c2-)"
[ -z "$use_external_menu" ] && use_external_menu=false
[ -z "$image_preview" ] && image_preview=false
[ -z "$json_output" ] && json_output=false
[ -z "$sub_or_dub" ] && sub_or_dub="sub"
[ -z "$score_on_completion" ] && score_on_completion="false"
[ "$no_anilist" = false ] && no_anilist=""
[ -z "$discord_presence" ] && discord_presence="false"
[ -z "$presence_script_path" ] && presence_script_path="jerrydiscordpresence.py"
[ -z "$rofi_prompt_config" ] && rofi_prompt_config="$HOME/.config/rofi/config.rasi"
if [ -z "$chafa_options" ]; then
case "$(uname -s)" in
MINGW* | *Msys) chafa_options="-f symbols" ;;
*) chafa_options="-f sixel" ;;
esac
fi
[ -z "$show_adult_content" ] && show_adult_content="false"
}
check_credentials() {
[ -f "$data_dir/anilist_token.txt" ] && access_token=$(cat "$data_dir/anilist_token.txt")
[ -z "$access_token" ] && printf "Paste your access token from this page:
https://anilist.co/api/v2/oauth/authorize?client_id=9857&response_type=token : " && read -r access_token &&
echo "$access_token" >"$data_dir/anilist_token.txt"
[ -f "$data_dir/anilist_user_id.txt" ] && user_id=$(cat "$data_dir/anilist_user_id.txt")
[ -z "$access_token" ] && exit 1
[ -z "$user_id" ] &&
user_id=$(curl -s -X POST "$anilist_base" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-H "Authorization: Bearer $access_token" \
-d "{\"query\":\"query { Viewer { id } }\"}" | $sed -nE "s@.*\"id\":([0-9]*).*@\1@p") &&
echo "$user_id" >"$data_dir/anilist_user_id.txt"
}
#### SCRAPING FUNCTIONS ####
## ALLANIME ##
# this has been adapted from ani-cli
# extract the video links from reponse of embed urls, extract mp4 links form m3u8 lists
get_links() {
episode_link="$(curl -e "$allanime_refr" -s "https://${allanime_base}$*" | sed 's|},{|\n|g' | sed -nE 's|.*link":"([^"]*)".*"resolutionStr":"([^"]*)".*|\2 >\1|p;s|.*hls","url":"([^"]*)".*"hardsub_lang":"en-US".*|\1|p')"
case "$episode_link" in
*repackager.wixmp.com*)
extract_link=$(printf "%s" "$episode_link" | cut -d'>' -f2 | sed 's|repackager.wixmp.com/||g;s|\.urlset.*||g')
for j in $(printf "%s" "$episode_link" | sed -nE 's|.*/,([^/]*),/mp4.*|\1|p' | sed 's|,|\n|g'); do
printf "%s >%s\n" "$j" "$extract_link" | sed "s|,[^/]*|${j}|g"
done | sort -nr
;;
*vipanicdn* | *anifastcdn*)
if printf "%s" "$episode_link" | head -1 | grep -q "original.m3u"; then
printf "%s" "$episode_link"
else
extract_link=$(printf "%s" "$episode_link" | head -1 | cut -d'>' -f2)
relative_link=$(printf "%s" "$extract_link" | sed 's|[^/]*$||')
curl -e "$allanime_refr" -s "$extract_link" -A "uwu" | sed 's|^#.*x||g; s|,.*|p|g; /^#/d; $!N; s|\n| >|' | sed "s|>|>${relative_link}|g" | sort -nr
fi
;;
*) [ -n "$episode_link" ] && printf "%s\n" "$episode_link" ;;
esac
printf "\033[1;32m%s\033[0m Links Fetched\n" "$provider_name" 1>&2
}
# innitialises provider_name and provider_id. First argument is the provider name, 2nd is the regex that matches that provider's link
provider_init() {
provider_name=$1
provider_id=$(printf "%s" "$resp" | sed -n "$2" | head -1 | cut -d':' -f2 | sed 's/../&\n/g' | sed 's/^01$/9/g;s/^08$/0/g;s/^05$/=/g;s/^0a$/2/g;s/^0b$/3/g;s/^0c$/4/g;s/^07$/?/g;s/^00$/8/g;s/^5c$/d/g;s/^0f$/7/g;s/^5e$/f/g;s/^17$/\//g;s/^54$/l/g;s/^09$/1/g;s/^48$/p/g;s/^4f$/w/g;s/^0e$/6/g;s/^5b$/c/g;s/^5d$/e/g;s/^0d$/5/g;s/^53$/k/g;s/^1e$/\&/g;s/^5a$/b/g;s/^59$/a/g;s/^4a$/r/g;s/^4c$/t/g;s/^4e$/v/g;s/^57$/o/g;s/^51$/i/g;' | tr -d '\n' | sed "s/\/clock/\/clock\.json/")
}
generate_links() {
case $1 in
# using gogoanime as the default provider since it provides m3u8 links and bc --start doesn't work with mp4 links (idk why)
1) provider_init "gogoanime" "/Luf-mp4 :/p" ;; # gogoanime(m3u8)(multi)
2) provider_init "wixmp" "/Default :/p" ;; # wixmp(default)(m3u8)(multi) -> (mp4)(multi)
3) provider_init "dropbox" "/Sak :/p" ;; # dropbox(mp4)(single)
4) provider_init "wetransfer" "/Kir :/p" ;; # wetransfer(mp4)(single)
5) provider_init "sharepoint" "/S-mp4 :/p" ;; # sharepoint(mp4)(single)
esac
[ -n "$provider_id" ] && get_links "$provider_id"
}
select_quality() {
case "$1" in
best) result=$(printf "%s" "$links" | head -n1) ;;
worst) result=$(printf "%s" "$links" | grep -E '^[0-9]{3,4}' | tail -n1) ;;
*) result=$(printf "%s" "$links" | grep -m 1 "$1") ;;
esac
[ -z "$result" ] && printf "Specified quality not found, defaulting to best\n" 1>&2 && result=$(printf "%s" "$links" | head -n1)
printf "%s" "$result" | cut -d'>' -f2
}
#### GENERAL HELPER FUNCTIONS ####
edit_configuration() {
if [ -f "$config_file" ]; then
#shellcheck disable=1090
. "${config_file}"
[ -z "$jerry_editor" ] && jerry_editor="vim"
"$jerry_editor" "$config_file"
else
printf "No configuration file found. Would you like to generate a default one? [Y/n] " && read -r generate
case "$generate" in
[Nn]*) exit 0 ;;
*)
[ ! -d "$config_dir" ] && mkdir -p "$config_dir"
send_notification "Jerry" "" "" "Getting the latest example config from github..."
curl -s "https://raw.githubusercontent.com/justchokingaround/jerry/main/examples/jerry.conf" -o "$config_dir/jerry.conf"
send_notification "Jerry" "" "" "New config generated!"
#shellcheck disable=1090
. "${config_file}"
[ -z "$jerry_editor" ] && jerry_editor="vim"
"$jerry_editor" "$config_file"
;;
esac
fi
exit 0
}
update_script() {
which_jerry="$(command -v jerry)"
if [ -z "$which_jerry" ]; then
send_notification "Can't find jerry in PATH"
exit 1
fi
if [ ! -w "$which_jerry" ]; then
if [ -n "$(command -v sudo)" ]; then
exec sudo -s "$which_jerry" "-u"
else
send_notification "Insufficient permissions to update and can't find sudo in PATH"
exit 1
fi
fi
update=$(curl -s "https://raw.githubusercontent.com/justchokingaround/jerry/main/jerry.sh" || exit 1)
update="$(printf '%s\n' "$update" | diff -u "$which_jerry" - 2>/dev/null)"
if [ -z "$update" ]; then
send_notification "Script is up to date :)"
else
if printf '%s\n' "$update" | patch "$which_jerry" -; then
send_notification "Script has been updated!"
else
send_notification "Can't update for some reason!"
fi
fi
exit 0
}
check_update() {
update=$(curl -s "https://raw.githubusercontent.com/justchokingaround/jerry/main/jerry.sh")
update="$(printf '%s\n' "$update" | diff -u "$(command -v jerry)" - 2>/dev/null)"
if [ -n "$update" ]; then
if [ "$use_external_menu" = false ]; then
printf "%s" "$1" && read -r answer
else
answer=$(printf "Yes\nNo" | launcher "$1")
fi
case "$answer" in
[Yy]*) update_script ;;
esac
fi
}
get_input() {
if [ "$use_external_menu" = false ]; then
printf "%s" "$1" && read -r query
else
if [ -n "$rofi_prompt_config" ]; then
query=$(printf "" | rofi -config "$rofi_prompt_config" -sort -dmenu -i -width 1500 -p "" -mesg "$1")
else
query=$(printf "" | launcher "$1")
fi
fi
}
generate_desktop() {
cat <<EOF
[Desktop Entry]
Name=$1
Exec=echo %k %c
Icon=$2
Type=Application
Categories=jerry;
EOF
}
launcher() {
case "$use_external_menu" in
true)
[ -z "$2" ] && rofi -config "$rofi_prompt_config" -sort -matching fuzzy -dmenu -i -width 1500 -p "" -mesg "$1" -matching fuzzy -sorting-method fzf
[ -n "$2" ] && rofi -config "$rofi_prompt_config" -sort -matching fuzzy -dmenu -i -width 1500 -p "" -mesg "$1" -display-columns "$2" -matching fuzzy -sorting-method fzf
;;
*)
[ -z "$2" ] && fzf --cycle --reverse --prompt "$1"
[ -n "$2" ] && fzf --cycle --reverse --prompt "$1" --with-nth "$2" -d "\t"
;;
esac
}
nth() {
stdin=$(cat -)
[ -z "$stdin" ] && return 1
prompt="$1"
[ $# -ne 1 ] && shift
line=$(printf "%s" "$stdin" | $sed -nE "s@^([0-9]*)[[:space:]]*[0-9]*[[:space:]]*([0-9/]*)[[:space:]]*[0-9:]*[[:space:]]*(.*)@\1\t\3 - Episode \2@p" | tr '\t' ' ' | launcher "$prompt" | cut -d\ -f1)
[ -n "$line" ] && printf "%s" "$stdin" | $sed -nE "s@^$line\t(.*)@\1@p" || exit 1
}
download_images() {
[ ! -d "$manga_dir/$title/chapter_$((progress + 1))" ] && mkdir -p "$manga_dir/$title/chapter_$((progress + 1))"
send_notification "Downloading images" "" "$images_cache_dir/$media_id.jpg" "$title - Chapter: $((progress + 1)) $chapter_title"
printf "%s\n" "$1" | while read -r link; do
number=$(printf "%03d" "$(printf "%s" "$link" | $sed -nE "s@[a-zA-Z]?([0-9]*)-.*@\1@p")")
image_name=$(printf "%s.%s" "$number" "$(printf "%s" "$link" | $sed -nE "s@.*\.(.*)@\1@p")")
download_link=$(printf "%s/data/%s/%s" "$mangadex_data_base_url" "$mangadex_hash" "$link")
curl -s "$download_link" -o "$manga_dir/$title/chapter_$((progress + 1))/$image_name" &
done
wait && sleep 2
}
convert_to_pdf() {
send_notification "Converting $title - Chapter: $((progress + 1)) $chapter_title to PDF" "2000" "$images_cache_dir/$media_id.jpg"
convert "$manga_dir/$title/chapter_$((progress + 1))"/* "$manga_dir/$title/chapter_$((progress + 1))/$title - Chapter $((progress + 1)).pdf" && wait
}
hdrezka_data_and_translation_id() {
data_id=$(printf "%s" "$episode_id" | sed -nE "s@[a-z]*/([0-9]*)-.*@\1@p")
case "$media_type" in
films)
default_translator_id=$(curl -s "https://hdrezka.website/${media_type}/$(printf "%s" "$episode_id" | tr '=' '/').html" -A "uwu" --compressed |
sed -nE "s@.*initCDNMoviesEvents\(${data_id}\, ([0-9]*)\,.*@\1@p")
;;
*)
default_translator_id=$(curl -s "https://hdrezka.website/${media_type}/$(printf "%s" "$episode_id" | tr '=' '/').html" -A "uwu" --compressed |
sed -nE "s@.*initCDNSeriesEvents\(${data_id}\, ([0-9]*)\,.*@\1@p")
;;
esac
translations=$(curl -s "https://hdrezka.website/${media_type}/$(printf "%s" "$episode_id" | tr '=' '/').html" -A "uwu" --compressed |
sed 's/b-translator__item/\n/g' | sed -nE "s@.*data-translator_id=\"([0-9]*)\"[^>]*>(.*)</li.*@\2\t\1@p" |
sed 's/<img title="\([^\"]*\)" .*>\(.*\)/(\1)\2/;s/^\(.*\)<\/li><\/ul> <\/div>.*\t\([0-9]*\)/\1\t\2/')
if [ -z "$translations" ]; then
translator_id=$default_translator_id
else
translator_id=$(printf "%s" "$translations" | fzf --cycle --reverse --with-nth 1 -d "\t" --header "Choose a translation" | cut -f2)
fi
}
download_thumbnails() {
printf "%s\n" "$1" | while read -r cover_url media_id title; do
curl -s -o "$images_cache_dir/$media_id.jpg" "$cover_url" &
if [ "$use_external_menu" = true ]; then
entry=/tmp/jerry/applications/"$media_id.desktop"
generate_desktop "$title" "$images_cache_dir/$media_id.jpg" >"$entry" &
fi
done
sleep $2
}
image_preview_fzf() {
if [ -n "$use_ueberzugpp" ]; then
UB_PID_FILE="/tmp/.$(uuidgen)"
if [ -z "$ueberzug_output" ]; then
ueberzugpp layer --no-stdin --silent --use-escape-codes --pid-file "$UB_PID_FILE" 2>/dev/null
else
ueberzugpp layer -o "$ueberzug_output" --no-stdin --silent --use-escape-codes --pid-file "$UB_PID_FILE" 2>/dev/null
fi
UB_PID="$(cat "$UB_PID_FILE")"
JERRY_UEBERZUG_SOCKET=/tmp/ueberzugpp-"$UB_PID".socket
choice=$(printf "%s" "$3" | fzf -i -q "$1" --prompt "$2" --cycle --preview-window="$preview_window_size" --preview="ueberzugpp cmd -s $JERRY_UEBERZUG_SOCKET -i fzfpreview -a add -x $ueberzug_x -y $ueberzug_y --max-width $ueberzug_max_width --max-height $ueberzug_max_height -f $images_cache_dir/{2}.jpg" --reverse --with-nth "3" -d "\t")
ueberzugpp cmd -s "$JERRY_UEBERZUG_SOCKET" -a exit
else
case "$(uname -s)" in
MINGW* | *Msys)
# Chafa on windows fails to detect terminal preview window size, so it is determined by view_dim
# TODO: Make $view_dim properly reflect $preview_window_size
view_dim="$(($(tput cols) / 2 - 4))x$(($(tput lines) - 2))"
choice=$(printf "%s" "$3" | fzf -i -q "$1" --prompt "$2" --cycle --preview-window="$preview_window_size" --preview="test -f $images_cache_dir/{2}.jpg && chafa --size=$view_dim $chafa_options $images_cache_dir/{2}.jpg || echo 'File not Found'" --reverse --with-nth "3" -d "\t")
;;
*)
choice=$(printf "%s" "$3" | fzf -i -q "$1" --prompt "$2" --cycle --preview-window="$preview_window_size" --preview="test -f $images_cache_dir/{2}.jpg && chafa $chafa_options $images_cache_dir/{2}.jpg || echo 'File not Found'" --reverse --with-nth "3" -d "\t")
;;
esac
fi
}
select_desktop_entry() {
if [ "$use_external_menu" = true ]; then
[ -n "$image_config_path" ] && choice=$(rofi -config "$rofi_prompt_config" -show drun -drun-categories jerry -filter "$1" -show-icons -theme "$image_config_path" -i -matching fuzzy -sorting-method fzf |
$sed -nE "s@.*/([0-9]*)\.desktop@\1@p") 2>/dev/null ||
choice=$(rofi -config "$rofi_prompt_config" -show drun -drun-categories jerry -filter "$1" -show-icons -i -matching fuzzy -sorting-method fzf | $sed -nE "s@.*/([0-9]*)\.desktop@\1@p") 2>/dev/null
else
image_preview_fzf "$1" "$2" "$3"
fi
}
#### ANILIST ANIME FUNCTIONS ####
get_anime_from_list() {
anime_list=$(curl -s -X POST "$anilist_base" \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer $access_token" \
-d "{\"query\":\"query(\$userId:Int,\$userName:String,\$type:MediaType){MediaListCollection(userId:\$userId,userName:\$userName,type:\$type){lists{name isCustomList isCompletedList:isSplitCompletedList entries{...mediaListEntry}}user{id name avatar{large}mediaListOptions{scoreFormat rowOrder animeList{sectionOrder customLists splitCompletedSectionByFormat theme}mangaList{sectionOrder customLists splitCompletedSectionByFormat theme}}}}}fragment mediaListEntry on MediaList{id mediaId status score progress progressVolumes repeat priority private hiddenFromStatusLists customLists advancedScores notes updatedAt startedAt{year month day}completedAt{year month day}media{id title{userPreferred romaji english native}coverImage{extraLarge large}type format status(version:2)episodes volumes chapters averageScore popularity isAdult countryOfOrigin genres bannerImage nextAiringEpisode{airingAt timeUntilAiring episode} startDate{year month day}}}\",\"variables\":{\"userId\":$user_id,\"type\":\"ANIME\"}}" | $sed "s@},{@\n@g" | $sed -nE "s@.*\"mediaId\":([0-9]*),\"status\":\"($1)\",\"score\":(.*),\"progress\":([0-9]*),.*\"userPreferred\":\"([^\"]*)\".*\"coverImage\":\{\"extraLarge\":\"([^\"]*)\".*\"episode([\"]*)s*[\"]*:([0-9]*).*\"startDate\":\{\"year\":([0-9]*).*@\6\t\1\t\5 \(\9\) \4|\8 episodes \7 \[\3\]@p" | $sed 's/\\\//\//g;s/\"/(releasing)/')
if [ -z "$anime_list" ]; then
send_notification "No anime found in your list" "2000"
exit 1
fi
if [ "$use_external_menu" = true ]; then
case "$image_preview" in
true)
download_thumbnails "$anime_list" "1"
select_desktop_entry "" "Choose anime: " "$anime_list"
[ -z "$choice" ] && exit 1
start_year=$(printf "%s" "$choice" | $sed -nE "s@.*\(([0-9?]{4})\).*@\1@p")
choice=$(printf "%s" "$choice" | $sed -nE "s@\([0-9?]{4}\)@ @p") # remove year from the title
media_id=$(printf "%s" "$choice" | cut -d\ -f1)
title=$(printf "%s" "$choice" | $sed -nE "s@$media_id (.*) [0-9?|]* episodes.*@\1@p" | $sed -E 's|\\u.{4}|+|g')
[ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* episodes.*@\1@p")
episodes_total=$(printf "%s" "$choice" | $sed -nE "s@.*[\| ]([0-9?]*) episodes.*@\1@p")
[ -z "$episodes_total" ] && episodes_total=9999
score=$(printf "%s" "$choice" | $sed -nE "s@.* episodes \[([0-9]*)\].*@\1@p")
;;
*)
tmp_anime_list=$(printf "%s" "$anime_list" | $sed -nE "s@(.*\.[jpneg]*)[[:space:]]*([0-9]*)[[:space:]]*(.*)@\3\t\2\t\1@p")
choice=$(printf "%s" "$tmp_anime_list" | launcher "Choose anime: " "1")
[ -z "$choice" ] && exit 1
start_year=$(printf "%s" "$choice" | $sed -nE "s@.*\(([0-9?]{4})\).*@\1@p")
choice=$(printf "%s" "$choice" | $sed -nE "s@\([0-9?]{4}\)@ @p") # remove year from the title
media_id=$(printf "%s" "$choice" | cut -f2)
title=$(printf "%s" "$choice" | $sed -nE "s@(.*) [0-9?|]* episodes.*@\1@p" | $sed -E 's|\\u.{4}|+|g')
[ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* episodes.*@\1@p")
episodes_total=$(printf "%s" "$choice" | $sed -nE "s@.*[\| ]([0-9?]*) episodes.*@\1@p")
[ -z "$episodes_total" ] && episodes_total=9999
score=$(printf "%s" "$choice" | $sed -nE "s@.* episodes \[([0-9]*)\].*@\1@p")
;;
esac
else
case "$image_preview" in
true)
download_thumbnails "$anime_list" "2"
select_desktop_entry "" "Choose anime: " "$anime_list"
[ -z "$choice" ] && exit 0
start_year=$(printf "%s" "$choice" | $sed -nE "s@.*\(([0-9?]{4})\).*@\1@p")
choice=$(printf "%s" "$choice" | $sed -nE "s@\([0-9?]{4}\)@ @p") # remove year from the title
media_id=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\.jpg@\1@p")
title=$(printf "%s" "$choice" | $sed -nE "s@[[:space:]]*(.*) [0-9?|]* episodes.*@\1@p" | $sed -E 's|\\u.{4}|+|g')
[ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* episodes.*@\1@p")
episodes_total=$(printf "%s" "$choice" | $sed -nE "s@.*[\| ]([0-9?]*) episodes.*@\1@p")
[ -z "$episodes_total" ] && episodes_total=9999
score=$(printf "%s" "$choice" | $sed -nE "s@.* episodes \[([0-9]*)\].*@\1@p")
;;
*)
choice=$(printf "%s" "$anime_list" | launcher "Choose anime: " "3")
[ -z "$choice" ] && exit 1
start_year=$(printf "%s" "$choice" | $sed -nE "s@.*\(([0-9?]{4})\).*@\1@p")
choice=$(printf "%s" "$choice" | $sed -nE "s@\([0-9?]{4}\)@ @p") # remove year from the title
media_id=$(printf "%s" "$choice" | cut -f2)
title=$(printf "%s" "$choice" | $sed -nE "s@.*$media_id\t(.*) [0-9?|]* episodes.*@\1@p" | $sed -E 's|\\u.{4}|+|g')
[ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* episodes.*@\1@p")
episodes_total=$(printf "%s" "$choice" | $sed -nE "s@.*[\| ]([0-9?]*) episodes.*@\1@p")
[ -z "$episodes_total" ] && episodes_total=9999
score=$(printf "%s" "$choice" | $sed -nE "s@.* episodes \[([0-9]*)\].*@\1@p")
;;
esac
[ -z "$choice" ] && exit 1
media_id=$(printf "%s" "$choice" | cut -f2)
title=$(printf "%s" "$choice" | $sed -nE "s@.*$media_id\t(.*) [0-9?|]* episodes.*@\1@p" | $sed -E 's|\\u.{4}|+|g')
[ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* episodes.*@\1@p")
episodes_total=$(printf "%s" "$choice" | $sed -nE "s@.*[\| ]([0-9?]*) episodes.*@\1@p")
[ -z "$episodes_total" ] && episodes_total=9999
score=$(printf "%s" "$choice" | $sed -nE "s@.* episodes \[([0-9]*)\].*@\1@p")
fi
}
search_anime_anilist() {
if [ "$show_adult_content" = true ]; then
isAdult_variable=""
else
isAdult_variable=",\"isAdult\":false"
fi
anime_list=$(curl -s -X POST "$anilist_base" \
-H 'Content-Type: application/json' \
-d "{\"query\":\"query(\$page:Int = 1 \$id:Int \$type:MediaType \$isAdult:Boolean = false \$search:String \$format:[MediaFormat]\$status:MediaStatus \$countryOfOrigin:CountryCode \$source:MediaSource \$season:MediaSeason \$seasonYear:Int \$year:String \$onList:Boolean \$yearLesser:FuzzyDateInt \$yearGreater:FuzzyDateInt \$episodeLesser:Int \$episodeGreater:Int \$durationLesser:Int \$durationGreater:Int \$chapterLesser:Int \$chapterGreater:Int \$volumeLesser:Int \$volumeGreater:Int \$licensedBy:[Int]\$isLicensed:Boolean \$genres:[String]\$excludedGenres:[String]\$tags:[String]\$excludedTags:[String]\$minimumTagRank:Int \$sort:[MediaSort]=[POPULARITY_DESC,SCORE_DESC]){Page(page:\$page,perPage:20){pageInfo{total perPage currentPage lastPage hasNextPage}media(id:\$id type:\$type season:\$season format_in:\$format status:\$status countryOfOrigin:\$countryOfOrigin source:\$source search:\$search onList:\$onList seasonYear:\$seasonYear startDate_like:\$year startDate_lesser:\$yearLesser startDate_greater:\$yearGreater episodes_lesser:\$episodeLesser episodes_greater:\$episodeGreater duration_lesser:\$durationLesser duration_greater:\$durationGreater chapters_lesser:\$chapterLesser chapters_greater:\$chapterGreater volumes_lesser:\$volumeLesser volumes_greater:\$volumeGreater licensedById_in:\$licensedBy isLicensed:\$isLicensed genre_in:\$genres genre_not_in:\$excludedGenres tag_in:\$tags tag_not_in:\$excludedTags minimumTagRank:\$minimumTagRank sort:\$sort isAdult:\$isAdult){id title{userPreferred}coverImage{extraLarge large color}startDate{year month day}endDate{year month day}bannerImage season seasonYear description type format status(version:2)episodes duration chapters volumes genres isAdult averageScore popularity nextAiringEpisode{airingAt timeUntilAiring episode}mediaListEntry{id status}studios(isMain:true){edges{isMain node{id name}}}}}}\",\"variables\":{\"page\":1,\"type\":\"ANIME\",\"sort\":\"SEARCH_MATCH\",\"search\":\"$1\"}}" | $sed "s@edges@\n@g" | $sed -nE "s@.*\"id\":([0-9]*),.*\"userPreferred\":\"(.*)\"\},\"coverImage\":.*\"extraLarge\":\"([^\"]*)\".*\"startDate\":\{\"year\":([0-9]*).*\"episode([\"]*)s*[\"]*:([0-9]*).*@\3\t\1\t\2 \(\4\) \6 episodes \5@p" | $sed 's/\\\//\//g;s/\"/(releasing)/')
if [ "$use_external_menu" = true ]; then
case "$image_preview" in
true)
download_thumbnails "$anime_list" "1"
select_desktop_entry "" "Choose anime: " "$anime_list"
[ -z "$choice" ] && exit 1
start_year=$(printf "%s" "$choice" | $sed -nE "s@.*\(([0-9?]{4})\).*@\1@p")
choice=$(printf "%s" "$choice" | $sed -nE "s@\([0-9?]{4}\)@ @p") # remove year from the title
media_id=$(printf "%s" "$choice" | cut -d\ -f1)
title=$(printf "%s" "$choice" | $sed -nE "s@$media_id (.*) [0-9?]* episodes.*@\1@p")
episodes_total=$(printf "%s" "$choice" | $sed -nE "s@.*[\| ]([0-9?]*) episodes.*@\1@p")
[ -z "$episodes_total" ] && episodes_total=9999
;;
*)
tmp_anime_list=$(printf "%s" "$anime_list" | $sed -nE "s@(.*\.[jpneg]*)[[:space:]]*([0-9]*)[[:space:]]*(.*)@\3\t\2\t\1@p")
choice=$(printf "%s" "$tmp_anime_list" | launcher "Choose anime: " "1")
start_year=$(printf "%s" "$choice" | $sed -nE "s@.*\(([0-9?]{4})\).*@\1@p")
choice=$(printf "%s" "$choice" | $sed -nE "s@\([0-9?]{4}\)@ @p") # remove year from the title
media_id=$(printf "%s" "$choice" | cut -f2)
title=$(printf "%s" "$choice" | $sed -nE "s@(.*) [0-9?|]* episodes.*@\1@p")
[ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* episodes.*@\1@p")
episodes_total=$(printf "%s" "$choice" | $sed -nE "s@.*[\| ]([0-9?]*) episodes.*@\1@p")
[ -z "$episodes_total" ] && episodes_total=9999
;;
esac
else
case "$image_preview" in
true)
download_thumbnails "$anime_list" "2"
select_desktop_entry "" "Choose anime: " "$anime_list"
[ -z "$choice" ] && exit 0
start_year=$(printf "%s" "$choice" | $sed -nE "s@.*\(([0-9?]{4})\).*@\1@p")
choice=$(printf "%s" "$choice" | $sed -nE "s@\([0-9?]{4}\)@ @p") # remove year from the title
media_id=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\.jpg@\1@p")
title=$(printf "%s" "$choice" | $sed -nE "s@[[:space:]]*(.*) [0-9?|]* episodes.*@\1@p")
episodes_total=$(printf "%s" "$choice" | $sed -nE "s@.*[\| ]([0-9?]*) episodes.*@\1@p")
[ -z "$episodes_total" ] && episodes_total=9999
;;
*)
choice=$(printf "%s" "$anime_list" | launcher "Choose anime: " "3")
start_year=$(printf "%s" "$choice" | $sed -nE "s@.*\(([0-9?]{4})\).*@\1@p")
choice=$(printf "%s" "$choice" | $sed -nE "s@\([0-9?]{4}\)@ @p") # remove year from the title
media_id=$(printf "%s" "$choice" | cut -f2)
title=$(printf "%s" "$choice" | $sed -nE "s@.*$media_id\t(.*) [0-9?|]* episodes.*@\1@p")
[ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* episodes.*@\1@p")
episodes_total=$(printf "%s" "$choice" | $sed -nE "s@.*[\| ]([0-9?]*) episodes.*@\1@p")
;;
esac
[ -z "$choice" ] && exit 0
media_id=$(printf "%s" "$choice" | cut -f2)
title=$(printf "%s" "$choice" | $sed -nE "s@.*$media_id\t(.*) [0-9?|]* episodes.*@\1@p")
[ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* episodes.*@\1@p")
episodes_total=$(printf "%s" "$choice" | $sed -nE "s@.*[\| ]([0-9?]*) episodes.*@\1@p")
fi
[ -z "$title" ] && exit 0
if [ -n "$no_anilist" ]; then
if [ "$show_adult_content" = true ]; then
isAdult_variable=""
else
isAdult_variable=",\"isAdult\":false"
fi
episodes_total=$(curl -s -X POST "https://graphql.anilist.co" -A "uwu" -H "Accept: application/json" -H "Content-Type: application/json" --data-raw "{\"query\":\"query media(\$id:Int,\$type:MediaType,\$isAdult:Boolean){Media(id:\$id,type:\$type,isAdult:\$isAdult){episodes nextAiringEpisode{episode}}}\",\"variables\":{\"id\":\"${media_id}\",\"type\":\"ANIME\"$isAdult_variable}}" | $sed -nE "s@.*episode([s]{0,1})\":([0-9]+).*@\1\2@p")
numeric_part=$(printf "%s" "$episodes_total" | sed -nE "s@s([0-9]*)@\1@p")
[ -n "$numeric_part" ] && episodes_total=$numeric_part || episodes_total=$((episodes_total - 1))
[ -n "$progress" ] && return
if [ "$episodes_total" = 1 ]; then
progress=0
else
[ -z "$episodes_total" ] && episodes_total=9999
if [ "$use_external_menu" = true ]; then
if [ -n "$rofi_prompt_config" ]; then
progress=$(printf "" | rofi -config "$rofi_prompt_config" -sort -dmenu -i -width 1500 -p "" -mesg "Please enter the episode number (1-${episodes_total}): ")
else
progress=$(printf "" | launcher "Please enter the episode number (1-${episodes_total}): ")
fi
else
printf "%s" "Please enter the episode number (1-${episodes_total}): " && read -r progress
[ -z "$progress" ] && progress=$episodes_total
fi
if [ -z "$progress" ]; then
send_notification "Error" "1000" "$images_cache_dir/$media_id.jpg" "No episode number provided"
exit 1
fi
progress=$((progress - 1))
fi
fi
}
update_progress() {
curl -s -X POST "$anilist_base" \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer $access_token" \
-d "{\"query\":\"mutation(\$id:Int \$mediaId:Int \$status:MediaListStatus \$score:Float \$progress:Int \$progressVolumes:Int \$repeat:Int \$private:Boolean \$notes:String \$customLists:[String]\$hiddenFromStatusLists:Boolean \$advancedScores:[Float]\$startedAt:FuzzyDateInput \$completedAt:FuzzyDateInput){SaveMediaListEntry(id:\$id mediaId:\$mediaId status:\$status score:\$score progress:\$progress progressVolumes:\$progressVolumes repeat:\$repeat private:\$private notes:\$notes customLists:\$customLists hiddenFromStatusLists:\$hiddenFromStatusLists advancedScores:\$advancedScores startedAt:\$startedAt completedAt:\$completedAt){id mediaId status score advancedScores progress progressVolumes repeat priority private hiddenFromStatusLists customLists notes updatedAt startedAt{year month day}completedAt{year month day}user{id name}media{id title{userPreferred}coverImage{large}type format status episodes volumes chapters averageScore popularity isAdult startDate{year}}}}\",\"variables\":{\"status\":\"$3\",\"progress\":$1,\"mediaId\":$2}}"
[ "$3" = "COMPLETED" ] && send_notification "Completed $title" "5000"
[ "$3" = "COMPLETED" ] && $sed -i "/$media_id/d" "$history_file"
}
update_episode_from_list() {
status_choice=$(printf "CURRENT\nREPEATING\nCOMPLETED\nPAUSED\nDROPPED\nPLANNING" | launcher "Filter by status: ")
get_anime_from_list "$status_choice"
if [ -z "$title" ] || [ -z "$progress" ]; then
exit 0
fi
send_notification "Current progress: $progress/$episodes_total episodes watched" "5000"
if [ "$use_external_menu" = false ]; then
printf "Enter a new episode number: "
read -r new_episode_number
else
new_episode_number=$(printf "" | launcher "Enter a new episode number: ")
fi
[ "$new_episode_number" -gt "$episodes_total" ] && new_episode_number=$episodes_total
[ "$new_episode_number" -lt 0 ] && new_episode_number=0
if [ -z "$new_episode_number" ]; then
send_notification "No episode number given"
exit 1
fi
send_notification "Updating progress for $title..."
[ "$new_episode_number" -eq "$episodes_total" ] && status="COMPLETED" || status="CURRENT"
response=$(update_progress "$new_episode_number" "$media_id" "$status")
send_notification "New progress: $new_episode_number/$episodes_total episodes watched"
[ "$new_episode_number" -eq "$episodes_total" ] && send_notification "Completed $title"
}
#### ANILIST MANGA FUNCTIONS ####
get_manga_from_list() {
manga_list=$(curl -s -X POST "$anilist_base" \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer $access_token" \
-d "{\"query\":\"query(\$userId:Int,\$userName:String,\$type:MediaType){MediaListCollection(userId:\$userId,userName:\$userName,type:\$type){lists{name isCustomList isCompletedList:isSplitCompletedList entries{...mediaListEntry}}user{id name avatar{large}mediaListOptions{scoreFormat rowOrder animeList{sectionOrder customLists splitCompletedSectionByFormat theme}mangaList{sectionOrder customLists splitCompletedSectionByFormat theme}}}}}fragment mediaListEntry on MediaList{id mediaId status score progress progressVolumes repeat priority private hiddenFromStatusLists customLists advancedScores notes updatedAt startedAt{year month day}completedAt{year month day}media{id title{userPreferred romaji english native}coverImage{extraLarge large}type format status(version:2)episodes volumes chapters averageScore popularity isAdult countryOfOrigin genres bannerImage startDate{year month day}}}\",\"variables\":{\"userId\":$user_id,\"type\":\"MANGA\"}}" |
tr "\[|\]" "\n" | $sed -nE "s@.*\"mediaId\":([0-9]*),\"status\":\"($1)\",\"score\":(.*),\"progress\":([0-9]*),.*\"userPreferred\":\"([^\"]*)\".*\"coverImage\":\{\"extraLarge\":\"([^\"]*)\".*\"chapters\":([0-9]*).*@\6\t\1\t\5 \4|\7 chapters \[\3\]@p" | $sed 's/\\\//\//g')
if [ "$use_external_menu" = true ]; then
case "$image_preview" in
true)
download_thumbnails "$manga_list" "1"
select_desktop_entry "" "Choose manga: " "$manga_list"
[ -z "$choice" ] && exit 1
media_id=$(printf "%s" "$choice" | cut -d\ -f1)
title=$(printf "%s" "$choice" | $sed -nE "s@$media_id (.*) [0-9?|]* chapters.*@\1@p" | $sed -E 's|\\u.{4}|+|g')
[ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* chapters.*@\1@p")
chapters_total=$(printf "%s" "$choice" | $sed -nE "s@.*\|([0-9?]*) chapters.*@\1@p")
score=$(printf "%s" "$choice" | $sed -nE "s@.*\|[0-9?]* chapters[[:space:]]*\[([0-9]*)\][[:space:]]*.*@\1@p")
;;
*)
tmp_manga_list=$(printf "%s" "$manga_list" | $sed -nE "s@(.*\.[jpneg]*)[[:space:]]*([0-9]*)[[:space:]]*(.*)@\3\t\2\t\1@p")
choice=$(printf "%s" "$tmp_manga_list" | launcher "Choose manga: " "1")
[ -z "$choice" ] && exit 1
media_id=$(printf "%s" "$choice" | cut -f2)
title=$(printf "%s" "$choice" | $sed -nE "s@(.*) [0-9?|]* chapters.*@\1@p" | $sed -E 's|\\u.{4}|+|g')
[ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* chapters.*@\1@p")
chapters_total=$(printf "%s" "$choice" | $sed -nE "s@.*\|([0-9?]*) chapters.*@\1@p")
score=$(printf "%s" "$choice" | $sed -nE "s@.*\|[0-9?]* chapters[[:space:]]*\[([0-9]*)\][[:space:]]*.*@\1@p")
;;
esac
else
case "$image_preview" in
true)
download_thumbnails "$manga_list" "1"
select_desktop_entry "" "Choose manga: " "$manga_list"
;;
*)
choice=$(printf "%s" "$manga_list" | launcher "Choose manga: " "3")
;;
esac
[ -z "$choice" ] && exit 1
media_id=$(printf "%s" "$choice" | cut -f2)
title=$(printf "%s" "$choice" | $sed -nE "s@.*$media_id\t(.*) [0-9?|]* chapters.*@\1@p" | $sed -E 's|\\u.{4}|+|g')
[ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* chapters.*@\1@p")
chapters_total=$(printf "%s" "$choice" | $sed -nE "s@.*\|([0-9?]*) chapters.*@\1@p")
score=$(printf "%s" "$choice" | $sed -nE "s@.*\|[0-9?]* chapters[[:space:]]*\[([0-9]*)\][[:space:]]*.*@\1@p")
fi
}
search_manga_anilist() {
if [ "$show_adult_content" = true ]; then
isAdult_variable=""
else
isAdult_variable=",\"isAdult\":false"
fi
manga_list=$(curl -s -X POST "$anilist_base" \
-H 'Content-Type: application/json' \
-d "{\"query\":\"query(\$page:Int = 1 \$id:Int \$type:MediaType \$isAdult:Boolean \$search:String \$format:[MediaFormat]\$status:MediaStatus \$countryOfOrigin:CountryCode \$source:MediaSource \$season:MediaSeason \$seasonYear:Int \$year:String \$onList:Boolean \$yearLesser:FuzzyDateInt \$yearGreater:FuzzyDateInt \$episodeLesser:Int \$episodeGreater:Int \$durationLesser:Int \$durationGreater:Int \$chapterLesser:Int \$chapterGreater:Int \$volumeLesser:Int \$volumeGreater:Int \$licensedBy:[Int]\$isLicensed:Boolean \$genres:[String]\$excludedGenres:[String]\$tags:[String]\$excludedTags:[String]\$minimumTagRank:Int \$sort:[MediaSort]=[POPULARITY_DESC,SCORE_DESC]){Page(page:\$page,perPage:20){pageInfo{total perPage currentPage lastPage hasNextPage}media(id:\$id type:\$type season:\$season format_in:\$format status:\$status countryOfOrigin:\$countryOfOrigin source:\$source search:\$search onList:\$onList seasonYear:\$seasonYear startDate_like:\$year startDate_lesser:\$yearLesser startDate_greater:\$yearGreater episodes_lesser:\$episodeLesser episodes_greater:\$episodeGreater duration_lesser:\$durationLesser duration_greater:\$durationGreater chapters_lesser:\$chapterLesser chapters_greater:\$chapterGreater volumes_lesser:\$volumeLesser volumes_greater:\$volumeGreater licensedById_in:\$licensedBy isLicensed:\$isLicensed genre_in:\$genres genre_not_in:\$excludedGenres tag_in:\$tags tag_not_in:\$excludedTags minimumTagRank:\$minimumTagRank sort:\$sort isAdult:\$isAdult){id title{userPreferred}coverImage{extraLarge large color}startDate{year month day}endDate{year month day}bannerImage season seasonYear description type format status(version:2)episodes duration chapters volumes genres isAdult averageScore popularity nextAiringEpisode{airingAt timeUntilAiring episode}mediaListEntry{id status}studios(isMain:true){edges{isMain node{id name}}}}}}\",\"variables\":{\"page\":1,\"type\":\"MANGA\",\"sort\":\"SEARCH_MATCH\",\"search\":\"$1\"$isAdult_variable}}" |
tr "\[\]" "\n" | $sed -nE "s@.*\"id\":([0-9]*),.*\"userPreferred\":\"(.*)\"\},\"coverImage\":.*\"extraLarge\":\"([^\"]*)\".*\"chapters\":([^,]*),.*@\3\t\1\t\2 \4 chapters@p" | $sed 's/\\\//\//g;s/null/?/')
if [ "$use_external_menu" = true ]; then
case "$image_preview" in
true)
download_thumbnails "$manga_list" "1"
select_desktop_entry "" "Choose manga: " "$manga_list"
[ -z "$choice" ] && exit 1
media_id=$(printf "%s" "$choice" | cut -d\ -f1)
title=$(printf "%s" "$choice" | $sed -nE "s@$media_id (.*) [0-9?]* chapters.*@\1@p")
chapters_total=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9?]*) chapters.*@\1@p")
;;
*)
tmp_manga_list=$(printf "%s" "$manga_list" | $sed -nE "s@(.*\.[jpneg]*)[[:space:]]*([0-9]*)[[:space:]]*(.*)@\3\t\2\t\1@p")
choice=$(printf "%s" "$tmp_manga_list" | launcher "Choose manga: " "1")
media_id=$(printf "%s" "$choice" | cut -f2)
title=$(printf "%s" "$choice" | $sed -nE "s@(.*) [0-9?|]* chapters.*@\1@p")
[ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* chapters.*@\1@p")
chapters_total=$(printf "%s" "$choice" | $sed -nE "s@.*\|([0-9?]*) chapters.*@\1@p")
;;
esac
else
case "$image_preview" in
true)
download_thumbnails "$manga_list" "1"
select_desktop_entry "" "Choose manga: " "$manga_list"
;;
*)
choice=$(printf "%s" "$manga_list" | launcher "Choose manga: " "3")
;;
esac
[ -z "$choice" ] && exit 0
media_id=$(printf "%s" "$choice" | cut -f2)
title=$(printf "%s" "$choice" | $sed -nE "s@.*$media_id\t(.*) [0-9?|]* chapters.*@\1@p")
[ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* chapters.*@\1@p")
chapters_total=$(printf "%s" "$choice" | $sed -nE "s@.*\|([0-9?]*) chapters.*@\1@p")
fi
[ -z "$title" ] && exit 0
}
update_chapter_from_list() {
status_choice=$(printf "CURRENT\nREPEATING\nCOMPLETED\nPAUSED\nDROPPED\nPLANNING" | launcher "Filter by status: ")
get_manga_from_list "$status_choice"
if [ -z "$title" ] || [ -z "$progress" ]; then
exit 0
fi
send_notification "Current progress: $progress/$chapters_total chapters read" "5000"
if [ "$use_external_menu" = false ]; then
printf "Enter a new chapters read number: "
read -r new_chapter_number
else
new_chapter_number=$(printf "" | launcher "Enter a new chapters read number: ")
fi
[ "$new_chapter_number" -gt "$chapters_total" ] && new_chapter_number=$chapters_total
[ "$new_chapter_number" -lt 0 ] && new_chapter_number=0
if [ -z "$chapters_total" ]; then
send_notification "No chapter number given"
exit 1
fi
send_notification "Updating progress for $title..."
[ "$new_chapter_number" -eq "$chapters_total" ] && status="COMPLETED" || status="CURRENT"
response=$(update_progress "$new_chapter_number" "$media_id" "$status")
send_notification "New progress: $new_chapter_number/$chapters_total chapters read"
[ "$new_chapter_number" -eq "$chapters_total" ] && send_notification "Completed $title"
}
#### ANILIST META FUICTIONS ####
update_status() {
status_choice=$(printf "CURRENT\nREPEATING\nCOMPLETED\nPAUSED\nDROPPED\nPLANNING" | launcher "Filter by status: ")
if [ "$1" = "ANIME" ]; then
get_anime_from_list "$status_choice"
else
get_manga_from_list "$status_choice"
fi
[ -z "$title" ] && exit 0
send_notification "Choose a new status for $title" "5000"
new_status=$(printf "CURRENT\nREPEATING\nCOMPLETED\nPAUSED\nDROPPED\nPLANNING" | launcher "Choose a new status: ")
[ -z "$new_status" ] && exit 0
send_notification "Updating status for $title..."
response=$(update_progress "$progress" "$media_id" "$new_status")
if printf "%s" "$response" | grep -q "errors"; then
send_notification "Failed to update status for $title"
else
send_notification "New status: $new_status"
fi
}
update_score() {
if [ "$2" = "immediate" ]; then
[ -z "$percentage_progress" ] || [ "$percentage_progress" -lt 85 ] && return
[ "$1" = "ANIME" ] && total="$episodes_total"
[ "$1" = "MANGA" ] && total="$chapters_total"
[ $((progress + 1)) != "$total" ] && return
else
status_choice=$(printf "CURRENT\nREPEATING\nCOMPLETED\nPAUSED\nDROPPED\nPLANNING" | launcher "Filter by status: ")
case "$1" in
"ANIME") get_anime_from_list "$status_choice" ;;
"MANGA") get_manga_from_list "$status_choice" ;;
esac
fi
send_notification "Enter new score for: \"$title\"" "5000"
send_notification "Current score: $score" "5000"
if [ "$use_external_menu" = false ]; then
printf "Enter new score: "
read -r new_score
else
new_score=$(printf "" | launcher "Enter new score: ")
fi
[ -z "$new_score" ] && send_notification "No score given" && exit 1
send_notification "Updating score for $title..."
response=$(curl -s -X POST "$anilist_base" \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer $access_token" \
-d "{\"query\":\"mutation(\$id:Int \$mediaId:Int \$status:MediaListStatus \$score:Float \$progress:Int \$progressVolumes:Int \$repeat:Int \$private:Boolean \$notes:String \$customLists:[String]\$hiddenFromStatusLists:Boolean \$advancedScores:[Float]\$startedAt:FuzzyDateInput \$completedAt:FuzzyDateInput){SaveMediaListEntry(id:\$id mediaId:\$mediaId status:\$status score:\$score progress:\$progress progressVolumes:\$progressVolumes repeat:\$repeat private:\$private notes:\$notes customLists:\$customLists hiddenFromStatusLists:\$hiddenFromStatusLists advancedScores:\$advancedScores startedAt:\$startedAt completedAt:\$completedAt){id mediaId status score advancedScores progress progressVolumes repeat priority private hiddenFromStatusLists customLists notes updatedAt startedAt{year month day}completedAt{year month day}user{id name}media{id title{userPreferred}coverImage{large}type format status episodes volumes chapters averageScore popularity isAdult startDate{year}}}}\",\"variables\":{\"score\":$new_score,\"mediaId\":$media_id}}")
if printf "%s" "$response" | grep -q "errors"; then
send_notification "Failed to update score for $title"
else
send_notification "New score: $new_score"
fi
}
get_anilist_info() {
case "$1" in
"ANIME")
get_input "Search anime: "
[ -z "$query" ] && exit 1
search_anime_anilist "$query"
;;
"MANGA")
get_input "Search manga: "
[ -z "$query" ] && exit 1
search_manga_anilist "$query"
;;
esac
[ -z "$media_id" ] && exit 1
info="$(curl -s -X POST "$anilist_base" \
-H 'Content-Type: application/json' \
-d "{\"query\":\"query media(\$id:Int,\$type:MediaType,\$isAdult:Boolean){Media(id:\$id,type:\$type,isAdult:\$isAdult){id title{userPreferred romaji english native}coverImage{extraLarge large}bannerImage startDate{year month day}endDate{year month day}description season seasonYear type format status(version:2)episodes duration chapters volumes genres synonyms source(version:3)isAdult isLocked meanScore averageScore popularity favourites isFavouriteBlocked hashtag countryOfOrigin isLicensed isFavourite isRecommendationBlocked isFavouriteBlocked isReviewBlocked nextAiringEpisode{airingAt timeUntilAiring episode}relations{edges{id relationType(version:2)node{id title{userPreferred}format type status(version:2)bannerImage coverImage{large}}}}characterPreview:characters(perPage:6,sort:[ROLE,RELEVANCE,ID]){edges{id role name voiceActors(language:JAPANESE,sort:[RELEVANCE,ID]){id name{userPreferred}language:languageV2 image{large}}node{id name{userPreferred}image{large}}}}staffPreview:staff(perPage:8,sort:[RELEVANCE,ID]){edges{id role node{id name{userPreferred}language:languageV2 image{large}}}}studios{edges{isMain node{id name}}}reviewPreview:reviews(perPage:2,sort:[RATING_DESC,ID]){pageInfo{total}nodes{id summary rating ratingAmount user{id name avatar{large}}}}recommendations(perPage:7,sort:[RATING_DESC,ID]){pageInfo{total}nodes{id rating userRating mediaRecommendation{id title{userPreferred}format type status(version:2)bannerImage coverImage{large}}user{id name avatar{large}}}}externalLinks{id site url type language color icon notes isDisabled}streamingEpisodes{site title thumbnail url}trailer{id site}rankings{id rank type format year season allTime context}tags{id name description rank isMediaSpoiler isGeneralSpoiler userId}mediaListEntry{id status score}stats{statusDistribution{status amount}scoreDistribution{score amount}}}}\",\"variables\":{\"id\":$media_id,\"type\":\"$1\"}}" |
jq -r '.data.Media.description' | $sed "s/<br>/\n/g")"
if [ "$use_external_menu" = true ]; then
if ! command -v "zenity" >/dev/null; then
send_notification "For this feature to work in the rofi mode, you must have zenity installed."
exit 1
fi
zenity --info --text="$info"
else
echo "$info" | $display
fi
}
#### ANIME SCRAPING FUNCTIONS ####
get_episode_info() {
case "$provider" in
allanime)
query_title=$(printf "%s" "$title" | tr ' ' '+')
response=$(curl -e "$allanime_refr" -s -G "https://api.$allanime_base/api" --data-urlencode 'variables={"search":{"allowAdult":false,"allowUnknown":false,"query":"'"$query_title"'"},"limit":40,"page":1,"translationType":"sub","countryOrigin":"ALL"}' --data-urlencode 'query=query( $search: SearchInput $limit:Int $page: Int $translationType: VaildTranslationTypeEnumType $countryOrigin: VaildCountryOriginEnumType ) { shows( search: $search limit: $limit page: $page translationType: $translationType countryOrigin: $countryOrigin ) { edges { _id name availableEpisodes __typename } }}' | sed 's|Show|\n|g' | sed -nE 's|.*_id":"([^"]*)","name":"([^"]*)".*sub":([1-9][^,]*).*|\1\t\2 (\3 episodes)|p')
[ -z "$response" ] && exit 1
# if it is only one line long, then auto select it
if [ "$(printf "%s\n" "$response" | wc -l)" -eq 1 ]; then
send_notification "Jerry" "" "" "Since there is only one result, it was automatically selected"
choice=$response
else
choice=$(printf "%s" "$response" | launcher "Choose anime: " 2)
fi
[ -z "$choice" ] && exit 1
title=$(printf "%s" "$choice" | cut -f2 | sed -E 's| \([0-9]* episodes\)||')
allanime_id=$(printf "%s" "$choice" | cut -f1)
episode_number=$((progress + 1))
episode_info=$(printf "%s\t%s" "$allanime_id" "$title")
;;
aniwatch)
aniwatch_id=$(curl -s "https://raw.githubusercontent.com/bal-mackup/mal-backup/master/anilist/anime/${media_id}.json" |
tr -d '\n ' | tr '}' '\n' | $sed -nE "s@.*\"Zoro\".*\"url\":\".*-([0-9]*)\".*@\1@p")
episode_info=$(curl -s "https://hianime.to/ajax/v2/episode/list/${aniwatch_id}" | $sed -e "s/</\n/g" -e "s/\\\\//g" | $sed -nE "s_.*a title=\"([^\"]*)\".*data-id=\"([0-9]*)\".*_\2\t\1_p" | $sed -n "$((progress + 1))p")
;;
yugen)
href=$(curl -s "https://raw.githubusercontent.com/bal-mackup/mal-backup/master/anilist/anime/${media_id}.json" |
tr -d '\n' | tr '}' '\n' | $sed -nE 's@.*"YugenAnime".*"url": *"([^"]*)".*@\1@p' | $sed -e "s@tv/anime@tv/watch@")
href="$href$((progress + 1))/"
ep_title=$(curl -s "$href" | $sed -nE "s@.*$((progress + 1))\s:\s([^<]*).*@\1@p")
if [ "$translation_type" = "dub" ]; then
href=$(printf "%s" "$href" | $sed -E 's|(/[^/]+)/([0-9]+)/$|\1-dub/\2/|')
fi
yugen_id=$(curl -s "$href" | $sed -nE "s@.*id=\"main-embed\" src=\".*/e/([^/]*)/\".*@\1@p")
episode_info=$(printf "%s\t%s" "$yugen_id" "$ep_title" | head -1)
;;
hdrezka)
query=$(curl -s "https://raw.githubusercontent.com/bal-mackup/mal-backup/master/anilist/anime/${media_id}.json" |
sed -nE "s@.*\"title\":.\"([^\"]*)\".*@\1@p" | head -1 | tr ' ' '+')
request=$(curl -s "https://hdrezka.website/search/?do=search&subaction=search&q=${query}" -A "uwu" --compressed)
response=$(printf "%s" "$request" | sed "s/<img/\n/g" | sed -nE "s@.*src=\"([^\"]*)\".*<a href=\"https://hdrezka\.website/(.*)/(.*)/(.*)\.html\">([^<]*)</a> <div>([0-9]*).*@\3/\4\t\5 [\6]\t\2@p")
if [ -z "$response" ]; then
send_notification "Error" "Could not query the anime on hdrezka"
exit 1
fi
if [ "$(printf "%s\n" "$response" | wc -l)" -eq 1 ]; then
send_notification "Jerry" "" "" "Since there is only one result, it was automatically selected"
episode_info=$response
else
episode_info=$(printf "%s" "$response" | launcher "Choose anime: " 2)
fi
;;
aniworld)
query=$(curl -s "https://raw.githubusercontent.com/bal-mackup/mal-backup/master/anilist/anime/${media_id}.json" |
sed -nE "s@.*\"title\":.\"([^\"]*)\".*@\1@p" | head -1 | tr ' ' '+')
request=$(curl -s "https://aniworld.to/ajax/search" -X POST --data-raw "keyword=${query}")
response=$(printf "%s" "$request" | tr '{}' '\n' | sed -nE "s@.*title\":\"([^\"]*)\".*\"link\":\"([^\"]*)\".*@\1\t\2@p" | sed 's/<\\\/em>//g; s/<em>//g')
if [ -z "$response" ]; then
send_notification "Error" "Could not query the anime on aniworld"
exit 1
fi
if [ "$(printf "%s\n" "$response" | wc -l)" -eq 1 ]; then
send_notification "Jerry" "" "" "Since there is only one result, it was automatically selected"
episode_info=$response
else
episode_info=$(printf "%s" "$response" | launcher "Choose anime: " 1)
fi
;;
crunchyroll)
cr_href=$(curl -s "https://raw.githubusercontent.com/bal-mackup/mal-backup/master/anilist/anime/${media_id}.json" |
tr -d '\n ' | tr '}' '\n' | $sed -nE "s@.*\"Crunchyroll\".*\"url\":\"([^\"]*)\".*@\1@p" | head -1)
cr_id=$(printf "%s" "$cr_href" | sed -nE "s@.*/([^\/]*)/.*@\1@p")
access_token=$(curl -s -X POST -H "Authorization: Basic Y3Jfd2ViOg==" -d "grant_type=client_id&scope=offline_access" "https://www.crunchyroll.com/auth/v1/token" | sed -nE "s@.*\"access_token\":\"([^\"]*)\".*@\1@p")
season_id=$(curl -s "https://www.crunchyroll.com/content/v2/cms/series/${cr_id}/seasons" \
-H "authorization: Bearer ${access_token}" | sed -nE "s@.*\"id\":\"([^\"]*)\".*@\1@p")
response=$(curl -s "https://www.crunchyroll.com/content/v2/cms/seasons/${season_id}/episodes" \
-H "authorization: Bearer ${access_token}" | sed "s/},{/\n/g")
title=$(printf "%s" "$response" | sed -nE "s@.*\"title\":\"([^\"]*)\".*@\1@p" | sed -n "$((progress + 1))p")
eid=$(printf "%s\n" "$response" | sed -nE "s@.*\"id\":\"([^\"]*)\".*@\1@p" | sed -n $((progress + 1))p)
episode_info="$(printf "%s\t%s" "$eid" "$title")"
;;
esac
}
extract_from_json() {
case "$provider" in
allanime)
resp=$(printf "%s" "$json_data" | tr '{}' '\n' | sed 's|\\u002F|\/|g;s|\\||g' | sed -nE 's|.*sourceUrl":"--([^"]*)".*sourceName":"([^"]*)".*|\2 :\1|p')
# generate links into sequential files
cache_dir="$(mktemp -d)"
link_providers="1 2 3 4 5"
for link_provider in $link_providers; do
generate_links "$link_provider" >"$cache_dir"/"$link_provider" &
done
wait
# select the link with matching quality
links=$(cat "$cache_dir"/* | sed 's|^Mp4-||g;/http/!d' | sort -g -r -s)
if [ "$json_output" = true ]; then
printf '{\n'
for file in $cache_dir/*; do
if [ -s "$file" ]; then
provider=$(basename "$file")
printf ' "%s": {\n' "provider_$provider"
cat $file | while read -r quality url; do
printf ' "%s": "%s",\n' "$quality" "${url#>}"
done
[ "$provider" = "5" ] && printf ' }\n' || printf ' },\n'
fi
done
printf '}\n'
exit 0
fi
video_link=$(select_quality "$quality")
rm -r "$cache_dir"
;;
aniwatch)
video_link=$(printf "%s" "$json_data" | tr '[' '\n' | $sed -nE 's@.*\"file\":\"(.*\.m3u8).*@\1@p' | head -1)
[ -n "$quality" ] && video_link=$(printf "%s" "$video_link" | $sed -e "s|/playlist.m3u8|/$quality/index.m3u8|")
subs_links=$(printf "%s" "$json_data" | tr "{}" "\n" | $sed -nE "s@.*\"file\":\"([^\"]*)\",\"label\":\"(.$subs_language)[,\"\ ].*@\1@p")
subs_arg="--sub-file"
num_subs=$(printf "%s" "$subs_links" | wc -l)
if [ "$num_subs" -gt 0 ]; then
subs_links=$(printf "%s" "$subs_links" | $sed -e "s/:/\\$path_thing:/g" -e "H;1h;\$!d;x;y/\n/$separator/" -e "s/$separator\$//")
subs_arg="--sub-files"
fi
[ -z "$subs_links" ] && send_notification "No subtitles found"
if [ "$json_output" = true ]; then
printf "%s\n" "$json_data"
exit 0
fi
subs_links=$(printf "%s" "$json_data" | tr "{}" "\n" | $sed -nE "s@\"file\":\"([^\"]*)\",\"label\":\"(.$subs_language)[,\"\ ].*@\1@p")
num_subs=$(printf "%s" "$subs_links" | wc -l)
if [ "$num_subs" -gt 0 ]; then
subs_links=$(printf "%s" "$subs_links" | $sed -e "s/:/\\$path_thing:/g" -e "H;1h;\$!d;x;y/\n/$separator/" -e "s/$separator\$//")
subs_arg="--sub-files=$subs_links"
else
subs_arg="--sub-file=$subs_links"
fi
[ -z "$subs_links" ] && send_notification "No subtitles found"
;;
yugen)