#!/usr/bin/env python

import threading
import time
import os, sys, urllib
import signal
import subprocess
import datetime as dt
proc = None
workerRtn = False
def makefileW(fpath, data):    
    text_file = open(fpath, "w")
    text_file.write(data)
    text_file.close()
def readfile(fpath):
    data = ''
    text_file = open(fpath, "r")
    data = text_file.read()
    text_file.close()
    return data
def remfiles(f):
    if os.path.isfile(f):
        if ".ts" in f:
          try:
            os.unlink(f)
          except:pass
    elif os.path.isdir(f):
        map(remfiles, [os.path.join(f,fi) for fi in os.listdir(f)])
        if "/" in f and "sessions" not in f:
          os.rmdir(f)    

def do_work1(id, stop):
    global proc    
    makefileW(sName+"/strStatus", "ON")
    k=0
    while True:
        try:
            i = 0                 
            while True:
                makefileW(sName+"/output.m3u8", "Stream OFFLINE")
                tstarttime = time.time()
                try:remfiles(sName)
                except:pass
                if workerRtn:
                    return
                lUrl1="http://198.144.158.231/allm/jb/getjb.php?chnl="+Url1
                cheader="User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0\r\nOrigin: https://tvz.jagobd.com\r\nReferer: https://tvz.jagobd.com/"
                makefileW(sName+"/strMsg", "Default Url: Stream ONLINE")
                print "starting ffmpeg with Default url with try: " + str(i)
                cmd = 'ffmpeg -headers "" -i '+lUrl1 + ' -c copy -f hls -segment_list_type hls -hls_list_size 3 -segment_list_flags +live -hls_flags delete_segments -hls_time 10 '+sName+'/output.m3u8'
                print cmd
                cmd = cmd.split()
                cmd[2]= cheader
                proc = subprocess.Popen(cmd,shell=False)
                makefileW(sName+"/fpid", str(proc.pid))
                proc.wait()          
                makefileW(sName+"/strMsg", "Default Url: Stream OFFLINE")
                if workerRtn:
                    return
                if time.time()-tstarttime > 60:
                    k=0
                    break
                time.sleep(2)
                if i > 3:
                    k = k+1
                    makefileW(sName+"/strMsg", "Stream OFFLINE :Retry-" + str(k) )                    
                    if k < 3:
                        time.sleep(60)
                    elif k < 6:
                        time.sleep(600)
                    else:
                        time.sleep(3600)                
                    if workerRtn:
                        return
                    break           
                i = i + 1
        except:            
            makefileW(sName+"/strMsg", "Stream OFFLINE : Unknown")
            break
                      
                    
    

def clean(*args):                          
    global workerRtn
    iThread = "False"
    workerRtn = True
    print "Goodbye!"                          
    try:  
      os.kill(proc.pid, signal.SIGINT)
    except:pass
    try:
      fpid = readfile(sName+"/fpid")
      os.system("kill -9 "+fpid)
    except:pass
    try:
      remfiles(sName)
    except:pass
    makefileW(sName+"/strStatus", "OFF")
    makefileW(sName+"/strMsg", "Stream OFFLINE")
    os._exit(0)

def iWorker2(id):
    time.sleep(10)
    while True:
      if iThread == "False":
        break
      print "Thread2 ON"
      if not os.path.isfile(sName+"/output.m3u8"):
         makefileW(sName+"/output.m3u8", "Stream OFFLINE")
      if readfile(sName+"/strStatus") == "OFF":
        clean()
        return
      if time.time() - os.stat(sName+"/output.m3u8").st_mtime > 60:
        try:  
          os.kill(proc.pid, signal.SIGINT)
        except:pass 
        try:
          fpid = readfile(sName+"/fpid")
          os.system("kill -9 "+fpid)
        except:pass     
      time.sleep(2)

def get_ldata(url, headers = None):
    import urllib2
    if 'geturl' in url:
        req = urllib2.Request(url.replace('geturl',''))
        response = urllib2.urlopen(req)
        data = response.read()
        response.close()
        return data
    else:
        return url  

idT = '0'
sName = sys.argv[0].replace('.py','')

try:
    pid = readfile(sName+"/pid")
    os.system("kill -9 "+pid)
except:pass
try:
    fpid = readfile(sName+"/fpid")
    os.system("kill -9 "+fpid)
except:pass
time.sleep(2)
makefileW(sName+"/strStatus","OFF")
makefileW(sName+"/pid",str(os.getpid()))

strData=readfile(sName+'/strData').split('^#^')
Url1 = strData[1].replace('&amp;','&')
makefileW(sName+"/toggle", "ON")
iThread = "True"

if readfile(sName+"/strStatus") == "OFF":
    for sig in (signal.SIGABRT, signal.SIGINT, signal.SIGTERM):
        signal.signal(sig, clean)    
    mainthrd1 = threading.Thread(target=iWorker2, args=(idT))
    mainthrd1.daemon=True
    mainthrd1.start()    
    do_work1(0, False)

clean()