Esempio n. 1
0
    def viewCapture(self, link):
        self.__db.insertSQL(
            "update playlist163 set over = 'N' where link = '" + link + "'")
        url = self.__url + str(link)

        s = requests.session()
        try:
            s = BeautifulSoup(
                s.get(url, headers=self.__headers).content, "lxml")
            musics = json.loads(
                s.find('textarea', {
                    'style': 'display:none;'
                }).text)
            for music in musics:
                name = MySQLdb.escape_string(music['name'].encode('utf-8'))
                author = MySQLdb.escape_string(
                    music['artists'][0]['name'].encode('utf-8'))
                sql = "insert into music163 (song_id,song_name,author) values (" + str(
                    music['id']) + ",'" + name + "','" + author + "')"
                if self.isSingle(music['id']) == True:
                    self.__db.insertSQL(sql)
                else:
                    c.Log('{} : {} {}'.format("ERROR 103", name, "Not Single"))
                self.__db.insertSQL(
                    "update playlist163 set over = 'Y' where link = '" +
                    str(link) + "'")
        except:
            c.Log('{} : {}'.format("Error 901", url))
Esempio n. 2
0
def SetupAmazonLibrary():
    common.Log('Trying to add Amazon source paths...')
    source_path = os.path.join(common.profilpath, 'sources.xml')
    source_added = False
    source = {'Amazon Movies': MOVIE_PATH, 'Amazon TV': TV_SHOWS_PATH}

    try:
        file = open(source_path)
        soup = BeautifulSoup(file)
        file.close()
    except:
        subtags = ['programs', 'video', 'music', 'pictures', 'files']
        soup = BeautifulSoup('<sources></sources>')
        root = soup.sources
        for cat in subtags:
            cat_tag = Tag(soup, cat)
            def_tag = Tag(soup, 'default')
            def_tag['pathversion'] = 1
            cat_tag.append(def_tag)
            root.append(cat_tag)

    video = soup.find("video")

    for name, path in source.items():
        path_tag = Tag(soup, "path")
        path_tag['pathversion'] = 1
        path_tag.append(path)
        source_text = soup.find(text=name)
        if not source_text:
            source_tag = Tag(soup, "source")
            name_tag = Tag(soup, "name")
            name_tag.append(name)
            source_tag.append(name_tag)
            source_tag.append(path_tag)
            video.append(source_tag)
            common.Log(name + ' source path added')
            source_added = True
        else:
            source_tag = source_text.findParent('source')
            old_path = source_tag.find('path').contents[0]
            if path not in old_path:
                source_tag.find('path').replaceWith(path_tag)
                common.Log(name + ' source path changed')
                source_added = True

    if source_added:
        SaveFile(source_path, str(soup))
        Dialog.ok(common.getString(30187), common.getString(30188),
                  common.getString(30189), common.getString(30190))
        if Dialog.yesno(common.getString(30191), common.getString(30192)):
            xbmc.executebuiltin('RestartApp')
Esempio n. 3
0
def getTMDBImages(title, imdb=None, content='movie', year=None):
    fanart = poster = id = None
    splitter = [' - ', ': ', ', ']
    TMDB_URL = 'http://image.tmdb.org/t/p/original'
    yearorg = year

    while not id:
        str_year = ''
        if year: str_year = '&year=' + str(year)
        movie = urllib.quote_plus(title)
        result = common.getURL('http://api.themoviedb.org/3/search/%s?api_key=%s&language=de&query=%s%s' % (content, common.tmdb, movie, str_year), silent=True)
        if not result:
            common.Log('Fanart: Pause 5 sec...')
            xbmc.sleep(5000)
            continue
        data = json.loads(result)
        if data['total_results'] > 0:
            result = data['results'][0]
            if result['backdrop_path']: fanart = TMDB_URL + result['backdrop_path']
            if result['poster_path']: poster = TMDB_URL + result['poster_path']
            id = result['id']
        elif year:
            year = 0
        else:
            year = yearorg
            oldtitle = title
            for splitchar in splitter:
                if title.count(splitchar):
                    title = title.split(splitchar)[0]
                    break
            if title == oldtitle:
                break
    if content == 'movie' and id and not fanart:
        fanart = common.na
    return fanart
Esempio n. 4
0
def EXPORT_EPISODE(asin=False, makeNFO=True, dispnotif=True):
    if not asin: asin = common.args.asin
    for data in tvDB.lookupTVdb(asin, single=False):
        Info = listtv.ADD_EPISODE_ITEM(data, onlyinfo=True)
        showname = common.cleanName(Info['TVShowTitle'])
        directorname = os.path.join(TV_SHOWS_PATH, showname)
        CreateDirectory(directorname)
        name = 'Season ' + str(Info['Season'])
        if dispnotif:
            SetupLibrary()
            common.Log('Amazon Export: %s %s' % (showname, name))
            #Dialog.notification('Export', showname + ' ' + name, sound = False)
            dispnotif = False
        seasonpath = os.path.join(directorname, name)
        CreateDirectory(seasonpath)
        filename = 'S%02dE%02d - %s' % (Info['Season'], Info['Episode'],
                                        Info['Title'])
        strm_file = filename + ".strm"
        u = '%s?asin=<%s>&mode=<play>&name=<%s>&sitemode=<PLAYVIDEO>&adult=<%s>&trailer=<0>&selbitrate=<0>' % (
            sys.argv[0], asin, urllib.quote_plus(
                Info['Title']), Info['isAdult'])
        SaveFile(strm_file, u, seasonpath)

        if makeNFO:
            nfo_file = filename + ".nfo"
            nfo = '<episodedetails>'
            nfo += streamDetails(Info)
            nfo += '</episodedetails>'
            SaveFile(nfo_file, nfo, seasonpath)
Esempio n. 5
0
def UpdateDialog(SERIES_COUNT, SEASON_COUNT, EPISODE_COUNT, delShows, delSeasons, delEpisodes):
    line1 = ''
    line2 = ''
    line3 = ''
    if SERIES_COUNT:
        line1 += '%s %s' % (common.getString(30132) % SERIES_COUNT, common.getString(30124))
        if delShows:
            line1 += ', %s %s' % (delShows, common.getString(30125))
    if (delShows) and (not SERIES_COUNT):
        line1 += '%s %s' % (common.getString(30132) % delShows, common.getString(30125))
    if SEASON_COUNT:
        line2 += '%s %s' % (common.getString(30133) % SEASON_COUNT, common.getString(30124))
        if delSeasons:
            line2 += ', %s %s' % (delSeasons, common.getString(30125))
    if (delSeasons) and (not SEASON_COUNT):
        line2 += '%s %s' % (common.getString(30133) % delSeasons, common.getString(30125))
    if EPISODE_COUNT:
        line3 += '%s %s' % (common.getString(30134) % EPISODE_COUNT, common.getString(30124))
        if delEpisodes:
            line3 += ', %s %s' % (delEpisodes, common.getString(30125))
    if (delEpisodes) and (not EPISODE_COUNT):
        line3 += '%s %s' % (common.getString(30134) % delEpisodes, common.getString(30125))
    if line1 + line2 + line3 == '':
        line2 = common.getString(30127)
    common.Log('TV Shows Update:\n%s\n%s\n%s' % (line1, line2, line3))
Esempio n. 6
0
def getIMDbID(asins, title):
    url = None
    imdb_id = None
    c = tvDB.cursor()
    for asin in asins.split(','):
        asin = '%' + asin + '%'
        url = c.execute('select imdburl from seasons where seriesasin like (?) and imdburl is not null', (asin,)).fetchone()
        if url:
            url = url[0]
            break
    if not url:
        while not imdb_id:
            response = common.getURL('http://www.omdbapi.com/?type=series&t=' + urllib.quote_plus(title))
            data = json.loads(response)
            if data['Response'] == 'True':
                imdb_id = data['imdbID']
            else:
                oldtitle = title
                title = title.split(' - ')[0]
                title = title.split(': ')[0]
                title = title.replace('?', '')
                if title == oldtitle:
                    imdb_id = common.na
    else:
        imdb_id = re.compile('/title/(.+?)/', re.DOTALL).findall(url)
    common.Log(imdb_id + asins.split(',')[0])
    return imdb_id
Esempio n. 7
0
 def insertSQL(self, sql):
     try:
         self.__cursor.execute(sql)
         self.__db.commit()
     except:
         self.__db.rollback()
         c.Log("ERROR 909 : SQL " + sql)
Esempio n. 8
0
def IStreamPlayback(url, asin, trailer):
    values = getFlashVars(url)
    if not values:
        return
    vMT = 'Trailer' if trailer == '1' else 'Feature'
    data = getUrldata(mode='catalog/GetPlaybackResources',
                      values=values,
                      extra=True,
                      vMT=vMT,
                      opt='&titleDecorationScheme=primary-content')
    title, plot, mpd, subs = getStreams(*data, retmpd=True)
    licURL = getUrldata(mode='catalog/GetPlaybackResources',
                        values=values,
                        extra=True,
                        vMT=vMT,
                        dRes='Widevine2License',
                        retURL=True)
    common.Log(mpd)
    listitem = xbmcgui.ListItem(path=mpd)

    if trailer == '1':
        if title:
            listitem.setInfo('video', {'Title': title + ' (Trailer)'})
        if plot:
            listitem.setInfo('video', {'Plot': plot})
    listitem.setSubtitles(subs)
    listitem.setProperty('inputstreamaddon', 'inputstream.mpd')
    listitem.setProperty('inputstream.mpd.license_type', 'com.widevine.alpha')
    listitem.setProperty('inputstream.mpd.license_key', licURL)
    xbmcplugin.setResolvedUrl(pluginhandle, True, listitem=listitem)
Esempio n. 9
0
def deleteremoved(asins, refresh=True):
    c = tvDB.cursor()
    delShows = 0
    delSeasons = 0
    delEpisodes = 0
    common.Log('ASINS to Remove: ' + asins.__str__())
    for item in asins:
        for seasonasin in item.split(','):
            title, season = lookupTVdb(value=seasonasin,
                                       rvalue='seriestitle, season',
                                       tbl='seasons',
                                       name='asin')
            if title and season:
                asin = '%' + seasonasin + '%'
                delEpisodes += c.execute('delete from episodes where seriestitle = (?) and season = (?) and seasonasin like (?)', (title, season, asin)).rowcount
                delSeasons += c.execute('delete from seasons where seriestitle = (?) and season = (?) and asin like (?)', (title, season, asin)).rowcount
                if not lookupTVdb(value=title,
                                  rvalue='asin',
                                  tbl='seasons',
                                  name='seriestitle'):
                    delShows += c.execute('delete from shows where seriestitle = (?)', (title,)).rowcount
    tvDB.commit()
    c.close()
    if refresh:
        xbmc.executebuiltin('Container.Refresh')
    return delShows, delSeasons, delEpisodes
Esempio n. 10
0
def updateFanart():
    if tmdb_art == '0': return
    asin = movie = year = None
    sqlstring = 'select asin, movietitle, year, fanart from movies where fanart is null'
    c = MovieDB.cursor()
    common.Log('Movie Update: Updating Fanart')
    if tmdb_art == '2':
        sqlstring += ' or fanart like "%images-amazon.com%"'
    for asin, movie, year, oldfanart in c.execute(sqlstring):
        movie = movie.lower().replace('[ov]', '').replace('omu', '').replace('[ultra hd]', '').split('(')[0].strip()
        result = appfeed.getTMDBImages(movie, year=year)
        if oldfanart:
            if result == common.na or not result:
                result = oldfanart
        updateMoviedb(asin, 'fanart', result)
    MovieDB.commit()
    common.Log('Movie Update: Updating Fanart Finished')
Esempio n. 11
0
 def viewCapture(self, song_id, page=1):
     if page == 1:
         dql = "delete from comment163 where song_id = " + str(song_id)
         self.__db.insertSQL(dql)
     data = {
         'params': self.createParams(page),
         'encSecKey': self.__encSecKey
     }
     url = "http://music.163.com/weapi/v1/resource/comments/R_SO_4_" + str(
         song_id) + "/?csrf_token="
     # url = "http://music.163.com/eapi/v1/resource/hotcomments/R_SO_4_" + str(song_id)
     try:
         req = requests.post(url,
                             headers=self.__headers,
                             data=data,
                             timeout=10)
         for comment in req.json()['comments']:
             if comment['likedCount'] > 30:
                 sql = "insert into comment163 (song_id,txt,author,liked) values (" + str(
                     song_id) + ",\"" + MySQLdb.escape_string(
                         comment['content'].encode(
                             'utf-8')) + "\",\"" + MySQLdb.escape_string(
                                 comment['user']['nickname'].encode('utf-8')
                             ) + "\"," + str(comment['likedCount']) + ")"
                 self.__db.insertSQL(sql)
         if page == 1:
             for comment in req.json()['hotComments']:
                 sql = "insert into comment163 (song_id,txt,author,liked) values (" + str(
                     song_id) + ",\"" + MySQLdb.escape_string(
                         comment['content'].encode(
                             'utf-8')) + "\",\"" + MySQLdb.escape_string(
                                 comment['user']['nickname'].encode('utf-8')
                             ) + "\"," + str(comment['likedCount']) + ")"
                 self.__db.insertSQL(sql)
         upd = "update music163 set over ='Y',comment=" + str(
             req.json()['total']) + " where song_id = " + str(song_id)
         self.__db.insertSQL(upd)
         return req.json()['total'] / 20
     except KeyboardInterrupt:
         print("INFO : 解释器请求退出")
         c.Log("ERROR 107 : 解释器请求退出")
         exit()
     except:
         c.Log("ERROR 910 : SONG_ID-" + str(song_id) + " PAGE-" + str(page))
         self.viewsCapture(song_id, page, page + 1)
Esempio n. 12
0
def Input(mousex=0,mousey=0,click=0,keys=False,delay='200'):
    screenWidth = int(xbmc.getInfoLabel('System.ScreenWidth'))
    screenHeight = int(xbmc.getInfoLabel('System.ScreenHeight'))
    keys_only = sc_only = keybd = ''
    if mousex == -1: mousex = screenWidth/2
    if mousey == -1: mousey = screenHeight/2

    spec_keys = {'{EX}': ('!{F4}', 'control+shift+q', 'kd:cmd t:q ku:cmd'),
                 '{SPC}': ('{SPACE}', 'space', 't:p'),
                 '{LFT}': ('{LEFT}', 'Left', 'kp:arrow-left'),
                 '{RGT}': ('{RIGHT}', 'Right', 'kp:arrow-right'),
                 '{U}': ('{UP}', 'Up', 'kp:arrow-up'),
                 '{DWN}': ('{DOWN}', 'Down', 'kp:arrow-down'),
                 '{BACK}': ('{BS}', 'BackSpace', 'kp:delete'),
                 '{RET}': ('{ENTER}', 'Return', 'kp:return')}
                 
    if keys:
        keys_only = keys
        for sc in spec_keys:
            while sc in keys:
                keys = keys.replace(sc, spec_keys[sc][platform-1]).strip()
                keys_only = keys_only.replace(sc, '').strip()
        sc_only = keys.replace(keys_only, '').strip()

    if platform == osWindows:
        app = os.path.join(common.pluginpath, 'tools', 'userinput.exe' )
        mouse = ' mouse %s %s' % (mousex,mousey)
        mclk = ' ' + str(click)
        keybd = ' key %s %s' % (keys,delay)
    elif platform == osLinux:
        app = 'xdotool'
        mouse = ' mousemove %s %s' % (mousex,mousey)
        mclk = ' click --repeat %s 1' % click
        if keys_only: keybd = ' type --delay %s %s' % (delay, keys_only)
        if sc_only: 
            if keybd: keybd += ' && ' + app
            keybd += ' key ' + sc_only
    elif platform == osOSX:
        app = 'cliclick'
        mouse = ' m:'
        if click == 1: mouse = ' c:'
        elif click == 2: mouse = ' dc:'
        mouse += '%s,%s' % (mousex,mousey)
        mclk = ''
        keybd = ' -w %s' % delay
        if keys_only: keybd += ' t:%s' % keys_only
        if keys <> keys_only: keybd += ' ' + sc_only

    if keys:
        cmd = app + keybd
    else:
        cmd = app + mouse
        if click: cmd += mclk
    common.Log('Run command: %s' % cmd)
    subprocess.call(cmd, shell=True)
Esempio n. 13
0
def updateAll():
    if common.updateRunning(): return
    import movies
    import tv
    from datetime import datetime
    common.addon.setSetting('update_running', datetime.today().strftime('%Y-%m-%d %H:%M'))
    common.Log('Starting DBUpdate')
    Notif = xbmcgui.Dialog().notification
    Notif(common.__plugin__, common.getString(30106), sound = False)
    tv.addTVdb(False)
    movies.addMoviesdb(False)
    NewAsins = common.getCategories()
    movies.setNewest(NewAsins)
    movies.updateFanart()
    tv.setNewest(NewAsins)
    tv.updateFanart()
    common.addon.setSetting('last_update', datetime.today().strftime('%Y-%m-%d'))
    common.addon.setSetting('update_running', 'false')
    Notif(common.__plugin__, common.getString(30126), sound = False)
    common.Log('DBUpdate finished')
Esempio n. 14
0
def addMoviesdb(full_update=True):
    try:
        if common.args.url == 'u':
            full_update = False
    except: pass
    dialog = xbmcgui.DialogProgress()

    if full_update:
        if common.updateRunning(): return
        dialog.create(common.getString(30120))
        dialog.update(0,common.getString(30121))
        createMoviedb()
        MOVIE_ASINS = []
        full_update = True
    else:
        MOVIE_ASINS = getMoviedbAsins(list=True)

    page = 1
    goAhead = 1
    endIndex = 0
    new_mov = 0
    
    while goAhead == 1:
        page+=1
        json = appfeed.getList('Movie', endIndex, NumberOfResults=MAX)
        titles = json['message']['body']['titles']
        if titles:
            for title in titles:
                if full_update and dialog.iscanceled():
                    goAhead = -1
                    break
                if title.has_key('titleId'):
                    endIndex += 1
                    asin = title['titleId']
                    found, MOVIE_ASINS = common.compasin(MOVIE_ASINS, asin)
                    if not found:
                        new_mov += ASIN_ADD(title)
                    updateMoviedb(asin, 'popularity', endIndex)
            if len(titles) < MAX: goAhead = 0
            else: endIndex = endIndex - int(MAX/4)
        else:
            goAhead = 0
        if full_update: dialog.update(int((endIndex)*100.0/MOV_TOTAL), common.getString(30122) % page, common.getString(30123) % new_mov)
        if full_update and dialog.iscanceled(): goAhead = -1
    if goAhead == 0:
        updateLibrary()
        common.addon.setSetting("MoviesTotal",str(endIndex))
        common.Log('Movie Update: New %s Deleted %s Total %s' % (new_mov, deleteremoved(MOVIE_ASINS), endIndex))
        if full_update: 
            setNewest()
            dialog.close()
            updateFanart()
        xbmc.executebuiltin("XBMC.Container.Refresh")
        MovieDB.commit()
Esempio n. 15
0
    def close(self):
        common.Log('Stopping Thread')
        self._stopEvent.set()
        xbmcgui.WindowDialog.close(self)
        vidDur = int(xbmc.getInfoLabel('ListItem.Duration')) * 60
        watched = xbmc.getInfoLabel('Listitem.PlayCount')
        isLast = xbmc.getInfoLabel('Container().Position') == xbmc.getInfoLabel('Container().NumItems')
        pBTime = time.time() - self._pbStart

        if pBTime > vidDur * 0.9 and not watched:
            xbmc.executebuiltin("Action(ToggleWatched)")
            if not isLast: xbmc.executebuiltin("Action(Up)")
Esempio n. 16
0
def AndroidPlayback(asin, trailer):
    manu = ''
    if os.access('/system/bin/getprop', os.X_OK):
        manu = subprocess.Popen(['getprop', 'ro.product.manufacturer'], stdout=subprocess.PIPE).communicate()[0].strip()

    if manu == 'Amazon':
        cmp = 'com.amazon.avod/com.amazon.avod.playbackclient.EdPlaybackActivity'
        pkg = 'com.fivecent.amazonvideowrapper'
        act = ''
        url = asin
    else:
        cmp = 'com.amazon.avod.thirdpartyclient/com.amazon.avod.thirdpartyclient.ThirdPartyPlaybackActivity'
        pkg = 'com.amazon.avod.thirdpartyclient'
        act = 'android.intent.action.VIEW'
        url = common.BASE_URL + '/piv-apk-play?asin=' + asin
        if trailer == '1': url += '&playTrailer=T'

    subprocess.Popen(['log', '-p', 'v', '-t', 'Kodi-Amazon', 'Manufacturer: '+manu])
    subprocess.Popen(['log', '-p', 'v', '-t', 'Kodi-Amazon', 'Starting App: %s Video: %s' % (pkg, url)])
    common.Log('Manufacturer: %s' % manu)
    common.Log('Starting App: %s Video: %s' % (pkg, url))
    xbmc.executebuiltin('StartAndroidActivity("%s", "%s", "", "%s")' % (pkg, act, url))
Esempio n. 17
0
def updateFanart():
    if tvdb_art == '0':
        return
    asin = title = None
    seasons = False
    c = tvDB.cursor()
    sqlstring = 'select asin, seriestitle, fanart, poster from shows where fanart is null'
    common.Log('TV Update: Updating Fanart')
    if tvdb_art == '2':
        sqlstring += ' or fanart like "%images-amazon.com%"'
    if tvdb_art == '3':
        sqlstring += ' or poster like "%images-amazon.com%"'
        seasons = True
    for asin, title, oldfanart, oldposter in c.execute(sqlstring).fetchall():
        title = title.lower().replace('[ov]', '').replace('[ultra hd]', '').replace('?', '').replace('omu', '').split('(')[0].strip()
        tvid, poster, fanart = appfeed.getTVDBImages(title, seasons=seasons)
        if not fanart:
            fanart = appfeed.getTMDBImages(title, content='tv')
        if oldfanart and not fanart:
            fanart = oldfanart
        if oldposter and not poster:
            poster = oldposter
        if tvid:
            if not fanart:
                fanart = common.na
            if not poster:
                fanart = common.na
        c.execute("update shows set fanart=? where asin = (?)", (fanart, asin))
        if tvdb_art == '3':
            c.execute("update shows set poster=? where asin = (?)", (poster, asin))
            if tvid:
                for season, url in tvid.items():
                    for singleasin in asin.split(','):
                        singleasin = '%' + singleasin + '%'
                        c.execute("update seasons set poster=? where seriesasin like (?) and season = (?)", (url, singleasin, season))
    tvDB.commit()
    common.Log('TV Update: Updating Fanart Finished')
Esempio n. 18
0
def Error(data):
    code = data['errorCode']
    common.Log('%s (%s) ' %(data['message'], code), xbmc.LOGERROR)
    if 'CDP.InvalidRequest' in code:
        return common.getString(30204)
    elif 'CDP.Playback.NoAvailableStreams' in code:
        return common.getString(30205)
    elif 'CDP.Playback.NotOwned' in code:
        return common.getString(30206)
    elif 'CDP.Authorization.InvalidGeoIP' in code:
        return common.getString(30207)
    elif 'CDP.Playback.TemporarilyUnavailable' in code:
        return common.getString(30208)
    else:
        return '%s (%s) ' %(data['message'], code)
Esempio n. 19
0
    def onAction(self, action):
        if not useIntRC: return

        ACTION_SELECT_ITEM = 7
        ACTION_PARENT_DIR = 9
        ACTION_PREVIOUS_MENU = 10
        ACTION_PAUSE = 12
        ACTION_STOP = 13
        ACTION_SHOW_INFO = 11
        ACTION_SHOW_GUI = 18
        ACTION_MOVE_LEFT = 1
        ACTION_MOVE_RIGHT = 2
        ACTION_MOVE_UP = 3
        ACTION_MOVE_DOWN = 4
        ACTION_PLAYER_PLAY = 79
        ACTION_VOLUME_UP = 88
        ACTION_VOLUME_DOWN = 89
        ACTION_MUTE = 91
        ACTION_NAV_BACK = 92
        ACTION_BUILT_IN_FUNCTION = 122
        KEY_BUTTON_BACK = 275
        ACTION_BACKSPACE = 110
        ACTION_MOUSE_MOVE = 107

        actionId = action.getId()
        common.Log('Action: Id:%s ButtonCode:%s' % (actionId, action.getButtonCode()))

        if action in [ACTION_SHOW_GUI, ACTION_STOP, ACTION_PARENT_DIR, ACTION_PREVIOUS_MENU, ACTION_NAV_BACK, KEY_BUTTON_BACK, ACTION_MOUSE_MOVE]:
            Input(keys='{EX}')
        elif action in [ACTION_SELECT_ITEM, ACTION_PLAYER_PLAY, ACTION_PAUSE]:
            Input(keys='{SPC}')
        elif action==ACTION_MOVE_LEFT:
            Input(keys='{LFT}')
        elif action==ACTION_MOVE_RIGHT:
            Input(keys='{RGT}')
        elif action==ACTION_MOVE_UP:
            Input(keys='{U}')
        elif action==ACTION_MOVE_DOWN:
            Input(keys='{DWN}')
        elif action==ACTION_SHOW_INFO:
            Input(9999,0)
            xbmc.sleep(800)
            Input(9999,-1)
        # numkeys for pin input
        elif actionId > 57 and actionId < 68:
            strKey = str(actionId-58)
            Input(keys=strKey)
Esempio n. 20
0
def getCmdLine(videoUrl, amazonUrl):
    scr_path = addon.getSetting("scr_path")
    br_path = addon.getSetting("br_path").strip()
    scr_param = addon.getSetting("scr_param").strip()
    kiosk = addon.getSetting("kiosk") == 'true'
    appdata = addon.getSetting("ownappdata") == 'true'
    cust_br = addon.getSetting("cust_path") == 'true'
    
    if playMethod == 1:
        if not os.path.exists(scr_path): return ''
        return scr_path + ' ' + scr_param.replace('{f}', getPlaybackInfo(amazonUrl)).replace('{u}', videoUrl)

    os_paths = [None, ('C:\\Program Files\\', 'C:\\Program Files (x86)\\'), ('/usr/bin/', '/usr/local/bin/'), 'open -a ']
    # path(0,win,lin,osx), kiosk, profile, args

    br_config = [[(None, ['Internet Explorer\\iexplore.exe'], '', ''), '-k ', '', ''], 
                 [(None, ['Google\\Chrome\\Application\\chrome.exe'], ['google-chrome', 'google-chrome-stable', 'google-chrome-beta', 'chromium-browser'], '"/Applications/Google Chrome.app"'),
                  '--kiosk ', '--user-data-dir=', '--start-maximized --disable-translate --disable-new-tab-first-run --no-default-browser-check --no-first-run '],
                 [(None, ['Mozilla Firefox\\firefox.exe'], ['firefox'], 'firefox'), '', '-profile ', ''],
                 [(None, ['Safari\\Safari.exe'], '', 'safari'), '', '', '']]
    
    if not cust_br: br_path = ''

    if platform != osOSX and not cust_br:
        for path in os_paths[platform]:
            for file in br_config[browser][0][platform]:
                if os.path.exists(path+file): 
                    br_path = path + file
                    break
                else: common.Log('Browser %s not found' % (path+file), xbmc.LOGDEBUG)
            if br_path: break
                
    if not os.path.exists(br_path) and platform != osOSX: return ''

    br_args = br_config[browser][3]
    if kiosk: br_args += br_config[browser][1]
    if appdata and br_config[browser][2]: 
        br_args += br_config[browser][2] + '"' + os.path.join(common.pldatapath, str(browser)) + '" '
        
    if platform == osOSX:
        if not cust_br: br_path = os_paths[osOSX] + br_config[browser][0][osOSX]
        if br_args.strip(): br_args = '--args ' + br_args
        
    br_path += ' %s"%s"' % (br_args, videoUrl)
    
    return br_path
Esempio n. 21
0
def parseSubs(data):
    subs = []
    if addon.getSetting('subtitles') == 'false':
        return subs
    for sub in data:
        lang = sub['displayName'].split('(')[0].strip()
        common.Log('Convert %s Subtitle' % lang)
        file = xbmc.translatePath('special://temp/%s.srt' % lang).decode('utf-8')
        soup = BeautifulSoup(common.getURL(sub['url']))
        enc = soup.originalEncoding
        num = 0
        with codecs.open(file, 'w', encoding='utf-8') as srt:
            for caption in soup.findAll('tt:p'):
                num += 1
                subtext = caption.renderContents().decode(enc).replace('<tt:br>', '\n').replace('</tt:br>', '')
                srt.write(u'%s\n%s --> %s\n%s\n\n' % (num, caption['begin'], caption['end'], subtext))
        subs.append(file)
    return subs
Esempio n. 22
0
 def viewCapture(self, page):
     s = requests.session()
     play_url = self.__play_url + str(page * 35)
     try:
         s = BeautifulSoup(
             s.get(play_url, headers=self.__headers).content, "lxml")
         lst = s.find('ul', {'class': 'm-cvrlst f-cb'})
         for play in lst.find_all('div', {'class': 'u-cover u-cover-1'}):
             title = MySQLdb.escape_string(
                 play.find('a', {'class': 'msk'})['title'].encode('utf-8'))
             link = MySQLdb.escape_string(
                 play.find('a', {'class': 'msk'})['href'].encode('utf-8'))
             cnt = MySQLdb.escape_string(
                 play.find('span', {
                     'class': 'nb'
                 }).text.encode('utf-8'))
             sql = "insert into playlist163 (title,link,cnt) values ('" + title + "','" + link + "','" + cnt + "')"
             if self.isSinglePlaylist(link) == True:
                 self.__db.insertSQL(sql)
     except:
         c.Log('{} : {} {}'.format("ERROR 104 ", "URL", link))
Esempio n. 23
0
def EXPORT_MOVIE(asin=False, makeNFO=True):
    SetupLibrary()
    if not asin: asin = common.args.asin
    for moviedata in moviesDB.lookupMoviedb(asin, single=False):
        Info = listmovie.ADD_MOVIE_ITEM(moviedata, onlyinfo=True)
        filename = Info['Title']
        if Info['Year']:
            filename = '%s (%s)' % (Info['Title'], Info['Year'])
        #Dialog.notification('Export', filename, sound = False)
        common.Log('Amazon Export: ' + filename)
        strm_file = filename + ".strm"
        u = '%s?asin=<%s>&mode=<play>&name=<%s>&sitemode=<PLAYVIDEO>&adult=<%s>&trailer=<0>&selbitrate=<0>' % (
            sys.argv[0], asin, urllib.quote_plus(
                Info['Title']), Info['isAdult'])
        SaveFile(strm_file, u, MOVIE_PATH)

        if makeNFO:
            nfo_file = filename + ".nfo"
            nfo = '<movie>'
            nfo += streamDetails(Info)
            nfo += '</movie>'
            SaveFile(nfo_file, nfo, MOVIE_PATH)
Esempio n. 24
0
def PLAYVIDEO():
    if not platform:
        Dialog.notification(common.__plugin__, 'Betriebssytem wird von diesem Addon nicht unterstützt', xbmcgui.NOTIFICATION_ERROR)
        return
    amazonUrl = common.BASE_URL + "/dp/" + common.args.asin
    waitsec = int(addon.getSetting("clickwait")) * 1000
    pin = addon.getSetting("pin")
    waitpin = int(addon.getSetting("waitpin")) * 1000
    waitprepin = int(addon.getSetting("waitprepin")) * 1000
    trailer = common.args.trailer
    isAdult = int(common.args.adult)
    pininput = addon.getSetting("pininput") == 'true'
    fullscr = addon.getSetting("fullscreen") == 'true'
    xbmc.Player().stop()
    
    if trailer == '1':
        videoUrl = amazonUrl + "/?autoplaytrailer=1"
    else:
        videoUrl = amazonUrl + "/?autoplay=1"

    if playMethod == 2 or platform == osAndroid:
        AndroidPlayback(common.args.asin, trailer)
        return
    else:
        if common.verbLog: videoUrl += '&playerDebug=true'
        url = getCmdLine(videoUrl, amazonUrl)
        if not url:
            Dialog.notification(common.__plugin__, common.getString(30198), xbmcgui.NOTIFICATION_ERROR)
            addon.openSettings()
            return
        common.Log('Executing: %s' % url)
        if platform == 1:
            process = subprocess.Popen(url, startupinfo=getStartupInfo())
        else:
            process = subprocess.Popen(url, shell=True)
        
    if isAdult == 1 and pininput:
        if fullscr: waitsec = waitsec*0.75
        else: waitsec = waitprepin
        xbmc.sleep(int(waitsec))
        Input(keys=pin)
        waitsec = 0
        if fullscr: xbmc.sleep(waitpin)
    
    if fullscr:
        xbmc.sleep(int(waitsec))
        if isAdult == 0: pininput = True
        if pininput:
            if browser != 0:
                Input(keys='f')
            else:
                Input(mousex=-1,mousey=350,click=2)
                xbmc.sleep(500)
                Input(mousex=9999,mousey=350)
            
    Input(mousex=9999,mousey=-1)
    
    if hasExtRC and not useIntRC: return

    myWindow = window()
    myWindow.wait(process)
Esempio n. 25
0
def addMoviesdb(full_update=True):
    try:
        if common.args.url == 'u':
            full_update = False
    except Exception:
        pass
    dialog = xbmcgui.DialogProgress()
    if full_update:
        if common.updateRunning():
            return
        dialog.create(common.getString(30120))
        dialog.update(0, common.getString(30121))
        createMoviedb()
        MOVIE_ASINS = []
        full_update = True
    else:
        MOVIE_ASINS = getMoviedbAsins(returnlist=True)

    page = 1
    goAhead = 1
    endIndex = 0
    new_mov = 0
    tot_mov = 0
    MAX = 120

    while goAhead == 1:
        json = appfeed.getList('Movie', endIndex,
                               NumberOfResults=MAX)['message']['body']
        titles = json['titles']
        if json['approximateSize'] == 0:
            MAX = MAX - 20
            if MAX < 1:
                MAX = 120
            continue
        endIndex = json['endIndex']
        if titles:
            for title in titles:
                if full_update and dialog.iscanceled():
                    goAhead = -1
                    break
                if 'titleId' in title:
                    asin = title['titleId']
                    if '_duplicate_' not in title['title']:
                        found, MOVIE_ASINS = common.compasin(MOVIE_ASINS, asin)
                        if not found:
                            new_mov += ASIN_ADD(title)
                        tot_mov += 1
                        updateMoviedb(asin, 'popularity', tot_mov)
        if endIndex == 0:
            goAhead = 0
        page += 1
        if full_update:
            dialog.update(int((tot_mov) * 100.0 / MOV_TOTAL),
                          common.getString(30122) % page,
                          common.getString(30123) % new_mov)
        if full_update and dialog.iscanceled():
            goAhead = -1
    if goAhead == 0:
        updateLibrary()
        common.addon.setSetting("MoviesTotal", str(tot_mov))
        common.Log('Movie Update: New %s Deleted %s Total %s' %
                   (new_mov, deleteremoved(MOVIE_ASINS), tot_mov))
        if full_update:
            setNewest()
            dialog.close()
            updateFanart()
        xbmc.executebuiltin("XBMC.Container.Refresh")
        MovieDB.commit()
Esempio n. 26
0
 def wait(self, process):
     common.Log('Starting Thread')
     self._wakeUpThread = threading.Thread(target=self._wakeUpThreadProc, args=(process,))
     self._wakeUpThread.start()
     self.doModal()
     self._wakeUpThread.join()
Esempio n. 27
0
def main():
    """check if .noautosubs extension flag or 'noautosubs' file should be set or cleared
    """

    # get the path and name of file clicked onto
    filepathname = xbmc.getInfoLabel('ListItem.FileNameAndPath')
    # get the path of file clicked onto
    filepath = xbmc.getInfoLabel('ListItem.Path')

    common.Log("Context menu invoked on: " + filepathname.encode('utf-8'),
               xbmc.LOGINFO)

    # check if noautosubs file exists
    # do nothing if clicked item is not a real file
    protocols = ("videodb", "plugin")
    if filepathname.lower().startswith(tuple(p + '://' for p in protocols)):
        common.Log("Source not supported. Ignoring it.", xbmc.LOGINFO)
        return

    # check if clicked item is a folder
    if xbmc.getCondVisibility('ListItem.IsFolder'):
        # clicked item is a folder
        # check if folder contains noautosubs file
        if (xbmcvfs.exists(os.path.join(filepathname, "noautosubs"))):
            common.Log(
                "'noautosubs' file exists: " + os.path.join(
                    filepathname,
                    "noautosubs   Opening YesNoDialog.").encode('utf-8'),
                xbmc.LOGDEBUG)
            YesNoDialog = xbmcgui.Dialog().yesno(
                "Subtitles Mangler",
                common.__addonlang__(32107).encode('utf-8'),
                line2=filepathname.encode('utf-8'),
                line3=common.__addonlang__(32104).encode('utf-8'),
                nolabel=common.__addonlang__(32042).encode('utf-8'),
                yeslabel=common.__addonlang__(32043).encode('utf-8'))
            # answering Yes deletes the file
            if YesNoDialog:
                common.Log(
                    "Answer is Yes. Deleting file: " +
                    os.path.join(filepathname, "noautosubs").encode('utf-8'),
                    xbmc.LOGDEBUG)
                # delete noautosubs file
                common.DeleteFile(os.path.join(filepathname, "noautosubs"))
            else:
                common.Log("Answer is No. Doing nothing.", xbmc.LOGDEBUG)

        else:
            common.Log(
                "'noautosubs' file does not exist in: " +
                filepathname.encode('utf-8') + "   Opening YesNoDialog.",
                xbmc.LOGDEBUG)
            YesNoDialog = xbmcgui.Dialog().yesno(
                "Subtitles Mangler",
                common.__addonlang__(32108).encode('utf-8'),
                line2=filepathname.encode('utf-8'),
                line3=common.__addonlang__(32106).encode('utf-8'),
                nolabel=common.__addonlang__(32042).encode('utf-8'),
                yeslabel=common.__addonlang__(32043).encode('utf-8'))
            # answering Yes creates the file
            if YesNoDialog:
                common.Log(
                    "Answer is Yes. Creating file: " +
                    os.path.join(filepathname, "noautosubs").encode('utf-8'),
                    xbmc.LOGDEBUG)
                # create .noautosubs file
                common.CreateNoAutoSubsFile(
                    os.path.join(filepathname, "noautosubs"))
            else:
                common.Log("Answer is No. Doing nothing.", xbmc.LOGDEBUG)

    else:
        # clicked item is a file
        # check if folder contains .noautosubs file
        if (xbmcvfs.exists(os.path.join(filepath, "noautosubs"))):
            common.Log(
                "'noautosubs' file exists: " + os.path.join(
                    filepath,
                    "noautosubs   Opening Ok dialog.").encode('utf-8'),
                xbmc.LOGDEBUG)
            xbmcgui.Dialog().ok(
                "Subtitles Mangler",
                common.__addonlang__(32101).encode('utf-8'),
                line2=filepath.encode('utf-8'),
                line3=common.__addonlang__(32102).encode('utf-8'))
        else:
            common.Log(
                "'noautosubs' file does not exist in: " +
                filepath.encode('utf-8'), xbmc.LOGDEBUG)
            # check if .noautosubs extension exists
            filebase, _fileext = os.path.splitext(filepathname)
            if (xbmcvfs.exists(filebase + ".noautosubs")):
                # extension flag is set for this file
                common.Log(
                    "'.noautosubs' file exists: " + filebase.encode('utf-8') +
                    ".noautosubs   Opening YesNoDialog.", xbmc.LOGDEBUG)
                YesNoDialog = xbmcgui.Dialog().yesno(
                    "Subtitles Mangler",
                    common.__addonlang__(32103).encode('utf-8'),
                    line2=filepathname.encode('utf-8'),
                    line3=common.__addonlang__(32104).encode('utf-8'),
                    nolabel=common.__addonlang__(32042).encode('utf-8'),
                    yeslabel=common.__addonlang__(32043).encode('utf-8'))
                # answering Yes clears the flag
                if YesNoDialog:
                    common.Log(
                        "Answer is Yes. Deleting file: " +
                        filebase.encode('utf-8') + ".noautosubs",
                        xbmc.LOGDEBUG)
                    # delete .noautosubs file
                    common.DeleteFile(filebase + ".noautosubs")
                else:
                    common.Log("Answer is No. Doing nothing.", xbmc.LOGDEBUG)

            else:
                # extension flag is not set for this file
                common.Log(
                    "'.noautosubs' file does not exist. Opening YesNoDialog.",
                    xbmc.LOGDEBUG)
                YesNoDialog = xbmcgui.Dialog().yesno(
                    "Subtitles Mangler",
                    common.__addonlang__(32105).encode('utf-8'),
                    line2=filepathname.encode('utf-8'),
                    line3=common.__addonlang__(32106).encode('utf-8'),
                    nolabel=common.__addonlang__(32042).encode('utf-8'),
                    yeslabel=common.__addonlang__(32043).encode('utf-8'))
                # answering Yes sets the flag
                if YesNoDialog:
                    common.Log(
                        "Answer is Yes. Creating file: " +
                        filebase.encode('utf-8') + ".noautosubs",
                        xbmc.LOGDEBUG)
                    # create .noautosubs file
                    common.CreateNoAutoSubsFile(filebase + ".noautosubs")
                else:
                    common.Log("Answer is No. Doing nothing.", xbmc.LOGDEBUG)
Esempio n. 28
0
#!/usr/bin/env python
# --* coding: utf-8 -*-
import common as c
if __name__ == '__main__':
    print("ERROR 102 : PLEASE DON'T USE AS MAIN PATH")
else:
    c.Log("USE SPIDER MODULE")