#!/usr/bin/env python

"""
Streame.net Service Code
    :slow video host, too slow for Plex Streaming
"""

RE_NORM = Regex(r'(https?://(?:www\.)?\w+\.\w+)(?:/embed-|/)(\w+)')
RE_THUMB = Regex(r'["\']?image["\']? *?: *?["\'](http[^"\']+)["\']')
RE_DUR = Regex(r'["\']?duration["\']? *?: *?["\'](\d+)["\']')
RE_SOURCES = Regex(r'sources *?\: *?(\[.*?\{[^\]]+\}.*?\]),')
RE_FMT = Regex(r'^.*?(1080|720|480|360|240)$')
FALLBACK = 'http://i.imgur.com/75YO83o.jpg'

####################################################################################################
def NormalizeURL(url):

    r = RE_NORM.search(url)
    return r.group(1) + '/embed-' + r.group(2) + '.html' if r else url

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

    nurl = url.replace('/embed-', '/') if '/embed-' in url else url
    html = HTML.ElementFromString(get_page(nurl))

    if html.xpath('//title/text()')[0] == '404 - Not Found':
        raise Ex.MediaExpired

    title = html.xpath('//input[@name="fname"]/@value')
    if not title:
        raise Ex.MediaExpired

    page = get_page(url)
    rt = RE_THUMB.search(page)
    rd = RE_DUR.search(page)

    thumb = rt.group(1) if rt else FALLBACK

    return VideoClipObject(
        title=title[0].strip(),
        duration=int(rd.group(1)) * 1000 if rd else None,
        thumb=Resource.ContentsOfURLWithFallback([thumb, FALLBACK]),
        source_title='Streame'
        )

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

    page = get_page(url)
    r = RE_SOURCES.search(page)
    if not r:
        raise Ex.MediaExpired

    s = r.group(1).replace("'", '"')
    if '"file"' not in s:
        s = s.replace('file', '"file"')
    if '"label"' not in s:
        s = s.replace('label', '"label"')

    sources = JSON.ObjectFromString(s)
    for s in sources:
        if s['label'].endswith('p'):
            label = int(s['label'][:-1])
        elif (len(s['label']) <= 4):
            label = int(s['label'])
        else:
            label = int(RE_FMT.sub(r'\1', s['label']))
        s.update({'label': label})

    Log.Debug(u"* Streame Video Sources = '{0}'".format(sources))

    return [
        MediaObject(
            audio_channels=2,
            optimized_for_streaming=False,
            video_resolution=str(s['label']),
            parts=[
                PartObject(key=s['file'])
                ]
            ) for s in reversed(Util.ListSortedByKey(sources, 'label'))
        ]

####################################################################################################
def get_page(url):
    try:
        page = HTTP.Request(url, cacheTime=10).content
    except:
        Log.Exception(u"* Error: Cannot open '{0}' >>>".format(url))
        raise Ex.MediaNotAvailable
    return page
