#!/usr/bin/env bash
#-------------------------------------------------------------------------------------------------------------------
#           CopyRight 2015-2023 Shorewall a.k.a. Kowalsky :D    
#           shorewall@mail.com   http://casapippozzi.cf
#
#           RaiNix is free software: you can redistribute it and/or modify
#           it under the terms of the GNU General Public License as published by
#           the Free Software Foundation, either version 3 of the License, or
#           (at your option) any later version.
#
#           This program is distributed in the hope that it will be useful,
#           but WITHOUT ANY WARRANTY; without even the implied warranty of
#           MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#           GNU General Public License for more details.
#
#           You should have received a copy of the GNU General Public License
#           along with this program.  If not, see <http://www.gnu.org/licenses/>.
#          
#           RaiNix e RaiVod: Rai live, Replay e Radiorai player, RaiPlay search tool for *Nix systems.
#           All you need to do (if you want) is change the Player and PlayerRadio vars.
#           Can also record the Radio, Replay flow and most of the live streaming, depending of your
#           ffmpeg level and the originating stream type.
#           This option must be used for study cases only. Respecting the DMCA rules.
#           The usage is under EXCUSIVE USERS RESPONSIBILITY.
#-------------------------------------------------------------------------------------------------------------------
#           RaiNixVod: Rai vod player & recorder
#
#           by K. aka Shorewall aka The Gray etc etc :-)
#
#           changelog: v 1.0.0   First releae. Just a Test for fun.
#           changelog: v 1.0.1   Added search option.
#           changelog: v 1.0.2   Changed some panel labels.
#           changelog: v 1.0.3   Added sub categ menu'.
#           changelog: v 1.0.4   Changed Suggeriti handling because of RAI changes
#           changelog: v 1.0.5   Added local http ts restreaming
#           changelog: v 1.0.7   Almost rewritten all the code. 
#           changelog: v 1.0.8   Code cleanup for Restreaming function. Added udp protocol. 
#                                           Added MonWait variable to handle Monitor buffering.
#                                           Patched a bug caused by RAI mod in the html code. 
#           changelog: v. 2.0.8  Better support for FFmpeg Streamlink and Hlsdl as alternative players for RAI new HLS manifests.
#                                  The user can set the preferred video engine by the SlinkPlayer or the HlsdlEngine vars.
#                                  Using FFMPEG as player the selected engine is the same as for Streamlink (SlinkPlayer var)
#                                  Some stuff for restreaming. Now this can be done using hlsdl+ffmpeg or ffmpeg alone.
#                                  Selecting the HTTP restream protocol requires anyway VLC.
#                                  The local monitor will be performed by the tool setted into MonPlayer var.
#                                  Undocumented option: ESC key on the main menu' allow to switch on-the-fly the
#                                  hardcoded player for video and radio streams.
#           changelog: v. 2.0.9  Added a secondary menu' option to use an alternate location link instead of the legacy HLS one,
#                                usually for VOD/Replay/Search links.
#           changelog: v. 2.1.0  Fixed new Rai Vod page layout.
#           changelog: v. 2.1.1  Fixed Preferiti section streams. Removed obsolete mp4 code.
#           changelog: v 2.1.1.1 Changed HandleButton function dialog because of incompatibility using latest version. 
#                                 
#
#----------------------------------------------------------------------------------------------------------------------------------
ScriptHome="$(cd "$(dirname "${BASH_SOURCE[0]}" )" && pwd)"
Me=`basename $0`
Version='2.1.1.1'
CodeName="'The new UA sniper'"
AnchorHome="http://www.raiplay.it"
SearchDetail="https://www.raiplay.it/atomatic/raiplay-search-service/api/v3/search"
ShowallPage="https://www.raiplay.it/ricerca.html"
#UserAgent="Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0"
UserAgent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Safari/605.1.15"
#UserAgent="Lavf/57.83.100"
#----------------------------------------------------------------------------------------------------------------------------------
CookieJar="/tmp/"$Me"_Cookies.txt"
socks=""
Curl="curl -s -k  -L $socks --max-time 20 -c $CookieJar -b $CookieJar"
Wget="wget -q --no-check-certificate -T 10 -O -"
ShowInfoDelay=2
MyPid="$$"
PlayerOpt=""
Psize=99
ResProtocols="http rtmp rtp rtsp udp"   # Set your restreaming protocol priority order
HlsdlEngine='mpv'                                  # set mpv or vlc or xine or mplayer engine when using hlsdl as  player
SlinkPlayer='mpv'  # set here your preferred streamlink video engine
FFmpeg='ffmpeg'    # Make FFmpeg variable to allow custom builds
Remonitor=1                                           # Enable restream monitor
ResTool="ffmpeg hlsdl"                          # ResTool is the first available in the list
MonPlayers='ffplay mpv vlc'
MonWait=5                                             # Buffering time before starting the restream monitor
#------------------------------------------------------------------------------------------------------------------------------
# Test your OS
case $( uname -s ) in
Linux)
 LocalIp=$(ip route | grep -om 1 'src.*' | cut -d ' ' -f2);;
 #LocalIp=$(ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/');;
*)
 LocalIp=$(ifconfig | grep inet | grep netmask | grep broadcast | head -1 | cut -d ' ' -f2);;
esac
#----------------------------------- Here you can change some settings  ------------------------------------------
MultiProcess=1                        # 0 or 1 : Setting 1 allow multiples Palyers/Recorders to run concurrently
#Curl="$Wget"                        # Uncomment here if you have any ssl problem. Usually on Debian & derivates
#----------------------------------------------------------------------------------------------------------------------------------
PlayersVod="mpv QMPlay2 smplayer vlc mplayer parole bomi dummy"   # Set your VOD/REPLAY players priority order
Recorders="ffmpeg hlsdl youtube-dl yt-dlp dummy"        # Set your RECORDER tool priority order
Terminals="xterm console dummy"                         # Supported terminal to start async tasks
FFmpegOpt="-v info -stats"	      								 #Set here your options for FFmpeg recording
# HideRecorder="0"		      							     		  # set=1 hides the recorder window. No xterm used. DANGEROUS!!!
NoTerm=1                                                                 # Set 1 to run w/o any terminal for async tasks
Wsl=0                                                                        # Set to 1 to run PLAYERS into an alternate environment/path
#----------------------------------------------------------------------------------------------------------------------------------
#----- These settings affect only FFmpeg recorder. Other tools can records using defaults
#----------------------------------------------------------------------------------------------------------------------------------
AudioCodec="copy"                                                 # set 'libmp3lame' to change audio recording format to mp3
#ReplRecFmt="mp4"
LiveRecFmt="avi"          # set out fmt for vod recording for ffmpeg. Usually avi or mp4 or mkv are ok.

#----------------------------------------------------------------------------------------------------------------------------------
PlayerVodW="/usr/local/bin/vlc"                               # setting the Wsl flags = 1. 
#----------------------------------------------------------------------------------------------------------------------------------
Savedir="$HOME/Video"							# Set your preferred folder to store recording data
Debug=0                                        # Set 1 to get step by step contents extracting Search links
Iconic="-iconic"								# Set this var to '' (null) for debugging purposes
Hold="-hold"								    # Set this var to '-hold' for debugging purposes
HlsdlVbr='-b'
#----------------------------------------------------------------------------------------------------------------------------------
MpvOpt="--demuxer-thread=yes  --demuxer-readahead-secs=15 --autofit=800x600"
MpvQuality="--hls-bitrate=max"       
#----------------------------------------------------------------------------------------------------------------------------------
Who=$(whoami)
Owner='root'
if [ "$1" != ""  ]; then               # My own setup prefs :-)
    HlsdlVbr=$(echo "$1" | awk -F 'called' '{print $2}')
    MonPid="$2"
    ResPid="$3"
fi
#----------------------------------------------------------------------------------------------------------------------------------
#--------------------       Changing after this point you can do only damages :-) on Linux -------------------
#-----------        All the following checks are done only if Rainix runs into a Lunix/BSD env.   ------------
#--------       Into 'UFO' systems the end user may need to adjust some player/recorder path ---------
#----------------------------------------------------------------------------------------------------------------------------------
for Recorder in $Recorders; do
	if [ -n "`which $Recorder 2>/dev/null`" ]; then
		break
	fi
done

if [  "$Recorder" = "dummy" ] && [ "$Wsl" = "0" ]; then
	dialog --title "Error" --infobox " Sorry none of the  predefined recorders was found to record the streams." 0 0; 
	sleep 3
	exit
fi
RecDef="$Recorder"
#-------------------------------------------------------------------------------------------------------------------
for MonPlayer in $MonPlayers; do
	if [ -n "`which $MonPlayer 2>/dev/null`" ]; then
		break
	fi
done
for PlayerVod in $PlayersVod; do
	if [ -n "`which $PlayerVod 2>/dev/null`" ]; then
		break
	fi
done
for ResTool in $ResTools; do
	if [ -n "`which $ResTool 2>/dev/null`" ]; then
		break
	fi
done
ResDef="$ResTool"
if [  "$PlayerVod" = "dummy" ] && [ "$Wsl" = "0" ]; then
	dialog --title "Error" --infobox " Sorry none of the predefined player was found to play Vod Streams. " 0 0; 
	sleep 3
	exit
fi
#----------------------------------------------------------------------------------------------------------------------------------
if [ "$Who" = "$Owner"  ]; then           # My own setup prefs :-). I'm the only crazy people using ROOT as default user.
    ResProtocols="udp rtp udp http rtsp"
    ResTool="hlsdl"
    ResDef='hlsdl'
    Savedir="$HOME/Film"
	HlsdlEngine="mpv"
	MonPlayer="mpv"
	SlinkPlayer='mplayer'
	PipeRoot="- | xine -"
fi
#------------------------------------------------------------------------------------------
for Terminal in $Terminals; do
	if [ -n "`which $Terminal 2>/dev/null`" ]; then
		break
	fi
done
RecTerm="$Terminal"
if [  "$NoTerm" = "1" ]; then
    Terminal='noterm'
fi
if [  "$Terminal" = "dummy" ] && [ "$Wsl" = "0" ]; then
	dialog --title "Error" --infobox " Sorry none of the predefined terminals ($Terminals) found to play async tasks. " 0 0; 
	sleep 3
	exit
fi
#-------------------------------------------------------------------------------------------------------------------
NormalizeName () {
     ChName=$(echo "$ChName" | tr  ' ' '_' | sed -e "s|&quot;|'|g" -e "s|\&amp;|\&|g" -e "s|&amp;#x27;|'|g" -e "s|\&#x27;|'|g" -e "s|\&amp;|\&|g"  -e "s|\&#232;|e|g" -e "s|\&#224;|a|g" | tr -d ' \n\t\r' | tr '/' '-' | tr  "'" '_' | tr '"' ':' | tr '()' ':' | tr '[]' ':')
}

#------------------------------------------------------------------------------------------------------------------
function Record () {
    Cleanup
    Ext='mp4'
    Tag=$(date +%Y%m%d_%H%M)
    mkdir -p "$Savedir" 2>/dev/null
    if [ "$Recorder" = "NotFound" ]; then
        dialog --title "Recording failure" --infobox " Sorry, no recording tool found. Recording will not work. " 6 30
        sleep 3
	    return
	fi
#-------------------------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------------------------
    if [ "$StreamType" = "Vod" ]; then
        Ext="$LiveRecFmt"
    fi
#-------------------------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------------------------
    if [ "$Link4k" = "1" ]; then
        Recorder="$FFmpeg"
    fi
    if [ "$Recorder" = "hlsdl" ] && [ "$AudioGroup" != "0" ]; then
        Recorder="$FFmpeg"
    fi
    if [ "$Recorder" = "yt_dlp" ] && [ "$AudioGroup" != "0" ]; then
        Recorder="$FFmpeg"
    fi
#-------------------------------------------------------------------------------------------------------------------
    FFmpegOn=$(echo "$Recorder" | grep -Eic ffmpeg)
#-------------------------------------------------------------------------------------------------------------------
    NormalizeName
#-------------------------------------------------------------------------------------------------------------------
    if [ "$FFmpegOn" = "1" ]; then
        echo "$FFmpeg $FFmpegOpt -user_agent 'Raiweb 999' -y -i "$ThisLink" -vcodec copy -acodec $AudioCodec $Savedir/${ChName}_${Tag}.$Ext" >> $ScriptHome/$Me.log
        Cmd="$FFmpeg -user_agent 'Raiweb 999' -y -i '"$ThisLink"' -vcodec copy -acodec $AudioCodec $FFmpegOpt $Savedir/${ChName}_${Tag}.$Ext "
    fi
#-------------------------------------------------------------------------------------------------------------------
    if [ "$Recorder" = "hlsdl" ]; then
        echo "$Recorder "$HlsdlVbr" -f  "$ThisLink" -o $Savedir/${ChName}_${Tag}.$Ext" >> $ScriptHome/$Me.log
        Cmd="$Recorder "$HlsdlVbr" -f  '"$ThisLink"' -o $Savedir/${ChName}_${Tag}.$Ext"
    fi
#-------------------------------------------------------------------------------------------------------------------
    if [ "$Recorder" = "youtube-dl" ]; then
        echo "$Recorder --hls-use-mpegts  '"$ThisLink"' --output $Savedir/${ChName}_${Tag}.$Ext" >> $ScriptHome/$Me.log
        Cmd="$Recorder --hls-use-mpegts  '"$ThisLink"' --output $Savedir/${ChName}_${Tag}.$Ext"
    fi
#___________________________________________________________________________________________________________________
    if [ "$Recorder" = "yt-dlp" ]; then
        echo "$Recorder -o $Savedir/${ChName}_${Tag}.$Ext '"$ThisLink"'" >> $ScriptHome/$Me.log
        Cmd="$Recorder -o $Savedir/${ChName}_${Tag}.$Ext '"$ThisLink"'"
    fi
#-------------------------------------------------------------------------------------------------------------------
 #  if [ "$Recorder" = "wget" ]; then
 #      echo "$Recorder '"$ThisLink"' --output $Savedir/${ChName}_${Tag}.mp4" >> $ScriptHome/$Me.log
 #      Cmd="$Recorder --user-agent='"$UserAgent"' -O $Savedir/${ChName}_${Tag}.mp4 '"$ThisLink"'"
 #  fi
#------------------------------------------------------------------------------------------------------------------
    ThisValid=$(echo "$ThisLink" | grep http | grep -Ec 'hmac|index|m3u8|mediapolis|mp4|mp3')
    if [ "$ThisValid" = "0" ]; then
        dialog --title "$ChName error" --infobox "Got an invalid link. May be a timeout occurred. Retry." 5 40
        sleep 2
        return
    fi
#-------------------------------------------------------------------------------------------------------------------

    dialog --title "$ChName starting" --infobox "Starting $ChName recording using $Recorder. " 6  50
 #   if [ "$HideRecorder" = "1" ]; then
 #       RecNoTerm
 #       sleep 3
 #       return
 #   fi
    if [ "$RecTerm" = "xterm" ]; then
        xterm -T "$ChName"  $Hold -e "$Cmd" &
    fi
    if [ "$RecTerm" = "konsole" ]; then
        konsole --noclose -e  "$Cmd" &
    fi
    sleep 3
}
#------------------------------------------------------------------------------------------
function ctrl_c () {
    clear
#   kill $! 2>/dev/null
#   wait $! 2>/dev/null
    kill -9 $MyPid
    exit
}
#------------------------------------------------------------------------------------------
trap ctrl_c INT
#trap ctrl_c SIGQUIT
#------------------------------------------------------------------------------------------
function Cleanup () {
    if [ "$MultiProcess"  = "1" ]; then
        return
    fi
    kill   $! 2>/dev/null
    wait $! 2>/dev/null
    return
}
#------------------------------------------------------------------------------------------
TestSys () {
for command in curl sed grep awk dialog jq; do
    if [ -z "`which $command 2>/dev/null`" ]; then
		NOTFOUND="`echo "$NOTFOUND $command"`"
    fi
done
if [ -n "$NOTFOUND" ]; then
    echo "Comandi non trovati. The script will not wowk."
    echo $NOTFOUND
    read < /dev/tty
    exit 1
fi
if [ -z "`which $Recorder 2>/dev/null`" ]; then
    clear 
    echo "$Recorder not found. The recording feature is not available."
    read null
fi
}
#-------------------------------------------------------------------------------------------
ShowInfo () {
    dialog --title "$BoxTitle" --infobox "$BoxMsg" 4 44
    sleep $ShowInfoDelay
    return
}
#-------------------------------------------------------------------------------------------
TestPlay () {
    if [ "$Terminal" = "konsole" ] || [ "$Wsl" = "1" ]; then
       return
    fi
    if [ "$Running" != "" ]; then
       Active=$(ps -au | grep $ThisPlayer)
    fi
    if [ "$Active" = "" ]; then
       Running=""
       Alerted="1"
       BoxTitle="Stream error"
       BoxMsg="Sorry. $StreamType stream not found or not playable. Check Xterm window & $Me log for details"
       ShowInfo
       read null
       Cleanup
    fi
}
#----------------------------------------------------------------------------------------------------------------------------------- 
RunPlayer () {
    PlayerOpt=""
    WinTitle=""
    Pipe=""
    kill "$ThisHlsPid" 2>/dev/null
    wait
    if [ "$ThisPlayer" = "QMPlay2X" ]; then       # Dummifyed this stat because of manifest changes
        Manifest=$($Curl -A "$UserAgent" "$ThisLink")
        VBest=$(echo "$Manifest" | grep -o 'BANDWIDTH.*' | cut -d '=' -f2 | cut -d ',' -f1  | sort -n | tail -1)
        if [ "$VBest" != "" ]; then
            ThisLink=$(echo "$Manifest" | grep -A1 "BANDWIDTH=$VBest" | tail -1)
        fi
    fi
    NormalizeName
    dialog --title "$ChName starting" --infobox "Starting $ChName using $ThisPlayer " 5 40
    if [ "$ThisPlayer" = "mpv" ]; then
         WinTitle="--title='$ChName'"
         PlayerOpt="$MpvOpt --force-window"
    else
        MpvQuality=""
    fi
    if [ "$ThisPlayer" = "vlc" ]; then
        WinTitle="--meta-title='$ChName' --avcodec-hw=none"
    fi
    if [ "$ThisPlayer" = "QMPlay2" ]; then
        PlayerOpt="--opennew"
    fi
    if [ "$ThisPlayer" = "hlsdl" ]; then
        kill $ThisHlsPid 2>/dev/null
        clear
        PlayerOpt='-b'
        NowRun=0
        Hold=""
        if [ "$HlsdlEngine" = "mpv" ]; then
            Pipe='-o - | mpv - --autofit=800x600'
            xterm -T "$ChName" $Hold $Iconic -e "$ThisPlayer -b '$ThisLink' $Pipe --title='$ChName-by-$ThisPlayer'" &
            NowRun=1
        fi
        if [ "$HlsdlEngine" = "vlc" ]; then
             Pipe='-o - | vlc - -q  --avcodec-hw=none'
             xterm -T "$ChName" $Hold $Iconic -e "$ThisPlayer -b '$ThisLink' $Pipe --meta-title='$ChName-by-$ThisPlayer'" &
             NowRun=1
        fi
        if [ "$HlsdlEngine" = "mplayer" ]; then
            Pipe='-o - | mplayer - -xy 800'
            xterm -T "$ChName" $Hold $Iconic -e "$ThisPlayer -b '$ThisLink' $Pipe -title '$ChName-by-$ThisPlayer'" &
            NowRun=1
        fi
        if [ "$HlsdlEngine" = "xine" ]; then
            Pipe='-o - | xine -'
            xterm -T "$ChName" $Hold $Iconic -e "$ThisPlayer -b '$ThisLink' $Pipe" &
            NowRun=1
        fi
        if [ "$NowRun" = "0" ]; then
            Pipe="-o - | $HlsdlEngine -"
            xterm -T "$ChName" $Hold $Iconic -e "$ThisPlayer -b '$ThisLink' $Pipe" &
        fi
        sleep 2
        ThisHlsPid=$(ps -au | grep hlsdl | grep "xterm" | grep "$HlsdlEngine" | tr -s ' ' | cut -d ' ' -f2)
    fi
    if [ "$ThisPlayer" = "streamlink" ]; then
        WinTitle="-t '$ChName'"
        Pipe="best"
        PlayerOpt=""
        MpvQuality=""
        Hold='-iconic'
        xterm -T "$ChName" $Hold $Iconic -e "$ThisPlayer $WinTitle '--player=$SlinkPlayer' '$ThisLink' $Pipe" &
        disown
    fi
    
    if [ "$ThisPlayer" = "ffmpeg" ]; then
        killall -9 ffmpeg 2>/dev/null
        kill     -9 $ThisX  2>/dev/null
        Hold='-iconic'
        Pipe="- | $SlinkPlayer -"
        if [ "$Who" = "$Owner"  ]; then   
            Pipe="$PipeRoot"
        fi
        xterm -T "$ChName" $Hold $Iconic -e "$ThisPlayer -i '$ThisLink'  -c copy -y   $Vmap -f mpegts $Pipe" &
        ThisX="$!"
        disown
    fi
    
    if [ "$ThisPlayer" != "hlsdl" ] && [ "$ThisPlayer" != "streamlink" ]; then
        if [ "$Terminal" = "xterm" ]; then
            xterm -T "$ChName" $Hold $Iconic -e "$ThisPlayer $WinTitle $PlayerOpt $MpvQuality '$ThisLink'" &
        fi 
    fi
     
    if [ "$Terminal" = "xterm" ]; then
        xterm -T "$ChName" $Hold $Iconic -e "$ThisPlayer $WinTitle $PlayerOpt $MpvQuality '$ThisLink'" &
    fi 
    if [ "$Terminal" = "konsole" ]; then
        konsole --noclose -e $ThisPlayer $WinTitle  $PlayerOpt $MpvQuality "$ThisLink" &  
    fi
    if [ "$Terminal" = "noterm" ]; then
        nohup $ThisPlayer $WinTitle $PlayerOpt $MpvQuality "$ThisLink" >/dev/null 2>&1 &
        disown
    fi
    Running="$!"
    echo  "$ChName $Org Relinker:  $Relinker"  >> $ScriptHome/$Me.log
    echo  "$ChName by $ThisPlayer: $ThisPlayer $WinTitle $PlayerOpt $MpvQuality "$ThisLink" "$Pipe""  >> $ScriptHome/$Me.log
    sleep 4
    TestPlay
}
#-------------------------------------------------------------------------------------------------------------------
GrabCat () {
    unset CatContentMenu
    CatLinks=""
    CatTitles=""
    IsRelinker=0
    Tipologia=$(echo "$CatLink" | grep -c tipologia)
    if [ "$CatLink" = "/tipologia" ]; then 
        CatName="Suggeriti"
        CatLink="/"
    fi
    dialog --title "$Me working.." --infobox "Loading $CatName category. This may take time.\n\nPls wait." 5 50
    CatLink="${CatLink}index.json"
    CatHome=$($Curl -A "$UserAgent" "$AnchorHome$CatLink" | jq  .)
    ThisJson="$CatHome"
    CatHasGen=$(echo "$CatHome" | grep -c "/genere/")
    if [ "$CatName" = "Sport" ]; then 
        CatHasGen="0"
    fi
    if [ "$CatHasGen" != "0" ]; then
        CatTitles=$(echo "$CatHome"| jq -r .contents[] | jq -r '.contents[] | select(.type == "RaiPlay Genere Item" and .sub_type == "RaiPlay V2 Genere Page")' 2>/dev/null | jq -r  .name | tr -s ' ')
        CatLinks=$(echo "$CatHome"| jq -r .contents[] | jq -r '.contents[] | select(.type == "RaiPlay Genere Item" and .sub_type == "RaiPlay V2 Genere Page")' 2>/dev/null | jq -r  .path_id)
     fi
     if [ "$CatHasGen" = "0" ] && [ "$CatName" != "Suggeriti" ] ; then
        CatLinks=$(echo "$CatHome" |  jq -r .contents[].contents[].path_id 2>/dev/null)        
        CatTitles=$(echo "$CatHome" |  jq -r .contents[].contents[].name 2>/dev/null | sed -e 's|^ ||g' | tr ' ' '_')
        ThisMenu=$(paste -d " " <(echo "$CatTitles") <(echo "$CatLinks")  | grep -v 'null' | sort -u)
        CatLinks=$(echo "$ThisMenu" | cut -d ' ' -f 2)
        CatTitles=$(echo "$ThisMenu" | cut -d ' ' -f 1 | tr '_' ' ')
    fi
    if [ "$CatName" = "Suggeriti" ]; then
        IsRelinker=1
        CatTitles=$(echo "$CatHome"| jq -r '.contents[].contents[] | select (.video_url != null)'  2>/dev/null | jq -r .name | tr -s ' ')
        CatLinks=$(echo "$CatHome" | jq -r '.contents[].contents[] | select (.video_url != null)'  2>/dev/null  | jq -r .video_url)
    fi
#---------------------------------------------------------------------------------------------------------------------------------------
    Index=0
    while read CatTitle; do
        let Index++
        CatContentMenu=("${CatContentMenu[@]}" $Index "$CatTitle")
    done <<< "$CatTitles"
    CatTotItems="$Index"
    ShowSubCat
}
#----------------------------------------------------------------------------------------------------------------------
ShowSubCat () {
    StreamType="Vod"
	DefSubCat="1"
    while [ 1 ]; do
        Option=$(dialog  --title "$Me $Version $Codename" --default-item "$DefSubCat"  --ok-label 'Proceed' --cancel-label 'Go Back'  --stdout --menu "Available $CatName sub cats/items: $CatTotItems" 18 60 11 "${CatContentMenu[@]}")
        Button="$?"
        if ! [ "$Option" -eq "$Option" ] 2>/dev/null; then
            return
        fi
        if [ "$Button" = "255" ]; then
            return
        fi
        DefSubCat="$Option"
        let SubcatPos=$Option*2-1
        SubcatName="${CatContentMenu[$SubcatPos]}"
        SubcatLink=$(echo "$CatLinks" | sed -n ${Option}p)
        LinkIsVideo=$(echo "$SubcatLink" | grep -Eic '/video|relinker')
        if [ "$LinkIsVideo" != "0" ]; then
            ChName="$SubcatName"
            ItemName="$SubcatName"
            ItemHome="$SubcatLink"
            AnalyzeContent
            continue
        fi
        GrabSubCatContent
	done
}
#----------------------------------------------------------------------------------------------------------------------
GrabSubCatContent () {
    StreamType="Vod"
	unset SubCatContentMenu
	SubCatHome=$($Curl -A "$UserAgent" "$AnchorHome$SubcatLink" | jq  .)
	ThisJson="$SubCatHome"
    if [ "$Debug" = "1" ]; then
        echo "$CatHome" > $ScriptHome/Rai_CatHome.json
        echo "$SubCatHome" > $ScriptHome/Rai_SubCatContent.json
    fi
	SubCatHasBlock=$(echo "$SubCatHome" | grep -c '"blocks":')
	if [ "$CatName" = "Suggeriti" ]; then
        SubItemsLink=$(echo "$SubCatHome"    | jq -r .first_item_path)
        SubItemsName=$(echo "$SubCatHome" | jq -r .name | tr ' ' '_')
        Option=1
        DefSubCatItem="$Option"
        ItemName=$(echo "$SubItemsName" | sed -n ${Option}p)
        ItemHome=$(echo "$SubItemsLink" | sed -n ${Option}p)
        ChName="$ItemName"
        AnalyzeContent
        return
    else
        if [ "$SubCatHasBlock" != "0" ]; then
            BlocksLinks=$(echo "$SubCatHome"    |  jq -r .blocks[].sets[].path_id 2>/dev/null)        
            BlocksNames=$(echo "$SubCatHome" |  jq -r .blocks[].sets[].name 2>/dev/null | tr ' ' '_')
        else
            ContentsLinks=$(echo "$SubCatHome"    |  jq -r .contents | grep -E '"weblink"' | cut -d '"' -f4 | sed -e 's|$|.json|g')
            ContentsNames=$(echo "$SubCatHome" |  jq -r  .contents | grep -E '"name"'  | cut -d '"' -f4 | tr ' ' '_') 
            ContentsLayout=$(echo "$SubCatHome" |  jq -r .contents  | grep -E '"layout"'    | cut -d '"' -f4)
        fi
    fi
    if [ "$SubCatHasBlock" != "0" ]; then
        CheckBlocks
    else
        CheckContents
    fi
}
#--------------------------------------------------------------------------------------------------------------------------------------
CheckContents () {
    Index=0
    unset ContentsMenu
    for  ThisTitle in $ContentsNames; do
#    while read ThisTitle; do
        let Index++
        ThisTitle=$(echo "$ThisTitle" | tr '_' ' ')
        ContentsMenu=("${ContentsMenu[@]}" $Index "$ThisTitle")
    done # <<< "$ContentsNames"
    ContentsTotItems="$Index"
    DefContent=1
    while [ 1 ]; do
        Option=$(dialog  --title "$Me $Version $Codename" --default-item "$DefContent"  --ok-label 'Proceed' --cancel-label 'Go Back'  --stdout --menu "Available $CatName $SubcatName contents: $ContentsTotItems" 22 60 15 "${ContentsMenu[@]}")
        Button="$?"
        if ! [ "$Option" -eq "$Option" ] 2>/dev/null; then
            return
        fi
        if [ "$Button" = "255" ]; then
            return
        fi
        DefContent="$Option"
        ItemName=$(echo "$ContentsNames"   | sed -n ${Option}p)
        ItemHome=$(echo "$ContentsLinks"      | sed -n ${Option}p)
        AnalyzeContent
	done
}
#--------------------------------------------------------------------------------------------------------------------------------------
AnalyzeContent () {
 	BoxMsg="Retrieving $ItemName info"
	BoxTitle="$Me $Version $Codename"
	ShowInfo
	if [ "$IsRelinker" = "1" ] ; then # && [ "$Layout" = "single" ] ; then
        ThisLink="$ItemHome"
        ChName="$ItemName"
        DescPos="1"
        Info="$ChName"
        HandleButton
        return
    fi
    ThisJson=$($Curl  -A "$UserAgent" "$AnchorHome$ItemHome" | jq .)
    if [ "$Debug" = "1" ]; then
        echo "$ThisJson" > $ScriptHome/Rai_Content.json
    fi
    Layout=$(echo "$ThisJson" | grep -o 'layout.*' | cut -d ':' -f2 | cut -d '"' -f2)
    if [ "$Layout" = "single" ]; then
        ItemPageUrl=$(echo "$ThisJson" | jq . | grep -o '"first_item_path".*' | cut -d '"' -f4)
        if [ "$ItemPageUrl" != "" ]; then
            RelinkerData=$($Curl  -A "$UserAgent" "$AnchorHome$ItemPageUrl")
            Relinker=$(echo "$RelinkerData" | grep -o '"content_url".*' | cut -d '"' -f4)
            Relinker=$(echo "$Relinker" | sed -e 's|^ ||g' -e 's| $||g')
        fi
        ItemContentUrl=$(echo "$ThisJson" | jq . |  grep -o '"content_url".*' | cut -d '"' -f4)
        if [ "$ItemContentUrl" != "" ]; then
            Relinker="$ItemContentUrl"
        fi
        ThisLink="$Relinker"
        ChName="$ItemName"
        DescPos="1"
        HandleButton
        return
    fi
# Relinker=$(echo "$ThisJson" | jq -r .items[].video_url 2>/dev/null)
    Relinker=$(echo "$ThisJson" | grep -m 1 mediapolis | cut -d '"' -f4)
    if [ "$Relinker" != "" ] ; then # && [ "$Layout" = "single" ] ; then
        ThisLink="$Relinker"
        ChName="$ItemName"
        DescPos="1"
        HandleButton
        return
    fi
    CheckBlocks
}
#----------------------------------------------------------------------------------------------------------------------
CheckBlocks () {
    BlocksData=$(echo "$ThisJson" | jq .)
    BlocksGroupName=$(echo "$BlocksData" | jq -r .name)
    BlocksTitles=$(echo "$BlocksData"  | jq -r .blocks[].name | tr ' ' '_')
#-------------------------------------------------------------------------------------------------------------------
    unset BlocksMenu
    BlocksIndex=0
    for Block  in $BlocksTitles; do
        let BlocksIndex++
        Block=$(echo "$Block" | tr '_' ' ')
         BlocksMenu=("${BlocksMenu[@]}" $BlocksIndex "$Block" )
    done
    DefBlock="1"
    while [ 1 ]; do
        if [ "$BlocksIndex" -gt "1" ]; then
            Option=$(dialog  --title "$Me $Version $Codename" --default-item "$DefBlock"  --ok-label 'Proceed' --cancel-label 'Go Back'  --stdout --menu "Available $BlocksGroupName options:" 22 60 15 "${BlocksMenu[@]}")
            Button="$?"
            if [ "$Button" = "1" ]; then
                return
            fi
            if [ "$Button" = "255" ]; then
                return
            fi
            DefBlock="$Option"
        else
            Option=1
        fi
        if [ "$Option" != "" ]; then
            unset BlockMenu
            BlockIndex=0
            BlockTitle=$(echo "$BlocksTitles"   | sed -n ${Option}p)
            let BlockId=$Option-1
            BlockNames=$(echo "$BlocksData" | jq -r .blocks[$BlockId].sets[].name | tr ' ' '_')
            BlockLinks=$(echo "$BlocksData"    | jq -r .blocks[$BlockId].sets[].path_id)
            for Block  in $BlockNames; do
                let BlockIndex++
                BlockMenu=("${BlockMenu[@]}" $BlockIndex "$Block")
            done
            if [ "$BlockIndex" = "1" ]; then
                BlockLink="$BlockLinks"
                GrabBlockItems
                 if [ "$BlocksIndex" = "1" ]; then
                    return
                fi
                continue
            fi
            while [ 1 ]; do
                Option=$(dialog  --title "$Me $Version $Codename" --default-item "$DefSubBlock"  --ok-label 'Proceed' --cancel-label 'Go Back'  --stdout --menu "Available $BlockTitle items:" 22 60 15 "${BlockMenu[@]}")
                Button="$?"
                DefSubBlock="$Option"
                BlockLink=$(echo "$BlockLinks"   | sed -n ${Option}p)
                if [ "$Button" = "1" ]; then
                    break
                fi
                if [ "$Button" = "255" ]; then
                    break
                fi
                GrabBlockItems
            done
            if [ "$BlocksIndex" -gt "1" ]; then
                continue
            else
                break
            fi
        fi
    done
}
#-------------------------------------------------------------------------------------------------------------------
GrabBlockItems () {
    BlockHome=$($Curl -A "$UserAgent" "$AnchorHome$BlockLink" | jq .)
    ThisJson="$BlockHome"
    if [ "$Debug" = "1" ]; then
        echo "$BlockHome" > $ScriptHome/Rai_BlockItemsContent.json
    fi    
    Lev3Data1=$(echo "$BlockHome" | jq . | jq -r .items[].episode_title)
    Lev3Data2=$(echo "$BlockHome" | jq . | jq -r .items[].subtitle)
    Lev3Data3=$(echo "$BlockHome" | jq . | jq -r .items[].name)
    Lev3Links=$(echo "$BlockHome" |  jq -r .items[].video_url)
    Lev3Items=$(echo "$Lev3Links"  | wc -l)
    if [ "$Lev3Links" = "" ]; then
        dialog --title "Empty section" --infobox "Sorry. This section looks empty." 4 45
        sleep 3
        return
    fi
    if [ "$Lev3Links" = "1" ]; then
        ThisLink="$Lev3Links"
        ChName="$Lev3Titles"
        DescPos="1"
        HandleButton
        return
    fi
#----------------------------------------------------------------------------------------------------------------------
    LoadL3Titles
    Lev3Titles=$(echo "$Lev3Titles" | tr -s ' ' | sed -e 's|^ ||g' -e 's| $||g' | tr ' ' '_' | tr '\n' ' ') # | tr ' ' '\n')
#------------------------------------------------------------------------------------------------------------------------
    unset Lev3Menu
    Index=0
    for Lev3Title in $Lev3Titles; do
        let Index++
        Lev3Title=$(echo "$Lev3Title" | sed -e 's|^_||g' -e 's|_$||g' | tr '_' ' ')
        Lev3Menu=("${Lev3Menu[@]}" $Index "$Lev3Title")
    done #<<< "$Lev3Titles"
    SubTotItems="$Index"
    if [ "$Index" = "1" ]; then
            ThisLink=$(echo "$Lev3Links")
            ChName=$(echo "$Lev3Titles")
            DescPos="1"
            HandleButton
            return
    fi
    L3DefItem=1
    while [ 1 ]; do 
        Option=$(dialog --title " $Me $Version $CodeName " --default-item "$L3DefItem" --ok-label 'Play/Record' --cancel-label "Go back" --stdout --menu "Rai Tv Vod: $ItemName > Pls select an item" 0 60 12 "${Lev3Menu[@]}")
        Button="$?"
        if [ "$Button" = "1" ]; then
            return
        fi
        if [ "$Button" = "255" ]; then
            return
        fi
        if [ "$Option" != "" ]; then
            L3DefItem="$Option"
            ThisLink=$(echo "$Lev3Links" | sed -n ${Option}p)
            Relinker="$ThisLink"
            ChName=$(echo "$Lev3Titles" | cut -d ' ' -f$Option)
            DescPos="$Option"
            HandleButton
        fi
    done
}
#--------------------------------------------------------------------------------------------------------------------------------------
HandleButton () {
    Dash=0
    ThisMp4=0
    ResTool="$ResDef"
    Recorder="$RecDef"
    RealLink=$($Curl  -A "$UserAgent" "$ThisLink&output=20")
    Dash=$(echo "$RealLink" | grep -c dash)
    LinkHls=$(echo "$RealLink" | grep -c m3u8)
#-----------------------------------------------------------------------------------------------------------------------------------
    if [ "$LinkHls" != "0" ]; then
        Manifest=$($Curl -A "$UserAgent" "$ThisLink")
        AudioGroup=$(echo "$Manifest" | grep -c 'AUDIO,GROUP-ID')
        Aeskey=$(echo "$Manifest" | grep -c 'SAMPLE-AES')
        Drmkey=$(echo "$Manifest" | grep -c 'dash')
        if [ "$Drmkey" != "0" ] || [ "$Aeskey" != "0" ]; then
            BoxMsg="$ItemName is protected by encryption and not playable on Linux"
            BoxTitle="$Me $Version $Codename"
            ShowInfo
            return
        fi
    else
        ThisMp4=1
    fi
#-----------------------------------------------------------------------------------------------------------------------------------
    Summ=""
    Info=""
    Summ=$(echo "$ThisJson" jq . | grep description | sed -n ${DescPos}p | awk -F '",' '{print $1}' | cut -d '"' -f4-)
    Summ=$(echo "$Summ" | cut -c 1-500 | tr -d '\\') # | sed 's/\(.*\) .*/\1/')
    Info="\n$Summ....\n"
    ThisName=$(echo "$ChName" | tr '_' ' ')
    if [ "$IsRelinker" = "1" ]; then
        Info="\n\n$ChName\n\n"
    fi
    ResLabel=' 3 Restream off'   
    dialog --title "$Me" --ok-label 'Proceed' --msgbox "** $ThisName **\n${Info}\n\nHit ENTER to continue:" 0 0
    response=$(dialog --ok-label 'Proceed' --cancel-label "GoBack"  --stdout --radiolist "Stream: $ChName\n${InfoShort}\n\nSelect using spacebar:\n" 0 0 0  1 Play on 2 Record off  $ResLabel)   
    Button=$?
    if [ "$Button" = "255" ] || [ "$Button" = "1" ]; then
        return
    fi
    if [ "$response" = "1" ]; then
        ThisPlayer="$PlayerVod"
        RunPlayer
        return
    fi
    if [ "$response" = "2" ]; then
        Record
        RecordingPids="$RecordingPids $!"
        return
    fi
    if [ "$response" = "3" ]; then
        Restream
        return
    fi
        
}
#-----------------------------------------------------------------------------------------------------------------------------------
SetPlayerLive () {
while [ 1 ]; do
    PlayersList="mpv QMPlay2 smplayer vlc parole bomi streamlink hlsdl ffplay ffmpeg"
    PlayersMenu="1 mpv 2 QMPlay2 3 smplayer 4 vlc 5 parole 6 bomi 7 streamlink 8 hlsdl 9 ffplay 10 ffmpeg"
    Reply=$(dialog --title " $Me $Version $CodeName " --default-item "1" --ok-label 'Set' --cancel-label "Goback" --stdout --menu "Select a player for live streams: " 0 40 10 $PlayersMenu)
    Button=$?
    if [ "$Reply" = "" ]; then
        return
    fi
    MyPlayer=$(echo "$PlayersList" | tr -s ' ' | cut -d ' ' -f $Reply)
    if [ -n "`which $MyPlayer 2>/dev/null`" ]; then
        PlayerVod="$MyPlayer"
		return
	fi
	clear
	dialog --title "Error" --infobox "The player $MyPlayer was not found into you system. Select a new one" 5 35;
	sleep 4
done
}
#-----------------------------------------------------------------------------------------------------------------------------
MapFFmpeg () {
 if [ "$MapFFmpeg" = "1" ]; then
        VideoLink="$ThisLink"
        Manifest=$($Curl -A "$UserAgent" "$ThisLink")
        VBest=$(echo "$Manifest"   | grep RESOLUTION | grep -o  'BANDWIDTH.*' | cut -d '=' -f2 | cut -d ',' -f1 | sort -nr | head -1)
        Vtrack=$(echo "$Manifest"  | grep RESOLUTION | grep -o  'BANDWIDTH.*' | grep -n "$VBest"   | cut -d ':' -f1 | head -1)
        if [ "$Vtrack" != "" ]; then
            Vtrack=$(( $Vtrack - 1 ))
        else
            Vtrack=0
        fi
        Atrack=$(echo "$Manifest" | grep '#EXT' | grep LANGUAGE | grep -in ita | cut -d ':' -f1)
        if [ "$Atrack" != "" ]; then
            Atrack=$(( $Atrack - 1 ))
        else
            Atrack=0
        fi
        if [ "$Atrack" = "" ] && [ "$Vtrack" = "" ]; then
            Vmap=""
        else
            Vmap="-map 0:v:$Vtrack'?' -map 0:a:$Atrack'?'"
        fi
    fi
}
#--------------------------------------------------------------------------------------------------------------------------------------
Restream () {
    ResTidy
    ResSetup
    ThisHls=$(echo "$ThisLink" | grep -Ec 'hls|m3u8')
    if [ "$ThisHls" != "0" ]; then
        MapFFmpeg
    else
        Vmap=""
    fi
    VideoLink="$ThisLink"
    ResLoad
 #---------------------------------------------------------------------------------------------------------------------------------
    if [ "$ResProt" = "udp" ]; then
        xterm $Hold $Iconic  -T "$ChName" -e  ffmpeg -user_agent 'Raiweb 999' -i "$VideoLink" -acodec copy -vcodec h264 -y  -f mpegts $Target &
        ResPid="$!"
        disown
    fi
    if [ "$ResProt" = "rtp" ]; then
        xterm $Hold $Iconic -T "$ChName" -e "ffmpeg -user_agent 'Raiweb 999' -i  '"$VideoLink"'  -c copy -b 3200k  -bsf:v h264_mp4toannexb $Vmap -f rtp_mpegts  $Target" &
        ResPid="$!"
        disown
    fi
    if [ "$ResProt" = "rtsp" ]; then
        if [ "$ResTool" = "ffmpeg" ]; then
            xterm $Hold $Iconic -T "$ChName" -e "ffmpeg  -user_agent 'Raiweb 999' -re -stream_loop -1 -i '"$VideoLink"' -c copy -rtpflags latm $Vmap -f rtsp -rtsp_transport tcp $Target"  &
        else
            xterm $Hold $Iconic  -T "$ChName" -e "hlsdl -b '"$VideoLink"' -o - | ffmpeg  -re -stream_loop -1 -i - -c copy -rtpflags latm -f rtsp -rtsp_transport tcp '"$Target"'"  &
        fi
        ResPid="$!"
        disown
    fi
    if [ "$ResProt" = "rtmp" ]; then
       if [ "$ResTool" = "ffmpeg" ]; then
       xterm $Hold $Iconic -T "$ChName" -e "ffmpeg -user_agent 'Raiweb 999' -re -i '"$VideoLink"' -vcodec libx264 -vprofile baseline -acodec aac -strict -2 -f flv  $Target" &
           else
         xterm $Hold $Iconic  -T "$ChName" -e "hlsdl -b '"$VideoLink"' -o - | ffmpeg -re -i - -vcodec libx264 -vprofile baseline -acodec aac -f flv '"$Target"'"  &
        fi
        ResPid="$!"
        disown
    fi
    if [ "$ResProt" = "http" ]; then
        if [ "$ResTool" = "hlsdl" ]; then
            xterm $Hold $Iconic -T "$ChName" -e "hlsdl -b -o - '"$VideoLink"' | vlc -I dummy -q --volume-step=10 - --sout '#standard{access=http,mux=ts,dst=$LocalIp:8530}'" &
        else
            xterm $Hold $Iconic -T "$ChName" -e "ffmpeg -user_agent 'Raiweb 999' -i  '"$VideoLink"'  -c copy  $Vmap -f mpegts - | vlc -I dummy -q --volume-step=10 - --sout '#standard{access=http,mux=ts,dst=$LocalIp:8530}'" &
        fi
         ResPid="$!"
         disown
    fi
    ResCheck
}
#-----------------------------------------------------------------------------------------
ResCheck () {
    ReCheck=0
    IsStreaming="00"
    if [ "$Remonitor" = "1" ]; then
        while [ 1 ]; do
            let ReCheck++
            sleep 3
            IsStreaming=$(ps -au | grep -E "$LocalIp|239.101.101.1" | grep  "$ResPid")  
            if [ "$IsStreaming" != "00" ]; then
                ResBuff
                ResMon
                return
            fi
            if [ "$ReCheck" = "10" ]; then
                dialog  --title "Restreaming failed" --infobox "$ChName failed to be restreamed on \n$Target\n\nCheck the XTERM for details." 10 45
                sleep 4
                return
            fi
         done
    fi
}
#-------------------------------------------------------------------------------------------------------------------------------
ResSetup () {
    ResProt=$(echo "$ResProtocols" | cut -d " " -f1)
    if [ "$ResProt" = "http" ]; then
        Target="http://$LocalIp:8530"
    fi
    if [ "$ResProt" = "udp" ]; then
        Target="udp://239.101.101.2:1234"
    fi
    if [ "$ResProt" = "rtp" ]; then
        Target="rtp://239.101.101.1:1234"
    fi
    if [ "$ResProt" = "rtsp" ]; then
        Target="rtsp://$LocalIp:8554/live"
    fi
    if [ "$ResProt" = "rtmp" ]; then
        Target="rtmp://$LocalIp:1935/live"
    fi
    kill -9 $MonPid 2>/dev/null
    kill -9 $ResPid  2>/dev/null
 }
#-----------------------------------------------------------------------------------------------------------------------------------
ResLoad () {
    dialog  --title "Restreaming" --infobox "$ChName  restream loading data.\n\nPls keep calm and wait!" 6 50
}
#-----------------------------------------------------------------------------------------------------------------------------------
ResBuff () {
    dialog  --title "Restreaming" --infobox "$ChName  restream starting on:\n$Target\n\nThe monitor should raise within a few secs.\n\nIf it doesn't or crashes check the xterm window content\n\nBuffering, pls wait." 9 50
    sleep 3
}
 #------------------------------------------------------------------------------------------------------------------------------
ResTidy () {
    kill -9 $MonPid 2>/dev/null
    kill -9 $ResPid  2>/dev/null
    ResPids=$(ps  -af | grep -E "$LocalIp:85|239.101.101.1:1234|$LocalIp:1935" | grep -v grep | tr -s ' ' | cut -d ' ' -f2 | sort -u | tr '\n' ' ')
    for Pid in $ResPids; do
        kill -9 $Pid 2>/dev/null
    done
}
 #----------------------------------------------------------------------------------------------------------------------------------- 
ResMon () {
    if [ "$Remonitor" = "0" ]; then
        return
    fi
#    sleep $MonWait
    if [ "$MonPlayer" =  "mpv" ]; then
        nohup mpv --title="$ChName-on-$Target" --force-window=immediate --no-ytdl --autofit=240x160  --volume=10 $Target >/dev/null 2>&1 &
        MonPid="$!"
        disown
        return
    fi
    if [ "$MonPlayer" =  "ffplay" ]; then
        nohup ffplay -loglevel panic -nostats -window_title "$ChName-on-$Target" -volume 2 -vf  scale=240:160 $Target >/dev/null 2>&1 &
        MonPid="$!"
        disown
        return
    fi
    if [ "$MonPlayer" =  "vlc" ]; then
        nohup vlc --meta-title "$ChName-on-$Target"  --no-audio "$Target"  >/dev/null 2>&1 &
        MonPid="$!"
        disown
        return
    fi
    if [ "$MonPlayer" =  "mplayer" ]; then
        nohup mplayer -title "$ChName-on-$Target" -xy 240  -volume 1 $Target >/dev/null 2>&1 &
        MonPid="$!"
        disown
        return
    fi
    nohup $MonPlayer $Target >/dev/null 2>&1 &
    MonPid="$!"
    disown
}
#-------------------------------------------------------------------------------------------------------------------
LoadL3Titles () {
    Lev3Titles1=$(echo "$Lev3Data1" | tr ' ' '_') # | tr "'" '_')
    Lev3Titles2=$(echo "$Lev3Data2" | tr ' ' '_')  #| tr "'" '_')
    Lev3Titles3=$(echo "$Lev3Data3" | tr ' ' '_') # | tr "'" '_')
#-----------------------------------------------------------------------------------------------------------------------
    Lev3TitlesCnt=$(echo -n "$Lev3Titles1" | grep  -v -E '^$' | wc -l) # grep -c '^')
    if [ "$Lev3TitlesCnt" = "$Lev3Items" ]; then
        Lev3Titles="$Lev3Titles1"
        return
    fi
    Lev3TitlesCnt=$(echo -n "$Lev3Titles2" | grep  -v -E '^$' | wc -l) #grep -c '^')
    if [ "$Lev3TitlesCnt" = "$Lev3Items" ]; then
        Lev3Titles="$Lev3Titles2"
        return
    fi
    Lev3TitlesCnt=$(echo -n "$Lev3Titles3" | grep  -v -E '^$' | wc -l) #grep -c '^')
    if [ "$Lev3TitlesCnt" = "$Lev3Items" ]; then
        Lev3Titles="$Lev3Titles3"
        return
    fi
}
#-------------------------------------------------------------------------------------------------------------------
ShowCat () {
    while [ 1 ]; do
        SubType='any'
        Option=$(dialog --title " $Me $Version $CodeName " --default-item "$DefItem" --ok-label 'Load items' --cancel-label "Exit" --stdout --menu "Rai Tv Vod Genres:$MenuItems > Pls select a category" 0 60 14 "${RaiMenu[@]}")
        Button="$?"
        DefItem=`echo $Option | awk '{print $1}'`
        if [ "$Button" = "1" ]; then
            exit
        fi
        if [ "$Button" = "255" ]; then
          SetPlayerLive
          continue
        fi
       # if [ "$Button" = "2" ]; then
       #     ForceMp4=1
       #     continue
       # fi
        if [ "$Option" = "$MenuItems" ]; then
            Search
            continue
        fi
         CatLink=$(echo "$VodLinks"      | sed -n ${Option}p)
        CatLink="/tipologia${CatLink}"                                                   # Dirty fix
        CatName=$(echo "$VodNames" | sed -n ${Option}p)
        GrabCat
    done
}
#-------------------------------------------------------------------------------------------------------------------
Vod () {
    unset RaiMenu
    VodHomeData=$($Curl -A "$UserAgent" "$AnchorHome")
    VodData=$(echo "$VodHomeData" | grep -o 'href="/film.*' | awk -F 'data-type="anchor"' '{print $1}' |  awk '{gsub(/href+/,"\nhref");print;}' | grep 'site-menu__list__item__link' | grep 'href="/') 
    VodNames=$(echo "$VodData" | cut -d '>' -f2 | cut -d '<' -f1 | sed -e 's| $||g' | grep -v lista)
    VodLinks=$(echo "$VodData"    | cut -d '"' -f2 | sed -e 's|$|/|' | grep -v lista)
 #-------------------------------------------------------------------------------------------------------------------
    if [ "$VodNames" = "" ]; then 
        dialog --title "Raiplay timeout" --infobox "Sorry. Got a timeout from Raiplay.it site. Try later.\nHit ENTER to EXIT" 4 63
        read < /dev/tty
        exit
    fi
#------------------------------------------------------------------------------------------------------------------- 
    Index=0
    while read Chan; do
        let Index++
        RaiMenu=("${RaiMenu[@]}" $Index "$Chan" )
    done <<< "$VodNames"
    let Index++
    RaiMenu=("${RaiMenu[@]}" $Index "Suggeriti" )
    let Index++
    RaiMenu=("${RaiMenu[@]}" $Index "Search RaiPlay site" )
    MenuItems="$Index"
}
#------------------------------------------------------------------------------------------------------------------
ShowResults () {
    clear
    ItemStart=1
    DefItemS=1
    ItemShown="$Psize"
    let MaxPages=$MaxFound/$Psize+1
    while [ 1 ];  do
        ItemAsked=$(dialog --title " $Me $Version " --default-item "$DefItemS" --ok-label "Play/Record"  --cancel-label "GoBack" --stdout --menu "Catched $MaxFound items. Search arg: $SearchArg. Displayed: 1/$IndexS\n(Max allowed streams limited by RAI. Some links may be dups or dead) " 0 0 25 "${SearchMenu[@]}")
        Button="$?"
        DefItemS="$ItemAsked"
        if [ "$Button" = "1" ] ||  [ "$Button" = "255" ]; then
            return
        fi
        Id=$(echo "$Ids" | sed -n ${ItemAsked}p)
        ItemName=$(echo "$DataPage" | grep -v '"programma"' | grep  -A3 "$Id" | grep  '"titolo"' | awk -F '"titolo"' '{print $2}' | cut -d '"'   -f2-  | sed -e 's|^ ||g' -e 's| $||g' -e 's|",$||g') 
        ItemHome=$(echo "$DataPage" | grep -v '"programma"' | grep  -A3 "$Id" | grep '"path_id"' | awk -F '"path_id"' '{print $2}'| cut -d '"' -f2-  | sed -e 's|^ ||g' -e 's| $||g' -e 's|",$||g')
        ChName="$ItemName"
        AnalyzeContent
    done
}
#------------------------------------------------------------------------------------------------------------------
grabPage () {
    unset SearchMenu; unset TitlesMap
    Ids=""
    dialog --title "Search takes time....:" --infobox "Searching for >> $SearchArg << pls wait. " 5 50
    Par='{"param":"'${SearchArg}'","page":'$PageSearch',"pageSize":'$Psize'}'
    RawData=$(curl -sL -A "$UserAgent" -H "Referer: $SearchPage" -H 'Content-Type: application/json; charset=UTF-8' -d $Par "$SearchDetail")
    DataPage=$(echo "$RawData"  | jq . | grep -Eo '"titolo":.*|"url":.*|"path_id":.*|"id".*|"programma".*')
    DataPage=$(echo "$DataPage" | sed -e "s|&quot;|'|g" -e "s|\&amp;|\&|g" -e "s|&amp;#x27;|'|g" -e "s|\&#x27;|'|g" -e "s|\&amp;|\&|g" | tr -d '\\')
    MaxFound=$(echo "$RawData" | jq . | grep -m1 '"totale"' | cut -d ':' -f2 | tr -d ' ,')
    Titles=$(echo "$DataPage" | grep '"titolo"' | cut -d ':' -f2-  | sed -e 's|,$||g' | sort -u)
    IndexS=0
    while read Title; do
        let IndexS++
        ThisId=$(echo "$DataPage" | grep -v '"programma"'  |  grep -B1 "$Title" | cut -d ':' -f2 | head -1 | tr -d ',')
        Ids="$Ids $ThisId"
        Title=$(echo "$Title" | cut -d '"' -f2- | sed -e 's|"$||g' -e 's|^ ||g')
        Type=$(echo "$DataPage" | grep  -A3 "$ThisId" | grep  '"programma"'  | cut -d ':' -f2- | cut -d '"' -f2 | sed -e 's|"$||g' -e 's|^ ||g')
        Ltitle=$(echo "$Title" | tr '[:upper:]' '[:lower:]')
        Ltype=$(echo "$Type" | tr '[:upper:]' '[:lower:]')
        if [  "$Ltype" != "$Ltitle" ]; then
            Tags=$(echo "$Title $Type" | sed -e 's|^ ||g' -e 's| $||g')
        else
            Tags="$Type"
        fi
        SearchMenu=("${SearchMenu[@]}" $IndexS "$Tags")
    done <<< "$Titles"
    Ids=$(echo "$Ids" | tr -s ' ' | tr ' ' '\n' | grep '"')
}
#------------------------------------------------------------------------------------------------------------------
Search () {
	while true; do
		SearchArg=`dialog --colors --stdout --cancel-label "GoBack" --title " $Me $Version " --backtitle "Search Mode Enabled" --inputbox "Enter a search argument" 8 60`
		Button="$?"
        if [ "$Button" = "1" ] ||  [ "$Button" = "255" ]; then
            return
        fi
		if [ "$SearchArg" == "" ]; then
			dialog --title "Search function:" --infobox " An empty search argument is invalid " 5 41
			sleep 3
			continue
		fi
		SearchArg="${SearchArg// /%20}"
		SearchPage="$ShowallPage?q=${SearchArg}"
		PageNumber=1
		PageSearch=0
		grabPage
        if [ "$MaxFound" = "0" ]; then
            dialog --title "No items found" --infobox "No items found using >> $SearchArg << Hit ENTER to continue" 5 50
            read < /dev/tty
            continue
        fi
#		SearchPager
		ShowResults
	done
}
#------------------------------------------------------------------------------------------------------------------
TestSys
Vod
ShowCat
clear
exit
#------------------------------------------------------------------------------------------------------------------
