# -*- coding: UTF-8 -*-
# /*
# *      Copyright (C) 2016 Ivars777
# *
# *
# *  This Program is free software; you can redistribute it and/or modify
# *  it under the terms of the GNU General Public License as published by
# *  the Free Software Foundation; either version 2, or (at your option)
# *  any later version.
# *
# *  This Program is distributed in the hope that it will be useful,
# *  but WITHOUT ANY WARRANTY; without even the implied warranty of
# *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# *  GNU General Public License for more details.
# *
# *  You should have received a copy of the GNU General Public License
# *  along with this program; see the file COPYING.  If not, write to
# *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
# *  http://www.gnu.org/copyleft/gpl.html
# *
# */

import re,os,sys
import json
try:
    import util
except:
    pp = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0,os.sep.join(pp.split(os.sep)[:-1]))
    import util
import requests
try:
    from requests.packages.urllib3.exceptions import InsecureRequestWarning
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
except:
    pass

__author__ = 'ivars777'
if __name__ <> "__main__":
    __name__ = 'kapnob'

headers2dict = lambda  h: dict([l.strip().split(": ") for l in h.strip().splitlines()])
headers = headers2dict("""
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
""")


def supports(url):
    return True if "kapnob.ru" in url else False

def resolve(url):
    HTTP_HEADER = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0',
        'Referer': url}  # 'Connection': 'keep-alive'
    stream = util.item()
    data = requests.get(url,headers = HTTP_HEADER).content
    m = re.search(r'subtitles: \[\s+{\s+src: "(.+?)",\s+label: "(.+?)",\s+language: "(.+?)"', data, re.DOTALL)
    if m:
        sub = {}
        sub["url"] = m.group(1)
        sub["name"] = m.group(2)
        sub["lang"] = m.group(3)
        sub["type"] = "srt"
        stream["subs"]=[sub]

    video_token = re.search("video_token: '(.+?)'",data).group(1)
    content_type = re.search("content_type: '(.+?)'",data).group(1)
    mw_key = re.search("mw_key: '(.+?)'",data).group(1)
    mw_domain_id = re.search("mw_domain_id: (\d+)",data).group(1)
    uuid = re.search("uuid: '(.+?)'",data).group(1)
    params = "video_token=%s&content_type=%s&mw_key=%s&mw_pid=&mw_domain_id=%s&ad_attr=0&debug=false&uuid=%s"%(
        video_token,content_type,mw_key,mw_domain_id,uuid)
    headers = headers2dict("""
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Iframe-Option: Direct
X-Requested-With: XMLHttpRequest
""")
    data = requests.post("http://cdn.kapnob.ru/sessions/new_session", data=params,headers=headers).content
    js = json.loads(data)
    stream["url"] = js["mans"]["manifest_m3u8"]
    stream["name"]= stream["url"]
    return [stream]


if __name__ == "__main__":

    url = "http://cdn.kapnob.ru/video/5e67c8b1ad018ffa/iframe"
    streams = resolve(url)
    if not streams:
        print "No streams found"
        sys.exit()
    for s in streams:
        print s
    print streams[0]["url"]
    util.play_video(streams)
    pass
