# -*- coding: utf-8 -*-
#
#  ExternalMovieInfoLoader
#
#  Coded by dre (c) 2014 - 2018
#  Coding idea and design by dre
#  E-Mail: dre@dreambox.tools
#  Support: board.dreambox.tools
#
# This plugin is open source but it is NOT free software.
#
# This plugin may only be distributed to and executed on hardware which
# is licensed by Dream Multimedia GmbH.
# In other words:
# It's NOT allowed to distribute any parts of this plugin or its source code in ANY way
# to hardware which is NOT licensed by Dream Multimedia GmbH.
# It's NOT allowed to execute this plugin and its source code or even parts of it in ANY way
# on hardware which is NOT licensed by Dream Multimedia GmbH.
#
# If you want to use or modify the code or parts of it,
# you have to keep MY license and inform me about the modifications by mail.
# In case of any modification of the code or parts of it you MUST request your own API-key.

from __future__ import print_function
from twisted.web.client import getPage as twisted_getPage
from urllib import urlencode
from binascii import hexlify
from twisted.web import error
from twisted.internet import defer

def getPage(url, parameter, json = False):
	emilDownloader = EmilHTTP()
	return emilDownloader.getPage(url,  parameter, json)

class EmilClient(object):
	instance = None
	def __init__(self):
		assert not EmilClient.instance, "only one EmilClient instance is allowed!"
		EmilClient.instance = self # set instance
		self.cookies = {}
		from enigma import eTPM
		etpm = eTPM()
		self.staticParameter = {}
		self.staticParameter["challenge"] = ""
		self.staticParameter["rnd"] = ""
		self.staticParameter["model"] = open("/proc/stb/info/model", "r").readline().strip()
		self.staticParameter["l2cert"] = hexlify(etpm.getCert(eTPM.TPMD_DT_LEVEL2_CERT))
		self.staticParameter["l3cert"] = hexlify(etpm.getCert(eTPM.TPMD_DT_LEVEL3_CERT))
		self.timeout = 10


class EmilHTTP(object):
	def __init__(self):
		self.staticParameter = EmilClient.instance.staticParameter
		self.cookies = EmilClient.instance.cookies
		self.timeout = 20
		self.deferred = defer.Deferred()
		self.headers = {'Content-Type':'application/x-www-form-urlencoded'}

	def callbackErr(self, data, url, parameter, destination_file = None):
		print("[EmilHTTP Error] : ", str(data.getErrorMessage()))
		if isinstance(data.value, error.Error):
			if data.value.status == "401":
				from enigma import eTPM
				etpm = eTPM()
				if isinstance(data.value.response, str):
					self.staticParameter["challenge"] = hexlify(etpm.challenge(data.value.response))
					self.staticParameter["rnd"] = data.value.response
					p = self.staticParameter.copy()
					if parameter is not None:
						p.update(parameter)
					twisted_getPage(url=url, agent="dbmc getPage-client", cookies=self.cookies, timeout=self.timeout, method='POST', headers=self.headers, postdata=urlencode(p)).addCallback(self.callbackOK).addErrback(self.callbackErr, url, parameter)
				else:
					self.deferred.errback(data)
			else:
				self.deferred.errback(data)
				print(data.value.response) 
		else:
			self.deferred.errback(data)

	def callbackOK(self, data):
		self.deferred.callback(data)

	def getPage(self, url, parameter, json = False):
		p = self.staticParameter.copy()
		p.update(parameter)
		if json:
			self.headers["Accept"] = "application/json"
		twisted_getPage(url=url, agent="dbmc getPage-client", cookies=self.cookies, timeout=self.timeout, method='POST', headers=self.headers, postdata=urlencode(p)).addCallback(self.callbackOK).addErrback(self.callbackErr, url, parameter)
		return self.deferred

