Source

xbmc-vplay-app / vPlayCore.py

'''
    vPlay plugin for XBMC
    Copyright (C) 2012 Stefan Cosma
    
    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 3 of the License, 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.  If not, see <http://www.gnu.org/licenses/>.
'''

import sys, urllib, random, os, codecs, time, xbmc

import simplejson as json

import vPlayCommunicator as vplaycomm
import vPlayScraper as vpscraper

class vPlayCore:
    __settings__ = sys.modules[ "__main__" ].__settings__
    __language__ = sys.modules[ "__main__" ].__language__
    __plugin__ = sys.modules[ "__main__"].__plugin__    
    __dbg__ = sys.modules[ "__main__" ].__dbg__
    
    comm = vplaycomm.vPlayCommunicator()
    
    urls = {}
    urls['login']       = "http://vplay.ro/in/"
    urls['vplay']       = "http://www.vplay.ro"
    urls['collections'] = "http://www.vplay.ro/coll"
    urls['clips']       = "http://www.vplay.ro/cat/all"
    urls['mostviewed']  = "http://www.vplay.ro/top50"
    urls['watch']       = "http://www.vplay.ro/watch"
    urls['dino']        = "http://www.vplay.ro/play/dinosaur.do"
    urls['sites']       = "http://www.vplay.ro/crossdomain.xml"
    urls['sub']         = "http://www.vplay.ro/play/subs.do"
    urls['search']      = "http://www.vplay.ro/search/"
    urls['searchcoll']  = "http://www.vplay.ro/coll/?s="
    urls['iplay']       = "i.vplay.ro"
    urls['player']      = "http://i.vplay.ro/f/embed.swf?key="

    random = random.random()
    scraper = vpscraper.vPlayScraper()


    def __init__(self):
        subs = os.path.join(xbmc.translatePath( "special://temp"), 'plugin.video.vplay2_subtitles')
        if os.path.isdir(subs) is False:
            os.makedirs(subs)
        self.subs_dir = subs
    

    def getAllClips(self, page = 1):
        html = self.get_html_page(self.urls['clips'] + "/" + str(page))
        if not html:
            return []
        
        return self.scraper.scrapAllClips(html)
    
    
    def getTopClips(self):
        html = self.get_html_page(self.urls['mostviewed'] + "/")
        if not html:
            return []

        return self.scraper.scrapTopClips(html)
    

    def getFavoriteShows(self):
        html = self.get_html_page(self.urls['collections'] + "/")
        if not html:
            return []

        return self.scraper.scrapFavoriteShows(html)
 
    
    def getAllShows(self, page = 1):
        html = self.get_html_page(self.urls['collections'] + "/" + str(page))
        if not html:
            return []

        return self.scraper.scrapAllShows(html, page == 1)
    
    
    def getGetShowSeasons(self, href):
        html = self.get_html_page(self.urls['vplay'] + str(href))
        if not html:
            return []

        return self.scraper.scrapShowSeasons(html)
    
    
    def getGetSeasonEpisodes(self, href):
        html = self.get_html_page(self.urls['vplay'] + str(href))
        if not html:
            return []

        return self.scraper.scrapSeasonEpisodes(html)
        
    
    def searchClips(self, searchstr):
        html = self.get_html_page(self.urls['search'] + urllib.quote(searchstr))
        if not html:
            return []
        
        return self.scraper.scrapAllClips(html)
        
    
    def searchCollections(self, searchstr):
        html = self.get_html_page(self.urls['searchcoll'] + urllib.quote_plus(searchstr))
        if not html:
            return []
        
        return self.scraper.scrapAllShows(html)
    
    
    def getRealLink(self, ep_id):
        values = self.processDinosaur(ep_id)
        if len(values) == 0:
            raise IOError('Could not get movie link')
        
        try:
            s = json.loads(values['subs'])
        except Exception, err:
            print self.__plugin__ + ": SUBS -> Got exception in json " + str(err)
            s = []
        
        print self.__plugin__ + ": SUBS -> " + str(s)
        #subs = self.getSubs(ep_id, s)
        
        subs = ''
        ret = {'url': values['nqURL'], 'subs': subs}
        return ret     
    
    
    def processDinosaur(self, key):
        cookie = None
        if self.__settings__.getSetting("session"):
            cookie = self.__settings__.getSetting("session")
        
        headers = {
            'Referer' : self.urls['collections'] + '/',
        }
        
        ret = self.comm.http_get(self.urls['watch'] + '/' + str(key), cookie, headers)
        #print self.__plugin__ + ": DINO -> ",  ret
        if ret['httpcode'] != 200:
            raise Exception('Could not get movie link')
        
        headers = {
            'Host'    : self.urls['iplay'],
            'Referer' : self.urls['watch'] + '/' + str(key),
        }
        
        ret = self.comm.http_get(self.urls['player'] + str(key), cookie, headers)
        #print self.__plugin__ + ": DINO -> ",  ret
        if ret['httpcode'] != 200:
            raise Exception('Could not get movie link')
        
        headers = {
            'Referer' : self.urls['player'] + str(key),
        }
        
        ret = self.comm.http_get(self.urls['sites'], cookie, headers)
        #print self.__plugin__ + ": DINO -> ",  ret
        if ret['httpcode'] != 200:
            raise Exception('Could not get movie link')

        postData = { 'key': str(key), 'external': 0, 'onLoad': "[type Function]" }
        
        headers = {
            'Origin'  : self.urls['iplay'],
            'Referer' : self.urls['player']  + str(key),
        }
        
        ret = self.comm.http_post(self.urls['dino'], postData, cookie, headers)
        #print self.__plugin__ + ": DINO -> ",  ret
        if ret['httpcode'] != 200:
            raise Exception('Could not get movie link')
        
        vals = ret['httpmsg'].split('&')
        attrs = {}
        for i in vals:
            if len(i) == 0:
                continue
            value = i.split('=')
            attrs[value[0]] = value[1]
        
        return attrs
    
    def getSubs(self, key, subs):
        cookie = None
        if self.__settings__.getSetting("session"):
            cookie = self.__settings__.getSetting("session")
            
        url = self.urls['sub'] + '?' + str(self.random)
        ret = {}
        
        sub_dir = os.path.join(self.subs_dir, str(key))
        if os.path.isdir(sub_dir) is False:
            try:
                os.makedirs(sub_dir)
            except Exception, err:
                return ret
        
        for i in subs:
            print self.__plugin__ + ": SUBS -> Processing " + str(i)
            sub_file_name = os.path.join(sub_dir, str(i) + '.sub')
            
            if os.path.isfile(sub_file_name) is True:
                ret[str(i).lower()] = sub_file_name
                continue
            
            postData = {"key": str(key), "lang":  str(i)}
            url_ret = self.comm.http_post(url, postData, cookie)
            if url_ret['httpcode'] != 200:
                print self.__plugin__ + ":SUBS -> Got code " + str(url_ret['httpcode'])
                continue
            
            data = url_ret['httpmsg'].strip('&subsData=').rstrip('\n')
            try:
                obj = json.loads(data)
                subfile = codecs.open(sub_file_name, 'w', 'utf-8')
                count = 1
                for j in obj:
                    sub_line = str(count) + '\n'
                    f = int(j['f'])
                    t = int(j['t'])
                    
                    sub_line = sub_line + self.convert_time_to_something(f) + " --> " + self.convert_time_to_something(t) + '\n'
                    sub_line = sub_line + j['s'] + '\n\n'
                    
                    subfile.write(sub_line)
                    count = count + 1
                subfile.close()
            except Exception, err:
                print self.__plugin__ + ":SUBS -> Got exception " + str(err)
                continue
            
            ret[str(i).lower()] = sub_file_name
            
        return ret
    
    
    def playVideo(self, ep_id):
        details = self.getRealLink(ep_id)
        print self.__plugin__ + ":details -> " + str(details)
        
        #details['url'] = self.checkVideoLink(details['url'])
        
        player = xbmc.Player( xbmc.PLAYER_CORE_MPLAYER )
        player.play(details['url'])
        
        while not player.isPlaying():
            time.sleep(1)
            
        #s = None 
        #if 'ro' in details['subs']:
        #    s = details['subs']['ro']
        #elif 'en' in details['subs']:
        #    s = details['subs']['en']
        #if s != None:
        #    player.setSubtitles(s)
    
    
    def convert_time_to_something(self, f):
        f = int(f)
        def min_and_sec(f):
            if f > 60:
                f_minute = f/60
                f_secunde = f%60
            else:
                f_minute = "00"
                f_secunde = f
            
            if f_minute < 10:
                f_minute = "0" + str(f_minute)
            if f_secunde < 10:
                f_secunde = "0" + str(f_secunde)
            return str(f_minute) + ":" + str(f_secunde) + ",0"

        if f > 3600:
            hours = f/3600
            f = f%3600
            if hours < 10:
                hours = "0" + str(hours)
            else:
                hours = str(hours)
        else:
            hours = "00"
        
        final = hours + ":" + min_and_sec(f)
            
        return final

        
    def get_html_page(self, url):
        cookie = None
        if self.__settings__.getSetting("session"):
            cookie = self.__settings__.getSetting("session")

        ret = self.comm.http_get(url, cookie)
        httpcode = int(ret['httpcode'])
        
        if httpcode == 200:
            return ret['httpmsg']
        else:
            raise IOError('Could not get page %s. Code: %s' % (url, httpcode))
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.