@echo Off

SETLOCAL EnableDelayedExpansion

REM   Credits for initial porting goes to @Panunzio
REM Version 3.3.0
title RaiWin (Linux original by SHOREWALL)

COLOR 1F

cls

set "ua=Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0"
set "base_url=https://www.raiplay.it"


set "homepath=%cd%"
set "m3upath=%cd%\EXE\LISTE_M3U"
set "whichhlsdl=%cd%\EXE"
set "hlsdlres=%cd%\EXE\hlsdl.exe"
set "quote=""
REM setting the path where are the EXE and REC directory
set "mypath=%cd%\EXE"
set "pathrec=%cd%\REC"


REM Auto setting your Local IP for restreaming
REM FOR /F "tokens=4 delims= " %%i in ('route print ^| find " 0.0.0.0"') do set LocalIp=%%i
FOR /f "delims=[] tokens=2" %%i in ('ping -4 -n 1 %ComputerName% ^| findstr [') do set LocalIp=%%i

REM Setting restreaming tool (hlsdl=0 or ffmpeg=1 - default=1)
REM set "ResTool=1"

REM Set record tool for .mp4 VOD  
set "Mp4Option=1"

:: set "editor=notepad"
set "editor=akelpad"

REM set "alternativeplayer=C:\Program Files (x86)\mpv\mpv"

REM setting your vlc path 64bit version (Clear REM in the line below and add REM to the other path) 
REM set "vlcpath=C:\Progra~1\videolan\vlc\vlc.exe"

REM set your vlc path 32bit version (Clear REM in the line below and add REM to the other path)
REM set "vlcpath=C:\Progra~2\videoLAN\VLC\vlc.exe" 

REM set your ffmpeg path if different
REM set "ffmpegpath=C:\Progra~1\Streamlink\ffmpeg\ffmpeg.exe"

set "info=SI"
set "TS=OFF"
set player=

if not exist REC mkdir REC

cd EXE

del *.txt 2>nul

echo  ">>> Verifica e impostazione del codepage. Pls wait <<<"
sleep 1
ver > osinfo.txt
type osinfo.txt | grep -Ec "10.0|6.3|6.2" > win10.txt
type osinfo.txt | grep -Ec "5.1|5.2" > winxp.txt
set /p win10=<win10.txt
set /p winxp=<winxp.txt
if "%win10%"=="1" ( 
CHCP 65001 2>nul
 ) else (
CHCP 850 2>nul
 )

if not exist LISTE_M3U mkdir LISTE_M3U

seq -s "_" 1 66 | tr "[:digit:]" "_" | sed -e "s|_| |" > sep.txt

call :DATECALC


if exist player.ini (
    set /P player=<player.ini 2>nul
)

if "%player%"=="" (
    echo.
    echo Nessun player impostato. Selezionarne uno proseguendo...
    echo. 
    pause
    goto :PLAYERSETUP
)

REM ========================================================
:INI

mode con: lines=29 cols=53
cls
	
set "RecRadio=0"
set "TvLive=0"

cls
echo.
echo                RAIPLAY.IT
cut -c 1-50 sep.txt
echo.
echo       First porting from Linux by Panunzio
echo       Full rework by Shorewall and Bird52
echo       Codename: No more troubles

cut -c 1-50 sep.txt
echo.   
echo     1) FILM
echo     2) SERIE ITALIANE
echo     3) SERIE INTERNAZIONALI
echo     4) BAMBINI
echo     5) TECHE RAI
echo     6) PROGRAMMI
echo     7) DOCUMENTARI
echo     8) LEARNING
echo     9) TEENS
echo    10) DIRETTE TV
echo    11) DIRETTE RADIO
echo    12) REPLAY
echo    13) CERCA
echo    14) AVVIA RESTREAMING
echo    15) SCELTA MEDIA PLAYER
echo    16) SCELTA TOOL RECORD
echo    17) LEGGI LE ISTRUZIONI
cut -c 1-50 sep.txt
echo.   
echo     0) USCITA
set /p SCE=.      SCEGLI DA 1 A 17: 

if "%SCE%"=="0" exit
if "%SCE%"=="1" set prog=film
if "%SCE%"=="2" set prog=serieitaliane
REM if "%SCE%"=="2" set "toolrec=1"
if "%SCE%"=="3" set prog=serieinternazionali
REM if "%SCE%"=="3" set "toolrec=1"
if "%SCE%"=="4" set prog=bambini
if "%SCE%"=="5" set prog=techerai
if "%SCE%"=="6" set prog=programmi
if "%SCE%"=="7" set prog=documentari
if "%SCE%"=="8" set prog=learning
if "%SCE%"=="9" set prog=teen
if "%SCE%"=="10" set prog=dirette& goto TV
if "%SCE%"=="11" set prog=https://www.raiplaysound.it& goto RAIRADIO
if "%SCE%"=="11" set "RecRadio=1"
if "%SCE%"=="12" set prog=guidatv& goto REPLAY
if "%SCE%"=="13" set prog=ricerca& goto CERCA
if "%SCE%"=="14" goto streamselect
if "%SCE%"=="15" set prog=mediaplayer& goto PLAYERSETUP
if "%SCE%"=="16" set prog=rectools& goto RECSETUP
if "%SCE%"=="17" (
    start %editor% "%homepath%\README.txt"
    cd EXE
    goto ini
)
REM if "%SCE%"=="15" goto CODEPAGE
if "%SCE%"=="" goto INI
if "%SCE%"==" " goto INI
if %SCE% LSS 1   goto INI
if %SCE% GTR 16 goto INI


call :VODSUBS

goto INI

REM ============================================
:VODSUBS

mode con: lines=5 cols=50
cls
echo.
echo.  CREAZIONE LISTA GENERI IN CORSO...
echo.  ATTENDERE!
echo.

wget -q -U "%ua%" --no-check-certificate -O - "%base_url%/tipologia/%prog%/index.json" | jq . | sed -e "s|\""|'|g"> dats.txt
call :utf dats.txt
echo.

set NewForm=false

if "%prog%"=="serieitaliane" (
    set NewForm=true
    type dats.txt | grep "'/genere/" | grep json  | cut -d "'" -f4  | sort -u > url_generi.txt
    type dats.txt | grep "'/genere/" | grep genere | grep json | tr -d "\t" | tr -d " " | sort -u | sed -e "s|^.*---||g" | cut -d "/" -f3 | sed -e "s|In-|In |" | cut -d "-" -f1 > generi.txt
)

if "%prog%"=="serieinternazionali" (
    set NewForm=true
    type dats.txt | grep "'/genere/" | grep json  | cut -d "'" -f4  | sort -u > url_generi.txt
    type dats.txt | grep "'/genere/" | grep genere | grep json | tr -d "\t" | tr -d " " | sort -u | sed -e "s|^.*---||g" | cut -d "/" -f3 | sed -e "s|In-|In |" | cut -d "-" -f1 > generi.txt
)

if "%prog%"=="documentari" (
    set NewForm=true
    type dats.txt | grep "'/genere/" | grep json  | cut -d "'" -f4  | sort -u > url_generi.txt
    type dats.txt | grep "'/genere/" | grep genere | grep json | tr -d "\t" | tr -d " " | sort -u | sed -e "s|Documentari---||g" | cut -d "/" -f3 | cut -d "-" -f1 > generi.txt
)

if "%prog%"=="film" (
    set NewForm=true
    type dats.txt | grep "'/genere/" | grep json  | cut -d "'" -f4  | sort -u > url_generi.txt
    type dats.txt | grep "'/genere/" | grep genere | grep json | tr -d "\t" | tr -d " " | sort -u | sed -e "s|^.*---||g" | cut -d "/" -f3 | sed -e "s|In-|In |" | cut -d "-" -f1 > generi.txt
    type url_generi.txt | rev | cut -d "-" -f6- | rev | tr -s "-" | sed -e "s|Film-||g" | cut -d "/" -f3 > generi.txt
)

if "%NewForm%"=="false" (
    type dats.txt | grep -A2 "'/genere/" | grep "'path_id'" | cut -d "'" -f4 > url_generi.txt
    type dats.txt | grep -A3 "'/genere/" | grep "'name'"    | cut -d "'" -f4 > generi.txt
)

call :SELECTGEN
EXIT /B

REM ===========================================  
:SELECTGEN

call :SCREENSIZER generi.txt

set /a "rows=%rows%+12"

if %cols% LSS 30 set /a "cols=%cols%+30"
set /a "seplen=%cols%-1"

mode con: lines=%rows% cols=%cols%
cls
cls
nl -s ") " generi.txt > generi_menu.txt

type sep.txt | cut -c 1-%seplen%
echo        RAIPLAY - %prog%
type sep.txt | cut -c 1-%seplen%
type generi_menu.txt 
type sep.txt | cut -c 1-%seplen%
echo     0) USCITA
echo     M) MENU' PRINCIPALE
set /p OPS=.      SCEGLI DA 1 A %numitems% : 

if "%OPS%"=="0" exit
if "%OPS%"=="m" goto INI
if "%OPS%"=="M" goto INI
if "%OPS%"=="" goto SELECTGEN
if "%OPS%"==" " goto SELECTGEN
IF %OPS% LSS 1 goto SELECTGEN
IF %OPS% GTR %numitems% goto SELECTGEN

call :LISTGEN

EXIT /B

REM ============================================
:LISTGEN
:LISTGEN

type generi.txt  | sed -n "%OPS%p" > genere.txt
set /p genere=< genere.txt

call :SCREENSIZER genere.txt

set /a cols=%cols%+42

type url_generi.txt  | sed -n "%OPS%"p > url_genere.txt
set /p url_genere=< url_genere.txt

mode con: lines=50 cols=%cols%
cls

echo.
if "%prog%"=="film" (
echo.  RECUPERO IN CORSO FILMS DI GENERE "%genere%") else (
echo.  RECUPERO IN CORSO %prog% "%genere%"
)
echo.  ATTENDERE!
echo.

wget -q -U "%ua%" --no-check-certificate -O -  "%base_url%/%url_genere%" |  jq -r ".contents[]" > dats.txt

type dats.txt | jq ".[] | select(.name != null)" | jq -r .path_id > jsonvideos.txt

type dats.txt | jq -r ".[] | select(.name != null)" | jq -r .name > names.txt

call :utf dats.txt

fart -q names.txt "?" "-"
fart -q names.txt "&" "e"
fart -q --remove names.txt \

nl -s ") " names.txt  > names_menu.txt

call :SELECTGROUP
pause
EXIT /B

REM =======================================
:SELECTGROUP

call :SCREENSIZER names.txt

set /a "rows=%numitems%+13"

if "%prog%"=="film" set /a "rows=%numitems%+16"

set /a "cols=%cols%+12"

if %rows% LSS 17 set rows=20
if %cols% LSS 50 set cols=60

set /a "seplen=%cols%-1"
mode con: lines=%rows% cols=%cols%
cls

type sep.txt | cut -c 1-%seplen%
echo       RAIPLAY - %prog% "%genere%"
type sep.txt | cut -c 1-%seplen%
type names_menu.txt | grep "."
type sep.txt | cut -c 1-%seplen%
echo.

echo     0) USCITA
echo     M) MENU' PRECEDENTE

if "%prog%"=="film" echo     I) INFORMAZIONI ^[%info%^]
if "%prog%"=="film" echo     R) REGISTRA ^[%TS%^]
if "%prog%"=="film" echo     C) APRI CARTELLA REC
if "%prog%"=="film" echo     X) CREA PLAYLIST "%prog% %genere%"
echo     U) VISUALIZZA ULTIMO LINK TROVATO
set /p OPT=.      SCEGLI DA 1 A %numitems%: 

if "%OPT%"==""  goto SELECTGROUP
echo %opt% |  tr -d " " | sed "s/[a-z]/\U&/g" > upper.tmp
set /p OPT=<upper.tmp

if "%OPT%"=="0" exit
if "%OPT%"=="M" goto SELECTGEN
if "%OPT%"=="X" goto MAKELIST
if "%OPT%"=="I" call :INF %INFO%& goto SELECTGROUP
if "%OPT%"=="U" start %editor% ulink.txt& goto SELECTGROUP
if "%OPT%"=="R" call :TS  %TS%& goto SELECTGROUP
if "%OPT%"=="C" start %SystemRoot%\explorer.exe "..\REC"& goto SELECTGROUP
IF %OPT% LSS 1 goto SELECTGROUP
IF %OPT% GTR %numitems%  goto SELECTGROUP
echo.

call :ANALIZEITEM
EXIT /B

REM ======================================
:ANALIZEITEM

type names.txt  | sed -n "%OPT%p" > thisname.txt
set /p name=< thisname.txt

wc -L thisname.txt  | tr -s " "  | cut -d " "  -f2 > namelen.txt
set /p namelen=<namelen.txt
set /a cols=%namelen%+36

mode con: lines=5 cols=%cols%
cls

echo.
if "%prog%"=="film" (
echo.  RECUPERO IN CORSO LINK DI "%name%") else (
echo.  RECUPERO IN CORSO STAGIONI DI "%name%"
)
echo.  ATTENDERE!
echo.
sleep 2
type jsonvideos.txt | sed -n "%OPT%p" > jsonvideo.txt
set /p jsonvideo=<jsonvideo.txt

wget -q -U "%ua%" --no-check-certificate -O -  "%base_url%/%jsonvideo%" | jq . | sed -e "s|\""|'|g" > dats.txt
call :utf dats.txt

type dats.txt | grep "/ContentSet-" | grep path_id | cut -d "'" -f 4 > stagioni.txt

grep -c "" stagioni.txt > numstag.txt
set /p numstag=< numstag.txt

if "%nusmtag%"=="0" goto NOSTREAM

if "%numstag%"=="1" set SR=1& call :SINGLE

call :MULTI

EXIT /B

REM =====================================
:MULTI

echo %name% | wc -L | tr -d " " > namelen.txt

set /p namelen=<namelen.txt

set /a cols=%namelen%+12

if %namelen% LSS 40 set /a cols=40

mode con: lines=14 cols=%cols%

cls
type sep.txt | cut -c 1-%cols%
echo        %name%
type sep.txt | cut -c 1-%cols%
echo        STAGIONI DISPONIBILI %numstag%
type sep.txt | cut -c 1-%cols%
echo.
echo     0) USCITA
echo     M) MENU' PRECEDENTE
set /p SR=.       SCEGLI DA 1 A %numstag%:

if "%SR%"=="0" exit
if "%SR%"=="M" goto SELECTGROUP
if "%SR%"=="m" goto SELECTGROUP
if "%SR%"=="" goto MULTI
if "%SR%"==" " goto MULTI
if %SR% LSS 1 goto MULTI
if %SR% GTR %numitems% goto MULTI

call :SINGLE

EXIT /B

REM ==================================
:SINGLE

type stagioni.txt | sed -n "%SR%p" > stagione.txt
set /p stagione=< stagione.txt

echo %name% | wc -L > namelen.txt
set /p namelen=<namelen.txt
set /a cols=%namelen%+52

mode con: lines=5 cols=%cols%
cls

echo.
echo.  RECUPERO DATI DI "%name%" IN CORSO
echo.  ATTENDERE!
echo.

wget -q -U "%ua%" --no-check-certificate -O - "%base_url%/%stagione%" | jq . | sed -e "s|\""|'|g" > dats.txt
call :utf dats.txt

type dats.txt | grep -A5 "mediapolis" | grep -E "'name'|mediapolis" > ThisStag.txt

type ThisStag.txt | grep "'video_url'"  | cut -d"'" -f 4 > links.txt

type ThisStag.txt | grep "'name'"  | cut -d"'" -f 4- | sed -e "s|',$||g"  | cut -c 1-80 > episodi.txt

fart -q episodi.txt "?" "-"
fart -q episodi.txt "&" "e"

REM ===============================================================
:SINGLERELOAD

set thisPanel=SINGLERELOAD

call :SCREENSIZER episodi.txt

type names.txt  | sed -n "%OPT%p" | tr ":" "-"> thisname.txt
set /p name=<thisname.txt

if "%prog%"=="film" (
    type links.txt > link.txt
    set /p link=<link.txt
	set /a "EPT=1"
	goto TRACKINFO
)

set /a "numitems=%rows%"
echo "%name%" | wc -L | tr -d " " > namelen.txt
set /p namelen=<namelen.txt
type episodi.txt | wc -L | tr -d " " > textlen.txt
set /p textlen=<textlen.txt
set /a cols=%textlen%+22

if %namelen% GTR %textlen% (
    set /a cols=%namelen%+20
)

if %textlen% GTR %namelen% (
    set /a cols=%textlen%+20
)

set /a "rows=%rows%+20"

if %rows% LSS 18 set rows=20
if %cols% LSS 45 set cols=45
set /a "seplen=%cols%-1"
mode con: lines=%rows% cols=%cols%
cls

nl -s ") " episodi.txt > episodi_menu.txt

type sep.txt | cut -c 1-%seplen%
echo        %name% (STAGIONE %SR%)
echo.
echo        ELENCO EPISODI
type sep.txt | cut -c 1-%seplen%
echo.
type episodi_menu.txt 
type sep.txt | cut -c 1-%seplen%
echo.
echo     0) USCITA
echo     M) MENU' PRECEDENTE
echo     I) INFORMAZIONI ^[%info%^]
echo     R) REGISTRA ^[%TS%^]
echo     C) APRI CARTELLA REC
echo     X) CREA PLAYLIST "%name%"
echo     U) VISUALIZZA ULTIMO LINK TROVATO
echo.
set /p EPT=.      SCEGLI DA 1 A %numitems%:

if "%EPT%"=="" goto SINGLERELOAD

echo %EPT% |  tr -d " " | sed "s/[a-z]/\U&/g" > upper.tmp
set /p EPT=<upper.tmp

if "%EPT%"=="0" exit
if "%EPT%"=="M" goto SELECTGROUP
if "%EPT%"=="I" call :INF %INFO%& goto SINGLERELOAD
if "%EPT%"=="R" call :TS %TS%& goto SINGLERELOAD& pause
if "%EPT%"=="C" start %SystemRoot%\explorer.exe "..\REC"& goto SINGLERELOAD
if "%EPT%"=="X" goto MAKELIST
if "%EPT%"=="U" start %editor% ulink.txt& goto SINGLERELOAD
IF %EPT% LSS 1 goto SINGLERELOAD
IF %EPT% GTR %numitems% goto SINGLERELOAD

type episodi.txt  | sed -n "%EPT%p" > episodio.txt
set /p episodio=<episodio.txt

awk "{print length}" episodio.txt > cols.txt
set /p cols=< cols.txt
set /a cols=cols+42

type links.txt | sed -n "%EPT%p" > link.txt
set /p link=<link.txt

call :TRACKINFO

EXIT /B

REM =======================================
:TRACKINFO

set /p link=<link.txt
set /a cols=%namelen%+28

if NOT "%prog%"=="radio" (
    if "%info%"=="SI" (
		mode con: lines=5 cols=%cols%
		cls	
        echo.
        echo.  RECUPERO IN CORSO INFO DI 
		echo   "%name%"
		echo.
        echo.  ATTENDERE!
        echo.
        call  :INFO
        call  :SHOWINFO
    )
)

REM ======================================
:TRACKLINK

set /a cols=%namelen%+42
mode CON:lines=5 cols=%cols%
cls
echo.
echo.  RECUPERO IN CORSO DEL LINK DI:
echo   "%name%"
echo.  ATTENDERE!
echo.
ping localhost -n 2 >nul
set /p link=<link.txt
set /a cols=%cols%+42
if "%searchmp4%"=="1" (
curl -sL -A "raiweb" --head %link% | grep Location | grep -o http.* > linkmp4.txt
set /p linkmp4=<linkmp4.txt
  )

sleep 1

echo TITOLO: %name% >> ulink.txt
echo LINK:  "%link%" >> ulink.txt

if "%TS%"=="ON" goto REC

call :RUN_PLAYER

/EXIT B

REM ===============================================
:REC

mode con: lines=29 cols=53
cls
cd %mypath%
set /P ffmpegpath=<ffmpeg.ini
set /P rectool=<recordtool.ini

set /a cols=%namelen%+50
set ffmpegdir=%quote%%ffmpegpath%%quote%

mode con: lines=10 cols=%cols%
cls

>name.txt echo %episodio%


type name.txt | sed "s# #_#g; s#:#-#g; s#\/#-#g" > nam.txt
set /p nam=<nam.txt

if "%RecRadio%"=="1" (
type name.txt | sed "s/\x22//g" > namerecradio.txt
  set /p name=<namerecradio.txt
   )
   
   
set "RECVQ=-b"
REM if "%searchmp4%"=="1" call :recmp4 
if %rectool%==HLSDL (
echo.
echo.  SCEGLIERE LA QUALITA' DI REGISTRAZIONE
echo.  PER IL FILE %name% ?
echo.
echo.  S= SCELTA DELLA QUALITA'
echo.  TASTO INVIO= MASSIMA QUALITA' DISPONIBILE
echo.
set /p EPT=.      SCEGLI 'S' o 'INVIO'

if "%EPT%"=="S" set "RECVQ="
if "%EPT%"=="s" set "RECVQ=" 
  )
if %cols% LSS 58 set cols=58

mode con: lines=12 cols=%cols%
cls
   
echo.
echo   NELLA CARTELLA REC SI STA SCARICANDO IL FILE:

if "%RecRadio%"=="0" echo   %name%.mp4 
if "%RecRadio%"=="1" echo   %name%.aac 

echo.
echo   LO STATO DELLA REGISTRAZIONE E' VISIBILE NELLA
echo   FINESTRA DEL RECORDER
echo   PER INTERROMPERLA CHIUDERE LA FINESTRA
echo.
sleep 7

if "%RecRadio%"=="0" set outfile="%pathrec%\%name%.mp4"
if "%RecRadio%"=="1" set outfile="%pathrec%\%name%.aac"


cd %whichhlsdl%
   
if "%RecRadio%"=="0" if %rectool%==HLSDL start hlsdl.exe %RECVQ% -o %outfile% "%link%&output=7" 
if "%RecRadio%"=="0" if %rectool%==FFMPEG start cmd.exe /k "%ffmpegdir% -user_agent "Raiweb 999" -i "%link%" -acodec aac -f mpegts %outfile%"
if "%RecRadio%"=="1" start hlsdl.exe %RECVQ% -f -o  %outfile% "%link%"
REM if "%RecRadio%"=="1" start cmd.exe /k "%ffmpegpath% -y -i %link% -acodec libmp3lame %outfile%"

cd %mypath%
set TS=OFF

if "%prog%"=="film" goto SELECTGROUP
if "%prog%"=="dirette" goto LSC
if "%prog%"=="https://www.raiplaysound.it" goto RSC
if "%prog%"=="guidatv" goto PSC
if "%prog%"=="ricerca" goto CER
goto SELECTGROUP

REM ===============================================

:TS
    if "%1"=="OFF" set TS=ON
    if "%1"=="ON"  set TS=OFF
EXIT /B

:INF
    if "%1"=="NO" set info=SI
    if "%1"=="SI"   set info=NO
EXIT /B

REM ========================================
:INFO

if "%prog%"=="ricerca" (
    type itemjson.txt | grep "description" | grep description | sed -n 1p | tr -s " " | cut -d "'" -f4-  | sed -e "s|',$||g" > inf.txt
) else (
    type dats.txt | grep "'description':" | cut -d "'" -f 4- | sed -e "s|',||g" > infs.txt
    type infs.txt | sed -n "%EPT%p" > inf.txt
)

type inf.txt | wc -L > cols.txt
set /p thisfold=<cols.txt

if %thisfold% GTR 60 set /a "thisfold=60"
if %thisfold% LSS 30 set /a "thisfold=60"
if %thisfold% LSS %namelen% set /a "thisfold=%namelen%+5"

fold -s -w %thisfold% inf.txt  | sed "s/^/   /g" > folded.txt

type folded.txt | grep . | wc -l | tr -d " " > rows.txt

set /p rows=<rows.txt

if "%rows%"=="0" (
    echo        Info non disponibili  > folded.txt
)
set /a "rows=%rows%+15"
set /a "cols=%thisfold%%+5"

EXIT /B

REM ==============================================
:SHOWINFO

fart -q --remove folded.txt \ 

mode con: lines=%rows% cols=%cols%
cls
type sep.txt | cut -c 1-%thisfold%
echo.
echo.  %name%
type sep.txt | cut -c 1-%thisfold%
echo.
type folded.txt
type sep.txt | cut -c 1-%thisfold%
echo.
echo    0) USCITA
echo    M) MENU' PRECEDENTE
echo    A) AVVIA RECUPERO LINK
echo.
set /p OR=.     SCEGLI: 

if "%OR%"=="" goto SHOWINFO
echo %OR% |  tr -d " " | sed "s/[a-z]/\U&/g" > upper.tmp
set /p OR=<upper.tmp

if "%OR%"=="0" exit
if "%OR%"=="M" (if "%prog%"=="guidatv" goto PSC)
if "%OR%"=="M" (if "%prog%"=="film" goto SELECTGROUP)
if "%OR%"=="M" (if "%prog%"=="ricerca" goto CER)
if "%OR%"=="M" goto SINGLERELOAD
if "%OR%"=="A" EXIT /B
if "%OR%"==" "  goto SHOWINFO
goto SHOWINFO
EXIT /B

REM ===========================================
:MAKELIST

if "%prog%"=="film" goto MAKELIST2

rem if "%prog%"=="ricerca" set "name="& set "SR=1"

type episodi.txt | wc -l tr -d " " > numitems.txt
set /p numitems=<numitems.txt

echo %name% | tr -s " " | tr " ?" "_-" > name.txt

fart -q --remove \ name.txt

type name.txt | wc -L > namelen.txt

set /p name=<name.txt
set /p cols=<namelen.txt+35

del "%genere%_%name%_S.%SR%".txt 2>nul

echo #EXTM3U > "%genere%_%name%_S.%SR%".txt

set "con=1"

mode con: lines=4 cols=%cols%
cls

echo.
echo   CREAZIONE PLAYLIST IN CORSO...
echo.


del jsonvideo.txt 2>nul
del jsonvid.txt   2>nul 
del link.txt      2>nul 

set "jsonvideo="
set "jsonvid="
set "link="

REM ======================================
:LOOP

type episodi.txt  | sed -n "%con%p" > episodio.txt
set /p episodio=< episodio.txt

type links.txt  | sed -n "%con%p" > link.txt
set /p link=< link.txt

echo #EXTINF:-1,"%episodio%" >> "%genere%_%name%_S.%SR%".txt

echo "%link%" | sed -e "s|\""||g" >> "%genere%_%name%_S.%SR%".txt

mode con: lines=6 cols=80
cls

echo.
echo   ELABORAZIONE: %con%/%numitems%
echo   TITOLO SHOW:  %episodio%
echo   LINK: %link%
echo.

set /a con=%con% + 1

if %con% GTR %numitems% goto stop

goto LOOP

:STOP

fart -q --remove "%genere%_%name%_S.%SR%".txt \

type "%genere%_%name%_S.%SR%".txt | grep -Eo "http.*|#EXT.*" | tr -d "\t" > "%m3upath%\%genere%_%name%_S.%SR%".m3u

type "%m3upath%\%genere%_%name%_S.%SR%".m3u | grep -c "http" > tot.txt
set /p tot=< tot.txt
type "%m3upath%\%genere%_%name%_S.%SR%".m3u | wc -L > cols.txt
set /p rows=< cols.txt

set /a cols=%cols%+20
if %cols% LSS 57 set cols=57

mode con: lines=8 cols=%cols%
cls

echo.
echo    TROVATI %tot% TITOLI VALIDI SU %numitems% DI PARTENZA
echo    E' STATA CREATA LA LISTA
echo    "%genere%_%name%_S.%SR%.m3u"
echo    NELLA CARTELLA EXE\LISTE_M3U
echo    PREMERE UN TASTO PER VISUALIZZARLA NEL BLOCCO NOTE.
echo.
pause > nul

mode con: lines=15 cols=%lus%
cls

start %editor% "%m3upath%\%genere%_%name%_S.%SR%.m3u"
pause
if "%prog%"=="ricerca" goto CER

goto SELECTGROUP

:MAKELIST2

del "Films_rai_%genere%.txt" 2>nul

echo #EXTM3U > "%m3upath%\Films_rai_%genere%.m3u"

set "con=1"

type jsonvideos.txt | wc -l | tr -d " " > numitems.txt
set /p numitems=<numitems.txt

mode con: lines=4 cols=34
cls

echo.
echo   CREAZIONE PLAYLIST IN CORSO...
echo.

:LOOP2

if exist jsonvideo.txt del jsonvideo.txt
if exist jsonvid.txt del jsonvid.txt
if exist link.txt del link.txt

set "jsonvideo="
set "jsonvid="
set "link="

type names.txt  | sed -n "%con%p" > name.txt
set /p name=<name.txt

type jsonvideos.txt | sed -n "%con%p" > jsonvideo.txt
set /p jsonvideo=<jsonvideo.txt

wget -q -U "%ua%" --no-check-certificate -O - "%base_url%/%jsonvideo%" | sed -e "s|\""|'|g" > dats.txt
call :utf dats.txt

type dats.txt | grep -o "'first_item_path' : '[^']*" | cut -d"'" -f 4 > jsonvid.txt
set /p jsonvid=<jsonvid.txt

wget -q -U "%ua%" --no-check-certificate -O - "%base_url%/%jsonvid%" | sed -e "s|\""|'|g" > dats.txt
call :utf dats.txt

type dats.txt | grep -o "'content_url'.*" | cut -d"'" -f 4 > link.txt

set /p link=<link.txt

echo #EXTINF:-1,"%name%" >>"Films_rai_%genere%".txt

echo "%link%" | sed -e "s|\""||g" >>"Films_rai_%genere%".txt

mode con: lines=6 cols=130
cls

echo.
echo   ELABORAZIONE: %con%/%numitems%
echo   TITOLO FILM:  %name%
echo   LINK: %link%
echo.

set /a con=%con% + 1

if %con% GTR %numitems% goto stop2

goto LOOP2

:STOP2

mode con: lines=7 cols=70
cls

fart -q "Films_rai_%genere%".txt """" "@"

type "Films_rai_%genere%".txt | sed -n "/\"\"/{s/.*//;x;d;};x;p;${x;p;}"  | sed "s/[ \t]*$//" | sed "/^$/d" | tr -d "@" > "%m3upath%\Films_rai_%genere%".m3u

type "%m3upath%\Films_rai_%genere%".m3u | grep -c "http" > nn.txt
set /p tot=<nn.txt

echo.
echo    TROVATI %tot% TITOLI VALIDI SU %numitems% DI PARTENZA
echo    E' STATA CREATA LA LISTA "Films_rai_%genere%.m3u"
echo    NELLA CARTELLA %m3upath%
echo    PREMERE UN TASTO PER VISUALIZZARLA NEL BLOCCO NOTE.
echo.

pause > nul

start %editor% "%m3upath%\Films_rai_%genere%.m3u"

goto SELECTGROUP

:NOSTREAM

mode con: lines=6 cols=34
cls

echo.
echo   NESSUN FLUSSO VIDEO TROVATO!
echo.

ping localhost -n 3 >nul

goto SELECTGROUP

REM =================================================

:TV
set "TvLive=1"
mode con: lines=7 cols=40
cls
echo.
echo.  CREAZIONE LISTA IN CORSO...
echo.  ATTENDERE!
echo.

wget -q -U "%ua%" --no-check-certificate -O -  "https://www.raiplay.it/dirette.json" | jq . > dats.txt

:LSC

type dats.txt | jq -r .contents[].channel > livenames.txt

type dats.txt  | jq -r .contents[].video.content_url | sed -e "s|https|https|g" > liveurls.txt

awk "BEGIN {a=0}; {if (length() > a) a = length()}; END {print a}" livenames.txt > cols.txt
set /p cols=< cols.txt

grep -c "" livenames.txt > rows.txt
set /p rows=< rows.txt
set "numitems=%rows%"

set /a "rows=%rows%+15"
set /a "cols=%cols%+2"

if %rows% LSS 15 set rows=15
if %cols% LSS 55 set cols=55

mode con: lines=%rows% cols=%cols%
cls
set /a "seplen=%cols%-1"
echo.
echo        RAIPLAY - DIRETTE TV
type sep.txt | cut -c 1-%seplen%
nl -s ") " livenames.txt
type sep.txt | cut -c 1-%seplen%
echo.
echo     0) USCITA
echo     M) MENU' PRINCIPALE
echo     R) REGISTRA ^[%TS%^]
echo     C) APRI CARTELLA REC
echo     U) VISUALIZZA ULTIMO LINK TROVATO
set /p reply=.      SCEGLI DA 1 A %numitems%:  

if "%reply%"=="" goto LSC
echo %reply% |  tr -d " " | sed "s/[a-z]/\U&/g" > upper.tmp
set /p reply=<upper.tmp

if "%reply%"=="0" exit
if "%reply%"=="M" goto INI
if "%reply%"=="m" goto INI
if "%reply%"=="R" call :TS %TS%& goto LSC
if "%reply%"=="C" start %SystemRoot%\explorer.exe "..\REC"& goto LSC
if "%reply%"=="U" start %editor% ulink.txt& goto LSC
IF %reply% LSS 1   goto LSC
IF %reply% GTR %numitems% goto LSC

type livenames.txt  | sed -n "%reply%p" > name.txt
set /p name=<name.txt
if "%name%"=="Rai 4K" (
cls
echo ------------------------------------------------
echo. ATTENZIONE: IL CANALE RAI 4K NON E' DISPONIBILE
echo ------------------------------------------------
pause
goto :LSC
  )

echo "%name%" | wc -L | tr -d " " > cols.txt
set /p cols=<cols.txt
set /a cols=%cols%+28

type liveurls.txt  | sed -n "%reply%p" > liveurl.txt
type liveurls.txt  | sed -n "%reply%p" > relinker.txt
type liveurls.txt  | sed -n "%reply%p" > link.txt
set /p liveurl=<liveurl.txt
set /p link=<liveurl.txt

mode con: lines=5 cols=%cols%
cls

echo.
echo.  RECUPERO IN CORSO LINK DI "%name%"
echo.  ATTENDERE!
echo.

rem wget -q -U "%ua%" --no-check-certificate -O - "%liveurl%" | sed -e "s|\""|'|g" > relinker.txt
rem wget -q -U "%ua%" --no-check-certificate -O - "%liveurl%" > link.txt

set "episodio=%name%"

call :TRACKLINK
if "%TvLive%=="1" (
  GOTO :INI
   )
goto LSC

REM =================================================
:RAIRADIO

mode con: lines=7 cols=32
cls

echo.
echo.  CREAZIONE LISTA IN CORSO...
echo.  ATTENDERE!
echo.

wget -q -U "%ua%" --no-check-certificate -O - "%prog%/dirette.json" | jq.exe -r .contents  > dats.txt

type dats.txt | grep "palinsesto_name" | cut -d ":" -f2 | tr -d "," |sed "s/\&egrave;/e/g"  > radionames.txt
type radionames.txt | grep -n "" | tr -d "," | sed "s/\x22//g; 1,9 s/^/    /; 10,99 s/^/   /; 100,999 s/^/  /; 1000,9999 s/^/ /; s/:/) /"  > rnames.txt
type dats.txt | grep "mediapolis.rai.it/relinker" | grep -o "http.*" | cut -d "'" -f2 | tr -d """" | tr -d "," > radiourls.txt 

call :SCREENSIZER rnames.txt

:RSC


set /a "rows=%rows%+13"
set /a "cols=%cols%+8"

if %rows% LSS 13 set rows=13
if %cols% LSS 45   set cols=45

mode con: lines=%rows% cols=%cols%
cls

echo.
echo        RAIPLAY - DIRETTE RADIO
type sep.txt | cut -c 1-32
type rnames.txt
type sep.txt | cut -c 1-32
echo.
echo     0) USCITA
echo     M) MENU' PRINCIPALE
echo     R) REGISTRA ^[%TS%^]
echo     C) APRI CARTELLA REC
echo     U) VISUALIZZA ULTIMO LINK TROVATO
set /p OR=.      SCEGLI DA 1 A %numitems%: 

if "%OR%"=="" goto RSC
echo %OR% |  tr -d " " | sed "s/[a-z]/\U&/g" > upper.tmp
set /p OR=<upper.tmp

if "%OR%"=="0" exit
if "%OR%"=="M" goto INI
if "%OR%"=="R" call :TS %TS%& goto RSC
if "%OR%"=="C" start %SystemRoot%\explorer.exe "..\REC"& goto RSC
if "%OR%"=="U" start %editor% ulink.txt& goto RSC
iF %OR% LSS 1 goto RSC
IF %OR% GTR %numitems% goto RSC

type radionames.txt  | sed -n "%OR%p" > name.txt
set /p name=<name.txt

awk "{print length}" name.txt> cols.txt
set /p cols=<cols.txt

set /a cols=cols+33
type radiourls.txt | sed -n "%OR%p" > link.txt

set "episodio=%name%"
set /a "rows=%rows%-13"
set /a "cols=%cols-8"
set "RecRadio=1"
call :TRACKLINK

goto RSC

REM =============================================
:REPLAY

set "EPT=1"

mode con: lines=5 cols=32
cls

echo.
echo.  CREAZIONE LISTA IN CORSO...
echo.  ATTENDERE!
echo.

wget -q -U "%ua%" --no-check-certificate -O - "%base_url%/%prog%/" | sed -e "s|\""|'|g" > dats.txt

type dats.txt | grep -o "<rai-tv-guide channels=.*" | awk -F "}]" "{print $1}" > redata.txt

type redata.txt | sed -e "s|'label'|\n'label'|g" | grep -v "RaiScuola\|RaiNews24\|RaiSport\|RaiPlay" | grep -o "'name'.*"  | cut -d "'" -f 4 > rechans.txt

type redata.txt  | sed -e "s|'label'|\n'label'|g" | grep -v "RaiScuola\|RaiNews24\|RaiSport\|RaiPlay" | grep -o "absolute_path.*" | cut -d "'" -f 3 > reurls.txt

nl -s ") " rechans.txt  > renames.txt

:RESC

call :SCREENSIZER renames.txt

set /a "rows=%rows%+12"

set /a "cols=%cols%+2"
if %rows% LSS 4 set rows=4

if %cols% LSS 50 set cols=50

mode con: lines=%rows% cols=%cols%
cls

echo.
echo        RAI REPLAY 
echo        PROGRAMMI DELLA SETTIMANA TRASCORSA
type sep.txt | cut -c 1-40
type renames.txt
type sep.txt | cut -c 1-40
echo.
echo     0) USCITA
echo     M) MENU' PRECEDENTE
set /p RE=.      SCEGLI DA 1 A 10: 

if "%RE%"=="0" exit
if "%RE%"=="m" goto INI
if "%RE%"=="M" goto INI
if "%RE%"=="" goto RESC
if "%RE%"==" " goto RESC
if %RE% LSS 1 goto RESC
if %RE% GTR %numitems% goto RESC

type rechans.txt | sed -n "%RE%p" > rechan.txt
set /p rechan=<rechan.txt

awk "{print length}" rechan.txt> cols.txt
set /p cols=<cols.txt

set /a cols=cols+42

type reurls.txt | sed -n "%RE%p" > reurl.txt
set /p reurl=<reurl.txt

REM ============================================

:SELECTDAY

mode con: lines=17 cols=50
cls

echo.
echo     Seleziona il giorno:
echo    ______________________________________
echo.
type    weekrenum.txt
echo    ______________________________________
echo.
echo      M) Torna indietro
echo.   
set /p DAY=.       Scegli un giorno: 

if "%DAY%"=="m"	  goto RESC
if "%DAY%"=="M"   goto RESC
if "%DAY%"==""    goto SELECTDAY
if "%DAY%"==" "   goto SELECTDAY
if %DAY% LSS 1    goto SELECTDAY
if %DAY% GTR 7    goto SELECTDAY

type  week.txt | cut -d " " -f1  | sed -n %day%p > thisday.txt
set /p currentdate=<thisday.txt
type  week.txt | cut -d " " -f2- | sed -n %day%p > thisday.txt
set /p giorno=<thisday.txt

REM ============================================ 

:GETPROGSOFTHEDAY

awk "{print length}" rechan.txt> cols.txt
set /p cols=<cols.txt
set /a cols=cols+42

mode con: lines=6 cols=%cols%
cls

echo.
echo.  RECUPERO IN CORSO LISTA PROGRAMMI DI "%rechan%"
echo.  GIORNO: "%giorno% %currentdate%"
echo.  ATTENDERE!
echo.

wget -q -U "%ua%" --no-check-certificate -O - "%base_url%/palinsesto/guidatv/%reurl%/%currentdate%.html" | sed -e "s|\""|'|g" | sed -e "s|data-pathdl=|\ndata-pathdl=|g"> pdata.txt
call :utf pdata.txt

type pdata.txt | grep "data-href='" | grep -o "class='info'.*" | cut -d ">" -f 2 | cut -d "<" -f1 > pros.txt

type pdata.txt | grep "data-href='" | grep -o "data-ora.*" | cut -d "'" -f 2 > ora.txt

type pdata.txt | grep -o "data-href='.*" | cut -d "'" -f 2 | sed -e "s|.html|.json|g" > purls.txt

awk "NR==FNR{a[FNR]=$0;next} {print a[FNR],\"-\",$0}" ora.txt pros.txt > sched.txt

nl -s ") " sched.txt  | cut -c 1-80 > pnames.txt

:PSC

call :SCREENSIZER pnames.txt

set /a rows=%rows%+15
set /a cols=%cols%+15 
 

mode con: lines=%rows% cols=%cols%
cls

fart -q --remove pnames.txt \ 

echo.
echo.   PROGRAMMI DISPONIBILI DI %rechan% DI %giorno% %currentdate%
type sep.txt | cut -c 1-%cols%
type pnames.txt 
type sep.txt | cut -c 1-%cols%
echo.
echo     0) USCITA
echo     M) MENU' PRECEDENTE
echo     I) INFORMAZIONI ^[%info%^]
echo     R) REGISTRA ^[%TS%^]
echo     C) APRI CARTELLA REC
echo     U) VISUALIZZA ULTIMO LINK TROVATO
set /p reply=.      SCEGLI DA 1 A %numitems%: 

if   "%reply%"=="" goto PSC
echo %reply% |  tr -d " " | sed "s/[a-z]/\U&/g" > upper.tmp
set /p reply=<upper.tmp

if "%reply%"==" " goto PSC
if "%reply%"=="0" exit
if "%reply%"=="M" goto SELECTDAY
if "%reply%"=="I" call :INF %INFO%& goto PSC
if "%reply%"=="R" call :TS %TS%& goto PSC
if "%reply%"=="C" start %SystemRoot%\explorer.exe "..\REC"& goto PSC
if "%reply%"=="U" start %editor% ulink.txt& goto PSC
if %reply% LSS 1 goto PSC
if %reply% GTR %numitems% goto PSC

type pros.txt  | sed -n "%reply%p" > name.txt
set /p name=<name.txt

awk "{print length}" name.txt> cols.txt
set /p cols=<cols.txt
set /p namelen=<cols.txt


set /a cols=%cols%+33

type purls.txt  | sed -n "%reply%p" > purl.txt
set /p purl=<purl.txt

echo "RECUPERO IN CORSO LINK DI %name%   " | wc -L | tr -d " " > cols.txt
set /p cols=<cols.txt
mode con: lines=5 cols=%cols%
cls

echo.
echo.  RECUPERO IN CORSO LINK DI "%name%"
echo.  ATTENDERE!
echo.

wget -q -U "%ua%" --no-check-certificate -O - "%base_url%/%purl%" | jq . | sed -e "s|\""|'|g" > dats.txt

set "episodio=%name%"
type dats.txt | grep -o "content_url'.*" | cut -d"'" -f 3  > link.txt
set /p link=<link.txt

call :TRACKINFO

goto PSC

REM =========================================
:CERCA

mode con: lines=10 cols=60
cls

echo.
echo            RAI REPLAY - CERCA ARGOMENTO
type sep.txt | cut -c 1-57
echo.   INSERISCI UNA O PIU' PAROLE CHIAVE NON ACCENTATE
echo.   NELLO SPAZIO SOTTOSTANTE E PREMI INVIO:
echo.   (SPAZIO PER TORNARE AL MENU' INIZIALE)
echo.
set /p PA=-^>

if "%PA%"=="" goto INI
if "%PA%"==" " goto INI

set "genere=%PA%"

>argomento.txt echo %PA%

type argomento.txt | sed "s# #+#g" > arg.txt
set /p arg=<arg.txt

awk "{print length}" argomento.txt> cols.txt
set /p cols=<cols.txt

set /a cols=cols+50

mode con: lines=5 cols=%cols%
cls

echo.
echo.  RICERCA IN CORSO DEI VIDEO PER "%PA%"
echo.  ATTENDERE!
echo.

curl -sLk -A "%ua%" -H "Referer: %base_url%/%prog%.html?q=%arg%" -H "Content-Type: application/json; charset=UTF-8" -d {\"param\":\"%arg%\",\"page\":\"0\",\"pageSize\":\"100\"} "https://www.raiplay.it/atomatic/raiplay-search-service/api/v3/search" | jq . | sed -e "s|\""|'|g" > rawdata.txt

:CER
type rawdata.txt | sed -e "s|&quot;|'|g" -e "s|\&amp;|\&|g" -e "s|&amp;#x27;|'|g" -e "s|\&#x27;|'|g" -e "s|\&amp;|\&|g" > datatemp.txt

type datatemp.txt | grep -Eo "'titolo':.*|'url':.*|'path_id':.*|'id'.*|'programma'.*" >  datapage.txt

fart -q --remove datapage.txt \ 

type datapage.txt | grep "'path_id':" | cut -d"'" -f 4 > links.txt
type datapage.txt | grep "'titolo'" | sed -e "s|',||g" | cut -d "'" -f4- > episodi.txt

type episodi.txt | wc -L | tr -d " " > cols.txt
set /p cols=< cols.txt
grep -c "" episodi.txt > rows.txt
set /p rows=< rows.txt
set "numitems=%rows%"
set /a "rows=%rows%+18"
set /a "cols=%cols%+2"

if %rows% LSS 18 set rows=18
if %cols%  LSS 80 set cols=80

mode con: lines=%rows% cols=%cols%
cls

call :utf episodi.txt

nl -s ") " episodi.txt | cut -c 1-80 > episodi_menu.txt

type sep.txt | cut -c 1-%cols%
echo        ELENCO DEI VIDEO TROVATI PER "%PA%"
echo        ATTENZIONE: ALCUNI TITOLI NON SEMPRE DISPONIBILI SUL SITO RAI
type sep.txt | cut -c 1-%cols%
type episodi_menu.txt
type sep.txt | cut -c 1-%cols%
echo.
echo     0) USCITA
echo     M) MENU' PRECEDENTE
echo     G) PAGINA INIZIALE
echo     I) INFORMAZIONI ^[%info%^]
echo     R) REGISTRA ^[%TS%^]
echo     C) APRI CARTELLA REC
REM echo     X) CREA PLAYLIST "%PA%"
echo     U) VISUALIZZA ULTIMO LINK TROVATO
set /p EPT=.      SCEGLI DA 1 A %numitems%:

if "%EPT%"=="" goto CER
echo %EPT% |  tr -d " " | sed "s/[a-z]/\U&/g" > upper.tmp
set /p EPT=<upper.tmp

if "%EPT%"=="0" exit
if "%EPT%"=="M" goto CERCA
if "%EPT%"=="G" goto INI
if "%EPT%"=="I" call :INF %INFO%& goto CER
if "%EPT%"=="R" call :TS %TS%& goto CER
if "%EPT%"=="C" start %SystemRoot%\explorer.exe "..\REC"& goto CER
if "%EPT%"=="X" goto MAKELIST
if "%EPT%"=="U" start %editor% ulink.txt& goto CER
IF %EPT% LSS 1 goto CER
IF %EPT% GTR %numitems% goto CER

type episodi.txt  | sed -n "%EPT%p" > episodio.txt
set /p name=<episodio.txt

echo %name% | wc -L | tr -d " " > namelen.txt
set /p namelen=<namelen.txt
set /a cols=%namelen%+42

mode con: lines=5 cols=%cols%
cls

echo.
echo.  RECUPERO DATI IN CORSO DI "%name%"
echo.  ATTENDERE!
echo.

type links.txt | sed -n "%EPT%p" > Jsonlink.txt
set /p jsonlink=<jsonlink.txt
wget -q -U "%ua%" --no-check-certificate -O - "%base_url%/%jsonlink%" | jq .| sed -e "s|\""|'|g" > itemjson.txt
call :utf itemjson.txt

set /a cols=%namelen%+42

:EXTRACTLINK

echo. 2>>link.txt
set link=
set "episodio=%name%"

>name.txt echo %name%


type itemjson.txt | grep -o "https://mediapolisvod.*" | cut -d "'" -f1 > link.txt

set /p link=<link.txt

if "%link%"=="" (
echo.
echo.  RECUPERO IN CORSO DEL LINK DI "%name%"
echo.  LIVELLO 2 ATTENDERE!
echo.
goto NEXTJSON
)

goto TRACKLINK

:NEXTJSON

type ItemJson.txt | grep -o "first_item_path.*" | cut -d "'" -f3 | cut -d "/" -f2- > jlink.txt
set /p jlink=<jlink.txt

wget -q -U "%ua%" --no-check-certificate -O - "%base_url%/%jlink%" | sed -e "s|\""|'|g" > thisjson.txt

type thisjson.txt | grep -o "https://mediapolisvod.*" | cut -d "'" -f1 > link.txt

set /p link=<link.txt

if "%link%"=="" (
echo.
echo.  RECUPERO DEL LINK DI "%name%" FALLITO
goto CER
)

goto TRACKLINK

REM =================================================
:RECSETUP
mode con: lines=27 cols=60
cls
echo     SCEGLI IL TOOL PER REGISTRARE
type sep.txt | cut -c 1-45 
echo. 
echo     1) HLSDL
echo     2) FFMPEG (controlla prima se e' installato)
echo     0) ANNULLA
echo.
set /p SelRec=.  SCEGLI DA 1 A 3 (0 per annullare):
REM if "%SelRec%"=="1" set "toolrec=0"
if "%SelRec%"=="1" set "whichrec=HLSDL"
REM if "%SelRec%"=="2" set "toolrec=1"
if "%SelRec%"=="2" set "whichrec=FFMPEG"
if "%SelRec%"=="0" goto INI
echo !whichrec! > recordtool.ini
echo.
echo Hai scelto %whichrec% come tool per registrare
if "%whichrec%"=="FFMPEG" (
echo. 
echo Con FFMPEG controlla prima se l'hai installato
  )
echo.
pause
goto INI

REM =================================================

REM =================================================
:RUN_PLAYER

if "%prog%" NEQ "dirette" (
 if "%prog%" NEQ "https://www.raiplaysound.it" (
  call :INFO
  call :SHOWINFO
  )
  ) 
set /a cols=%cols%+38

mode con: lines=30 cols=90
cls

SET /P player=<player.ini
SET /P playerpath=<playerpath.ini
echo "%name%" | wc -L > namelen.txt
set /P namelen=<namelen.txt

cd "%playerpath%"

if exist %player% goto PLAY 2>nul

mode con: lines=10 cols=60
cls
echo.
echo C'e' qualcosa di sbagliato nelle impostazioni del player:
echo.
echo Path: %playerpath%
echo Player: %player%
echo.
echo Va sistemato con l'opzione apposita nel menu iniziale
echo.
pause

EXIT /B
REM ===========================================
:PLAY
REM set vlc="Z:\\root\Scrivania\RaiNix_Win\VLCPortable\App\vlc\vlc.exe"

if "%searchmp4%"=="1" set link=%linkmp4%
if "%TvLive%"=="1" set link="%link%&output=7"

REM PLAY WITH CHOSEN PLAYER OR RESTREAMING

if "%res%"=="1" goto RESTREAM
if %player%==smplayer.exe start %player% %link%
REM if %player%==vlc.exe start %player%  %link% --meta-title="%name%"
if %player%==QMPlay2.exe start %player% %link%
if %player%==PotPlayerMini64.exe start %player% %link%
if %player%==mpv.exe start %player% %link%
if %player%==mpvnet.exe start %player% %link%
if %player%==KMPlayer64.exe start %player% %link%
if %player%==mpc-hc.exe start %player% %link%


set /a cols=%namelen%+42
mode con: lines=7 cols=%cols%
cls
echo.

echo   AVVIO IN CORSO DI "%name%" con %player%
echo.
echo   ATTENDERE QUALCHE SECONDO...

 REM start hlsdl or as alternative player for streaming crash
 
REM if %player%==hlsdl.exe (
REM    start %player% -o - | "%alternativeplayer%" --force-window=yes - %link% > nul
REM   )
REM   if %player%==streamlink.exe (
REM  start %player% -o - | "%alternativeplayer%" --force-window=yes - %link% best > nul
REM  ) 


    
"%mypath%"\sleep 3

REM Go back to the base directory

cd %mypath%

if "%prog%"=="film" goto SELECTGROUP
if "%prog%"=="dirette" goto LSC
if "%prog%"=="https://www.raiplaysound.it" goto RSC
if "%prog%"=="guidatv" goto PSC
if "%prog%"=="ricerca" goto CER

goto :SINGLERELOAD

echo You should not be here...
pause
EXIT /B

REM ===================================================
:PLAYERSETUP


mode con: lines=27 cols=60
cls
echo.
echo     SCEGLI IL MEDIA PLAYER
type sep.txt | cut -c 1-45 
echo    premi '0' per uscire oppure scegli:
type sep.txt | cut -c 1-45
echo     1) SMPLAYER (32/64bit)
echo     2) QMPLAY2 (32/64bit)
REM echo     3) VLC 
echo     3) MPV.NET (32/64bit)
echo     4) MPV (32/64bit)
echo     5) KMPLAYER (solo 64bit)
echo     6) MEDIA PLAYER CLASSIC
rem echo     7) hlsdl+vlc 
type sep.txt | cut -c 1-45
echo.
set /p PS=.  SCEGLI DA 1 A 6 E ATTENDI:
echo. 

if "%PS%"=="0" goto INI
if "%PS%"=="1" set ThisPlayer=smplayer.exe
if "%PS%"=="2" set ThisPlayer=QMPlay2.exe
REM if "%PS%"=="3" set ThisPlayer=vlc.exe
if "%PS%"=="3" set ThisPlayer=mpvnet.exe
if "%PS%"=="4" set ThisPlayer=mpv.exe
if "%PS%"=="5" set ThisPlayer=KMPlayer64.exe
if "%PS%"=="6" set ThisPlayer=mpc-hc.exe
if "%PS%"=="" goto PLAYERSETUP
if %PS% LSS 1 goto PLAYERSETUP
if %PS% GTR 6 goto PLAYERSETUP

echo %homepath% | sed -e "s| $||g" > searchlibs.txt
set | grep -i Program | cut -d "=" -f2 | grep -Ev "Data" | sort -u >> searchlibs.txt

wc -l searchlibs.txt  | tr -s " " | cut -d " " -f2 > searchmax.txt

set /p libs=< searchmax.txt
seq -s "," 1 %libs% > searchmax.txt
set /p libs=< searchmax.txt

set player=
set playerpath=
set "progfiles=C:\Progra~1\"
set "progx86=C:\Progra~2\"

echo Ricerca del player in corso.

REM which %thisplayer% 2>nul > player.ini
REM set /P player=<player.ini

REM   for %%G in (%libs%) do (
REM       type searchlibs.txt | sed -n "%%Gp" > thislib.txt
REM       call :setvar

if "%player%"=="" (	
where /r %progfiles% %thisplayer% 2>nul > player.ini
set /P player=<player.ini
 )
 
if "%player%"=="" (	
  where /r %progx86% %thisplayer% 2>nul > player.ini
 set /P player=<player.ini
    )


if "%player%" NEQ "" goto FILLED
echo.
echo Il player %thisplayer% non e' disponibile nel path di sistema.
echo.
echo Inserisci qui il path completo dove si trova il tuo player
echo.
echo oppure tasto ENTER per tornare al Menu Iniziale
set /P PlayerPath=
if "%PlayerPath%"=="" (
goto INI
 )

REM =================================================== 
:FILLED

basename "%player%" "%thisplayer%" > playerpath.ini

echo %ThisPlayer% > player.ini
set player=%thisplayer%
set /P playerpath=<playerpath.ini

cut -c 1-45 sep.txt
echo.
echo.  OK TROVATO MEDIA PLAYER:
echo.
echo.  %player%
echo.  %playerpath%
cut -c 1-45 sep.txt
echo.

pause
if exist ffmpeg.ini (
set /P ffmpegpath=<ffmpeg.ini 2>nul
 ) 
if "%ffmpegpath%"=="" (
goto :FFMPEG
)

goto INI

REM ===================================================
:SEARCHVLC

set vlcpath=
set "progfiles=C:\Progra~1\"
set "progx86=C:\Progra~2\"
set "ThisVLC=vlc.exe"
if "%vlcpath%"=="" (	
where /r %progfiles% %ThisVLC%  2>nul > vlc.ini 
set /P vlcpath=<vlc.ini
)
if "%vlcpath%"=="" (	
where /r %progx86% %ThisVLC%  2>nul > vlc.ini  
set /P vlcpath=<vlc.ini
)
if "%vlcpath%"=="" (
echo.
echo.
echo ATTENZIONE....
echo VLC necessario per restreaming
echo Installarlo e riavviare RAIWIN
echo.
echo Tasto ENTER per chiudere 
echo.
pause
exit
)
if "%vlcpath%" NEQ "" goto STREAMSELECT
REM ===================================================
:FFMPEG
set ffmpegpath=
set "progfiles=C:\Progra~1\"
set "progx86=C:\Progra~2\"
set "ThisFFMPEG=ffmpeg.exe"
if "%ffmpegpath%"=="" (	
where /r %progfiles% %ThisFFMPEG% 2>nul > ffmpeg.ini
set /P ffmpegpath=<ffmpeg.ini
goto :INI
)
if "%ffmpegpath%"=="" (	
where /r %progx86% %ThisFFMPEG% 2>nul > ffmpeg.ini
set /P ffmpegpath=<ffmpeg.ini
goto :INI
 )
if %ffmpegpath%=="" (
echo.
echo ATTENZIONE!: FFMPEG non installato. 
echo.
echo Consigliato installarlo e poi riavviare RAIWIN
echo.
echo Tasto ENTER per uscire
echo.
pause
exit

)

REM if "%ffmpegpath%" NEQ "" goto :PLAYERSETUP
REM ===================================================
:RESTREAM

cd %mypath%

set /P ffmpegpath=<ffmpeg.ini

if not exist ffmpeg.ini (
echo ATTENZIONE!: FFMPEG non installato. 
echo Consigliato installarlo e riavviare RAIWIN
echo poi andare opzione scelta media player 
echo Tasto ENTER per uscire
pause
exit
)
set ffmpegdir=%quote%%ffmpegpath%%quote%

if "%TvLive%"=="1" (
	wget -q -U "%ua%" --no-check-certificate -O - "%liveurl%&output=20" | sed -e "s|&|^&|g" > ResLink.txt
	set /P link=<ResLink.txt
)

REM ===================================================


 if "%ResTool%"=="0" if "%ProRestream%"=="rtmp" start cmd.exe /k "%hlsdlres% -b -o - "%link%" | %ffmpegdir% -re -i - -vcodec libx264 -vprofile baseline -acodec aac -f flv %ProRestream%://%LocalIp%:%PortRestream%" > nul
 if "%ResTool%"=="0" if "%ProRestream%"=="http" start cmd.exe /k "%hlsdlres% -b -o - "%link%" |  %ffmpegdir% -i - -c copy -f mpegts - | "%vlcpath%" - -I dummy -q --volume-step=10 - --sout "#standard{access=http,mux=ts,dst=%LocalIp%:%PortRestream%}"" > nul
 if "%ResTool%"=="0" if "%ProRestream%"=="rtsp" start cmd.exe /k "%hlsdlres% -b -o - "%link%" | %ffmpegdir%  -re -stream_loop -1 -i - -c copy -rtpflags latm -f rtsp -rtsp_transport tcp %ProRestream%://%LocalIp%:%PortRestream%" > nul
 if "%ResTool%"=="1" if "%ProRestream%"=="http" start cmd.exe /k "%ffmpegdir% -user_agent "Raiweb 999" -i "%link%" -c copy -f mpegts - | "%vlcpath%" - -I dummy -q --volume-step=10 - --sout "#standard{access=http,mux=ts,dst=%LocalIp%:%PortRestream%"" > nul
 if "%ResTool%"=="1" if "%ProRestream%"=="rtmp" start cmd.exe /k "%ffmpegdir% -re -user_agent "Raiweb 999" -i "%link%" -vcodec libx264 -vprofile baseline -acodec aac -strict -2 -f flv %ProRestream%://%LocalIp%:%PortRestream%" > nul
 if "%ResTool%"=="1" if "%ProRestream%"=="rtsp" start cmd.exe /k "%ffmpegdir%  -re -stream_loop -1 -user_agent "Raiweb 999" -i "%link%" -c copy -rtpflags latm -map 0:v:0 -map 0:a:0 -f rtsp -rtsp_transport tcp %ProRestream%://%LocalIp%:%PortRestream%" > nul 

echo   AVVIO IN CORSO DEL RESTREAMING: %name% CON: %toolstream%
echo.
echo   APRI SU ALTRO DISPOSITIVO UN PLAYER CON INDIRIZZO %ProRestream%://%LocalIp%:%PortRestream%
echo =========================================================================
echo   ATTENDERE QUALCHE SECONDO...A FINE RESTREAMING CHIUDERE LA FINESTRA E 
echo.
pause
taskkill /F /IM vlc.exe 2>nul
if "%toolstream%"=="ffmpeg" taskkill /F /IM ffmpeg.exe 2>nul
if "%toolstream%"=="hlsdl" taskkill /F /IM hlsdl.exe 2>nul
set "res=0"
GOTO :INI


:STREAMSELECT

if exist vlc.ini (
   set /P vlcpath=<vlc.ini 
     ) 
if "%vlcpath%"=="" (
 GOTO :SEARCHVLC
 )

mode con: lines=27 cols=60
cls
echo     SCEGLI IL PROTOCOLLO DI RESTREAMING
type sep.txt | cut -c 1-45 
echo. 
echo     1) HTTP
echo     2) RTMP (usa server rtsp/rtmp)
echo     3) RTSP (usa server rtsp/rtmp)
echo     0) ANNULLA
echo.
set /p SelStream=.  SCEGLI DA 1 A 3 (0 per annullare):

if "%SelStream%"=="1" set ProRestream=http
if "%SelStream%"=="2" set ProRestream=rtmp
if "%SelStream%"=="3" set ProRestream=rtsp
if "%SelStream%"=="0" goto INI
if "%ProRestream%"=="http" set "PortRestream=8535"
if "%ProRestream%"=="rtmp" set "PortRestream=1935/live"
if "%ProRestream%"=="rtsp" set "PortRestream=8554/live"
echo --------------------------------------------------------
echo  SCEGLI ORA IL TOOL PER IL RESTREAMING
echo.
echo     1) HLSDL
echo     2) FFMPEG
echo     0) ANNULLA SCELTA
echo.
set /p SelTool=.  SCEGLI DA 1 A 2 (0 per annullare):

if "%SelTool%"=="1" set ResTool=0
if "%SelTool%"=="2" set ResTool=1
if "%SelTool%"=="0" goto INI
if "%ResTool%"=="0" set "toolstream=hlsdl"
if "%ResTool%"=="1" set "toolstream=ffmpeg"
 echo ===============================================
    set "res=1"
    echo HAI ATTIVATO IL RESTREAMING
	echo.
	pause
	echo ===============================================
	goto INI
	

:FILLED

basename "%player%" "%thisplayer%" > playerpath.ini

echo %ThisPlayer% > player.ini
set player=%thisplayer%
set /P playerpath=<playerpath.ini

cut -c 1-45 sep.txt
echo.
echo.  OK TROVATO MEDIA PLAYER:
echo.
echo.  %player%
echo.  %playerpath%
cut -c 1-45 sep.txt
echo.

pause
goto INI

  
: USELINKMP4


mode con: lines=27 cols=60
cls
type sep.txt | cut -c 1-45 
echo     SCEGLI SE USARE I LINK HLS LEGACY O ALTERNATIVI
echo. 
echo     NOTA: L'OPZIONE LINK ALTERNATIVO E' SOLO PER I VOD E 
echo     NON PER I CANALI LIVE
type sep.txt | cut -c 1-45 
echo. 
echo     1) HLS LEGACY LINK
echo     2) LINK ALTERNATIVO
echo     3) ANNULLA
echo.
set /p MP4RO=.  SCEGLI DA 1 A 3:

if "%MP4RO%"=="2" (
    set "searchmp4=1"
    set ResTool=1
    set "toolstream=ffmpeg"
    echo ====================================================
    echo     HAI SCELTO D'USARE IL LINK ALTERNATIVO PER I VOD
    echo. 
    echo ======================================================
   )
if "%MP4RO%"=="1" (
    set "searchmp4=0"
    echo ====================================================
    echo     HAI SCELTO D'USARE IL LINK LEGACY PER I VOD
    echo. 
    echo ======================================================
   )
if "%MP4RO%"=="3" goto INI
pause
goto INI

:RECMP4

mode con: lines=12 cols=%cols%
cls

echo.
echo   NELLA CARTELLA REC SI STA SCARICANDO IL FILE:
echo   "%name%.mp4" 
echo.
echo   LO STATO DELLA REGISTRAZIONE E' VISIBILE NELLA
echo   FINESTRA DEL RECORDER
echo   PER INTERROMPERLA CHIUDERE LA FINESTRA
echo.

sleep 7

set outfile="%pathrec%\%name%.mp4"
set link=%linkmp4%  
REM cd %pathrec%
if "%Mp4Option%"=="1" start cmd.exe /k "%ffmpegpath% -y -i %link% -vcodec copy -acodec copy %outfile%"
if "%Mp4Option%"=="0" start cmd.exe /k "wget --no-check-certificate -O %outfile% %link%"
REM start cmd.exe /k "aria2c -d %pathrec% %link%"
cd %mypath%
pause 
goto INI


REM ========================================
:UTF
  if "%win10%"=="1" EXIT /B 
  iconv  -c -f utf-8 -t 850 %1 > utf.txt
  type utf.txt > %1
EXIT /B

REM ========================================
:SCREENSIZER
    wc -L %1  | tr -s " " | cut -d " " -f2 > cols.txt
    set /p cols=<cols.txt
    wc -l  %1  | tr -s " " | cut -d " " -f2 > rows.txt
    set /p rows=<rows.txt
    set /a "numitems=%rows%"
EXIT /B
REM ========================================
:SETVAR
set /P thislib=<thislib.txt
if "%winxp%"=="1" (
	find "%thislib%" -name "%thisplayer%" 2> nul > player.ini
) else (
	where /r "%thislib%" "%thisplayer%" 2> nul > player.ini
)
set /P player=<player.ini
if not "%player%"=="" goto :FILLED
EXIT /B

REM ==========================================
:DATECALC
for %%G in (1,2,3,4,5,6,7) do (
    dateunix  -d "%%G day ago" +%%d-%%m-%%Y_%%A >> week.txt
)
fart -q week.txt "_" " "
fart -q week.txt "Sunday" "Domenica"
fart -q week.txt "Monday" "Lunedi'"
fart -q week.txt "Thursday" "Giovedi'"
fart -q week.txt "Wednesday" "Mercoledi'"
fart -q week.txt "Tuesday" "Martedi'"
fart -q week.txt "Friday" "Venerdi'"
fart -q week.txt "Saturday" "Sabato"
nl -s ") " week.txt | grep "0" > weekrenum.txt
exit /B

CMD /K
