#!/usr/bin/env python

"""
ShareRepo.com Service Code

Host reidrects to Sharex.space so in now a Part of FileNuke code
"""

USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'

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

    if '/embed-' in url:
        url = url.replace('/embed-', '/')
    return url

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

    try:
        page = HTTP.Request(url).content
        html = HTML.ElementFromString(page)
    except:
        raise Ex.MediaNotAvailable

    title = html.xpath('//strong[@class="title"]/text()')
    if not title:
        raise Ex.MediaExpired

    fallback = 'http://i.imgur.com/75YO83o.jpg'
    rt = Regex(r'[\"\']?image[\"\']?\:\s*?[\"\']([^\"\']+)[\"\']').search(page)
    thumb = rt.group(1) if rt else fallback

    return VideoClipObject(
        title=title[0].strip(),
        thumb=Resource.ContentsOfURLWithFallback([thumb, fallback]),
        source_title='ShareRepo'
        )

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

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

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

    http_headers = dict()
    http_headers['User-Agent'] = USER_AGENT

    page = HTTP.Request(url, headers=http_headers).content

    r = Regex(r'file\:\s*?[\"\'](http[^\"\']+(?<!m3u8|smil))[\"\']').search(page)
    if r:
        http_headers.update({'Referer': url})
        Log.Debug('* PlayVideo URL = \"%s\"' %r.group(1))
        return IndirectResponse(VideoClipObject, key=r.group(1), http_headers=http_headers)

    raise Ex.MediaNotAvailable
