#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""DesiTelly Service Code"""

import json, re

ART = 'http://i.imgur.com/GwSnkxE.jpg'
COVER = 'http://i.imgur.com/0snKSZt.png'

####################################################################################################
def MetadataObjectForURL(url):

	d = get_data(url)
	thumb1 = d['thumb']
	thumb2 = thumb1
	if thumb1 == '':
		thumb1 = COVER
		thumb2 = ART

	return MovieObject(
		title=d['title'],
		thumb=Resource.ContentsOfURLWithFallback(thumb1, COVER),
		art=Resource.ContentsOfURLWithFallback(thumb2, ART),
		source_title='Desi Telly'
	)

####################################################################################################
@deferred
def MediaObjectsForURL(url):

	d = get_data(url)
	parts = []
	for u in d['urls']:
		if d['use_openload_pairing'] and 'openload' in u:
			r = pairing_method_OpenLoad(u)
			if r != None:
				u = r
		if '.json' in u:
			json = JSON.ObjectFromURL(u)

			f4m_url = json['content']['media']['f4m']
			xml = XML.ElementFromURL(f4m_url)
			
			burl = xml.xpath('//a:baseURL/text()', namespaces={'a': 'http://ns.adobe.com/f4m/1.0'})[0]
			vurls = xml.xpath('//a:media/@url', namespaces={'a': 'http://ns.adobe.com/f4m/1.0'})
			
			u=burl + '/' + vurls[0]
			
		po = PartObject(key=u)
		parts.append(po)
	return [
		MediaObject(
			container=Container.MP4,
			video_codec=VideoCodec.H264,
			audio_codec=AudioCodec.AAC,
			audio_channels=2,
			optimized_for_streaming=True,
			parts=parts
			)
		]

####################################################################################################
def get_data(url):
	return JSON.ObjectFromString(D(url.split('desitelly://')[1]))
	
openloadhdr = {
	'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0',
	'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
	'Accept-Encoding': 'none',
	'Accept-Language': 'en-US,en;q=0.8',
	'Connection': 'keep-alive'}
	
API_URL = 'https://api.openload.co/1'
PAIR_INFO_URL = API_URL + '/streaming/info'
GET_VIDEO_URL = API_URL + '/streaming/get?file=%s'
VALID_URL = r'https?://(?:openload\.(?:co|io)|oload\.tv)/(?:f|embed)/(?P<id>[a-zA-Z0-9-_]+)'

def matchOpenLoadID(url):
	VALID_URL_RE = re.compile(VALID_URL)
	m = VALID_URL_RE.match(url)
	assert m
	return m.group('id')

def pairing_method_OpenLoad(url):
	
	video_id = matchOpenLoadID(url)
	
	get_info = HTTP.Request(GET_VIDEO_URL % video_id, headers=openloadhdr).content
	#print "get_info --- %s" % get_info
	get_info = json.loads(get_info)
	status = get_info.get('status')
	#print "status --- %s" % status
	if status == 200:
		result = get_info.get('result', {})
		return result.get('url')
	elif status == 403:
		pair_info = HTTP.Request(PAIR_INFO_URL, headers=openloadhdr).content
		#print "pair_info --- %s" % pair_info
		pair_info = json.loads(pair_info)
		if pair_info.get('status') == 200:
			pair_url = pair_info.get('result', {}).get('auth_url')
			if pair_url:
				#print 'Open this url: %s, solve captcha, click "Pair" button and try again' % pair_url
				Log('Open this url: %s, solve captcha, click "Pair" button and try again' % pair_url)
			else:
				#print 'Pair URL not found'
				Log('Pair URL not found: %s' % video_id)
		else:
			#print 'Error loading pair info'
			Log('Error loading pair info: %s' % video_id)
	else:
		#print 'Error loading JSON metadata'
		msg = get_info.get('msg')
		Log('Error %s - %s: %s' % (status, msg, video_id))
		
	return None
