﻿import requests
import bs4
from bs4 import NavigableString
import re
from telegram import Bot, InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, InlineQueryResultCachedAudio
from telegram.ext import CommandHandler, Updater, CallbackQueryHandler, Filters, MessageHandler
import logging
import threading
from time import strftime
import shlex
from os import remove, listdir
from os.path import isfile
from oneFRM import *
from urllib.parse import quote, unquote
import subprocess
import sys
import time

logging.basicConfig(handlers = [logging.FileHandler('cpb.log', 'w', 'utf-8')], format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG)
updater = Updater(token='619496649:AAF1SGV4HQ6ZoXO7AJe_Ujh6xWnNlfiPk1g')
dispatcher = updater.dispatcher

def run_command(command):
	file  = open('status.txt','w', encoding='utf-8')
	file.close()
	filename = None
	process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE, bufsize=1, universal_newlines=True)
	while True:
		output = process.stdout.readline()
		
		if output == '' and process.poll() is not None:
			break
		if output:
			file  = open('status.txt','a', encoding='utf-8')
			file.write(output)
			m = re.search('/var/www/virtual/themanha/html/(.+)', output)
			if m:
				filename = list(m.groups())[0]
			file.close()
	process.poll()
	rc = process.returncode
	
	return rc, filename.strip()
	
	
def msghdl(bot, update):
	DDL = update.message.text
	if DDL.startswith('http'):
		cd = unquote(DDL.split('/')[-1])
		#~ file = open('1fcooker.txt')
		#~ SID = file.readline().strip()
		#~ cookies = {'SID':SID}
		#~ r = requests.head(update.message.text, cookies = cookies)
		#~ DDL = r.headers.get('location')
		#~ r = requests.head()
		#~ d = r.headers.get('content-disposition')
		#~ size = r.headers.get('content-length')
		#~ cd =  re.split(';', d)[1][11:-1]
		print(cd)
		
		update.message.reply_text(f'Launching download with aria2c of `{DDL}`',parse_mode ='Markdown')
		
		rc, fname  = run_command(f"aria2c '{DDL}'")
		if rc != 0:
			update.message.reply_text(f'aria2c returned the following evil returncode: `{rc}`',parse_mode ='Markdown')
			
	elif DDL == 'retry':
		cd = None
		list = listdir()
		for item in list:
			if item.endswith('.ts') and isfile(item):
				cd = item
				fname = item
		if cd == None:
			update.message.reply_text('Couldn\'t find any ts files in the current working dir',parse_mode ='Markdown')
			return
	else:
		update.message.reply_text('Oops, that was wrong.',parse_mode ='Markdown')
		return
	

	x = re.fullmatch(r'(.+) - (S\d\dE\d\d) ([^\[1]+)(\[On Demand\] )?(\d+)i HDMania.ts', cd)
	if x:
		showname = x.groups()[0]
		nums = x.groups()[1]
		epname = x.groups()[2].strip()
		ondem = x.groups()[3]
		res = x.groups()[4]
		
		if ondem:
			addition = 'OD'
		else:
			addition = 'TV'
		
		new_name = f'{showname} {nums} {epname} {res} {addition} AAC2.0 x264-kingofusers.mkv'
		
		print(x.groups())
		#~ exit()
		
		file = open('Pstats.txt','w')
		file.close()
		
		update.message.reply_text('Launching ffmpeg command...\nhttps://themanha.uber.space/Pstats.txt')
		
		exit_code_ffmpeg = subprocess.call(['ffmpeg','-i',fname,'-vf','yadif','-profile:v','high','-level:v','4.1','-pix_fmt','yuv420p','-c:v','libx264','-preset','veryslow','-crf','18','-c:a','copy','-nostats','-vstats_file','Pstats.txt',new_name])
			
		#~ exit_code_ffmpeg = 0
		if exit_code_ffmpeg == 0:
			remove(fname)
			
			link = 'https://themanha.uber.space/'+quote(new_name)
			
			#~ link = 'http://ipv4.download.thinkbroadband.com/20MB.zip'
			
			res = upload1F(link)
				
			if res == 'NeedsLogin':
				#~ print(res)
				SID = login('lucas.halbig@gmail.com','werkenntwen')
				#~ print(SID)
				file = open('1fcooker.txt','w')
				file.write(SID)
				file.close()
				res = upload1F(link)
				if res.endswith('You will be notified when the request is done.'):
					#~ remove(ofname)
					update.message.reply_text('1fichier returned that it will send an email once done')
				else:
					print('DAMN')
			else:
				if res.endswith('You will be notified when the request is done.'):
					#~ remove(ofname)
					#~ bot
					update.message.reply_text('1fichier returned that it will send an email once done')
		else:
			update.message.reply_text(f'Shit it failed with exit code {exit_code_ffmpeg}')
	else:
		update.message.reply_text('Bot not configured for this kind of file')
	#~ print(ondem)
	
dispatcher.add_handler(MessageHandler(Filters.text, msghdl))
updater.start_polling()
updater.idle()