#!/usr/bin/env python

"""
FilesUpload.org Service Code
    Most direct video URLs are removed within a few days of creation, not a good streaming host
    URLError: <urlopen error [SSL: TLSV1_ALERT_INTERNAL_ERROR] tlsv1 alert internal error (_ssl.c:590)>
"""

RE_NORM1 = Regex(r'(https?://(?:www\.)?\w+\.\w+/)[^/]+/(.+)')
RE_NORM2 = Regex(r'(https?://(?:www\.)?\w+\.\w+/)(.+)')

####################################################################################################
def NormalizeURL(url):
    r = None
    if len(url.split('/')) > 5:
        r = RE_NORM1.search(url)
    elif len(url.split('/')) == 5:
        r = RE_NORM2.search(url)

    return r.group(1) + 'download-or-watch/' + r.group(2) if r else url

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

    try:
        html = HTML.ElementFromURL(url)
    except:
        Log.Exception(u"* Error: Cannot open '{0}' >>>".format(url))
        raise Ex.MediaNotAvailable

    if html.xpath('//title[starts-with(text(), "File not found")]'):
        raise Ex.MediaExpired

    return VideoClipObject(
        title=url.rsplit('/', 1)[1],
        thumb='http://i.imgur.com/75YO83o.jpg',
        source_title='FilesUpload'
        )

####################################################################################################
def MediaObjectsForURL(url):

    return [
        MediaObject(
            audio_channels=2,
            optimized_for_streaming=False,
            parts=[
                PartObject(key=Callback(PlayVideo, url=url))
                ]
            )
        ]

####################################################################################################
@indirect
def PlayVideo(url, **kwargs):

    try:
        html = HTML.ElementFromURL(url)
    except:
        Log.Exception(u"* Error: Cannot open '{0}' >>>".format(url))
        raise Ex.MediaNotAvailable

    vurl = html.xpath('//video/source/@src')
    if vurl:
        vurl = String.DecodeHTMLEntities(vurl[0]) if '&amp;' in vurl[0] else vurl[0]
        Log.Debug(u"* PlayVideo URL = {0}".format(vurl))
        return IndirectResponse(VideoClipObject, key=vurl)

    raise Ex.MediaNotAvailable
