jerry.sh

1630 lines · 89516 bytes · executable

   1
   2#!/bin/sh
   3
   4JERRY_VERSION=1.9.9
   5source /home/wraient/venv/bin/activate
   6anilist_base="https://graphql.anilist.co"
   7config_file="$HOME/.config/jerry/jerry.conf"
   8jerry_editor=${VISUAL:-${EDITOR}}
   9tmp_dir="/tmp/jerry"
  10tmp_position="/tmp/jerry_position"
  11
  12cleanup() {
  13    # tput clear
  14    rm -rf "$tmp_dir" 2>/dev/null
  15    if [ "$image_preview" = true ] && [ "$use_external_menu" = false ]; then
  16        killall ueberzugpp 2>/dev/null
  17        rm /tmp/ueberzugpp-* 2>/dev/null
  18    fi
  19}
  20trap cleanup EXIT INT TERM
  21
  22applications="$HOME/.local/share/applications/jerry"
  23images_cache_dir="/tmp/jerry/jerry-images"
  24
  25command -v bat >/dev/null 2>&1 && display="bat" || display="less"
  26case "$(uname -s)" in
  27    MINGW* | *Msys) separator=';' && path_thing='' && sed="sed" ;;
  28    *arwin) sed="gsed" && player="iina" ;;
  29    *) separator=':' && path_thing="\\" && sed="sed" ;;
  30esac
  31command -v notify-send >/dev/null 2>&1 && notify="true" || notify="false"
  32send_notification() {
  33    [ "$json_output" = true ] && return
  34    if [ "$use_external_menu" = false ] || [ -z "$use_external_menu" ]; then
  35        [ -z "$4" ] && printf "\33[2K\r\033[1;34m%s\n\033[0m" "$1" && return
  36        [ -n "$4" ] && printf "\33[2K\r\033[1;34m%s - %s\n\033[0m" "$1" "$4" && return
  37    fi
  38    [ -z "$2" ] && timeout=3000 || timeout="$2"
  39    if [ "$notify" = "true" ]; then
  40        [ -z "$3" ] && notify-send -e "$1" "$4" -t "$timeout" -h string:x-dunst-stack-tag:tes
  41        [ -n "$3" ] && notify-send -e "$1" "$4" -t "$timeout" -i "$3" -h string:x-dunst-stack-tag:tes
  42    fi
  43}
  44dep_ch() {
  45    for dep; do
  46        command -v "$dep" >/dev/null || send_notification "Program \"$dep\" not found. Please install it."
  47    done
  48}
  49dep_ch "grep" "$sed" "curl" "fzf" || true
  50
  51if [ "$use_external_menu" = true ]; then
  52    dep_ch "rofi" || true
  53fi
  54
  55usage() {
  56    printf "
  57  Usage: %s [options] [query]
  58  If a query is provided, it will be used to search for an anime, and will default to the 'Watch New Anime' option.
  59
  60  Options:
  61    -c, --continue
  62      Continue watching from currently watching list (using the user's anilist account)
  63    --dub
  64      Allows user to watch anime in dub
  65    -e, --edit
  66      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
  67    -d, --discord
  68      Display currently watching anime in Discord Rich Presence (jerrydiscordpresence.py is required for this, check the wiki for instructions on how to install it)
  69    -h, --help
  70      Show this help message and exit
  71    -i, --image-preview
  72      Allows image preview in fzf and rofi
  73    -j, --json
  74      Outputs the json containing video links, subtitle links, referrers etc. to stdout
  75    -l, --language
  76      Specify the subtitle language
  77    -n, --number
  78      Specify the episode number for an anime
  79    --rofi, --dmenu, --external-menu
  80      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)
  81    -q, --quality
  82      Specify the video quality
  83    -s, --syncplay
  84      Watch anime together with friends, using Syncplay (only tested using mpv)
  85    -u, --update
  86      Update the script
  87    -v, --version
  88      Show the script version
  89    --vlc
  90      Use VLC as the video player
  91    -w, --website
  92      Choose which website to get video links from (default: allanime) (currently supported: allanime, aniwatch, yugen, hdrezka and crunchyroll)
  93
  94    Note: 
  95      All arguments can be specified in the config file as well.
  96      If an argument is specified in both the config file and the command line, the command line argument will be used.
  97
  98    Some example usages:
  99     ${0##*/} -q 720 banana fish
 100     ${0##*/} --rofi -l russian cyberpunk edgerunners -i -n 2
 101     ${0##*/} -l spanish cyberpunk edgerunners --number 2 --json
 102
 103" "${0##*/}"
 104}
 105
 106configuration() {
 107    [ -n "$XDG_CONFIG_HOME" ] && config_dir="$XDG_CONFIG_HOME/jerry" || config_dir="$HOME/.config/jerry"
 108    [ -n "$XDG_DATA_HOME" ] && data_dir="$XDG_DATA_HOME/jerry" || data_dir="$HOME/.local/share/jerry"
 109    [ ! -d "$data_dir" ] && mkdir -p "$data_dir"
 110    #shellcheck disable=1090
 111    [ -f "$config_file" ] && . "${config_file}"
 112    if [ -z "$player" ]; then
 113        case "$(uname -s)" in
 114            MINGW* | *Msys) player="mpv.exe" ;;
 115            *) player="mpv" ;;
 116        esac
 117    fi
 118    [ -z "$provider" ] && provider="allanime"
 119    [ -z "$download_dir" ] && download_dir="$PWD"
 120    [ -z "$manga_dir" ] && manga_dir="$data_dir/jerry-manga"
 121    [ -z "$manga_format" ] && manga_format="image"
 122    [ -z "$manga_opener" ] && manga_opener="feh"
 123    [ -z "$history_file" ] && history_file="$data_dir/jerry_history.txt"
 124    [ -z "$subs_language" ] && subs_language="english"
 125    subs_language="$(printf "%s" "$subs_language" | cut -c2-)"
 126    [ -z "$use_external_menu" ] && use_external_menu=false
 127    [ -z "$image_preview" ] && image_preview=false
 128    [ -z "$json_output" ] && json_output=false
 129    [ -z "$sub_or_dub" ] && sub_or_dub="sub"
 130    [ -z "$score_on_completion" ] && score_on_completion="false"
 131    [ "$no_anilist" = false ] && no_anilist=""
 132    [ -z "$discord_presence" ] && discord_presence="false"
 133    [ -z "$presence_script_path" ] && presence_script_path="jerrydiscordpresence.py"
 134    if [ -z "$chafa_options" ]; then
 135        case "$(uname -s)" in
 136            MINGW* | *Msys) chafa_options="-f symbols" ;;
 137            *) chafa_options="-f sixel" ;;
 138        esac
 139    fi
 140    [ -z "$show_adult_content" ] && show_adult_content="false"
 141}
 142
 143check_credentials() {
 144    [ -f "$data_dir/anilist_token.txt" ] && access_token=$(cat "$data_dir/anilist_token.txt")
 145    [ -z "$access_token" ] && printf "Paste your access token from this page:
 146https://anilist.co/api/v2/oauth/authorize?client_id=9857&response_type=token : " && read -r access_token &&
 147        echo "$access_token" >"$data_dir/anilist_token.txt"
 148    [ -f "$data_dir/anilist_user_id.txt" ] && user_id=$(cat "$data_dir/anilist_user_id.txt")
 149    [ -z "$access_token" ] && exit 1
 150    [ -z "$user_id" ] &&
 151        user_id=$(curl -s -X POST "$anilist_base" \
 152            -H "Content-Type: application/json" \
 153            -H "Accept: application/json" \
 154            -H "Authorization: Bearer $access_token" \
 155            -d "{\"query\":\"query { Viewer { id } }\"}" | $sed -nE "s@.*\"id\":([0-9]*).*@\1@p") &&
 156        echo "$user_id" >"$data_dir/anilist_user_id.txt"
 157}
 158
 159#### SCRAPING FUNCTIONS ####
 160## ALLANIME ##
 161# this has been adapted from ani-cli
 162
 163# extract the video links from reponse of embed urls, extract mp4 links form m3u8 lists
 164get_links() {
 165    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')"
 166    case "$episode_link" in
 167        *repackager.wixmp.com*)
 168            extract_link=$(printf "%s" "$episode_link" | cut -d'>' -f2 | sed 's|repackager.wixmp.com/||g;s|\.urlset.*||g')
 169            for j in $(printf "%s" "$episode_link" | sed -nE 's|.*/,([^/]*),/mp4.*|\1|p' | sed 's|,|\n|g'); do
 170                printf "%s >%s\n" "$j" "$extract_link" | sed "s|,[^/]*|${j}|g"
 171            done | sort -nr
 172            ;;
 173        *vipanicdn* | *anifastcdn*)
 174            if printf "%s" "$episode_link" | head -1 | grep -q "original.m3u"; then
 175                printf "%s" "$episode_link"
 176            else
 177                extract_link=$(printf "%s" "$episode_link" | head -1 | cut -d'>' -f2)
 178                relative_link=$(printf "%s" "$extract_link" | sed 's|[^/]*$||')
 179                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
 180            fi
 181            ;;
 182        *) [ -n "$episode_link" ] && printf "%s\n" "$episode_link" ;;
 183    esac
 184    printf "\033[1;32m%s\033[0m Links Fetched\n" "$provider_name" 1>&2
 185}
 186
 187# innitialises provider_name and provider_id. First argument is the provider name, 2nd is the regex that matches that provider's link
 188provider_init() {
 189    provider_name=$1
 190    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/")
 191}
 192
 193generate_links() {
 194    case $1 in
 195        # using gogoanime as the default provider since it provides m3u8 links and bc --start doesn't work with mp4 links (idk why)
 196        1) provider_init "gogoanime" "/Luf-mp4 :/p" ;; # gogoanime(m3u8)(multi)
 197        2) provider_init "wixmp" "/Default :/p" ;;     # wixmp(default)(m3u8)(multi) -> (mp4)(multi)
 198        3) provider_init "dropbox" "/Sak :/p" ;;       # dropbox(mp4)(single)
 199        4) provider_init "wetransfer" "/Kir :/p" ;;    # wetransfer(mp4)(single)
 200        5) provider_init "sharepoint" "/S-mp4 :/p" ;;  # sharepoint(mp4)(single)
 201    esac
 202    [ -n "$provider_id" ] && get_links "$provider_id"
 203}
 204
 205select_quality() {
 206    case "$1" in
 207        best) result=$(printf "%s" "$links" | head -n1) ;;
 208        worst) result=$(printf "%s" "$links" | grep -E '^[0-9]{3,4}' | tail -n1) ;;
 209        *) result=$(printf "%s" "$links" | grep -m 1 "$1") ;;
 210    esac
 211    [ -z "$result" ] && printf "Specified quality not found, defaulting to best\n" 1>&2 && result=$(printf "%s" "$links" | head -n1)
 212    printf "%s" "$result" | cut -d'>' -f2
 213}
 214
 215#### GENERAL HELPER FUNCTIONS ####
 216
 217edit_configuration() {
 218    if [ -f "$config_file" ]; then
 219        #shellcheck disable=1090
 220        . "${config_file}"
 221        [ -z "$jerry_editor" ] && jerry_editor="vim"
 222        "$jerry_editor" "$config_file"
 223    else
 224        printf "No configuration file found. Would you like to generate a default one? [Y/n] " && read -r generate
 225        case "$generate" in
 226            [Nn]*) exit 0 ;;
 227            *)
 228                [ ! -d "$config_dir" ] && mkdir -p "$config_dir"
 229                send_notification "Jerry" "" "" "Getting the latest example config from github..."
 230                curl -s "https://raw.githubusercontent.com/justchokingaround/jerry/main/examples/jerry.conf" -o "$config_dir/jerry.conf"
 231                send_notification "Jerry" "" "" "New config generated!"
 232                #shellcheck disable=1090
 233                . "${config_file}"
 234                [ -z "$jerry_editor" ] && jerry_editor="vim"
 235                "$jerry_editor" "$config_file"
 236                ;;
 237        esac
 238    fi
 239    exit 0
 240
 241}
 242
 243update_script() {
 244    which_jerry="$(command -v jerry)"
 245    if [ -z "$which_jerry" ]; then
 246        send_notification "Can't find jerry in PATH"
 247        exit 1
 248    fi
 249
 250    if [ ! -w "$which_jerry" ]; then
 251        if [ -n "$(command -v sudo)" ]; then
 252            exec sudo -s "$which_jerry" "-u"
 253        else
 254            send_notification "Insufficient permissions to update and can't find sudo in PATH"
 255            exit 1
 256        fi
 257    fi
 258
 259    update=$(curl -s "https://raw.githubusercontent.com/justchokingaround/jerry/main/jerry.sh" || exit 1)
 260    update="$(printf '%s\n' "$update" | diff -u "$which_jerry" - 2>/dev/null)"
 261    if [ -z "$update" ]; then
 262        send_notification "Script is up to date :)"
 263    else
 264        if printf '%s\n' "$update" | patch "$which_jerry" -; then
 265            send_notification "Script has been updated!"
 266        else
 267            send_notification "Can't update for some reason!"
 268        fi
 269    fi
 270    exit 0
 271}
 272
 273check_update() {
 274    update=$(curl -s "https://raw.githubusercontent.com/justchokingaround/jerry/main/jerry.sh")
 275    update="$(printf '%s\n' "$update" | diff -u "$(command -v jerry)" - 2>/dev/null)"
 276    if [ -n "$update" ]; then
 277        if [ "$use_external_menu" = false ]; then
 278            printf "%s" "$1" && read -r answer
 279        else
 280            answer=$(printf "Yes\nNo" | launcher "$1")
 281        fi
 282        case "$answer" in
 283            [Yy]*) update_script ;;
 284        esac
 285    fi
 286}
 287
 288get_input() {
 289    if [ "$use_external_menu" = false ]; then
 290        printf "%s" "$1" && read -r query
 291    else
 292        if [ -n "$rofi_prompt_config" ]; then
 293            query=$(printf "" | rofi -theme "$rofi_prompt_config" -sort -dmenu -i -width 1500 -p "" -mesg "$1")
 294        else
 295            query=$(printf "" | launcher "$1")
 296        fi
 297    fi
 298}
 299
 300generate_desktop() {
 301    cat <<EOF
 302[Desktop Entry]
 303Name=$1
 304Exec=echo %k %c
 305Icon=$2
 306Type=Application
 307Categories=jerry;
 308EOF
 309}
 310
 311launcher() {
 312    case "$use_external_menu" in
 313        true)
 314            [ -z "$2" ] && rofi -sort -matching fuzzy -dmenu -i -width 1500 -p "" -mesg "$1" -matching fuzzy -sorting-method fzf
 315            [ -n "$2" ] && rofi -sort -matching fuzzy -dmenu -i -width 1500 -p "" -mesg "$1" -display-columns "$2" -matching fuzzy -sorting-method fzf
 316            ;;
 317        *)
 318            [ -z "$2" ] && fzf --cycle --reverse --prompt "$1"
 319            [ -n "$2" ] && fzf --cycle --reverse --prompt "$1" --with-nth "$2" -d "\t"
 320            ;;
 321    esac
 322}
 323
 324nth() {
 325    stdin=$(cat -)
 326    [ -z "$stdin" ] && return 1
 327    prompt="$1"
 328    [ $# -ne 1 ] && shift
 329    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)
 330    [ -n "$line" ] && printf "%s" "$stdin" | $sed -nE "s@^$line\t(.*)@\1@p" || exit 1
 331}
 332
 333download_images() {
 334    [ ! -d "$manga_dir/$title/chapter_$((progress + 1))" ] && mkdir -p "$manga_dir/$title/chapter_$((progress + 1))"
 335    send_notification "Downloading images" "" "$images_cache_dir/$media_id.jpg" "$title - Chapter: $((progress + 1)) $chapter_title"
 336    printf "%s\n" "$1" | while read -r link; do
 337        number=$(printf "%03d" "$(printf "%s" "$link" | $sed -nE "s@[a-zA-Z]?([0-9]*)-.*@\1@p")")
 338        image_name=$(printf "%s.%s" "$number" "$(printf "%s" "$link" | $sed -nE "s@.*\.(.*)@\1@p")")
 339        download_link=$(printf "%s/data/%s/%s" "$mangadex_data_base_url" "$mangadex_hash" "$link")
 340        curl -s "$download_link" -o "$manga_dir/$title/chapter_$((progress + 1))/$image_name" &
 341    done
 342    wait && sleep 2
 343}
 344
 345convert_to_pdf() {
 346    send_notification "Converting $title - Chapter: $((progress + 1)) $chapter_title to PDF" "2000" "$images_cache_dir/$media_id.jpg"
 347    convert "$manga_dir/$title/chapter_$((progress + 1))"/* "$manga_dir/$title/chapter_$((progress + 1))/$title - Chapter $((progress + 1)).pdf" && wait
 348}
 349
 350hdrezka_data_and_translation_id() {
 351    data_id=$(printf "%s" "$episode_id" | sed -nE "s@[a-z]*/([0-9]*)-.*@\1@p")
 352    case "$media_type" in
 353        films)
 354            default_translator_id=$(curl -s "https://hdrezka.website/${media_type}/$(printf "%s" "$episode_id" | tr '=' '/').html" -A "uwu" --compressed |
 355                sed -nE "s@.*initCDNMoviesEvents\(${data_id}\, ([0-9]*)\,.*@\1@p")
 356            ;;
 357        *)
 358            default_translator_id=$(curl -s "https://hdrezka.website/${media_type}/$(printf "%s" "$episode_id" | tr '=' '/').html" -A "uwu" --compressed |
 359                sed -nE "s@.*initCDNSeriesEvents\(${data_id}\, ([0-9]*)\,.*@\1@p")
 360            ;;
 361    esac
 362    translations=$(curl -s "https://hdrezka.website/${media_type}/$(printf "%s" "$episode_id" | tr '=' '/').html" -A "uwu" --compressed |
 363        sed 's/b-translator__item/\n/g' | sed -nE "s@.*data-translator_id=\"([0-9]*)\"[^>]*>(.*)</li.*@\2\t\1@p" |
 364        sed 's/<img title="\([^\"]*\)" .*>\(.*\)/(\1)\2/;s/^\(.*\)<\/li><\/ul> <\/div>.*\t\([0-9]*\)/\1\t\2/')
 365    if [ -z "$translations" ]; then
 366        translator_id=$default_translator_id
 367    else
 368        translator_id=$(printf "%s" "$translations" | fzf --cycle --reverse --with-nth 1 -d "\t" --header "Choose a translation" | cut -f2)
 369    fi
 370}
 371
 372download_thumbnails() {
 373    printf "%s\n" "$1" | while read -r cover_url media_id title; do
 374        curl -s -o "$images_cache_dir/$media_id.jpg" "$cover_url" &
 375        if [ "$use_external_menu" = true ]; then
 376            entry=/tmp/jerry/applications/"$media_id.desktop"
 377            generate_desktop "$title" "$images_cache_dir/$media_id.jpg" >"$entry" &
 378        fi
 379    done
 380    sleep $2
 381}
 382
 383image_preview_fzf() {
 384    if [ -n "$use_ueberzugpp" ]; then
 385        UB_PID_FILE="/tmp/.$(uuidgen)"
 386        if [ -z "$ueberzug_output" ]; then
 387            ueberzugpp layer --no-stdin --silent --use-escape-codes --pid-file "$UB_PID_FILE" 2>/dev/null
 388        else
 389            ueberzugpp layer -o "$ueberzug_output" --no-stdin --silent --use-escape-codes --pid-file "$UB_PID_FILE" 2>/dev/null
 390        fi
 391        UB_PID="$(cat "$UB_PID_FILE")"
 392        JERRY_UEBERZUG_SOCKET=/tmp/ueberzugpp-"$UB_PID".socket
 393        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")
 394        ueberzugpp cmd -s "$JERRY_UEBERZUG_SOCKET" -a exit
 395    else
 396        case "$(uname -s)" in
 397            MINGW* | *Msys)
 398                # Chafa on windows fails to detect terminal preview window size, so it is determined by view_dim
 399                # TODO: Make $view_dim properly reflect $preview_window_size
 400                view_dim="$(($(tput cols) / 2 - 4))x$(($(tput lines) - 2))"
 401                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")
 402                ;;
 403            *)
 404                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")
 405                ;;
 406        esac
 407    fi
 408}
 409
 410select_desktop_entry() {
 411    if [ "$use_external_menu" = true ]; then
 412        [ -n "$image_config_path" ] && choice=$(rofi -show drun -drun-categories jerry -filter "$1" -show-icons -theme "$image_config_path" -i -matching fuzzy -sorting-method fzf |
 413            $sed -nE "s@.*/([0-9]*)\.desktop@\1@p") 2>/dev/null ||
 414            choice=$(rofi -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
 415    else
 416        image_preview_fzf "$1" "$2" "$3"
 417    fi
 418}
 419
 420#### ANILIST ANIME FUNCTIONS ####
 421get_anime_from_list() {
 422    anime_list=$(curl -s -X POST "$anilist_base" \
 423        -H 'Content-Type: application/json' \
 424        -H "Authorization: Bearer $access_token" \
 425        -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)/')
 426    if [ -z "$anime_list" ]; then
 427        send_notification "No anime found in your list" "2000"
 428        exit 1
 429    fi
 430    if [ "$use_external_menu" = true ]; then
 431        case "$image_preview" in
 432            true)
 433                download_thumbnails "$anime_list" "1"
 434                select_desktop_entry "" "Choose anime: " "$anime_list"
 435                [ -z "$choice" ] && exit 1
 436                start_year=$(printf "%s" "$choice" | $sed -nE "s@.*\(([0-9?]{4})\).*@\1@p")
 437                choice=$(printf "%s" "$choice" | $sed -nE "s@\([0-9?]{4}\)@ @p") # remove year from the title
 438                media_id=$(printf "%s" "$choice" | cut -d\  -f1)
 439                title=$(printf "%s" "$choice" | $sed -nE "s@$media_id (.*) [0-9?|]* episodes.*@\1@p" | $sed -E 's|\\u.{4}|+|g')
 440                [ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* episodes.*@\1@p")
 441                episodes_total=$(printf "%s" "$choice" | $sed -nE "s@.*[\| ]([0-9?]*) episodes.*@\1@p")
 442                [ -z "$episodes_total" ] && episodes_total=9999
 443                score=$(printf "%s" "$choice" | $sed -nE "s@.* episodes \[([0-9]*)\].*@\1@p")
 444                ;;
 445            *)
 446                tmp_anime_list=$(printf "%s" "$anime_list" | $sed -nE "s@(.*\.[jpneg]*)[[:space:]]*([0-9]*)[[:space:]]*(.*)@\3\t\2\t\1@p")
 447                choice=$(printf "%s" "$tmp_anime_list" | launcher "Choose anime: " "1")
 448                [ -z "$choice" ] && exit 1
 449                start_year=$(printf "%s" "$choice" | $sed -nE "s@.*\(([0-9?]{4})\).*@\1@p")
 450                choice=$(printf "%s" "$choice" | $sed -nE "s@\([0-9?]{4}\)@ @p") # remove year from the title
 451                media_id=$(printf "%s" "$choice" | cut -f2)
 452                title=$(printf "%s" "$choice" | $sed -nE "s@(.*) [0-9?|]* episodes.*@\1@p" | $sed -E 's|\\u.{4}|+|g')
 453                [ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* episodes.*@\1@p")
 454                episodes_total=$(printf "%s" "$choice" | $sed -nE "s@.*[\| ]([0-9?]*) episodes.*@\1@p")
 455                [ -z "$episodes_total" ] && episodes_total=9999
 456                score=$(printf "%s" "$choice" | $sed -nE "s@.* episodes \[([0-9]*)\].*@\1@p")
 457                ;;
 458        esac
 459    else
 460        case "$image_preview" in
 461            true)
 462                download_thumbnails "$anime_list" "2"
 463                select_desktop_entry "" "Choose anime: " "$anime_list"
 464                [ -z "$choice" ] && exit 0
 465                start_year=$(printf "%s" "$choice" | $sed -nE "s@.*\(([0-9?]{4})\).*@\1@p")
 466                choice=$(printf "%s" "$choice" | $sed -nE "s@\([0-9?]{4}\)@ @p") # remove year from the title
 467                media_id=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\.jpg@\1@p")
 468                title=$(printf "%s" "$choice" | $sed -nE "s@[[:space:]]*(.*) [0-9?|]* episodes.*@\1@p" | $sed -E 's|\\u.{4}|+|g')
 469                [ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* episodes.*@\1@p")
 470                episodes_total=$(printf "%s" "$choice" | $sed -nE "s@.*[\| ]([0-9?]*) episodes.*@\1@p")
 471                [ -z "$episodes_total" ] && episodes_total=9999
 472                score=$(printf "%s" "$choice" | $sed -nE "s@.* episodes \[([0-9]*)\].*@\1@p")
 473                ;;
 474            *)
 475                choice=$(printf "%s" "$anime_list" | launcher "Choose anime: " "3")
 476                [ -z "$choice" ] && exit 1
 477                start_year=$(printf "%s" "$choice" | $sed -nE "s@.*\(([0-9?]{4})\).*@\1@p")
 478                choice=$(printf "%s" "$choice" | $sed -nE "s@\([0-9?]{4}\)@ @p") # remove year from the title
 479                media_id=$(printf "%s" "$choice" | cut -f2)
 480                title=$(printf "%s" "$choice" | $sed -nE "s@.*$media_id\t(.*) [0-9?|]* episodes.*@\1@p" | $sed -E 's|\\u.{4}|+|g')
 481                [ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* episodes.*@\1@p")
 482                episodes_total=$(printf "%s" "$choice" | $sed -nE "s@.*[\| ]([0-9?]*) episodes.*@\1@p")
 483                [ -z "$episodes_total" ] && episodes_total=9999
 484                score=$(printf "%s" "$choice" | $sed -nE "s@.* episodes \[([0-9]*)\].*@\1@p")
 485                ;;
 486        esac
 487
 488        [ -z "$choice" ] && exit 1
 489        media_id=$(printf "%s" "$choice" | cut -f2)
 490        title=$(printf "%s" "$choice" | $sed -nE "s@.*$media_id\t(.*) [0-9?|]* episodes.*@\1@p" | $sed -E 's|\\u.{4}|+|g')
 491        [ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* episodes.*@\1@p")
 492        episodes_total=$(printf "%s" "$choice" | $sed -nE "s@.*[\| ]([0-9?]*) episodes.*@\1@p")
 493        [ -z "$episodes_total" ] && episodes_total=9999
 494        score=$(printf "%s" "$choice" | $sed -nE "s@.* episodes \[([0-9]*)\].*@\1@p")
 495    fi
 496}
 497
 498search_anime_anilist() {
 499    if [ "$show_adult_content" = true ]; then
 500        isAdult_variable=""
 501    else
 502        isAdult_variable=",\"isAdult\":false"
 503    fi
 504    anime_list=$(curl -s -X POST "$anilist_base" \
 505        -H 'Content-Type: application/json' \
 506        -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)/')
 507
 508    if [ "$use_external_menu" = true ]; then
 509        case "$image_preview" in
 510            true)
 511                download_thumbnails "$anime_list" "1"
 512                select_desktop_entry "" "Choose anime: " "$anime_list"
 513                [ -z "$choice" ] && exit 1
 514                start_year=$(printf "%s" "$choice" | $sed -nE "s@.*\(([0-9?]{4})\).*@\1@p")
 515                choice=$(printf "%s" "$choice" | $sed -nE "s@\([0-9?]{4}\)@ @p") # remove year from the title
 516                media_id=$(printf "%s" "$choice" | cut -d\  -f1)
 517                title=$(printf "%s" "$choice" | $sed -nE "s@$media_id (.*) [0-9?]* episodes.*@\1@p")
 518                episodes_total=$(printf "%s" "$choice" | $sed -nE "s@.*[\| ]([0-9?]*) episodes.*@\1@p")
 519                [ -z "$episodes_total" ] && episodes_total=9999
 520                ;;
 521            *)
 522                tmp_anime_list=$(printf "%s" "$anime_list" | $sed -nE "s@(.*\.[jpneg]*)[[:space:]]*([0-9]*)[[:space:]]*(.*)@\3\t\2\t\1@p")
 523                choice=$(printf "%s" "$tmp_anime_list" | launcher "Choose anime: " "1")
 524                start_year=$(printf "%s" "$choice" | $sed -nE "s@.*\(([0-9?]{4})\).*@\1@p")
 525                choice=$(printf "%s" "$choice" | $sed -nE "s@\([0-9?]{4}\)@ @p") # remove year from the title
 526                media_id=$(printf "%s" "$choice" | cut -f2)
 527                title=$(printf "%s" "$choice" | $sed -nE "s@(.*) [0-9?|]* episodes.*@\1@p")
 528                [ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* episodes.*@\1@p")
 529                episodes_total=$(printf "%s" "$choice" | $sed -nE "s@.*[\| ]([0-9?]*) episodes.*@\1@p")
 530                [ -z "$episodes_total" ] && episodes_total=9999
 531                ;;
 532        esac
 533    else
 534        case "$image_preview" in
 535            true)
 536                download_thumbnails "$anime_list" "2"
 537                select_desktop_entry "" "Choose anime: " "$anime_list"
 538                [ -z "$choice" ] && exit 0
 539                start_year=$(printf "%s" "$choice" | $sed -nE "s@.*\(([0-9?]{4})\).*@\1@p")
 540                choice=$(printf "%s" "$choice" | $sed -nE "s@\([0-9?]{4}\)@ @p") # remove year from the title
 541                media_id=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\.jpg@\1@p")
 542                title=$(printf "%s" "$choice" | $sed -nE "s@[[:space:]]*(.*) [0-9?|]* episodes.*@\1@p")
 543                episodes_total=$(printf "%s" "$choice" | $sed -nE "s@.*[\| ]([0-9?]*) episodes.*@\1@p")
 544                [ -z "$episodes_total" ] && episodes_total=9999
 545                ;;
 546            *)
 547                choice=$(printf "%s" "$anime_list" | launcher "Choose anime: " "3")
 548                start_year=$(printf "%s" "$choice" | $sed -nE "s@.*\(([0-9?]{4})\).*@\1@p")
 549                choice=$(printf "%s" "$choice" | $sed -nE "s@\([0-9?]{4}\)@ @p") # remove year from the title
 550                media_id=$(printf "%s" "$choice" | cut -f2)
 551                title=$(printf "%s" "$choice" | $sed -nE "s@.*$media_id\t(.*) [0-9?|]* episodes.*@\1@p")
 552                [ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* episodes.*@\1@p")
 553                episodes_total=$(printf "%s" "$choice" | $sed -nE "s@.*[\| ]([0-9?]*) episodes.*@\1@p")
 554                ;;
 555        esac
 556
 557        [ -z "$choice" ] && exit 0
 558        media_id=$(printf "%s" "$choice" | cut -f2)
 559        title=$(printf "%s" "$choice" | $sed -nE "s@.*$media_id\t(.*) [0-9?|]* episodes.*@\1@p")
 560        [ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* episodes.*@\1@p")
 561        episodes_total=$(printf "%s" "$choice" | $sed -nE "s@.*[\| ]([0-9?]*) episodes.*@\1@p")
 562    fi
 563    [ -z "$title" ] && exit 0
 564
 565    if [ -n "$no_anilist" ]; then
 566        if [ "$show_adult_content" = true ]; then
 567            isAdult_variable=""
 568        else
 569            isAdult_variable=",\"isAdult\":false"
 570        fi
 571
 572        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")
 573        numeric_part=$(printf "%s" "$episodes_total" | sed -nE "s@s([0-9]*)@\1@p")
 574        [ -n "$numeric_part" ] && episodes_total=$numeric_part || episodes_total=$((episodes_total - 1))
 575
 576        [ -n "$progress" ] && return
 577        if [ "$episodes_total" = 1 ]; then
 578            progress=0
 579        else
 580            [ -z "$episodes_total" ] && episodes_total=9999
 581            if [ "$use_external_menu" = true ]; then
 582                if [ -n "$rofi_prompt_config" ]; then
 583                    progress=$(printf "" | rofi -theme "$rofi_prompt_config" -sort -dmenu -i -width 1500 -p "" -mesg "Please enter the episode number (1-${episodes_total}): ")
 584                else
 585                    progress=$(printf "" | launcher "Please enter the episode number (1-${episodes_total}): ")
 586                fi
 587            else
 588                printf "%s" "Please enter the episode number (1-${episodes_total}): " && read -r progress
 589                [ -z "$progress" ] && progress=$episodes_total
 590            fi
 591            if [ -z "$progress" ]; then
 592                send_notification "Error" "1000" "$images_cache_dir/$media_id.jpg" "No episode number provided"
 593                exit 1
 594            fi
 595            progress=$((progress - 1))
 596        fi
 597    fi
 598}
 599
 600update_progress() {
 601    curl -s -X POST "$anilist_base" \
 602        -H 'Content-Type: application/json' \
 603        -H "Authorization: Bearer $access_token" \
 604        -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}}"
 605    [ "$3" = "COMPLETED" ] && send_notification "Completed $title" "5000"
 606    [ "$3" = "COMPLETED" ] && $sed -i "/$media_id/d" "$history_file"
 607}
 608
 609update_episode_from_list() {
 610    status_choice=$(printf "CURRENT\nREPEATING\nCOMPLETED\nPAUSED\nDROPPED\nPLANNING" | launcher "Filter by status: ")
 611    get_anime_from_list "$status_choice"
 612
 613    if [ -z "$title" ] || [ -z "$progress" ]; then
 614        exit 0
 615    fi
 616
 617    send_notification "Current progress: $progress/$episodes_total episodes watched" "5000"
 618
 619    if [ "$use_external_menu" = false ]; then
 620        printf "Enter a new episode number: "
 621        read -r new_episode_number
 622    else
 623        new_episode_number=$(printf "" | launcher "Enter a new episode number: ")
 624    fi
 625    [ "$new_episode_number" -gt "$episodes_total" ] && new_episode_number=$episodes_total
 626    [ "$new_episode_number" -lt 0 ] && new_episode_number=0
 627
 628    if [ -z "$new_episode_number" ]; then
 629        send_notification "No episode number given"
 630        exit 1
 631    fi
 632
 633    send_notification "Updating progress for $title..."
 634    [ "$new_episode_number" -eq "$episodes_total" ] && status="COMPLETED" || status="CURRENT"
 635    response=$(update_progress "$new_episode_number" "$media_id" "$status")
 636    send_notification "New progress: $new_episode_number/$episodes_total episodes watched"
 637    [ "$new_episode_number" -eq "$episodes_total" ] && send_notification "Completed $title"
 638}
 639
 640#### ANILIST MANGA FUNCTIONS ####
 641get_manga_from_list() {
 642    manga_list=$(curl -s -X POST "$anilist_base" \
 643        -H 'Content-Type: application/json' \
 644        -H "Authorization: Bearer $access_token" \
 645        -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\"}}" |
 646        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')
 647
 648    if [ "$use_external_menu" = true ]; then
 649        case "$image_preview" in
 650            true)
 651                download_thumbnails "$manga_list" "1"
 652                select_desktop_entry "" "Choose manga: " "$manga_list"
 653                [ -z "$choice" ] && exit 1
 654                media_id=$(printf "%s" "$choice" | cut -d\  -f1)
 655                title=$(printf "%s" "$choice" | $sed -nE "s@$media_id (.*) [0-9?|]* chapters.*@\1@p" | $sed -E 's|\\u.{4}|+|g')
 656                [ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* chapters.*@\1@p")
 657                chapters_total=$(printf "%s" "$choice" | $sed -nE "s@.*\|([0-9?]*) chapters.*@\1@p")
 658                score=$(printf "%s" "$choice" | $sed -nE "s@.*\|[0-9?]* chapters[[:space:]]*\[([0-9]*)\][[:space:]]*.*@\1@p")
 659                ;;
 660            *)
 661                tmp_manga_list=$(printf "%s" "$manga_list" | $sed -nE "s@(.*\.[jpneg]*)[[:space:]]*([0-9]*)[[:space:]]*(.*)@\3\t\2\t\1@p")
 662                choice=$(printf "%s" "$tmp_manga_list" | launcher "Choose manga: " "1")
 663                [ -z "$choice" ] && exit 1
 664                media_id=$(printf "%s" "$choice" | cut -f2)
 665                title=$(printf "%s" "$choice" | $sed -nE "s@(.*) [0-9?|]* chapters.*@\1@p" | $sed -E 's|\\u.{4}|+|g')
 666                [ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* chapters.*@\1@p")
 667                chapters_total=$(printf "%s" "$choice" | $sed -nE "s@.*\|([0-9?]*) chapters.*@\1@p")
 668                score=$(printf "%s" "$choice" | $sed -nE "s@.*\|[0-9?]* chapters[[:space:]]*\[([0-9]*)\][[:space:]]*.*@\1@p")
 669                ;;
 670        esac
 671    else
 672        case "$image_preview" in
 673            true)
 674                download_thumbnails "$manga_list" "1"
 675                select_desktop_entry "" "Choose manga: " "$manga_list"
 676                ;;
 677            *)
 678                choice=$(printf "%s" "$manga_list" | launcher "Choose manga: " "3")
 679                ;;
 680        esac
 681        [ -z "$choice" ] && exit 1
 682        media_id=$(printf "%s" "$choice" | cut -f2)
 683        title=$(printf "%s" "$choice" | $sed -nE "s@.*$media_id\t(.*) [0-9?|]* chapters.*@\1@p" | $sed -E 's|\\u.{4}|+|g')
 684        [ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* chapters.*@\1@p")
 685        chapters_total=$(printf "%s" "$choice" | $sed -nE "s@.*\|([0-9?]*) chapters.*@\1@p")
 686        score=$(printf "%s" "$choice" | $sed -nE "s@.*\|[0-9?]* chapters[[:space:]]*\[([0-9]*)\][[:space:]]*.*@\1@p")
 687    fi
 688}
 689
 690search_manga_anilist() {
 691    if [ "$show_adult_content" = true ]; then
 692        isAdult_variable=""
 693    else
 694        isAdult_variable=",\"isAdult\":false"
 695    fi
 696
 697    manga_list=$(curl -s -X POST "$anilist_base" \
 698        -H 'Content-Type: application/json' \
 699        -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}}" |
 700        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/?/')
 701
 702    if [ "$use_external_menu" = true ]; then
 703        case "$image_preview" in
 704            true)
 705                download_thumbnails "$manga_list" "1"
 706                select_desktop_entry "" "Choose manga: " "$manga_list"
 707                [ -z "$choice" ] && exit 1
 708                media_id=$(printf "%s" "$choice" | cut -d\  -f1)
 709                title=$(printf "%s" "$choice" | $sed -nE "s@$media_id (.*) [0-9?]* chapters.*@\1@p")
 710                chapters_total=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9?]*) chapters.*@\1@p")
 711                ;;
 712            *)
 713                tmp_manga_list=$(printf "%s" "$manga_list" | $sed -nE "s@(.*\.[jpneg]*)[[:space:]]*([0-9]*)[[:space:]]*(.*)@\3\t\2\t\1@p")
 714                choice=$(printf "%s" "$tmp_manga_list" | launcher "Choose manga: " "1")
 715                media_id=$(printf "%s" "$choice" | cut -f2)
 716                title=$(printf "%s" "$choice" | $sed -nE "s@(.*) [0-9?|]* chapters.*@\1@p")
 717                [ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* chapters.*@\1@p")
 718                chapters_total=$(printf "%s" "$choice" | $sed -nE "s@.*\|([0-9?]*) chapters.*@\1@p")
 719                ;;
 720        esac
 721    else
 722        case "$image_preview" in
 723            true)
 724                download_thumbnails "$manga_list" "1"
 725                select_desktop_entry "" "Choose manga: " "$manga_list"
 726                ;;
 727            *)
 728                choice=$(printf "%s" "$manga_list" | launcher "Choose manga: " "3")
 729                ;;
 730        esac
 731        [ -z "$choice" ] && exit 0
 732        media_id=$(printf "%s" "$choice" | cut -f2)
 733        title=$(printf "%s" "$choice" | $sed -nE "s@.*$media_id\t(.*) [0-9?|]* chapters.*@\1@p")
 734        [ -z "$progress" ] && progress=$(printf "%s" "$choice" | $sed -nE "s@.* ([0-9]*)\|[0-9?]* chapters.*@\1@p")
 735        chapters_total=$(printf "%s" "$choice" | $sed -nE "s@.*\|([0-9?]*) chapters.*@\1@p")
 736    fi
 737
 738    [ -z "$title" ] && exit 0
 739}
 740
 741update_chapter_from_list() {
 742    status_choice=$(printf "CURRENT\nREPEATING\nCOMPLETED\nPAUSED\nDROPPED\nPLANNING" | launcher "Filter by status: ")
 743    get_manga_from_list "$status_choice"
 744
 745    if [ -z "$title" ] || [ -z "$progress" ]; then
 746        exit 0
 747    fi
 748
 749    send_notification "Current progress: $progress/$chapters_total chapters read" "5000"
 750
 751    if [ "$use_external_menu" = false ]; then
 752        printf "Enter a new chapters read number: "
 753        read -r new_chapter_number
 754    else
 755        new_chapter_number=$(printf "" | launcher "Enter a new chapters read number: ")
 756    fi
 757    [ "$new_chapter_number" -gt "$chapters_total" ] && new_chapter_number=$chapters_total
 758    [ "$new_chapter_number" -lt 0 ] && new_chapter_number=0
 759
 760    if [ -z "$chapters_total" ]; then
 761        send_notification "No chapter number given"
 762        exit 1
 763    fi
 764
 765    send_notification "Updating progress for $title..."
 766    [ "$new_chapter_number" -eq "$chapters_total" ] && status="COMPLETED" || status="CURRENT"
 767    response=$(update_progress "$new_chapter_number" "$media_id" "$status")
 768    send_notification "New progress: $new_chapter_number/$chapters_total chapters read"
 769    [ "$new_chapter_number" -eq "$chapters_total" ] && send_notification "Completed $title"
 770}
 771
 772#### ANILIST META FUICTIONS ####
 773
 774update_status() {
 775    status_choice=$(printf "CURRENT\nREPEATING\nCOMPLETED\nPAUSED\nDROPPED\nPLANNING" | launcher "Filter by status: ")
 776    if [ "$1" = "ANIME" ]; then
 777        get_anime_from_list "$status_choice"
 778    else
 779        get_manga_from_list "$status_choice"
 780    fi
 781    [ -z "$title" ] && exit 0
 782    send_notification "Choose a new status for $title" "5000"
 783    new_status=$(printf "CURRENT\nREPEATING\nCOMPLETED\nPAUSED\nDROPPED\nPLANNING" | launcher "Choose a new status: ")
 784    [ -z "$new_status" ] && exit 0
 785    send_notification "Updating status for $title..."
 786    response=$(update_progress "$progress" "$media_id" "$new_status")
 787    if printf "%s" "$response" | grep -q "errors"; then
 788        send_notification "Failed to update status for $title"
 789    else
 790        send_notification "New status: $new_status"
 791    fi
 792}
 793
 794update_score() {
 795    if [ "$2" = "immediate" ]; then
 796        [ -z "$percentage_progress" ] || [ "$percentage_progress" -lt 85 ] && return
 797        [ "$1" = "ANIME" ] && total="$episodes_total"
 798        [ "$1" = "MANGA" ] && total="$chapters_total"
 799        [ $((progress + 1)) != "$total" ] && return
 800    else
 801        status_choice=$(printf "CURRENT\nREPEATING\nCOMPLETED\nPAUSED\nDROPPED\nPLANNING" | launcher "Filter by status: ")
 802        case "$1" in
 803            "ANIME") get_anime_from_list "$status_choice" ;;
 804            "MANGA") get_manga_from_list "$status_choice" ;;
 805        esac
 806    fi
 807    send_notification "Enter new score for: \"$title\"" "5000"
 808    send_notification "Current score: $score" "5000"
 809    if [ "$use_external_menu" = false ]; then
 810        printf "Enter new score: "
 811        read -r new_score
 812    else
 813        new_score=$(printf "" | launcher "Enter new score: ")
 814    fi
 815    [ -z "$new_score" ] && send_notification "No score given" && exit 1
 816    send_notification "Updating score for $title..."
 817    response=$(curl -s -X POST "$anilist_base" \
 818        -H 'Content-Type: application/json' \
 819        -H "Authorization: Bearer $access_token" \
 820        -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}}")
 821    if printf "%s" "$response" | grep -q "errors"; then
 822        send_notification "Failed to update score for $title"
 823    else
 824        send_notification "New score: $new_score"
 825    fi
 826}
 827
 828get_anilist_info() {
 829    case "$1" in
 830        "ANIME")
 831            get_input "Search anime: "
 832            [ -z "$query" ] && exit 1
 833            search_anime_anilist "$query"
 834            ;;
 835        "MANGA")
 836            get_input "Search manga: "
 837            [ -z "$query" ] && exit 1
 838            search_manga_anilist "$query"
 839            ;;
 840    esac
 841    [ -z "$media_id" ] && exit 1
 842    info="$(curl -s -X POST "$anilist_base" \
 843        -H 'Content-Type: application/json' \
 844        -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\"}}" |
 845        jq -r '.data.Media.description' | $sed "s/<br>/\n/g")"
 846    if [ "$use_external_menu" = true ]; then
 847        if ! command -v "zenity" >/dev/null; then
 848            send_notification "For this feature to work in the rofi mode, you must have zenity installed."
 849            exit 1
 850        fi
 851        zenity --info --text="$info"
 852    else
 853        echo "$info" | $display
 854    fi
 855}
 856
 857#### ANIME SCRAPING FUNCTIONS ####
 858get_episode_info() {
 859    case "$provider" in
 860        allanime)
 861            query_title=$(printf "%s" "$title" | tr ' ' '+')
 862            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')
 863            [ -z "$response" ] && exit 1
 864            # if it is only one line long, then auto select it
 865            if [ "$(printf "%s\n" "$response" | wc -l)" -eq 1 ]; then
 866                send_notification "Jerry" "" "" "Since there is only one result, it was automatically selected"
 867                choice=$response
 868            else
 869                choice=$(printf "%s" "$response" | launcher "Choose anime: " 2)
 870            fi
 871            [ -z "$choice" ] && exit 1
 872            title=$(printf "%s" "$choice" | cut -f2 | sed -E 's| \([0-9]* episodes\)||')
 873            allanime_id=$(printf "%s" "$choice" | cut -f1)
 874            episode_number=$((progress + 1))
 875            episode_info=$(printf "%s\t%s" "$allanime_id" "$title")
 876            ;;
 877        aniwatch)
 878            aniwatch_id=$(curl -s "https://raw.githubusercontent.com/bal-mackup/mal-backup/master/anilist/anime/${media_id}.json" |
 879                tr -d '\n ' | tr '}' '\n' | $sed -nE "s@.*\"Zoro\".*\"url\":\".*-([0-9]*)\".*@\1@p")
 880            episode_info=$(curl -s "https://aniwatch.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")
 881            ;;
 882        yugen)
 883            href=$(curl -s "https://raw.githubusercontent.com/bal-mackup/mal-backup/master/anilist/anime/${media_id}.json" |
 884                tr -d '\n' | tr '}' '\n' | $sed -nE 's@.*"YugenAnime".*"url": *"([^"]*)".*@\1@p' | $sed -e "s@tv/anime@tv/watch@")
 885            href="$href$((progress + 1))/"
 886            ep_title=$(curl -s "$href" | $sed -nE "s@.*$((progress + 1))\s:\s([^<]*).*@\1@p")
 887            if [ "$translation_type" = "dub" ]; then
 888                href=$(printf "%s" "$href" | $sed -E 's|(/[^/]+)/([0-9]+)/$|\1-dub/\2/|')
 889            fi
 890            yugen_id=$(curl -s "$href" | $sed -nE "s@.*id=\"main-embed\" src=\".*/e/([^/]*)/\".*@\1@p")
 891            episode_info=$(printf "%s\t%s" "$yugen_id" "$ep_title" | head -1)
 892            ;;
 893        hdrezka)
 894            query=$(curl -s "https://raw.githubusercontent.com/bal-mackup/mal-backup/master/anilist/anime/${media_id}.json" |
 895                sed -nE "s@.*\"title\":.\"([^\"]*)\".*@\1@p" | head -1 | tr ' ' '+')
 896            request=$(curl -s "https://hdrezka.website/search/?do=search&subaction=search&q=${query}" -A "uwu" --compressed)
 897            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")
 898            if [ -z "$response" ]; then
 899                send_notification "Error" "Could not query the anime on hdrezka"
 900                exit 1
 901            fi
 902            if [ "$(printf "%s\n" "$response" | wc -l)" -eq 1 ]; then
 903                send_notification "Jerry" "" "" "Since there is only one result, it was automatically selected"
 904                episode_info=$response
 905            else
 906                episode_info=$(printf "%s" "$response" | launcher "Choose anime: " 2)
 907            fi
 908            ;;
 909        aniworld)
 910            query=$(curl -s "https://raw.githubusercontent.com/bal-mackup/mal-backup/master/anilist/anime/${media_id}.json" |
 911                sed -nE "s@.*\"title\":.\"([^\"]*)\".*@\1@p" | head -1 | tr ' ' '+')
 912            request=$(curl -s "https://aniworld.to/ajax/search" -X POST --data-raw "keyword=${query}")
 913            response=$(printf "%s" "$request" | tr '{}' '\n' | sed -nE "s@.*title\":\"([^\"]*)\".*\"link\":\"([^\"]*)\".*@\1\t\2@p" | sed 's/<\\\/em>//g; s/<em>//g')
 914            if [ -z "$response" ]; then
 915                send_notification "Error" "Could not query the anime on aniworld"
 916                exit 1
 917            fi
 918            if [ "$(printf "%s\n" "$response" | wc -l)" -eq 1 ]; then
 919                send_notification "Jerry" "" "" "Since there is only one result, it was automatically selected"
 920                episode_info=$response
 921            else
 922                episode_info=$(printf "%s" "$response" | launcher "Choose anime: " 1)
 923            fi
 924            ;;
 925        crunchyroll)
 926            cr_href=$(curl -s "https://raw.githubusercontent.com/bal-mackup/mal-backup/master/anilist/anime/${media_id}.json" |
 927                tr -d '\n ' | tr '}' '\n' | $sed -nE "s@.*\"Crunchyroll\".*\"url\":\"([^\"]*)\".*@\1@p" | head -1)
 928            cr_id=$(printf "%s" "$cr_href" | sed -nE "s@.*/([^\/]*)/.*@\1@p")
 929            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")
 930            season_id=$(curl -s "https://www.crunchyroll.com/content/v2/cms/series/${cr_id}/seasons" \
 931                -H "authorization: Bearer ${access_token}" | sed -nE "s@.*\"id\":\"([^\"]*)\".*@\1@p")
 932            response=$(curl -s "https://www.crunchyroll.com/content/v2/cms/seasons/${season_id}/episodes" \
 933                -H "authorization: Bearer ${access_token}" | sed "s/},{/\n/g")
 934            title=$(printf "%s" "$response" | sed -nE "s@.*\"title\":\"([^\"]*)\".*@\1@p" | sed -n "$((progress + 1))p")
 935            eid=$(printf "%s\n" "$response" | sed -nE "s@.*\"id\":\"([^\"]*)\".*@\1@p" | sed -n $((progress + 1))p)
 936            episode_info="$(printf "%s\t%s" "$eid" "$title")"
 937            ;;
 938    esac
 939}
 940
 941extract_from_json() {
 942    case "$provider" in
 943        allanime)
 944            resp=$(printf "%s" "$json_data" | tr '{}' '\n' | sed 's|\\u002F|\/|g;s|\\||g' | sed -nE 's|.*sourceUrl":"--([^"]*)".*sourceName":"([^"]*)".*|\2 :\1|p')
 945            # generate links into sequential files
 946            cache_dir="$(mktemp -d)"
 947            link_providers="1 2 3 4 5"
 948            for link_provider in $link_providers; do
 949                generate_links "$link_provider" >"$cache_dir"/"$link_provider" &
 950            done
 951            wait
 952            # select the link with matching quality
 953            links=$(cat "$cache_dir"/* | sed 's|^Mp4-||g;/http/!d' | sort -g -r -s)
 954            if [ "$json_output" = true ]; then
 955                printf '{\n'
 956                for file in $cache_dir/*; do
 957                    if [ -s "$file" ]; then
 958                        provider=$(basename "$file")
 959                        printf '  "%s": {\n' "provider_$provider"
 960                        cat $file | while read -r quality url; do
 961                            printf '    "%s": "%s",\n' "$quality" "${url#>}"
 962                        done
 963                        [ "$provider" = "5" ] && printf '  }\n' || printf '  },\n'
 964                    fi
 965                done
 966                printf '}\n'
 967                exit 0
 968            fi
 969            video_link=$(select_quality "$quality")
 970            rm -r "$cache_dir"
 971            ;;
 972        aniwatch)
 973            json_key="file"
 974            encrypted=$(printf "%s" "$json_data" | tr "{}" "\n" | $sed -nE "s_.*\"${json_key}\":\"([^\"]*)\".*_\1_p" | grep "\.m3u8")
 975            if [ -n "$encrypted" ]; then
 976                video_link=$(printf "%s" "$json_data" | tr "{|}" "\n" | $sed -nE "s_.*\"${json_key}\":\"([^\"]*)\".*_\1_p" | head -1)
 977            else
 978                json_key="sources"
 979                encrypted=$(printf "%s" "$json_data" | tr "{}" "\n" | $sed -nE "s_.*\"${json_key}\":\"([^\"]*)\".*_\1_p")
 980                embed_type="6"
 981                enikey=$(curl -s "http://zoro-keys.freeddns.org/keys/e${embed_type}/key.txt" | tr -d ' ' |
 982                    $sed 's/\[\([0-9]*\),\([0-9]*\)\]/\1-\2/g;s/\[//g;s/\]//g;s/,/ /g')
 983
 984                encrypted_video_link=$(printf "%s" "$json_data" | tr "{|}" "\n" | $sed -nE "s_.*\"sources\":\"([^\"]*)\".*_\1_p" | head -1)
 985
 986                final_key=""
 987                tmp_encrypted_video_link="$encrypted_video_link"
 988                for key in $enikey; do
 989                    start="${key%-*}"
 990                    start=$((start + 1))
 991                    end="${key#*-}"
 992                    key=$(printf "%s" "$encrypted_video_link" | cut -c"$start-$end")
 993                    final_key="$final_key$key"
 994                    tmp_encrypted_video_link=$(printf "%s" "$tmp_encrypted_video_link" | $sed "s|$key||g")
 995                done
 996
 997                # ty @CoolnsX for helping me with figuring out how to implement aes in openssl
 998                video_link=$(printf "%s" "$tmp_encrypted_video_link" | base64 -d |
 999                    openssl enc -aes-256-cbc -d -md md5 -k "$final_key" 2>/dev/null | $sed -nE "s_.*\"file\":\"([^\"]*)\".*_\1_p")
1000                json_data=$(printf "%s" "$json_data" | $sed -e "s|${encrypted_video_link}|${video_link}|")
1001            fi
1002            [ -n "$quality" ] && video_link=$(printf "%s" "$video_link" | $sed -e "s|/playlist.m3u8|/$quality/index.m3u8|")
1003
1004            if [ "$json_output" = true ]; then
1005                printf "%s\n" "$json_data"
1006                exit 0
1007            fi
1008            subs_links=$(printf "%s" "$json_data" | tr "{}" "\n" | $sed -nE "s@\"file\":\"([^\"]*)\",\"label\":\"(.$subs_language)[,\"\ ].*@\1@p")
1009            num_subs=$(printf "%s" "$subs_links" | wc -l)
1010            if [ "$num_subs" -gt 0 ]; then
1011                subs_links=$(printf "%s" "$subs_links" | $sed -e "s/:/\\$path_thing:/g" -e "H;1h;\$!d;x;y/\n/$separator/" -e "s/$separator\$//")
1012                subs_arg="--sub-files=$subs_links"
1013            else
1014                subs_arg="--sub-file=$subs_links"
1015            fi
1016            [ -z "$subs_links" ] && send_notification "No subtitles found"
1017            ;;
1018        yugen)
1019            if [ "$json_output" = true ]; then
1020                printf "%s\n" "$json_data"
1021                exit 0
1022            fi
1023            hls_link_1=$(printf "%s" "$json_data" | tr '{}' '\n' | $sed -nE "s@.*\"hls\": \[\"([^\"]*)\".*@\1@p")
1024            # hls_link_2=$(printf "%s" "$json_data" | tr '{}' '\n' | $sed -nE "s@.*hls.*, \"([^\"]*)\".\]*@\1@p")
1025            # gogo_link=$(printf "%s" "$json_data" | tr '{}' '\n' | $sed -nE "s@.*\"src\": \"([^\"]*)\", \"type\": \"embed.*@\1@p")
1026            if [ -n "$quality" ]; then
1027                video_link=$(printf "%s" "$hls_link_1" | $sed -e "s/\.m3u8$/\.$quality.m3u8/")
1028            else
1029                video_link=$hls_link_1
1030            fi
1031            ;;
1032        hdrezka)
1033            encrypted_video_link=$(printf "%s" "$json_data" | sed -nE "s@.*\"url\":\"([^\"]*)\".*@\1@p" | sed "s/\\\//g" | cut -c'3-' | sed 's|//_//||g')
1034            # the part below is pain
1035            subs_links=$(printf "%s" "$json_data" | sed -nE "s@.*\"subtitle\":\"([^\"]*)\".*@\1@p" |
1036                sed -e 's/\[[^]]*\]//g' -e 's/,/\n/g' -e 's/\\//g' -e "s/:/\\$path_thing:/g" -e "H;1h;\$!d;x;y/\n/$separator/" -e "s/$separator\$//")
1037            # TODO: fix subs
1038            subs_arg="--sub-files=$subs_links"
1039
1040            # ty @CoolnsX for helping me out with the decryption
1041            table='ISE=,IUA=,IV4=,ISM=,ISQ=,QCE=,QEA=,QF4=,QCM=,QCQ=,XiE=,XkA=,Xl4=,XiM=,XiQ=,IyE=,I0A=,I14=,IyM=,IyQ=,JCE=,JEA=,JF4=,JCM=,JCQ=,ISEh,ISFA,ISFe,ISEj,ISEk,IUAh,IUBA,IUBe,IUAj,IUAk,IV4h,IV5A,IV5e,IV4j,IV4k,ISMh,ISNA,ISNe,ISMj,ISMk,ISQh,ISRA,ISRe,ISQj,ISQk,QCEh,QCFA,QCFe,QCEj,QCEk,QEAh,QEBA,QEBe,QEAj,QEAk,QF4h,QF5A,QF5e,QF4j,QF4k,QCMh,QCNA,QCNe,QCMj,QCMk,QCQh,QCRA,QCRe,QCQj,QCQk,XiEh,XiFA,XiFe,XiEj,XiEk,XkAh,XkBA,XkBe,XkAj,XkAk,Xl4h,Xl5A,Xl5e,Xl4j,Xl4k,XiMh,XiNA,XiNe,XiMj,XiMk,XiQh,XiRA,XiRe,XiQj,XiQk,IyEh,IyFA,IyFe,IyEj,IyEk,I0Ah,I0BA,I0Be,I0Aj,I0Ak,I14h,I15A,I15e,I14j,I14k,IyMh,IyNA,IyNe,IyMj,IyMk,IyQh,IyRA,IyRe,IyQj,IyQk,JCEh,JCFA,JCFe,JCEj,JCEk,JEAh,JEBA,JEBe,JEAj,JEAk,JF4h,JF5A,JF5e,JF4j,JF4k,JCMh,JCNA,JCNe,JCMj,JCMk,JCQh,JCRA,JCRe,JCQj,JCQk'
1042
1043            for i in $(printf "%s" "$table" | tr ',' '\n'); do
1044                encrypted_video_link=$(printf "%s" "$encrypted_video_link" | sed "s/$i//g")
1045            done
1046
1047            video_links=$(printf "%s" "$encrypted_video_link" | sed 's/_//g' | base64 -d | tr ',' '\n' | sed -nE "s@\[([^\]*)\](.*)@\"\1\":\"\2\",@p")
1048            video_links_json=$(printf "%s" "$video_links" | tr -d '\n' | sed "s/,$//g")
1049            json_data=$(printf "%s" "$json_data" | sed -E "s@\"url\":\"[^\"]*\"@\"url\":\{$video_links_json\}@")
1050            if [ "$json_output" = true ]; then
1051                printf "%s\n" "$json_data"
1052                exit 0
1053            fi
1054            if [ -n "$quality" ]; then
1055                video_link=$(printf "%s" "$video_links" | sed -nE "s@\"${quality}.*\":\".* or ([^\"]*)\".*@\1@p" | tail -1)
1056            else
1057                # auto selects best quality
1058                video_link=$(printf "%s" "$video_links" | sed -nE "s@\".*\":\".* or ([^\"]*)\".*@\1@p" | tail -1)
1059            fi
1060            [ -z "$video_link" ] && exit 1
1061            ;;
1062    esac
1063    [ "$((progress + 1))" -eq "$episodes_total" ] && status="COMPLETED" || status="CURRENT"
1064}
1065
1066get_json() {
1067    case "$provider" in
1068        allanime)
1069            json_data=$(curl -e "$allanime_refr" -s -G "https://api.$allanime_base/api" --data-urlencode 'variables={"showId":"'"$episode_id"'","translationType":"'"$translation_type"'","episodeString":"'"$episode_number"'"}' --data-urlencode 'query=query ($showId: String!, $translationType: VaildTranslationTypeEnumType!, $episodeString: String!) {    episode(        showId: $showId        translationType: $translationType        episodeString: $episodeString    ) {        episodeString sourceUrls    }}')
1070            ;;
1071        aniwatch)
1072            source_id=$(curl -s "https://aniwatch.to/ajax/v2/episode/servers?episodeId=$episode_id" |
1073                $sed "s/</\n/g;s/\\\//g" | $sed -nE "s@.*data-type=\"$translation_type\" data-id=\"([0-9]*)\".*@\1@p" | head -1)
1074            [ -z "$source_id" ] && source_id=$(curl -s "https://aniwatch.to/ajax/v2/episode/servers?episodeId=$episode_id" |
1075                $sed "s/</\n/g;s/\\\//g" | $sed -nE "s@.*data-type=\"raw\" data-id=\"([0-9]*)\".*@\1@p" | head -1)
1076            embed_link=$(curl -s "https://aniwatch.to/ajax/v2/episode/sources?id=$source_id" | $sed -nE "s_.*\"link\":\"([^\"]*)\".*_\1_p")
1077
1078            # get the juicy links
1079            parse_embed=$(printf "%s" "$embed_link" | $sed -nE "s_(.*)/embed-(2|4|6)/e-([0-9])/(.*)\?k=1\$_\1\t\2\t\3\t\4_p")
1080            provider_link=$(printf "%s" "$parse_embed" | cut -f1)
1081            embed_type=$(printf "%s" "$parse_embed" | cut -f2)
1082            e_number=$(printf "%s" "$parse_embed" | cut -f3)
1083            source_id=$(printf "%s" "$parse_embed" | cut -f4)
1084
1085            json_data=$(curl -s "${provider_link}/embed-${embed_type}/ajax/e-${e_number}/getSources?id=${source_id}" -H "X-Requested-With: XMLHttpRequest")
1086            ;;
1087        yugen)
1088            json_data=$(curl -s 'https://yugenanime.tv/api/embed/' -X POST -H 'X-Requested-With: XMLHttpRequest' --data-raw "id=$episode_id&ac=0")
1089            ;;
1090        hdrezka)
1091            hdrezka_data_and_translation_id
1092            tmp_season_id=$(curl -s "https://hdrezka.website/${media_type}/${episode_id}.html" -A "uwu" --compressed | sed "s/<li/\n/g" |
1093                sed -nE "s@.*data-tab_id=\"([0-9]*)\">([^<]*)</li>.*@\2\t\1@p")
1094            if [ -n "$tmp_season_id" ]; then
1095                tmp_season_id=$(printf "%s" "$tmp_season_id" | fzf -1 --cycle --reverse --with-nth 1 -d '\t' --header "Choose a season: ")
1096                [ -z "$tmp_season_id" ] && exit 1
1097                season_title=$(printf "%s" "$tmp_season_id" | cut -f1)
1098                season_id=$(printf "%s" "$tmp_season_id" | cut -f2)
1099            fi
1100            episode_id=$((progress + 1))
1101            json_data=$(curl -s -X POST "https://hdrezka.website/ajax/get_cdn_series/" -A "uwu" --data-raw "id=${data_id}&translator_id=${translator_id}&season=${season_id}&episode=${episode_id}&action=get_stream" --compressed)
1102            ;;
1103        aniworld)
1104            anime_link=$(printf "%s" "$episode_info" | cut -f2 | sed 's/\\//g')
1105            episode=$(curl -s "https://aniworld.to${anime_link}" | sed -nE "s@.*href=\"([^\"]*-$((progress + 1)))\".*data-episode-id=\"[0-9]*\".*title=\"([^\"]*)\".*@\1\t\2@p")
1106            if [ -z "$episode" ]; then
1107                send_notification "Error" "Could not find this episode on aniworld"
1108                exit 1
1109            fi
1110            episode_href=$(printf "%s" "$episode" | cut -f1)
1111            episode_title=$(printf "%s" "$episode" | cut -f2)
1112            redirect_url=$(curl -s "https://aniworld.to${episode_href}" | sed -nE "s@.*href=\"(/redirect[^\"]*)\".*@\1@p" | head -1)
1113            video_link=$(curl -sL "https://aniworld.to${redirect_url}" | sed -nE "s@.*\"(.*\.m3u8[^\"]*)\".*@\1@p" | head -1)
1114            ;;
1115        crunchyroll)
1116            if [ -n "$cr_token" ]; then
1117                video_link=$("$cr_wrapper" --eid "$episode_id" --token "$cr_token")
1118            else
1119                video_link=$("$cr_wrapper" --eid "$episode_id" --email "$cr_email" --password "$cr_password")
1120            fi
1121            ;;
1122    esac
1123
1124    [ -n "$json_data" ] && extract_from_json
1125}
1126
1127#### MANGA SCRAPING FUNCTIONS ####
1128get_chapter_info() {
1129    manga_provider="mangadex"
1130    case "$manga_provider" in
1131        mangadex)
1132            mangadex_id=$(curl -s "https://raw.githubusercontent.com/bal-mackup/mal-backup/master/anilist/manga/${media_id}.json" | tr -d "\n" | $sed -nE "s@.*\"Mangadex\":[[:space:]{]*\"([^\"]*)\".*@\1@p")
1133            chapter_info=$(curl -s "https://api.mangadex.org/chapter?manga=$mangadex_id&translatedLanguage[]=en&chapter=$((progress + 1))&includeEmptyPages=0" | $sed "s/}]},/\n/g" |
1134                $sed -nE "s@.*\"id\":\"([^\"]*)\".*\"chapter\":\"$((progress + 1))\",\"title\":\"([^\"]*)\".*@\1\t\2@p" | head -1)
1135            ;;
1136    esac
1137}
1138
1139get_manga_json() {
1140    case "$manga_provider" in
1141        mangadex)
1142            json_data=$(curl -s "https://api.mangadex.org/at-home/server/$chapter_id" | $sed "s/\\\//g")
1143            if [ "$json_output" = true ]; then
1144                printf "%s\n" "$json_data"
1145                exit 0
1146            fi
1147            mangadex_data_base_url=$(printf "%s" "$json_data" | $sed -nE "s@.*\"baseUrl\":\"([^\"]*)\".*@\1@p")
1148            mangadex_hash=$(printf "%s" "$json_data" | $sed -nE "s@.*\"hash\":\"([^\"]*)\".*@\1@p")
1149            image_links=$(printf "%s" "$json_data" | $sed -nE "s@.*data\":\[(.*)\],.*@\1@p" | $sed "s/,/\n/g;s/\"//g")
1150            if [ -z "$mangadex_data_base_url" ] || [ -z "$mangadex_hash" ] || [ -z "$image_links" ]; then
1151                send_notification "Jerry" "3000" "" "Error: could not get manga"
1152                exit 1
1153            fi
1154            download_images "$image_links"
1155            ;;
1156    esac
1157}
1158
1159#### MEDIA FUNCTIONS ####
1160
1161add_to_history() {
1162    if [ -n "$percentage_progress" ] && [ "$percentage_progress" -gt 85 ]; then
1163        if [ -z "$no_anilist" ]; then
1164            response=$(update_progress "$((progress + 1))" "$media_id" "$status")
1165            if printf "%s" "$response" | grep -q "errors"; then
1166                send_notification "Error" "" "" "Could not update progress"
1167            else
1168                send_notification "Updated progress to $((progress + 1))/$episodes_total episodes watched" ""
1169                [ -n "$history" ] && $sed -i "/^$media_id/d" "$history_file"
1170            fi
1171        else
1172            if [ -n "$history" ]; then
1173                if [ $((progress + 1)) -eq "$episodes_total" ]; then
1174                    $sed -i "/^$media_id/d" "$history_file"
1175                    send_notification "Completed" "" "" "$title"
1176                else
1177                    $sed -i "s/^${media_id}\t[0-9/]*\t[0-9:]*/${media_id}\t$((progress + 2))\/${episodes_total}\t00:00:00/" "$history_file"
1178                    send_notification "Updated progress to $((progress + 1)) episodes watched"
1179                fi
1180            else
1181                printf "%s\t%s/%s\t00:00:00\t%s\n" "$media_id" "$((progress + 2))" "$episodes_total" "$title" >>"$history_file"
1182                send_notification "Updated progress to $((progress + 1)) episodes watched"
1183            fi
1184        fi
1185    else
1186        send_notification "Current progress" "" "" "$progress/$episodes_total episodes watched"
1187        [ -z "$no_anilist" ] && send_notification "Your progress has not been updated"
1188        if ! grep -q "^$media_id" "$history_file" 2>&1; then
1189            printf "%s\t%s/%s\t%s\t%s\n" "$media_id" "$((progress + 1))" "$episodes_total" "$stopped_at" "$title" >>"$history_file"
1190        else
1191            $sed -i "s/^${media_id}\t[0-9/]*\t[0-9:]*/${media_id}\t$((progress + 1))\/${episodes_total}\t${stopped_at}/" "$history_file"
1192        fi
1193        send_notification "Stopped at: $stopped_at" "5000"
1194    fi
1195}
1196
1197play_video() {
1198    case "$provider" in
1199        aniwatch) displayed_title="$title - Ep $((progress + 1)) $episode_title" ;;
1200        yugen) displayed_title="$title - Ep $episode_title" ;;
1201        hdrezka) displayed_title="$episode_title - Ep $((progress + 1))" ;;
1202        aniworld) displayed_title="$episode_title" ;;
1203        *) displayed_title="$title - Ep $((progress + 1))" ;;
1204    esac
1205    case $player in
1206        mpv | mpv.exe)
1207            if [ -f "$history_file" ] && [ -z "$using_number" ]; then
1208                history=$(grep -E "^${media_id}[[:space:]]*$((progress + 1))" "$history_file")
1209            elif [ -f "$history_file" ]; then
1210                history=$(grep -E "^${media_id}[[:space:]]*[0-9/]*" "$history_file")
1211            fi
1212            [ -n "$history" ] && resume_from=$(printf "%s" "$history" | cut -f3)
1213            opts="$player_arguments"
1214            if [ -n "$resume_from" ]; then
1215                opts="$opts --start=${resume_from}"
1216                send_notification "Resuming from" "" "" "$resume_from"
1217            fi
1218            if [ -n "$subs_links" ]; then
1219                send_notification "$title" "4000" "$images_cache_dir/$media_id.jpg" "$title"
1220                if [ "$discord_presence" = "true" ]; then
1221                    eval "$presence_script_path" \"$player\" \"${title}\" \"${start_year}\" \"$((progress + 1))\" \"${video_link}\" \"${subs_links}\" ${opts} 2>&1 | tee $tmp_position
1222                else
1223                    $player "$video_link" $opts "$subs_arg" "$subs_links" --force-media-title="$displayed_title" --msg-level=ffmpeg/demuxer=error 2>&1 | tee $tmp_position
1224                fi
1225            else
1226                send_notification "$title" "4000" "$images_cache_dir/$media_id.jpg" "$title"
1227                if [ "$discord_presence" = "true" ]; then
1228                    eval "$presence_script_path" \"$player\" \"${title}\" \"${start_year}\" \"$((progress + 1))\" \"${video_link}\" \"\" ${opts} 2>&1 | tee $tmp_position
1229                else
1230                    $player "$video_link" $opts --force-media-title="$displayed_title" --msg-level=ffmpeg/demuxer=error 2>&1 | tee $tmp_position
1231                fi
1232            fi
1233            stopped_at=$($sed -nE "s@.*AV: ([0-9:]*) / ([0-9:]*) \(([0-9]*)%\).*@\1@p" "$tmp_position" | tail -1)
1234            percentage_progress=$($sed -nE "s@.*AV: ([0-9:]*) / ([0-9:]*) \(([0-9]*)%\).*@\3@p" "$tmp_position" | tail -1)
1235            add_to_history
1236            ;;
1237        *yncpla*) syncplay "$video_link" -- --force-media-title="${title}" >/dev/null 2>&1 ;;
1238        vlc) vlc --play-and-exit --meta-title="${title}" "$video_link" >/dev/null 2>&1 & ;;
1239        iina) iina --no-stdin --keep-running --mpv-force-media-title="${title}" "$video_link" >/dev/null 2>&1 & ;;
1240    esac
1241    if [ "$player" != "mpv" ] && [ "$player" != "mpv.exe" ]; then
1242        completed_episode=$(printf "Yes\nNo" | launcher "Have you completed watching this episode? [Y/n] ")
1243        case "$completed_episode" in
1244            [Yy]*)
1245                percentage_progress=100
1246                add_to_history
1247                ;;
1248            *) exit 0 ;;
1249        esac
1250    fi
1251}
1252
1253read_chapter() {
1254    # zathura --mode fullscreen
1255    case "$manga_format" in
1256        pdf)
1257            [ -f "$manga_dir/$title/chapter_$((progress + 1))/$title - Chapter $((progress + 1)).pdf" ] || convert_to_pdf
1258            send_notification "Opening - $title" "1000" "$images_cache_dir/$media_id.jpg" "Chapter: $((progress + 1)) $chapter_title"
1259            ${manga_opener} "$manga_dir/$title/chapter_$((progress + 1))/$title - Chapter $((progress + 1)).pdf"
1260            ;;
1261        image)
1262            send_notification "Opening - $title" "1000" "$images_cache_dir/$media_id.jpg" "Chapter: $((progress + 1)) $chapter_title"
1263            ${manga_opener} "$manga_dir/$title/chapter_$((progress + 1))"
1264            ;;
1265    esac
1266    [ "$((progress + 1))" -eq "$chapters_total" ] && status="COMPLETED" || status="CURRENT"
1267    completed_chapter=$(printf "Yes\nNo" | launcher "Do you want to update progress? [Y/n] ")
1268    case "$completed_chapter" in
1269        [Yy]*)
1270            response=$(update_progress "$((progress + 1))" "$media_id" "$status")
1271            if printf "%s" "$response" | grep -q "errors"; then
1272                send_notification "Error" "" "" "Could not update progress"
1273            else
1274                send_notification "Updated progress to $((progress + 1))/$chapters_total chapters read" "" "$images_cache_dir/$media_id.jpg"
1275                progress=$((progress + 1))
1276            fi
1277            ;;
1278        [Nn]*)
1279            send_notification "Your progress has not been updated"
1280            ;;
1281        *) exit 0 ;;
1282    esac
1283}
1284
1285watch_anime() {
1286    if [ "$sub_or_dub" = "dub" ] || [ "$sub_or_dub" = "sub" ]; then
1287        translation_type="$sub_or_dub"
1288    elif [ -z "$translation_type" ]; then
1289        dub_choice=$(printf "Sub\nDub" | launcher "Would you like to watch Sub or Dub?")
1290        case "$dub_choice" in
1291            "Sub")
1292                translation_type="sub"
1293                ;;
1294            "Dub")
1295                translation_type="dub"
1296                ;;
1297            *)
1298                send_notification "Error" "" "" "Invalid translation type"
1299                exit 1
1300                ;;
1301        esac
1302    fi
1303
1304    echo "came here"
1305    echo "Title : $title"
1306
1307    get_episode_info
1308
1309    if [ -z "$episode_info" ]; then
1310        send_notification "Error" "" "" "$title not found"
1311        exit 1
1312    fi
1313
1314    echo "episode_info : $episode_info"
1315    echo "Title : $title"
1316
1317    if [ "$provider" != "aniworld" ]; then
1318        episode_id=$(printf "%s" "$episode_info" | cut -f1)
1319        episode_title=$(printf "%s" "$episode_info" | cut -f2)
1320        [ "$provider" = "hdrezka" ] && media_type=$(printf "%s" "$episode_info" | cut -f3)
1321        if [ "$episode_id" = "$episode_title" ]; then
1322            episode_title=""
1323        fi
1324    fi
1325
1326    get_json
1327    echo "episode id: $episode_id"
1328    echo "episode no: $episode_number"
1329    [ -z "$video_link" ] && exit 1
1330    # echo "video_link : $video_link"
1331    
1332    play_video
1333
1334}
1335
1336read_manga() {
1337
1338    get_chapter_info
1339    if [ -z "$chapter_info" ]; then
1340        send_notification "Error" "" "" "$title not found"
1341        exit 1
1342    fi
1343    chapter_id=$(printf "%s" "$chapter_info" | cut -f1)
1344    chapter_title=$(printf "%s" "$chapter_info" | cut -f2)
1345
1346    get_manga_json
1347    read_chapter
1348
1349}
1350
1351watch_anime_choice() {
1352    if [ -z "$media_id" ] && [ -z "$no_anilist" ]; then
1353        get_anime_from_list "CURRENT|REPEATING"
1354    elif [ -z "$media_id" ]; then
1355        [ -z "$query" ] && get_input "Search anime: "
1356        [ -z "$query" ] && exit 1
1357        search_anime_anilist "$query"
1358    fi
1359    if [ -z "$media_id" ] || [ -z "$title" ] || [ -z "$episodes_total" ]; then
1360        send_notification "Jerry" "" "" "Error, no anime found"
1361        exit 1
1362    fi
1363    send_notification "Loading" "3000" "$images_cache_dir/$media_id.jpg" "$title"
1364    watch_anime
1365    [ "$score_on_completion" = true ] && update_score "ANIME" "immediate"
1366}
1367
1368read_manga_choice() {
1369    [ -z "$media_id" ] && get_manga_from_list "CURRENT|REPEATING"
1370    [ -z "$chapters_total" ] && chapters_total="9999"
1371    if [ -z "$media_id" ] || [ -z "$title" ] || [ -z "$progress" ]; then
1372        send_notification "Jerry" "" "" "Error, no manga found"
1373        exit 1
1374    fi
1375    send_notification "Loading" "" "$images_cache_dir/$media_id.jpg" "$title"
1376    read_manga
1377    [ "$score_on_completion" = true ] && update_score "MANGA" "immediate"
1378}
1379
1380binge() {
1381    while :; do
1382        if [ "$1" = "ANIME" ]; then
1383            watch_anime_choice
1384            [ -z "$percentage_progress" ] || [ "$percentage_progress" -lt 85 ] && break
1385            [ $((progress + 1)) = "$episodes_total" ] && break
1386            if  [ $player != mpv ] && [ $player != mpv.exe ]; then
1387                send_notification "Please only select Yes if you have finished watching the episode" "5000"
1388                binge_watching=$(printf "Yes\nNo" | launcher "Do you want to keep binge watching? [Y/n] ")
1389            
1390                case $binge_watching in
1391                    [Nn]*) break ;;
1392                esac
1393            fi
1394            progress=$((progress + 1))
1395            resume_from=""
1396        elif [ "$1" = "MANGA" ]; then
1397            read_manga_choice
1398            [ $((progress + 1)) = "$chapters_total" ] && break
1399            case $completed_chapter in
1400                [Nn]*) break ;;
1401            esac
1402        else
1403            exit 1
1404        fi
1405    done
1406}
1407
1408main() {
1409    if [ -z "$no_anilist" ]; then
1410        check_credentials
1411        if [ -z "$access_token" ] || [ -z "$user_id" ]; then
1412            exit 1
1413        fi
1414        [ -n "$query" ] && mode_choice="Watch New Anime"
1415        [ -z "$mode_choice" ] && mode_choice=$(printf "Watch Anime\nRead Manga\nUpdate (Episodes, Status, Score)\nInfo\nWatch New Anime\nRead New Manga" | launcher "Choose an option: ")
1416    else
1417        # TODO: implement manga stuff for no_anilist
1418        [ -n "$query" ] && mode_choice="Watch Anime"
1419        [ -z "$mode_choice" ] && mode_choice=$(printf "Resume from History\nWatch Anime" | launcher "Choose an option: ")
1420    fi
1421    case "$mode_choice" in
1422        "Watch Anime") binge "ANIME" ;;
1423        "Read Manga") binge "MANGA" ;;
1424        "Update (Episodes, Status, Score)")
1425            update_choice=$(printf "Change Episodes Watched\nChange Chapters Read\nChange Status\nChange Score" | launcher "Choose an option: ")
1426            case "$update_choice" in
1427                "Change Episodes Watched") update_episode_from_list ;;
1428                "Change Chapters Read") update_chapter_from_list ;;
1429                "Change Status")
1430                    media_type=$(printf "ANIME\nMANGA" | launcher "Choose a media type: ")
1431                    [ -z "$media_type" ] && exit 0
1432                    update_status "$media_type"
1433                    ;;
1434                "Change Score")
1435                    media_type=$(printf "ANIME\nMANGA" | launcher "Choose a media type: ")
1436                    [ -z "$media_type" ] && exit 0
1437                    update_score "$media_type"
1438                    ;;
1439            esac
1440            ;;
1441        # TODO: implement more info features
1442        "Info")
1443            if ! command -v "jq" >/dev/null; then
1444                send_notification "For this feature to work, you must have jq installed."
1445                exit 1
1446            fi
1447            media_type=$(printf "ANIME\nMANGA" | launcher "Choose a media type: ")
1448            [ -z "$media_type" ] && exit 0
1449            get_anilist_info "$media_type"
1450            ;;
1451        "Watch New Anime")
1452            [ -z "$query" ] && get_input "Search anime: "
1453            [ -z "$query" ] && exit 1
1454            search_anime_anilist "$query"
1455            [ -z "$progress" ] && progress=0
1456            [ "$json_output" = true ] || send_notification "Disclaimer" "5000" "" "You need to complete the 1st episode to update your progress"
1457            binge "ANIME"
1458            ;;
1459        "Read New Manga")
1460            [ -z "$query" ] && get_input "Search manga: "
1461            [ -z "$query" ] && exit 1
1462            search_manga_anilist "$query"
1463            [ -z "$progress" ] && progress=0
1464            [ "$json_output" = true ] || send_notification "Disclaimer" "5000" "" "You need to complete the 1st chapter to update your progress"
1465            binge "MANGA"
1466            ;;
1467        "Resume from History")
1468            history_choice=$($sed -n "1h;1!{x;H;};\${g;p;}" "$history_file" | nl -w 1 | nth "Choose an entry: ")
1469            media_id=$(printf "%s" "$history_choice" | cut -f1)
1470            progress=$(printf "%s" "$history_choice" | cut -f2 | cut -d'/' -f1)
1471            progress=$((progress - 1))
1472            episodes_total=$(printf "%s" "$history_choice" | cut -f2 | cut -d'/' -f2)
1473            resume_from=$(printf "%s" "$history_choice" | cut -f3)
1474            title=$(printf "%s" "$history_choice" | cut -f4)
1475            [ -z "$media_id" ] && exit 1
1476            binge "ANIME"
1477            ;;
1478    esac
1479}
1480
1481configuration
1482query=""
1483# TODO: add an argument for video_providers
1484while [ $# -gt 0 ]; do
1485    case "$1" in
1486        --)
1487            shift
1488            query="$*"
1489            break
1490            ;;
1491        -c | --continue) mode_choice="Watch Anime" && shift ;;
1492        --clear-history | --delete-history)
1493            while true; do
1494                printf "This will delete your jerry history. Are you sure? [Y/n] "
1495                read -r choice
1496                case $choice in
1497                    [Yy]* | "")
1498                        #shellcheck disable=1090
1499                        [ -f "$config_file" ] && . "$config_file"
1500                        [ -z "$history_file" ] && history_file="$HOME/.local/share/jerry/jerry_history.txt"
1501                        rm "$history_file"
1502                        echo "History deleted."
1503                        exit 0
1504                        ;;
1505                    [Nn]*)
1506                        return 1
1507                        ;;
1508                    *) echo "Please answer yes or no." ;;
1509                esac
1510            done
1511            shift
1512            ;;
1513        -d | --discord) discord_presence=true && shift ;;
1514        --dub) sub_or_dub="dub" && shift ;;
1515        -e | --edit) edit_configuration ;;
1516        -h | --help)
1517            usage && exit 0
1518            ;;
1519        -i | --image-preview)
1520            image_preview=true
1521            shift
1522            ;;
1523        -j | --json)
1524            json_output=true
1525            no_anilist=1
1526            shift
1527            ;;
1528        -l | --language)
1529            subs_language="$2"
1530            if [ -z "$subs_language" ]; then
1531                subs_language="english"
1532                shift
1533            else
1534                if [ "${subs_language#-}" != "$subs_language" ]; then
1535                    subs_language="english"
1536                    shift
1537                else
1538                    subs_language="$(echo "$subs_language" | cut -c2-)"
1539                    shift 2
1540                fi
1541            fi
1542            ;;
1543        -n | --number)
1544            progress=$(($2 - 1))
1545            using_number=1
1546            shift 2
1547            ;;
1548        --no-anilist) no_anilist=1 && shift ;;
1549        --rofi | --dmenu | --external-menu)
1550            use_external_menu=true
1551            shift
1552            ;;
1553        -q | --quality)
1554            quality="$2"
1555            if [ -z "$quality" ]; then
1556                quality="1080"
1557                shift
1558            else
1559                if [ "${quality#-}" != "$quality" ]; then
1560                    quality="1080"
1561                    shift
1562                else
1563                    shift 2
1564                fi
1565            fi
1566            ;;
1567        -s | --syncplay)
1568            player="syncplay"
1569            shift
1570            ;;
1571        -u | -U | --update)
1572            update_script
1573            ;;
1574        -v | -V | --version)
1575            send_notification "Jerry Version: $JERRY_VERSION"
1576            exit 0
1577            ;;
1578        --vlc)
1579            player="vlc"
1580            shift
1581            ;;
1582        -w | --website)
1583            provider="$2"
1584            if [ -z "$provider" ]; then
1585                provider="allanime"
1586                shift
1587            else
1588                if [ "${provider#-}" != "$provider" ]; then
1589                    provider="allanime"
1590                    shift
1591                else
1592                    shift 2
1593                fi
1594            fi
1595            ;;
1596        *)
1597            if [ "${1#-}" != "$1" ]; then
1598                query="$query $1"
1599            else
1600                query="$query $1"
1601            fi
1602            shift
1603            ;;
1604    esac
1605done
1606# check for update
1607# check_update "A new update is out. Would you like to update jerry? [Y/n] "
1608query="$(printf "%s" "$query" | tr ' ' '-' | $sed "s/^-//g")"
1609case "$provider" in
1610    allanime)
1611        provider="allanime"
1612        allanime_refr="https://allanime.to"
1613        allanime_base="allanime.day"
1614        ;;
1615    zoro | kaido | aniwatch) provider="aniwatch" ;;
1616    yugen | yugenanime) provider="yugen" ;;
1617    hdrezka | rezka) provider="hdrezka" ;;
1618    crunchyroll | cr) provider="crunchyroll" ;;
1619    aniworld) provider="aniworld" ;;
1620    *) send_notification "Invalid provider" && exit 1 ;;
1621esac
1622if [ "$image_preview" = true ]; then
1623    test -d "$images_cache_dir" || mkdir -p "$images_cache_dir"
1624    if [ "$use_external_menu" = true ]; then
1625        mkdir -p "/tmp/jerry/applications/"
1626        [ ! -L "$applications" ] && ln -sf "/tmp/jerry/applications/" "$applications"
1627    fi
1628fi
1629
1630main