#!/bin/bash
#-------------------------------------------------------------------------------------------------------------------
#     CopyRight 2015-2019 Shorewall a.k.a. Kowalsky :D    
#           shorewall@mail.com   http://depippis.tk
#
#           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: 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 RadioPlayer vars.
#           Can also record the Radio, Replay flow and most of the live streaming, depending of your
#           ffmpeg level and the originating stream type. 
#
#           by K. aka Shorewall aka The Gray etc etc :-)
#
#           Many thanks to my friend Paolo Di Stefano (www.paolodistefano.name) for changing some SED 
#           statements making the V2 syntax *BSD compatible
#
#           Many thanks to my friend Laser that pushed into my mind the idea to add  a 'search' option
#           for  RaiPlay site. I just copied 'as-is' the basic initial coding (search panel and the data grab)
#           from its own RaiNix mod :-) to proceed with my coding.
#
#           Just a short story. This V3 release continues my fight with the RAI sites. It started many years ago' with
#           RAISMTH the well known Firefox addon written with my friend MITM. Even if today Firefox on Linux can
#           easily play the RAI contents I think that is my right look at these contents w/o being overloaded by tons of
#           endless advertising.
#           Until I pay a 'canone' I want to watch at these contents using the method I prefer, and w/o
#           so much advertising or being forced to be signed up and profiled by RAI & Co. My data are mine.
#
#
#   changelog: v 3.0.0   ** Major** Added search option for RaiPlay site.
#                                   Removed some dummy code.
#                                   Removed checking for export Display variable. Assuming the Linux box is OK by default
#                                   The script must non take care of user's O.S. bugs. The end-user must do.
#                                   Removed gnome-terminal support.
#                                   Many cosmetic changes on menu's layout to make them more clear & standard.
#
#                                   FOR A FULL AND WELL DETAILED SCRIPT FEATURES/USAGE DESCRIPTION
#                                   GO TO MY FRIEND Paolo site: http://www.paolodistefano.name   
#
#
#   notes: v 3.0.0      1) When an Adobe HDS flow is selected the stream can be player only if StreamLink is installed.
#						         2)  The SetVbr option applies only to StreamLink. Mpv can set the required quality only if an hlsvariant
#                               type stream is detected. Otherwise the best video quality is applied.
#                               3)  The search option is a work-in-progress. Even if mostly working there are some
#                               well known bugs:
#                                   A) RAI started using mpeg-dash flows DRM PROTECTED. 
#                                       Do u remember the old smooth-streaming saga? Just same story.
#                                       So mpv & vlc cannot play these flow locally. Just the browser can (for now... :-). 
#                                       StreamLink has the plugin but many flows are DRM protected. Sorry
#                                   B) Playable items are only searched at first level, with a direct relinker. Some items requires
#                                       further scan to catch the link. Too much code to get a few more results working.
#                                   C) The search query sometime give back duplicate items. Again too much code to fix
#                                        this small bug. Therefore keep the dups into the list for now.
#                               4)  If u prefer more detailed search output set the DeepInfo flag to 1 (default is 0), but
#                               u will pay a long delay showing the results menu' also on paging.
#.
#                               This release SUPERSEDES the old V1 and V2 scripts that will non be updated anymore.
#
#
#----------------------------------------------------------------------------------------------------------------------------------
ScriptHome="$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
Me=`basename $0`
Version='3.0.0'
CodeName="'Aurora, my old beloved dog'"
AnchorLive="http://www.raiplay.it/dirette"
AnchorRadio="http://rai.it/dl/portaleRadio/popup/ContentSet-003728e4-db46-4df8-83ff-606426c0b3f5-json.html?jsonp=call"
AnchorReplay="http://www.raiplay.it/guidatv/index.html"
SearchDetail="https://atomatic.rai.it/raiplay-search-service/api/v2/searchdetail"
ShowallPage="https://www.raiplay.it/showall.html"
#----------------------------------------------------------------------------------------------------------------------------------
UserAgent="Mozilla/5.0 (X11; Linux i686; rv:23.0) Gecko/20100101 RaiFacker/3.0"
#----------------------------------------------------------------------------------------------------------------------------------
#---------------------------- Uncomment a  UserAgent for Mobiles if you are experiencing    -------------
#---------------------------- long delays starting on Ubuntu systems                                          -------------
#----------------------------------------------------------------------------------------------------------------------------------
#UserAgent="Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25"
#UserAgent="Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30"
#----------------------------------------------------------------------------------------------------------------------------------
CookieJar="/tmp/"$Me"_Cookies.txt"
socks=""
Curl="curl -s -L $socks--max-time 30 -c $CookieJar -b $CookieJar"
ShowInfoDelay=3
MyPid="$$"
PlayerOpt=""
#----------------------------------- Here you can change some settings  ------------------------------------------
RadioPlayer="vlc"														# Set your RADIO preferred player
#----------------------------------------------------------------------------------------------------------------------------------
MultiProcess=1                          # 0 or 1 : Setting 1 allow multiples Palyers/Recorders to run concurrently
FFmpegBroker="0"                                                      # Extreme use. FFmpeg download and pipe FFplay
PlayersLive="mpv streamlink ffplay dummy"              # Set your LIVE & REPLAY player  priority  order
PlayersVod="mpv ffplay vlc dummy "                          # Set your VOD player priority order
Recorder="ffmpeg"														 # Default recorder if Streamlink is not installed.
RecorderOpt=""															 # Set here your options for FFmpeg recording
LsRecorder="0"														     # set=1 forces Streamlink as recorder if installed
#----------------------------------------------------------------------------------------------------------------------------------
Savedir="/tmp/Rai"							# Set your preferred folder to store recording data
mkdir -p "$Savedir" 2>/dev/null
Iconic="-iconic"								# Set this var to '' (null) for debugging purposes
Hold=""											# Set this var to '-hold' for debugging purposes
Psize=25                                         # Search results x PAGE (Keep LOW, search takes time if DeepInfo=1)
DeepInfo=0                                     # Search stream pages to extract some more info about search resulkts  
#----------------------------------------------------------------------------------------------------------------------------------
FFplayOpt="-infbuf  -vf  scale=800:490 -framedrop"
MpvOpt="--demuxer-thread=yes  --demuxer-readahead-secs=15 --autofit=800x600"
MpvQuality="--hls-bitrate=max"
StreamLink=$(which streamlink)
LsQuality="best"
Who=$(whoami)
if [ "$Who" = "root"  ]; then
#	LsOpt="--yes-run-as-root"
	LsOpt=''
fi
if [ "$DeepInfo" != "1"  ]; then
    Fast='Fast'
fi
#----------------------------------------------------------------------------------------------------------------------------------
#---------------------------  Changing after this point you can do only damages :-)  -------------------------
#----------------------------------------------------------------------------------------------------------------------------------
for PlayerBin in $PlayersLive; do
	if [ -n "`which $PlayerBin 2>/dev/null`" ]; then
		break
	fi
done

if [  "$PlayerBin" = "dummy" ]; then
	dialog --title "Error" --infobox " Sorry none of the  predefined player was found to play Live Streams. " 0 0; 
	sleep 3
	exit
fi
#-------------------------------------------------------------------------------------------------------------------
for PlayerVod in $PlayersVod; do
	if [ -n "`which $PlayerVod 2>/dev/null`" ]; then
		break
	fi
done

if [  "$PlayerVod" = "dummy" ]; then
	dialog --title "Error" --infobox " Sorry none of the predefined player was found to play Vod Streams. " 0 0; 
	sleep 3
	exit
fi
#----------------------------------- recording tools check ------------------------------------------------ 
if [ -z "`which ffmpeg 2>/dev/null`" ]; then
		FFmpeg=0
		dialog --title "FFmpeg missing" --infobox " Warning HLS/Mp4 recording function may not work w/o FFmpeg. " 6 30; 
		sleep 3
fi
if [ -z "`which streamlink 2>/dev/null`" ]; then
		LiveHsd=0
		dialog --title "Streamlink missing" --infobox " Warning HDS recording function cannot work w/o Streamlink. " 6 30; 
		sleep 3 
fi
#---------------------------------------------- players checking ----------------------------------------
if [ "$PlayerVod" = "ffplay" ]; then
    PlayerVod="$PlayerVod $FFplayOpt"
fi
if [ "$PlayerVod" = "mpv" ]; then
    PlayerVod="$PlayerVod $MpvOpt"
fi

if [ "$PlayerBin" = "ffplay" ]; then
    PlayerOpt="$FFplayOpt"
fi
if [ "$PlayerBin" = "mpv" ]; then
	PlayerOpt="$MpvOpt"
fi
if [ "$PlayerBin" = "streamlink" ]; then
	PlayerOpt="$LsOpt"
fi
Player="$PlayerBin $PlayerOpt"

if [ "$PlayerBin" = "streamlink" ] || [ "$LsRecorder" = "1" ]; then
	dialog --title "Warning!" --infobox "Warning! Using Streamlink as player or recorder may fail some stream. In such case pls set LsRecorder flag to 0 and/or change the selected LIVE player. Hit ENTER to continue." 7 50
	read < /dev/tty
fi
#-------------------------------------------------------------------------------------------------------------------
function Record () {
    Cleanup
    if [ "$LiveHsd" = "0" ] && [ "$FFmpeg" = "0" ]; then
        dialog --title "Recording failure" --infobox " Sorry, both FFmpeg and Streamlink was not found. Recording will not work. " 6 30
        sleep 3
	    return
	fi
    ChName=$(echo "$ChName" | tr -d ' \n\t\r')
    if [ "$StreamType" = "Replay" ] && [ "$SubType" != "Search" ]; then
        ChName="$ThisName"
    fi
    Tag=$(date +%Y%m%d_%H%M)
    if [ "$StreamType" = "Radio" ]; then
       Aac=$($Curl  -A "$UserAgent" "$ThisLink" | grep m3u8)
       if [ "$Aac" = "" ] ; then
				Ext="mp3"
	   else
				Ext="aac"
	   fi
       dialog --title "$ChName starting" --infobox "Starting radio $ChName recording using $Recorder. " 6 60
       echo "$ChName $Recorder  -y -i "$ThisLink" -acodec copy $Savedir/${ChName}_${Tag}.${Ext}" >> $ScriptHome/$Me.log
       xterm -T "$ChName" $Hold -e $Recorder -y -i "$ThisLink" -acodec copy $Savedir/${ChName}_${Tag}.${Ext} &
       sleep 3 
       return
    fi
    if [ "$StreamLink" != "" ]  && [ "$LsRecorder" = "1" ]; then
        if [ "$StreamType" = "Replay" ] ; then
            Hls=$($Curl  -A "$UserAgent" "$ThisLink" | grep BANDWIDTH)
            if [ "$Hls" = "" ] ; then
				LsPlugin="httpstream"
			else
				LsPlugin="hlsvariant"
			fi
		fi
		if [ "$StreamType" = "Live" ]; then
		    if [ "$LinkF4m" != "" ]; then
				LsPlugin="hds"
			else
				LsPlugin="hlsvariant"
			fi
		fi
        dialog --title "$ChName starting" --infobox "Starting $ChName recording using StreamLink. " 6 30
        sleep 2
        SetEmbedPlayer
        if [ "$Noembed" = "1" ]; then
			dialog --title "$ChName not starting" --infobox "No embed player (/mpv,ffplay,vlc) found to start  StreamLink. " 6 30
	        sleep 3
   	       return
        fi
        Iconic=""
	    echo  "$ChName by StreamLink: $LsPlayer -f -o $Savedir/${ChName}_${Tag}.avi '$LsPlugin://$ThisLink' $LsQuality"  >> $ScriptHome/$Me.log
	    if [ "$Terminal" = "xterm" ]; then
		    xterm -T "$ChName" $Hold $Iconic -e "$LsPlayer -f -o $Savedir/${ChName}_${Tag}.avi '$LsPlugin://$ThisLink' $LsQuality" &
	    fi
	    if [ "$Terminal" = "konsole" ]; then
		     konsole --noclose -e "$ChName" $Hold $Iconic -e "$LsPlayer -f -o $Savedir/${ChName}_${Tag}.avi '$LsPlugin://$ThisLink' $LsQuality" &
	    fi
	    return
    fi

    dialog --title "$ChName starting" --infobox "Starting $ChName recording using $Recorder. " 6 30
    sleep 2
    echo "$ChName $Recorder -y -i "$ThisLink" -vcodec copy -acodec copy $RecorderOpt $Savedir/${ChName}_${Tag}.avi" >> $ScriptHome/$Me.log

    if [ "$Terminal" = "xterm" ]; then
       xterm -T "$ChName"  $Hold -e $Recorder -y -i "$ThisLink" -vcodec copy -acodec copy $RecorderOpt $Savedir/${ChName}_${Tag}.avi & 
    fi
    if [ "$Terminal" = "konsole" ]; then
       konsole --noclose -e  $Recorder -y -i "$ThisLink" -vcodec copy -acodec copy $RecorderOpt $Savedir/${ChName}_${Tag}.avi &
    fi 
    return
}
#------------------------------------------------------------------------------------------
#trap Record SIGQUIT#
#trap Record INT 
#------------------------------------------------------------------------------------------
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 ; do
    if [ -z "`which $command 2>/dev/null`" ]; then
		NOTFOUND="`echo "$NOTFOUND $command"`"
    fi
done
if [ -n "$NOTFOUND" ]; then
    echo "Comandi non trovati:"
    echo $NOTFOUND
    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
#------------------------------------------------------------------------------------------
Terminal="xterm"
TermTest=`which xterm`
if [ "$TermTest" = "" ] ; then
    Terminal="konsole"
    TermTest=`which konsole`
fi
if [ "$TermTest" = "" ]; then
   clear
   echo "Sorry. No term (xterm - konsole) available to start the stream"
   exit 12
fi
}
#-------------------------------------------------------------------------------------------
ShowInfo () {
    dialog --title "$BoxTitle" --infobox " $BoxMsg " 4 44
    sleep $ShowInfoDelay
    return
}
#-------------------------------------------------------------------------------------------------------------------
Live () {
  StreamType="Live"
  LiveNames=$($Curl -A "$UserAgent" "$AnchorLive"  | grep '<div' | grep 'channel_'  | cut -d'"' -f2 | cut -d '_' -f2 | sed -e 's|^Rai|Rai |g')
  LiveLinks=$(echo "$LiveNames"    | tr -d '_'  | tr '[:upper:]' '[:lower:]')
 #-------------------------------------------------------------------------------------------------------------------
  Index=0
  while read Chan; do
      let Index++
      RaiMenu=("${RaiMenu[@]}" $Index "$Chan" )
  done <<< "$LiveNames"
  LiveItems="$Index"
  let Index++
  RaiMenu=("${RaiMenu[@]}" $Index "Radio Rai")
  let Index++
  RaiMenu=("${RaiMenu[@]}" $Index "Rai Replay")
  let Index++
  RaiMenu=("${RaiMenu[@]}" $Index "Set Video Quality (Ls/Mpv only opt.)")
  MenuItems="$Index"
}
#-------------------------------------------------------------------------------------------------------------------
GetChan () {
  ReplayChans=$($Curl -A "$UserAgent" "$AnchorReplay" | grep data-channel | grep 'class="program' | cut -d '"' -f2)
  ReplayChans=$(echo "$ReplayChans"  | grep -v 'RaiScuola' | grep -v 'RaiNews24' | grep -v 'RaiSport' | grep -v 'RaiPlaySport')
  Index=0
  unset RepMenu
  while read RepChan; do
      let Index++
      RepMenu=("${RepMenu[@]}" $Index "$RepChan" )
  done <<< "$ReplayChans"
   while [ 1 ]; do
      Chan=$(dialog --title " $Me $Version " --default-item "$Chan" --cancel-label "GoBack" --stdout --menu "Rai Replay Channels:$Index > Select a channel" 0 60 0 "${RepMenu[@]}")
      if [ "$Chan" == "" ]; then
			return
      fi
      let NamePos=$Chan*2-1
      ChName="${RepMenu[$NamePos]}"
      GetDate
  done
}
#-------------------------------------------------------------------------------------------------------------------
# Linux or *BSD conditional statement for RaiReplay

GetDate () {
  Linux=$(uname | grep -c -i linux)
  if [ "$Linux" != "0" ]; then
	  Week=`for i in {1..7}; do date -d "$i day ago" +%d-%m-%Y" "%A; done`
  else
	  Week=`for i in {1..7}; do date -v "-"$i"d" "+%d-%m-%Y  %A"; done`
  fi

  while [ 1 ]; do
      Day=$(dialog --title "Rai Replay $ChName" --default-item "$Day" --cancel-label "GoBack" --stdout --menu "Select a date" 0 50 0 $Week)
      if [ "$Day" == "" ]; then
			return
      fi
      DayName=$(echo $Week | grep -o "$Day.*"| cut -d ' ' -f2)
      Replay 
  done
}
#-------------------------------------------------------------------------------------------------------------------
Replay () {
  StreamType="Replay"
  Pos="0"
  unset ReplayMenu
  ReplayPage="$AnchorReplay?canale=${ChName}&giorno=$Day&new"
  PageReplay=$($Curl -A "$UserAgent" "$ReplayPage" | grep  -E 'class="info"|configuratore')
  Name=$(echo "$PageReplay" | grep -o 'class="info".*' | cut -d '>' -f2 | cut -d '<' -f1 | sed -e 's/^/"/;s/$/"/g')
  Time=$(echo "$PageReplay"   | grep -o "data-ora.*"   | cut -d '"' -f2)
  for Token in $Time; do
      let Pos++
      ReplayMenu=("${ReplayMenu[@]}" $Token "`echo "$Name" | sed -n ${Pos}p | tr -d '"'`")
  done
  while [ 1 ]; do
      Prog=$(dialog --title " RaiReplay $ChName $DayName " --default-item "$Prog" --ok-label 'Play' --extra-button --extra-label 'Record' --cancel-label "GoBack" --stdout --menu "Mind, some programs are not allowed on REPLAY by RAI." 0 60 0 "${ReplayMenu[@]}")
      Button="$?"
      if [ "$Prog" == "" ]; then
			return
      fi
      HomeLink=$(echo "$PageReplay" | grep "$Prog" | grep -o 'data-href=".*' | cut -d '"' -f2 | sed -e 's|^|http://www.raiplay.it|g')
      ProgData=$($Curl -A "$UserAgent" "$HomeLink" | grep 'data-video')
      ThisLink=$(echo "$ProgData"    |  grep  -o 'data-video-url=.*' | cut -d '"' -f2)
      ThisName=$(echo "$ProgData" |  grep  -o 'data-video-title=.*' | cut -d '"' -f2 | tr ' ' '_')
#    ThisLink=$(echo "$PageReplay" | grep "$Prog" | grep -o 'data-mediapolis=".*' | cut -d '"' -f2)
      if [ "$ThisLink" == "" ]; then
         BoxTitle="Link failure"
         BoxMsg="Sorry, the $ThisName broadcast is not available"
         ShowInfo
         continue
      fi
      if [ "$Button" = "3" ]; then
		 Record
		 RecordingPids="$RecordingPids $?"
		 continue
      fi
      Cleanup
      MpvPlay=$(echo "$PlayerVod" | grep -c mpv)
      if [ "$MpvPlay" = "1" ]; then
	       PlayerVod="mpv --title='$ThisName' $MpvOpt $MpvQuality"
	  fi
      echo "$ChName: $PlayerVod $ThisLink" >> $ScriptHome/$Me.log
      dialog --title " Replay starting " --infobox "Starting a RAI Replay flow may require some time. Pls wait. " 6 30
      if [ "$Terminal" = "xterm" ]; then
	      xterm -T "'$ThisName'" $Hold $Iconic -e $PlayerVod "$ThisLink" &
      fi
      if [ "$Terminal" = "konsole" ]; then
         konsole --noclose -e $PlayerVod "$ThisLink" &  
      fi
      Running="$!"
      sleep 5
      TestPlay
  done
}
#-------------------------------------------------------------------------------------------------------------------
SetVbr () {
    while [ 1 ]; do
		VqReply=$(dialog --default-item "$VQual" --cancel-label "GoBack" --stdout --menu "Select a video quality rate " 15 50 5 1 Best  2 Lower)
		if [ "$VqReply" == "" ]; then
		   return
		fi	
        if ((VqReply >= 1 && VqReply <= 2)); then
           VQual="$VqReply"
		   if [ "$VQual" = "1" ]; then
			   LsQuality="best"
			   MpvQuality="--hls-bitrate=max"
		   else
		       LsQuality="worst"
		       MpvQuality="--hls-bitrate=min"
		   fi  
           return
        fi
    done
}
#-------------------------------------------------------------------------------------------------------------------
RadioRai () {
    StreamType="Radio"
    RadioPage=$($Curl -A "$UserAgent" "$AnchorRadio" | grep -o '{"nome":.*' | sed -e 's|},{|}\'$'\n{|g' | grep -v 'Altri')
    RadioNames=""
    RadioLinks=""
    while read RadioChan; do
         RadioName=$(echo "$RadioChan" | grep -o '"nome":.*' | cut -d '"' -f4 | tr -d ' ')
         RadioLink=$(echo "$RadioChan" | grep -o '"liveDesktop":.*' | cut -d '"' -f4)
         RadioNames="$RadioNames $RadioName"
         RadioLinks="$RadioLinks $RadioLink"   
    done <<< "$RadioPage"
    RadioMenu=$(for radio in $RadioNames; do let RadioNum++; echo $RadioNum $radio; done;let RadioNum++; echo $RadioNum RadioPlayer)
    RadioLinks=$(echo "$RadioLinks" | sed -e 's/^ //;s/ $//g')
    RadioLive=$(echo "$RadioLinks"  | wc -w)
    let MaxItems=$RadioLive+1
    while [ 1 ]; do    
		RadioChan=$(dialog --title " $Me $Version " --default-item "$RadioChan" --ok-label "Play"  --extra-button --extra-label "Record" --cancel-label "GoBack" --stdout --menu "Rai Tv Radio channels:$RadioLive > Pls select a station" 0 60 0 $RadioMenu)
		Button="$?"
		if [ "$RadioChan" == "" ]; then
			return
		fi
        ChName=$(echo "$RadioNames" | sed -e 's/^ *//g;s/ *$//g' | cut -d ' ' -f $RadioChan)
        if ((RadioChan >= 1 && RadioChan <= RadioLive)); then
            ThisLink=$(echo "$RadioLinks" | cut -d ' ' -f $RadioChan)
            Cleanup
            if [ "$Button" = "3" ]; then
	            Record
                RecordingPids="$RecordingPids $!"
	            continue
			fi
            echo "RadioRai $ChName $RadioPlayer $ThisLink" >> $ScriptHome/$Me.log
            ChName=$(echo "$ChName" | tr -d "\r\n\t ")
            Cmd="$RadioPlayer"
            if  [ "$RadioPlayer" = "vlc" ]; then
                Cmd="$RadioPlayer --meta-title=$ChName"
            fi
            if  [ "$RadioPlayer" = "mpv" ]; then
                Cmd="$RadioPlayer --title=$ChName"
            fi
            if [ "$Terminal" = "xterm" ]; then
				xterm -T "$ChName" $Iconic -e $Cmd "$ThisLink" &
			fi
			if [  "$Terminal" = "konsole" ]; then
				konsole --noclose -e $Cmd "$ThisLink" &  
           fi
           continue
        fi
        if [ "$RadioChan" = "$MaxItems" ]; then
           NewPlayer=$(dialog --stdout --inputbox " Please enter a new radio player " 0 0 $RadioPlayer) 
           if [ "$NewPlayer" != "" ]; then
              RadioPlayer="$NewPlayer"
           fi
        fi 
    done
}
#-------------------------------------------------------------------------------------------
TestPlay () {
    if [ "$Terminal" = "konsole" ]; then
       return
    fi
    if [ "$Running" != "" ]; then
       Active=$(ps -A | grep $Running)
    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
}
#-------------------------------------------------------------------------------------------------------------------
ShowMedia () {
  VQual=1
  while [ 1 ]; do
    SubType='any'
    Reply=$(dialog --title " $Me $Version $CodeName " --default-item "$DefItem" --ok-label 'Play/Set' --extra-button --extra-label 'Record' --help-button --help-label 'Rai Search' --cancel-label "Exit" --stdout --menu "Rai Tv Live channels:$LiveItems > Pls select a channel/option" 0 60 17 "${RaiMenu[@]}")
    Button="$?"
    ReplayItem=$((MenuItems-1))
    RadioRai=$((MenuItems-2))
    DefItem=`echo $Reply | awk '{print $1}'`
    if [ "$Button" = "1" ]; then
		exit
    fi
    if [ "$Reply" = "$MenuItems" ]; then
		SetVbr
        continue
    fi
    if [ "$Reply" = "$ReplayItem" ]; then
	    StreamType="Replay"
		GetChan
        continue
    fi
    if [ "$Reply" = "$RadioRai" ]; then
	    StreamType="Radio"
		RadioRai
        continue
    fi
    if [ "$Button" = "2" ]; then
	    Search
        continue
    fi
    if [ "$Reply" -le "$RadioRai" ]; then
	    StreamType="Live"
	    LinkItem="$Reply"
	    ChPageUrl=$(echo "$LiveLinks"  | sed -n "${LinkItem}p" | tr -d '\r\t\n ')
	    ChName=$(echo "$LiveNames"   | sed -n "${LinkItem}p")
	    PlayLive
	    if [ "$Button" = "3" ]; then
			continue
	    fi
	    TestPlay
	    continue
	fi
  done
}
#------------------------------------------------------------------------------------------------------------------
SetEmbedPlayer () {
    Noembed=0
    ChName=$(echo "$ChName" | tr ' ' '_')
    if [ -n "`which mpv 2>/dev/null`" ]; then
	     LsPlayer="streamlink  --title='$ChName by StreamLink' $LsOpt --player 'mpv  --autofit=800x600'"
		return
	fi
    if [ -n "`which vlc 2>/dev/null`" ]; then
		 LsPlayer="streamlink  --title='$ChName by StreamLink' $LsOpt  --player 'vlc --width 800 --height 600'"
		return
	fi
    if [ -n "`which ffplay 2>/dev/null`" ]; then
		LsPlayer="streamlink  $LsOpt  --player 'ffplay -window_title $ChName-by-StreamLink'"
		return
	fi
	Noembed=1
}
#------------------------------------------------------------------------------------------------------------------
PlayByFFmeg () {
         clear
         FFtitle=$(echo $ChName | tr -d ' ')
         echo "Using FFplay need time to probe the best VBR rate. Pls be patient"
	     AStream=$(ffprobe -hide_banner -show_streams -select_streams a "$ThisLink" | grep 'index' | tail -n 1 | cut -d '=' -f2)
	     VStream=$(ffprobe -hide_banner -show_streams -select_streams v "$ThisLink" | grep 'index' | tail -n 1 | cut -d '=' -f2)
         xterm -hold -e "ffmpeg -hide_banner -i  '"$ThisLink"'  -map 0:$AStream  -map 0:$VStream -c copy  -f mpegts - |  ffplay -hide_banner -window_title "$FFtitle" -" &
	     Running="$!"
	     sleep 3
         return
}
#------------------------------------------------------------------------------------------------------------------
PlayLive () {
    Cleanup
    LinkF4m=""
    LinkM3u8=""
    Player="$PlayerBin"
	ChName=$(echo "$ChName" | tr -d "\r\n\t " | sed -e 's|Rai|Rai |g')
    Relinker=$($Curl  -A "$UserAgent" --url "$AnchorLive/$ChPageUrl" | grep -i -o 'data-video-url.*' | cut -d '"' -f2 )
    EmbedLink=$($Curl  -A "$UserAgent" --url "$Relinker&output=45" | grep content | grep http | cut -d '>' -f2 | cut -d '<' -f1  | tr -d ' ' | tr -d '\r\n\t')
    LinkM3u8=$(echo "$EmbedLink" | grep m3u8)
    LinkF4m=$(echo "$EmbedLink"   | grep f4m)
	ThisLink="$EmbedLink"
    Title=""
     if [ "$Button" = "3" ]; then
       Record
        RecordingPids="$RecordingPids $!"
       return
    fi

     if [ "$FFmpegBroker" = "1" ]; then
		    PlayByFFmeg
			return
	 fi
     if [ "$LinkF4m" != "" ]; then
         if [ "$StreamLink" != ""  ]; then
             dialog --title " $ChName starting " --infobox " Starting $ChName using StreamLink. Need a few seconds. " 6 30
             SetEmbedPlayer
              if [ "$Noembed" = "1" ]; then
			      dialog --title " $ChName not starting " --infobox " No embed player (/mpv,ffplay,vlc) found to start  StreamLink. " 6 30
			       sleep 3
			       return
              fi
	         xterm -T "$ChName" $Hold $Iconic -e "$Player 'hds://$ThisLink' $LsQuality" &
	         echo  "$ChName Relinker:  $Relinker"  >> $ScriptHome/$Me.log
	         echo  "$ChName by StreamLink: $LsPlayer  'hds://$ThisLink' $LsQuality"  >> $ScriptHome/$Me.log
	         Running="$!"
		     sleep 3
	         return
		 else 
			 clear
			 echo "Sorry $ChName stream uses an HDS protocol, playable only using 'streamlink'."
			 echo "Pls hit ENTER to go back to the main menu'"
			 read < /dev/tty
			 return
		fi
    fi
    dialog --title "$ChName starting" --infobox "Starting $ChName using $PlayerBin " 4 30
    if [ "$PlayerBin" = "mpv" ]; then
         Title="--title='$ChName'"
    else
        MpvQuality=""
        MpvOpt=''
    fi
    if [ "$PlayerBin" = "streamlink" ]; then
		 SetEmbedPlayer
		 if [ "$Noembed" = "1" ]; then
			 dialog --title " $ChName not starting " --infobox "No embed player (/mpv,ffplay,vlc) found to start  StreamLink. " 6 30
			 sleep 3
			 return
         fi
         xterm -T "$ChName" $Hold $Iconic -e "$LsPlayer 'hlsvariant://$ThisLink' $LsQuality" &
         Running="$!"
         echo  "$ChName by $PlayerBin: $LsPlayer 'hlsvariant://$ThisLink' $LsQuality"  >> $ScriptHome/$Me.log
	     sleep 3
         return
    fi
    if [ "$Terminal" = "xterm" ]; then
       xterm -T "$ChName" $Hold $Iconic -e "$Player $Title $MpvQuality $MpvOpt '$ThisLink'" &
    fi 
    if [ "$Terminal" = "konsole" ]; then
       konsole --noclose -e $Player $Title $MpvQuality $MpvOpt "$ThisLink" &  
    fi
    Running="$!"
    echo  "$ChName Relinker:  $Relinker"  >> $ScriptHome/$Me.log
    echo  "$ChName by $PlayerBin: $Player $Title $MpvQuality $MpvOpt "$ThisLink""  >> $ScriptHome/$Me.log
    sleep 2
}
#------------------------------------------------------------------------------------------------------------------
ShowResults () {
    clear
    NextPage=0
    PrevPage=0
    ItemShown="$Psize"
    while [ 1 ];  do
        ItemAsked=$(dialog --title " $Me $Version " --default-item "$DefItem" --ok-label "Play/Record"  --extra-button --extra-label "Next Page" --help-button --help-label 'Prev Page' --cancel-label "GoBack" --stdout --menu "Catched $MaxFound items (some may be empty by RAI). Pls select one:" 0 0 25 "${SearchMenu[@]}") # $SearchMenu)
        Button="$?"
        DefItem="$ItemAsked"
        if [ "$Button" = "1" ]; then
            return
        fi
        if [ "$Button" = "2" ]  && [ "$PageNumber" -ge "$Psize" ]; then
            PageNumber=$((PageNumber-Psize))
            ItemShown=$((ItemShown-Psize))
            DefItem=1
            grabPage
            SearchPager
            continue
        fi
        if [ "$Button" = "3" ] && [ "$PageNumber" -lt "$MaxFound" ]; then
            if [ "$ItemShown" -ge "$MaxFound" ]; then
                continue
            fi
            let ItemShown=$ItemShown+$Psize
            let PageNumber=$PageNumber+$Psize
            DefItem=1
            grabPage
            SearchPager
            continue
        fi
        HandleLink
    done
}
#------------------------------------------------------------------------------------------------------------------
HandleLink () {
    if [ "$Button" = "0" ] && [ "$ItemAsked" != "" ]; then
        ThisTitle=$(echo "$Titles"  | sed -n ${ItemAsked}p)
        ThisType=$(echo "$Types" | sed -n ${ItemAsked}p)
        Relinker=$(echo "$DataPage" | head -$ItemAsked | tail -1 | awk -F '"media":{"url"' '{print $2}' | cut -d '"' -f2)
        if [ "$Relinker" = "" ]; then
            Url=$(echo "$DataPage"  | head -$ItemAsked | tail -1  | awk -F '"url"' '{print $2}' | cut -d '"' -f2 | tr -d "'")
            WebData=$($Curl  "$Url")
            VideoPage=$(echo "$Url" | grep -c '/video/')
            if [ "$VideoPage" = "1" ]; then
                Relinker=$(echo "$WebData" |  grep -m1 -o '"http://mediapolisvod.*' | cut -d '"' -f2 | tr -d ' ' | tr -d ' \n')
            else
                WebPage=$(echo  "$WebData" | grep -o 'singleVodUrl.*'  | cut -d '"' -f3)
                Relinker=$($Curl  "http://raiplay.it$WebPage" | awk -F '"contentUrl"' '{print $2}' | cut -d '"' -f2 | tr -d ' ' | tr -d ' \n')
#             Relinker=$($Curl  "http://raiplay.it$WebPage" | grep -o '"http://mediapolisvod.*' | cut -d '"' -f2 | tr -d ' ' | tr -d ' \n')
            fi
            if [ "$Relinker" = "" ]; then
                dialog --title " Stream url not found" --infobox "$ThisTitle media points to an empty url. Hit ENTER to continue" 5 50
                echo "Search: $ThisTitle >> VIDEO NOT FOUND << Url: $Url" >> $ScriptHome/$Me.log
                read < /dev/tty
                return
            fi
        fi
        Dash=$($Curl "$Relinker" | grep -c 'dash')
        if [ "$Dash" != "0" ]; then
            dialog --title " Sorry MPEG-DASH stream" --infobox "An MPEG-DASH stream (DRM LOCKED) cannot be played by $Me. Hit ENTER to continue" 5 60
            Manifest=$($Curl "$Relinker" | grep http)
            echo "Search dash: $ThisTitle  Relinker: $Relinker  ManifestUrl: $Manifest" >> $ScriptHome/$Me.log
            read < /dev/tty
            return
        fi
        if [ "$Relinker" != "" ]; then
            Summ=$(echo "$DataPage" | head -$ItemAsked | tail -1 | awk -F '"sommario"' '{print $2}' | cut -d '"' -f2)
            Summ=$(echo "$Summ" | cut -c 1-420 | sed 's/\(.*\) .*/\1/')
            if [ "$Summ" = "" ]; then
                if [ "$ThisType" != "" ]; then
                    Info="\n\n$ThisType\n\n"
                else
                    Info="\n\n"
                fi
            else
                Info="\n\n$Summ....\n\n"
            fi
            dialog --title "$Me" --yesno "Do you want: $ThisTitle ${Info}being downloaded? ESC to Go Back" 0 0 
            response=$?
            # 0 means user hit [yes] button.
            # 1 means user hit [no] button.
            # 255 means user hit [Esc] key
            if [ "$response" = "255" ]; then
                return 
            fi
            if [ "$response" = "0" ]; then
                ThisLink="$Relinker"
#             ChName="RaiPlay@${SearchArg}"
                ChName="$ThisTitle"
                Record
                return 
            else
                :
            fi
        fi
        if [ `echo "$PlayerVod" | grep -c mpv` = "1" ]; then
            Title="--title=$ThisTitle"
        fi
        if [ `echo "$PlayerVod" | grep -c vlc` = "1" ]; then
            Title="--meta-title=$ThisTitle"
        fi
        xterm -iconic -e $PlayerVod $Title "$Relinker" &
        dialog --title " Stream on the go" --infobox "The player will start in a while..." 4 40
        sleep 3
        echo "Search: $ThisTitle Cmd: $PlayerVod  $Relinker" >> $ScriptHome/$Me.log
        ItemAsked=''
    fi
}
#------------------------------------------------------------------------------------------------------------------
SearchPager () {
        ItemNum=0
        unset SearchMenu
        Dates=""; Types=""; Titles=""; Relinkers=""
        PathID=$(echo "$DataPage"  | awk -F '"url"' '{print $2}' | cut -d '"' -f2 | tr -d "'")
        for Url in $PathID; do
            if [ "$DeepInfo" = "1" ]; then
                WebData=$($Curl  "$Url")
#             echo "$WebData" > WebData.txt
            fi
            Title=$(echo "$DataPage"  | grep "$Url" | awk -F '"titolo"' '{print $2}' | cut -d '"' -f2 | tr -d '\n' | sed -e 's|^ ||g' -e 's| $||g' | tr ' ' '_' )
            Type=$(echo "$DataPage"  | grep "$Url" | awk -F '"tipo"' '{print $2}' | cut -d '"' -f2  | tr -d '\n'  | sed -e 's|^ ||g' -e 's| $||g' | tr ' ' '_' )
            if [ "$Type" = "" ]; then
                :
#             Type='n/a'
            fi
            if [ "$DeepInfo" = "1" ]; then
                Chan=$(echo "$WebData"| grep -m1 '"channel"' |awk -F '"channel"' '{print $2}' | cut -d '"' -f2 | tr -d '\n' | tr -s ' ' | tr ' ' '_')
                Date=$(echo "$WebData"| grep 'itemprop="datePublished"' | awk -F '"datePublished"' '{print $2}' | cut -d '"' -f2 | tr -d '\n' | tr -s ' ' | tr ' ' '_')
                if [ "$Chan" = "" ]; then
                     Chan='RaiPlay'
                fi
                if [ "$Date" = "" ]; then
                    Date='01-01-2010'
                fi
            else
                Chan='RaiPlay'
                Date='01-01-2010'
            fi
            Dates="$Dates $Date<>$Chan<>"
            Titles="$Titles $Title"
            Types="$Types $Type"
        done
        Dates=$(echo "$Dates"  | sed -e 's|^ ||g' -e 's| $||g' | tr ' ' '\n')
        Titles=$(echo "$Titles"    | sed -e 's|^ ||g' -e 's| $||g' | tr ' ' '\n')
        Types=$(echo "$Types"  | sed -e 's|^ ||g' -e 's| $||g' | tr ' ' '\n')
        ItemFound=$(echo "$Dates" | wc -l)
        Index=0
        for (( i = 1; i <= $ItemFound; i++ )); do
            let Index++
            ThisDate=$(echo "$Dates"  | sed -n ${Index}p)
            ThisTitle=$(echo "$Titles"   | sed -n ${Index}p)
            ThisType=$(echo "$Types"  | sed -n ${Index}p)
            if [ "$DeepInfo" = "1" ]; then
                Tags=$(echo "$ThisDate $ThisType $ThisTitle" | tr -s ' ' | sed -e 's|^ ||g' -e 's| $||g')
             else
                Tags=$(echo "$ThisType $ThisTitle" | tr -s ' ' | sed -e 's|^ ||g' -e 's| $||g')
            fi
            SearchMenu=("${SearchMenu[@]}" $Index "$Tags")
        done
}
#------------------------------------------------------------------------------------------------------------------
#------- This function basic initially written by my friend Laser :-)
#------------------------------------------------------------------------------------------------------------------
grabPage () {
        dialog --title "Search takes time....:" --infobox "Searching for >> $SearchArg <<, pls wait. " 5 50
 		Par='{"param":"'${SearchArg}'","page":'$PageNumber',"pageSize":'$Psize'}'
		RawData=$(curl -sL -H "Referer: $SearchPage" -H 'Content-Type: application/json; charset=UTF-8' -d $Par "$SearchDetail") 
# 		echo "$RawPage" > $ScriptHome/RawData.txt
		DataPage=$(echo "$RawData"  | sed -e 's|{"id"|\'$'\n{"id"|g' | sed -e "s|&quot;|'|g" -e "s|&amp;#x27;|'|g" -e "s|\&#x27;|'|g" )
		MaxFound=$(echo "$DataPage" | awk -F '"total":' '{print $2}' | cut -d ',' -f1)
# 		echo "$DataPage" > $ScriptHome/DataPage1.txt
		DataPage=$(echo "$DataPage" | grep '{"id":"ContentItem')
#		echo "$DataPage" > $ScriptHome/DataPage2.txt
}
#------------------------------------------------------------------------------------------------------------------
#------- This function basic initially written by my friend Laser :-)
#------------------------------------------------------------------------------------------------------------------
Search () {
	while true; do
		SearchArg=`dialog --colors --stdout --cancel-label "GoBack" --title " $Me $Version " --backtitle "$Fast Search Mode Enabled" --inputbox "Enter a search argument" 8 60`
		Button="$?"
		if [ "$Button" = "1" ]; then
			return
		fi
		if [ "$SearchArg" == "" ]; then
			dialog --title "Search function:" --infobox " An empty search argument is invalid " 5 41
			sleep 2
			continue
		fi
		SearchArg="${SearchArg// /%20}"
		SearchPage="$ShowallPage?q=${SearchArg}"
		PageNumber=0
		StreamType='Replay'
		SubType='Search'
		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
Live
ShowMedia
clear
exit
#------------------------------------------------------------------------------------------------------------------
