Esempio n. 1
0
def create_meta_packs():
	import shutil
	global metaget
	container = metacontainers.MetaContainer()
	savpath = container.path
	AZ_DIRECTORIES.append('123')
	letters_completed = 0
	letters_per_zip = 27
	start_letter = ''
	end_letter = ''

	for type in ('tvshow','movie'):
		for letter in AZ_DIRECTORIES:
			if letters_completed == 0:
				start_letter = letter
				metaget.__del__()
				shutil.rmtree(container.cache_path)
				metaget=metahandlers.MetaData(preparezip=prepare_zip)

			if letters_completed <= letters_per_zip:
				scan_by_letter(type, letter)
				letters_completed += 1

			if (letters_completed == letters_per_zip
				or letter == '123' or get_dir_size(container.cache_path) > (500*1024*1024)):
				end_letter = letter
				arcname = 'MetaPack-%s-%s-%s.zip' % (type, start_letter, end_letter)
				arcname = os.path.join(savpath, arcname)
				metaget.__del__()
				zipdir(container.cache_path, arcname)
				metaget=metahandlers.MetaData(preparezip=prepare_zip)
				letters_completed = 0
				xbmc.sleep(5000)
Esempio n. 2
0
def show_torrent_info(info_hash):
    """
    Display current torrent info

    :param info_hash:
    :return:
    """
    torr_info = jsonrq.get_torrent_info(info_hash)
    info_dialog = xbmcgui.DialogProgress()
    info_dialog.create(torr_info['name'])
    while not info_dialog.iscanceled():
        info_dialog.update(torr_info['progress'],
                           _('state: {0}; seeds: {1}; peers: {2}').format(
                               torr_info['state'],
                               torr_info['num_seeds'],
                               torr_info['num_peers']
                           ),
                           _('size: {0}MB; DL speed: {1}KB/s; UL speed: {2}KB/s').format(
                               torr_info['size'],
                               torr_info['dl_speed'],
                               torr_info['ul_speed']
                           ),
                           _('total DL: {0}MB; total UL: {1}MB').format(
                               torr_info['total_download'],
                               torr_info['total_upload'])
                           )
        xbmc.sleep(1000)
        torr_info = jsonrq.get_torrent_info(info_hash)
Esempio n. 3
0
	def apt_commit_complete(self):

		# on commit complete, remove the notification from the Home window

		self.window.setProperty('OSMC_notification', 'false')

		# remove the file that blocks further update checks
		try:
			os.remove(self.block_update_file)
		except:
			pass

		if self.check_if_reboot_required():
			# the files flagging that an installed package needs a reboot are present


			# 0 "Prompt for all actions" -- PROMPT
			# 1 "Display icon on home screen only" -- PROMPT
			# 2 "Download updates, then prompt" -- PROMPT
			# 3 "Download and display icon" -- PROMPT
			# 4 "Download, install, prompt if restart needed" -- PROMPT

			# display dialogue saying that osmc needs to reboot
			reboot = DIALOG.yesno(lang(32077), lang(32079), lang(32080), yeslabel=lang(32081), nolabel=lang(32082))

			if reboot:

				exit_osmc_settings_addon()
				xbmc.sleep(1000)
				
				xbmc.executebuiltin('Reboot')

			else:
				# skip further update checks until osmc has rebooted
				self.skip_update_check = True 
Esempio n. 4
0
def install_metapack(pack):
	packs = metapacks.list()
	pack_details = packs[pack]
	mc = metacontainers.MetaContainer()
	work_path  = mc.work_path
	cache_path = mc.cache_path
	zip = os.path.join(work_path, pack)

	net = Net()
	cookiejar = ADDON.get_profile()
	cookiejar = os.path.join(cookiejar,'cookies')

	html = net.http_GET(pack_details[0]).content
	net.save_cookies(cookiejar)
	name = re.sub('-', r'\\\\u002D', pack)

	r = '"name": "%s".*?"id": "([^\s]*?)".*?"secure_prefix":"(.*?)",' % name
	r = re.search(r,html)
	pack_url  = 'http://i.minus.com'
	pack_url += r.group(2)
	pack_url += '/d' + r.group(1) + '.zip'

	complete = download_metapack(pack_url, zip, displayname=pack)
	extract_zip(zip, work_path)
	xbmc.sleep(5000)
	copy_meta_contents(work_path, cache_path)
	for table in mc.table_list:
		install = mc._insert_metadata(table)
Esempio n. 5
0
def Main():
    restart_reload = False
    try:
        w = Translator( "Translator-Main.xml", CWD )
        w.doModal()
        restart_reload = w.RestartXBMC_ReloadLanguage
        del w
    except:
        print_exc()
    xbmc.executebuiltin( "Dialog.Close(busydialog)" )

    if restart_reload:
        choices = [ "Restart XBMC", "Reload Language", "Close Dialog" ]
        selected = xbmcgui.Dialog().select( "XBMC language file has been changed!", choices )
        if selected == 0:
            if not UNDER_XBOX:
                xbmc.executebuiltin( "XBMC.Minimize()" )
            xbmc.executebuiltin( "XBMC.RestartApp()" )
            if os.environ.get( "OS", "win32" ) == "win32":
                os.startfile( os.path.join( CWD, "resources", "RestartXBMC", "windows.bat" ) )

        elif selected == 1:
            xbmc.executebuiltin( "ActivateWindow(appearancesettings)" )
            xbmc.sleep( 100 )
            xbmc.executebuiltin( "SetFocus(-99)" )
            xbmc.executebuiltin( "SetFocus(-80)" )

        else:
            xbmcgui.Dialog().ok( "XBMC Translator", "XBMC requires to restart to change your language.", "Or reload language." )
Esempio n. 6
0
  def Reload_Season(self):
     #-- load season list
    season_list = self.getControl(SEASON_LIST)
    season_list.reset()
    #---
    self.win.setProperty('Mode', u'Loader')
    xbmc.sleep(500)
    #---
    list = self.getSeasonData()
    #-- set serial list
    for rec in list:
        name = rec['name']
        item = xbmcgui.ListItem(name, thumbnailImage = rec['img'])
        item.setInfo(type='video', infoLabels={ 'plot':        rec['descr']})

        label2=[]
        if len(rec['name_orig']) > 0:
          label2.append(rec['name_orig'])
        if len(rec['season_number']) > 0:
          label2.append(u'[COLOR=66FFFFFF]Сезон:[/COLOR] %s' % rec['season_number'])
        if len(rec['year']) > 0:
          label2.append(u'[COLOR=66FFFFFF]Год:[/COLOR] %s' % rec['year'])
        item.setLabel2(u'[CR]'.join(label2))

        #item.setProperty('watch_started', 'True')
        item.setProperty('season_id', rec['season_id'])
        season_list.addItem(item)
    #---
    self.win.setProperty('Mode', self.mode)
    xbmc.sleep(500)
    self.win.setFocusId(SEASON_LIST)
Esempio n. 7
0
  def Reload_Movie(self):
    del self.list[:]

    #-- load movie list
    movie_list = self.getControl(MOVIE_LIST)
    movie_list.reset()
    #---
    self.win.setProperty('Mode', u'Loader')
    xbmc.sleep(500)
    #---
    list = self.getMovieData()
    #-- set serial list
    for rec in list:
        name = rec['name']
        if len(rec['name_orig'])>0:
            name = name + ' - ' + rec['name_orig']
        #name = name + ' (' + rec['season_number'] + u' сезон)'
        self.getControl(413).setLabel(name)

        for mov in rec['movie']:
            item = xbmcgui.ListItem(mov['movie_name'], thumbnailImage = rec['img'])
            item.setProperty('url', mov['url'])
            item.setProperty('img', rec['img'])

            item.setInfo(type='video', infoLabels={ 'plot':        rec['descr']})
            #item.setProperty('watched', 'True')

            movie_list.addItem(item)

            #-- add new item to the list
            self.list.append({'name': mov['movie_name'], 'url': mov['url'], 'img': rec['img']})
    #---
    self.win.setProperty('Mode', self.mode)
    xbmc.sleep(500)
    self.win.setFocusId(MOVIE_LIST)
Esempio n. 8
0
 def onPlayBackEnded(self):
     url = "http://"+LOCAL_IP+":"+str(VIDEO_PORT)+"/"
     xbmc.sleep(300)
     if os.path.exists("/proc/"+str(self.spsc_pid)) and xbmc.getCondVisibility("Window.IsActive(epg.xml)") and settings.getSetting('safe_stop')=="true":
         if not xbmc.Player(xbmc.PLAYER_CORE_AUTO).isPlaying():
             player = streamplayer(xbmc.PLAYER_CORE_AUTO , spsc_pid=self.spsc_pid , listitem=self.listitem)
             player.play(url, self.listitem)     
Esempio n. 9
0
def handle_wait_socket(time_to_wait,title,text,segunda=''):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        connected = False
        ret = mensagemprogresso.create(' '+title)
        secs=0
        percent=0
        increment = int(100 / time_to_wait)
        cancelled = False
        while secs < time_to_wait:
                try:
                        result = sock.connect(('127.0.0.1',8902))
                        connected = True
                        print("Connected to port 8902, server is working")
                        break
                        sock.close()
                except:
                        print("Stil trying to connect")
                secs = secs + 1
                percent = increment*secs
                secs_left = str((time_to_wait - secs))
                if segunda=='': remaining_display = translate(40187) + " " + str(percent) + " %"
                else: remaining_display=segunda
                mensagemprogresso.update(percent,text,remaining_display)
                xbmc.sleep(1000)
                if (mensagemprogresso.iscanceled()):
                        cancelled = True
                        break
        if cancelled == True:
                return False
        elif connected == True:
                mensagemprogresso.close()
                return True
        else:
                mensagemprogresso.close()
                return False
Esempio n. 10
0
    def submit(self):
        token = self.plex_network.sign_into_myplex(self.name_field.getText(), self.password_field.getText())

        if token is not None:
            self.name_label.setVisible(False)
            self.password_label.setVisible(False)
            self.name_field.setVisible(False)
            self.password_field.setVisible(False)
            self.manual_button.setVisible(False)
            self.cancel_button.setVisible(False)
            self.submit_button.setVisible(False)
            self.pin_button.setVisible(False)
            # tick mark
            self.tick = pyxbmct.Image("%s/resources/media/tick.png" % GLOBAL_SETUP['__cwd__'], aspectRatio=2)
            self.placeControl(self.tick, 2, 2, columnspan=2, rowspan=2)

            self.description.setText('Successfully Signed In')
            xbmc.sleep(2000)

            log_print("Successfully signed in")

            self.close()
        else:
            log_print("Not Successful signed in")
            self.display_manual(True)
Esempio n. 11
0
    def submit_pin(self):
        result = self.plex_network.check_signin_status(self.identifier)

        if result:
            self.digit_one.setVisible(False)
            self.digit_two.setVisible(False)
            self.digit_three.setVisible(False)
            self.digit_four.setVisible(False)
            self.manual_button.setVisible(False)
            self.cancel_button.setVisible(False)
            self.submit_button.setVisible(False)
            self.pin_button.setVisible(False)
            self.submit_pin_button.setVisible(False)
            # tick mark
            self.tick = pyxbmct.Image("%s/resources/media/tick.png" % GLOBAL_SETUP['__cwd__'], aspectRatio=2)
            self.placeControl(self.tick, 2, 2, columnspan=2, rowspan=2)

            self.description.setText('Successfully Signed In')
            xbmc.sleep(2000)

            log_print("Successfully signed in")

            self.close()
        else:
            log_print("Not Successful signed in")
            self.display_pin(True)
Esempio n. 12
0
 def run(self, oGuiElement, sTitle, sUrl):
     sPluginHandle = cPluginHandler().getPluginHandle();
     #meta = oGuiElement.getInfoLabel()
     meta = {'label': sTitle, 'title': sTitle}
     item = xbmcgui.ListItem(path=sUrl, iconImage="DefaultVideo.png",  thumbnailImage=self.sThumbnail)
     
     item.setInfo( type="Video", infoLabels= meta )
                 
     if (cConfig().getSetting("playerPlay") == '0'):   
                         
         sPlayerType = self.__getPlayerType()
         xbmcPlayer = xbmc.Player(sPlayerType)
         xbmcPlayer.play( sUrl, item )
         xbmcplugin.endOfDirectory(sPluginHandle, True, False, False) 
         
     else:
         xbmcplugin.setResolvedUrl(sPluginHandle, True, item)
     
     timer = int(cConfig().getSetting('param_timeout'))
     xbmc.sleep(timer)
     
     while not xbmc.abortRequested:
         try: 
            self.currentTime = self.getTime()
            self.totalTime = self.getTotalTime()
         except: break
         xbmc.sleep(1000)
Esempio n. 13
0
 def startPlayer(self):
     sPlayerType = self.__getPlayerType()
     xbmcPlayer = xbmc.Player(sPlayerType)
     oPlayList = self.__getPlayList()
     xbmcPlayer.play(oPlayList)
     timer = int(cConfig().getSetting('param_timeout'))
     xbmc.sleep(timer)            
Esempio n. 14
0
File: main.py Progetto: bialagary/mw
def RESOLVETVDL(name, url, thumb):

    data = 0
    try:
        data = GRABMETA(movie_name, year)
    except:
        data = 0
    hmf = urlresolver.HostedMediaFile(url)
    host = ""
    if hmf:
        url = urlresolver.resolve(url)
        host = hmf.get_host()
        if ".mp4" in url:
            ext = ".mp4"
        elif ".flv" in url:
            ext = ".flv"
        elif ".avi" in url:
            ext = ".avi"
        if not ext == "":

            console = "Downloads/TV Shows/" + dlfoldername
            params = {"url": url, "name": name, "thumb": thumb, "dlfoldername": dlfoldername}

            xbmc.sleep(1000)

            addToQueue(name, url, thumb, ext, console)
 def update_states(self):
     xbmc.sleep(2000)  # delay because MovieDB takes some time to update
     _, __, self.account_states = TheMovieDB.extended_episode_info(tvshow_id=self.tvshow_id,
                                                                   season=self.info["season"],
                                                                   episode=self.info["episode"],
                                                                   cache_time=0)
     super(DialogEpisodeInfo, self).update_states()
Esempio n. 16
0
 def __init__(self):
     xbmc.Player().stop()
     self.log=Logger("TSEngine")
     self.push=Logger('OUT')
     self.alive=True
     self.progress = xbmcgui.DialogProgress()
     self.player=None
     self.files={}
     self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self._sock.settimeout(3)
     self.progress.create(translate(40000),translate(40052))
     self.tsserv =None
     self.conn=False
     self.title=None
     self.filename=None
     self.mode=None
     self.url=None
     self.local=False
     self.saved=False
     self.pos=[25,50,75,100]
     l=False
     while xbmc.Player().isPlaying(): 
         l=True
         if xbmc.abortRequested:
             self.log.out("XBMC asked to abort request")
             return False
         if self.progress.iscanceled():
             return False
         xbmc.sleep(300)
     
     settings.setSetting('active','1')
     if l: xbmc.sleep(500)
Esempio n. 17
0
def panPlay():
    li = xbmcgui.ListItem(_station[0])
    li.setPath("special://home/addons/%s/silent.m4a" % _plugin)
    li.setProperty(_plugin, _stamp)
    li.setProperty('mimetype', 'audio/aac')

    _lock.acquire()
    start = time.time()
    panFill()

    while not _play:
        time.sleep(0.01)
        xbmc.sleep(1000)

        if xbmc.abortRequested:
            _lock.release()
            exit()

        if (threading.active_count() == 1) or ((time.time() - start) >= 60):
            if _play: break	# check one last time before we bail

            xbmc.log("%s.Play BAD (%13s, %ds)" % (_plugin, _stamp, time.time() - start))
            xbmcgui.Dialog().ok(_name, 'No Tracks Received', '', 'Try again later')
            exit()

    _playlist.clear()
    _lock.release()
    time.sleep(0.01)	# yield to the song threads
    xbmc.sleep(1000)	# might return control to xbmc and skip the other threads ?

    xbmcplugin.setResolvedUrl(_handle, True, li)
    _player.play(_playlist)
    xbmc.executebuiltin('ActivateWindow(10500)')

    xbmc.log("%s.Play  OK (%13s)           '%s - %s'" % (_plugin, _stamp, _station.id[-4:], _station.name))
def update_servers():
    server_path = os.path.join(config.get_runtime_path(), "servers", '*.xml')

    server_files = sorted(glob.glob(server_path))

    # ----------------------------
    import xbmc
    import xbmcgui
    progress = xbmcgui.DialogProgressBG()
    progress.create("Update servers list")
    # ----------------------------

    for index, server in enumerate(server_files):
        # ----------------------------
        percentage = index * 100 / len(server_files)
        # ----------------------------
        server_name = os.path.basename(server)[:-4]
        t = Thread(target=updater.update_server, args=[server_name])
        t.setDaemon(True)
        t.start()
        # ----------------------------
        progress.update(percentage, ' Update server: ' + server_name)
        # ----------------------------
        while threading.active_count() >= MAX_THREADS:
            xbmc.sleep(500)

    # ----------------------------
    progress.close()
Esempio n. 19
0
 def get_media_url(self, host, media_id):
     web_url = self.get_url(host, media_id)
     html = self.net.http_GET(web_url).content
     tries = 0
     while tries < MAX_TRIES:
         data = {}
         r = re.findall(r'type="hidden"\s*name="([^"]+)"\s*value="([^"]+)', html)
         for name, value in r:
             data[name] = value
         data['method_free'] = 'Free Download'
         data.update(captcha_lib.do_captcha(html))
         headers = {
             'Referer': web_url
         }
         html = self.net.http_POST(web_url, data, headers=headers).content
         if tries > 0:
             xbmc.sleep(6000)
         
         if '>File Download Link Generated<' in html:
             r = re.search("onClick\s*=\s*\"window\.open\('([^']+)", html)
             if r:
                 return r.group(1) + '|User-Agent=%s' % (common.IE_USER_AGENT)
         
         tries = tries + 1
         
     raise UrlResolver.ResolverError('Unable to locate link')
Esempio n. 20
0
def forecast(loc,locid):
	xbmc.log('weather location: %s' % locid,level=log_level)
	retry = 0
	while (retry < 6) and (not xbmc.abortRequested):
		query = get_weather(locid)
		if query != '':
			retry = 6
		else:
			retry += 1
			xbmc.sleep(10000)
			xbmc.log('Weather Download Failed',level=log_level)
	#xbmc.log('forecast data: %s' % query,level=log_level)
	retry = 0
	while (retry < 6) and (not xbmc.abortRequested):
		fquery = get_forecast(locid)
		if fquery != '':
			retry = 6
		else:
			retry += 1
			xbmc.sleep(10000)
			xbmc.log('Forecast Download Failed',level=log_level)
	#xbmc.log('forecast data: %s' % fquery,level=log_level)
	if fquery != '':
		properties(query,fquery,loc,locid)
	else:
		clear()
Esempio n. 21
0
 def end(self):
     if util.DEBUG:
         xbmc.sleep(500) #Give threads a chance to finish
         import threading
         util.LOG('Remaining Threads:')
         for t in threading.enumerate():
             util.LOG('  {0}'.format(t.name))
Esempio n. 22
0
    def run(self, content, name, url, year, imdb, tvdb, meta):

        if control.window.getProperty('PseudoTVRunning') == 'True':
            return control.player.play(url, control.item(path=url))

        self.getVideoInfo(content, name, year, imdb, tvdb)

        if self.folderPath.startswith('plugin://') and not meta == None:
            poster, thumb, meta = self.getMeta(meta)
        else:
            poster, thumb, meta = self.getLibraryMeta()

        item = control.item(path=url, iconImage='DefaultVideo.png', thumbnailImage=thumb)
        item.setInfo(type='Video', infoLabels = meta)
        try: item.setArt({'poster': poster, 'tvshow.poster': poster, 'season.poster': poster})
        except: pass
        item.setProperty('Video', 'true')
        item.setProperty('IsPlayable', 'true')
        control.player.play(url, item)

        for i in range(0, 240):
            if self.isPlayingVideo(): break
            xbmc.sleep(1000)
        while self.isPlayingVideo():
            try: self.totalTime = self.getTotalTime()
            except: pass
            try: self.currentTime = self.getTime()
            except: pass
            xbmc.sleep(1000)
        control.window.clearProperty('script.trakt.ids')
        time.sleep(5)
Esempio n. 23
0
def VerifyKeymapHot():
    dest = os.path.join(xbmc.translatePath('special://profile/keymaps'), KEYMAP_HOT)

    if os.path.exists(dest):
        return False

    key = ADDON.getSetting('HOTKEY').lower()

    includeKey = key in ['f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12', 'g']

    if not includeKey:
        DeleteKeymap(KEYMAP_HOT)
        return True

    cmd = '<keymap><Global><keyboard><%s>XBMC.RunScript(special://home/addons/plugin.program.super.favourites/hot.py)</%s></keyboard></Global></keymap>'  % (key, key)
    
    f = open(dest, mode='w')
    f.write(cmd)
    f.close()
    xbmc.sleep(1000)

    tries = 4
    while not os.path.exists(dest) and tries > 0:
        tries -= 1
        f = open(dest, mode='w')
        f.write(t)
        f.close()
        xbmc.sleep(1000)

    return True
 def list_dialog(self, movie_id):
     xbmc.executebuiltin("ActivateWindow(busydialog)")
     listitems = [LANG(32139)]
     account_lists = get_account_lists()
     for item in account_lists:
         listitems.append("%s (%i)" % (item["name"], item["item_count"]))
     listitems.append(LANG(32138))
     xbmc.executebuiltin("Dialog.Close(busydialog)")
     index = xbmcgui.Dialog().select(heading=LANG(32136),
                                     list=listitems)
     if index == 0:
         listname = xbmcgui.Dialog().input(heading=LANG(32137),
                                           type=xbmcgui.INPUT_ALPHANUM)
         if listname:
             list_id = create_list(listname)
             xbmc.sleep(1000)
             change_list_status(list_id=list_id,
                                movie_id=movie_id,
                                status=True)
     elif index == len(listitems) - 1:
         self.remove_list_dialog(account_lists)
     elif index > 0:
         change_list_status(list_id=account_lists[index - 1]["id"],
                            movie_id=movie_id,
                            status=True)
 def context_menu(self):
     item_id = self.listitem.getProperty("id")
     if self.type == "tv":
         listitems = [LANG(32169)]
     else:
         listitems = [LANG(32113)]
     if self.logged_in:
         listitems += [LANG(14076)]
         if not self.type == "tv":
             listitems += [LANG(32107)]
         if self.mode == "list":
             listitems += [LANG(32035)]
     selection = xbmcgui.Dialog().select(heading=LANG(32151),
                                         list=listitems)
     if selection == 0:
         if set_rating_prompt(self.type, item_id):
             xbmc.sleep(2000)
             self.update(force_update=True)
             self.getControl(500).selectItem(self.position)
     elif selection == 1:
         change_fav_status(media_id=item_id,
                           media_type=self.type,
                           status="true")
     elif selection == 2:
         self.list_dialog(item_id)
     elif selection == 3:
         change_list_status(list_id=self.list_id,
                            movie_id=item_id,
                            status=False)
         self.update(force_update=True)
         self.getControl(500).selectItem(self.position)
    def run(self):
        self.logMsg("Started")
        
        self.updateRecent()
        lastRun = datetime.today()
        lastProfilePath = xbmc.translatePath('special://profile')
        
        while (xbmc.abortRequested == False):
            td = datetime.today() - lastRun
            secTotal = td.seconds
            
            profilePath = xbmc.translatePath('special://profile')
            
            updateInterval = 60
            if (xbmc.Player().isPlaying()):
                updateInterval = 300
                
            if(secTotal > updateInterval or lastProfilePath != profilePath):
                self.updateRecent()
                lastRun = datetime.today()

            lastProfilePath = profilePath
            
            xbmc.sleep(3000)
                        
        self.logMsg("Exited")
Esempio n. 27
0
File: gui.py Progetto: bdntv/bdntv
    def onAction(self, action):
        if action.getId() in [ACTION_PARENT_DIR, ACTION_PREVIOUS_MENU, KEY_NAV_BACK, KEY_CONTEXT_MENU]:
            self.close()
            return

        if self.getFocusId() == self.C_CHANNELS_LIST and action.getId() == ACTION_LEFT:
            listControl = self.getControl(self.C_CHANNELS_LIST)
            idx = listControl.getSelectedPosition()
            buttonControl = self.getControl(self.C_CHANNELS_SELECTION)
            buttonControl.setLabel('[B]%s[/B]' % self.channelList[idx].title)

            self.getControl(self.C_CHANNELS_SELECTION_VISIBLE).setVisible(False)
            self.setFocusId(self.C_CHANNELS_SELECTION)

        elif self.getFocusId() == self.C_CHANNELS_SELECTION and action.getId() in [ACTION_RIGHT, ACTION_SELECT_ITEM]:
            self.getControl(self.C_CHANNELS_SELECTION_VISIBLE).setVisible(True)
            xbmc.sleep(350)
            self.setFocusId(self.C_CHANNELS_LIST)

        elif self.getFocusId() == self.C_CHANNELS_SELECTION and action.getId() == ACTION_UP:
            listControl = self.getControl(self.C_CHANNELS_LIST)
            idx = listControl.getSelectedPosition()
            if idx > 0:
                self.swapChannels(idx, idx - 1)

        elif self.getFocusId() == self.C_CHANNELS_SELECTION and action.getId() == ACTION_DOWN:
            listControl = self.getControl(self.C_CHANNELS_LIST)
            idx = listControl.getSelectedPosition()
            if idx < listControl.size() - 1:
                self.swapChannels(idx, idx + 1)
Esempio n. 28
0
    def processVideoThemes(self, jsonGet, target):
        # Only process anything if it is enabled
        if self.uploadsDisabled:
            return

        # Check if we need to upload the TV Shows
        if (target == 'tvshows') and not self.isTvShowsEnabled:
            return

        # Check if we need to upload the movies
        if (target == 'movies') and not self.isMoviesEnabled:
            return

        # Get the videos that are in the library
        themeList = self.getVideos(jsonGet, target)

        lastFileUploaded = False
        for videoItem in themeList:
            # We want to wait between each upload, there is no rush and we do not want
            # to interfere with anything that is playing, so spread out the uploads
            # As each sleep is a tenth of a second, lets split the uploads by 5 minutes each
            uploadWait = 3000
            while (uploadWait > 0) and lastFileUploaded:
                # Check to make sure we have not been requested to stop yet
                if xbmc.abortRequested:
                    return
                # Wait for a tenth of a second
                xbmc.sleep(100)
                uploadWait = uploadWait - 1

            lastFileUploaded = self.uploadThemeItem(videoItem)

            # Check if all uploads were disabled
            if self.uploadsDisabled or xbmc.abortRequested:
                return
    def get_media_url(self, host, media_id):
        web_url = self.get_url(host, media_id)
        html = self.net.http_GET(web_url).content
        form_values = {}
        stream_url = ''
        for i in re.finditer('<input type="hidden" name="([^"]+)" value="([^"]+)', html):
            form_values[i.group(1)] = i.group(2)

        xbmc.sleep(2000)
        html = self.net.http_POST(web_url, form_data=form_values).content
        
        r = re.search("file\s*:\s*'([^']+)'", html)
        if r:
            stream_url = r.group(1)

        for match in re.finditer('(eval\(function.*?)</script>', html, re.DOTALL):
            js_data = jsunpack.unpack(match.group(1))
            match2 = re.search('<param\s+name="src"\s*value="([^"]+)', js_data)
            if match2:
                stream_url = match2.group(1)
            else:
                match2 = re.search('<embed.*?type="video.*?src="([^"]+)', js_data)
                if match2:
                    stream_url = match2.group(1)
            
        if stream_url:
            return stream_url + '|User-Agent=%s&Referer=%s' % (common.IE_USER_AGENT, web_url)

        raise UrlResolver.ResolverError('Unable to resolve cloudyvideos link. Filelink not found.')
Esempio n. 30
0
    def LOAD_AND_PLAY_VIDEO(self, url, title, icon,year='',plot=''):
        progress = xbmcgui.DialogProgress()
        progress.create('Postęp', '')
        message = ptv.getLocalizedString(30406)
        progress.update( 10, "", message, "" )
        xbmc.sleep( 1000 )
        progress.update( 30, "", message, "" )
        progress.update( 50, "", message, "" )
        VideoLink = ''
        VideoLink = self.pp.getVideoLink(url)

        videoUrl = VideoLink
        progress.update( 70, "", message, "" )
        pluginhandle = int(sys.argv[1])
        if videoUrl == '':
            progress.close()
            d = xbmcgui.Dialog()
            d.ok('Nie znaleziono streamingu', 'Mo�e to chwilowa awaria.', 'Spr�buj ponownie za jaki� czas')
            return False
        if icon == '' or  icon == 'None':
            icon = "DefaultVideo.png"
        if plot == '' or plot == 'None':
            plot = ''
        liz=xbmcgui.ListItem(title, iconImage=icon, thumbnailImage=icon, path=videoUrl )
        liz.setInfo( type="video", infoLabels={ "Title": title} )
        xbmcPlayer = xbmc.Player()

        progress.update( 90, "", message, "" )
        progress.close()
        #listitem = xbmcgui.ListItem(path=videoUrl)
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
Esempio n. 31
0
    def settings_command(self, action):

        if action == 'update':

            self.call_child_script('update_manual')

            return 'Called child action - update_manual'

        if action == 'backup':

            self.update_settings()

            bckp = OSMC_Backups.osmc_backup(self.s, self.progress_bar)

            try:

                bckp.start_backup()

            except Exception as e:

                log('Backup Error Type and Args: %s : %s \n\n %s' %
                    (type(e).__name__, e.args, traceback.format_exc()))

                ok = DIALOG.ok(lang(32096), lang(32097))

            return 'Called BACKUP script complete'

        if action == 'restore':

            self.update_settings()

            bckp = OSMC_Backups.osmc_backup(self.s, self.progress_bar)

            try:

                bckp.start_restore()

                restart_required = bckp.restoring_guisettings

                if bckp.success != 'Full':

                    ok = DIALOG.ok('Restore', 'Some items failed to restore.',
                                   'See log for details.')

                    for x in bckp.success:

                        if x.endswith('userdata/guisettings.xml'):

                            restart_required = False

                if restart_required:

                    user_input_restart_now = DIALOG.yesno(lang(32110),
                                                          lang(32098),
                                                          lang(32099),
                                                          yeslabel=lang(32100),
                                                          nolabel=lang(32101))

                    if user_input_restart_now:

                        subprocess.Popen(
                            ['sudo', 'systemctl', 'restart', 'mediacenter'])

            except Exception as e:

                log('Backup Error Type and Args: %s : %s \n\n %s' %
                    (type(e).__name__, e.args, traceback.format_exc()))

                ok = DIALOG.ok(lang(32096), lang(32097))

            return 'Called RESTORE script complete'

        elif action == 'install':

            # check, _ = self.check_for_legit_updates()

            # if check == 'bail':

            # 	return  'Update not legit, bail'

            # if not self.EXTERNAL_UPDATE_REQUIRED:

            # 	__addon__.setSetting('install_now_visible', 'false')

            # 	self.call_child_script('commit')

            # 	return 'Called child action - commit'

            # else:

            ans = DIALOG.yesno(lang(32072), lang(32075), lang(32076))

            if ans:

                __addon__.setSetting('install_now_visible', 'false')

                exit_osmc_settings_addon()
                xbmc.sleep(1000)

                subprocess.Popen(
                    ['sudo', 'systemctl', 'start', 'manual-update'])

                return "Calling external update"
Esempio n. 32
0
    def end(self):
        if settings.getSetting("kill_type") == "1" or xbmc.getCondVisibility(
                'system.platform.windows'):
            self.active = False
            comm = 'SHUTDOWN'
            if self.conn: self.TSpush(comm)
            self.log.out("Ending")
            try:
                self._sock.shutdown(socket.SHUT_WR)
            except:
                pass
            if self.tsserv: self.tsserv.active = False
            if self.tsserv: self.tsserv.join()
            self.log.out("end thread")
            self._sock.close()
            self.log.out("socket closed")
            if self.progress: self.progress.close()

            if settings.getSetting('engine-status') == "true":
                try:
                    lat123._close()
                except:
                    pass

            if xbmc.getCondVisibility('system.platform.windows'):
                if settings.getSetting('shutdown-engine') == "true":
                    subprocess.Popen('taskkill /F /IM ace_engine.exe /T',
                                     shell=True)
                else:
                    pass
            elif xbmc.getCondVisibility(
                    'system.platform.linux'
            ) and not xbmc.getCondVisibility('System.Platform.Android'):
                if settings.getSetting('shutdown-engine') == "true":
                    try:
                        self.proc.kill()
                        self.proc.wait()
                        if settings.getSetting(
                                'openelecx86_64'
                        ) == "true" or settings.getSetting(
                                'openeleci386') == "true":
                            os.system(
                                "kill $(ps aux | grep '[a]cestream' | awk '{print $1}')"
                            )
                    except:
                        pass
            elif xbmc.getCondVisibility('system.platform.OSX'):
                if settings.getSetting('shutdown-engine') == "true":
                    try:
                        self.proc.kill()
                        self.proc.wait()
                    except:
                        pass
            elif xbmc.getCondVisibility(
                    'System.Platform.Android') and settings.getSetting(
                        "engine_app") == "0":
                if settings.getSetting('shutdown-engine') == "true":
                    try:
                        self.proc.kill()
                        self.proc.wait()
                    except:
                        pass
                    try:
                        xbmc_user = os.getlogin()
                        procshut_ace = subprocess.Popen(
                            ['ps', '|', 'grep', 'python'],
                            shell=False,
                            stdout=subprocess.PIPE)
                        for line in procshut_ace.stdout:
                            match = re.findall(r'\S+', line.rstrip())
                            if match:
                                if 'acestream' in match[-1] and len(match) > 2:
                                    if xbmc_user == match[0]:
                                        os.system("kill " + match[1])
                                    else:
                                        os.system("su -c kill " + match[1])
                    except:
                        pass

        if settings.getSetting(
                "kill_type"
        ) == "0" and not xbmc.getCondVisibility('system.platform.windows'):
            if xbmc.getCondVisibility(
                    'system.platform.linux'
            ) and not xbmc.getCondVisibility('System.Platform.Android'):
                os.system(
                    "kill $(ps aux | grep '[a]cestream' | awk '{print $1}')")
                os.system(
                    "kill $(ps aux | grep '[a]cestream' | awk '{print $2}')")
                os.system(
                    "kill $(ps aux | grep '[s]tart.py' | awk '{print $2}')")
                if settings.getSetting('save') != "true":
                    try:
                        cache_file = self.lnk.split('/')[-2]
                        if settings.getSetting('acestream_cachefolder') == '':
                            acestream_cachefolder_file = os.path.join(
                                os.getenv("HOME"), '.ACEStream', 'cache',
                                cache_file)
                        else:
                            acestream_cachefolder_file = os.path.join(
                                settings.getSetting('acestream_cachefolder'),
                                cache_file)
                        xbmcvfs.delete(acestream_cachefolder_file)
                    except:
                        pass

            elif xbmc.getCondVisibility('system.platform.OSX'):
                os.system("kill $(ps aux | grep '[s]tart.py')")
                if settings.getSetting('save') != "true":
                    try:
                        cache_file = self.lnk.split('/')[-2]
                        acestream_cachefolder_file = os.path.join(
                            os.getenv("HOME"), '.ACEStream', 'cache',
                            cache_file)
                        xbmcvfs.delete(acestream_cachefolder_file)
                    except:
                        pass

            elif xbmc.getCondVisibility('System.Platform.Android'):
                try:
                    procshut_ace = subprocess.Popen(
                        ['ps', '|', 'grep', 'python'],
                        shell=False,
                        stdout=subprocess.PIPE)
                    for line in procshut_ace.stdout:
                        match = re.findall(r'\S+', line.rstrip())
                        if match:
                            if 'acestream' in match[-1] and len(match) > 2:
                                os.system("kill " + match[1])
                                xbmc.sleep(200)
                except:
                    pass
                if settings.getSetting('save') != "true":
                    try:
                        cache_file = self.lnk.split('/')[-2]
                        if settings.getSetting('acestream_cachefolder') == '':
                            acestream_cachefolder_file = os.path.join(
                                '/sdcard', '.ACEStream', 'cache', cache_file)
                        else:
                            acestream_cachefolder_file = os.path.join(
                                settings.getSetting('acestream_cachefolder'),
                                cache_file)
                        xbmcvfs.delete(acestream_cachefolder_file)
                    except:
                        pass

            self.active = False
            self.log.out("Force Killing")
            try:
                self._sock.shutdown(socket.SHUT_WR)
            except:
                pass
            if self.tsserv: self.tsserv.active = False
            if self.tsserv: self.tsserv.join()
            self.log.out("end thread")
            self._sock.close()
            self.log.out("socket closed")
            if self.progress: self.progress.close()
Esempio n. 33
0
    def get_link(self, index=0, title='', icon='', thumb=''):
        self.title = title
        self.log.out("play")
        self.tsserv.ind = index
        self.progress.update(89, translate(1005), '')
        for k, v in self.files.iteritems():
            if v == index:
                self.filename = urllib.unquote(k).replace('/', '_').replace(
                    '\\', '_')
        try:
            avail = os.path.exists(self.filename.decode('utf-8'))
        except:
            try:
                avail = os.path.exists(self.filename)
                self.filename = self.filename.encode('utf-8')
            except:
                self.filename = 'temp.avi'
        self.log.out('Starting file:%s' % self.filename)

        try:
            self.filename = settings.getSetting('folder') + self.filename
        except:
            self.filename = None
            save = False

        self.log.out('Get filename to save:%s' % self.filename)
        spons = ''
        if self.mode != 'PID': spons = ' 0 0 0'
        comm = 'START ' + self.mode + ' ' + self.url + ' ' + str(index) + spons
        self.TSpush(comm)
        self.progress.update(89, translate(1004), '')
        while not self.tsserv.got_url and not self.progress.iscanceled(
        ) and not self.tsserv.err:
            self.progress.update(int(self.tsserv.proc), self.tsserv.label,
                                 self.tsserv.line)
            xbmc.sleep(200)
            if xbmc.abortRequested:
                self.log.out("XBMC is shutting down")
                break
        if self.tsserv.err: self.sm('Failed to load file')
        self.progress.update(100, translate(1005), '')
        if settings.getSetting('save') == 'true': save = True
        else: save = False

        if self.tsserv.event and save:
            self.progress.update(0, translate(400006), " ")
            comm = 'SAVE %s path=%s' % (self.tsserv.event[0] + ' ' +
                                        self.tsserv.event[1],
                                        urllib.quote(self.filename))
            self.TSpush(comm)
            self.tsserv.event = None
            succ = True

            while not os.path.exists(self.filename.decode(
                    'utf-8')) and not self.progress.iscanceled():
                if xbmc.abortRequested or self.progress.iscanceled():
                    self.log.out("XBMC asked to abort request")
                    succ = False
                    break
                xbmc.sleep(200)
            if not succ: return False
            self.tsserv.got_url = self.filename.decode('utf-8')
            self.local = True

        self.active = True
        self.progress.close()
        return self.tsserv.got_url
Esempio n. 34
0
def sleep(time):
    while time > 0 and not xbmc.abortRequested:
        xbmc.sleep(min(100, time))
        time = time - 100
                                else:
                                    playon = xbmcgui.Dialog().yesno(
                                        __language__(32004),
                                        __language__(32005),
                                        __language__(32003))
                                if (playon):
                                    xbmc.Player().pause()
                                else:
                                    if (getSetting("BrowseForShow").lower() ==
                                            "true"):
                                        browsenow = xbmcgui.Dialog().yesno(
                                            __language__(32006),
                                            __language__(32007))
                                    else:
                                        browsenow = False

                                    xbmc.Player().stop()
                                    if browsenow:
                                        command = '{"jsonrpc": "2.0", "method": "GUI.ActivateWindow", "params": { "window": "videos", "parameters": [ "videodb://2/2/%d/%d" ] }, "id": 1}' % (
                                            playingTvshowid, playingSeason)
                                        result = xbmc.executeJSONRPC(command)
                                        result = unicode(result,
                                                         'utf-8',
                                                         errors='ignore')


player_monitor = MyPlayer()

while not xbmc.abortRequested:
    xbmc.sleep(100)
Esempio n. 36
0
    smartmontools.checkConfigurationFilesExistance()

    if addon.getSetting(consts.settingDBupdates) == "true":
        smartmontools.updateDatabase()

    if addon.getSetting(consts.settingRunDaemonOnStartup) == "true":
        smartd.startDaemon()
        if smartd.daemonRunning():
            if addon.getSetting(consts.settingSmartdStartupPopup) == True:
                xbmc.executebuiltin("Notification(smartmontools, " +
                                    addon.getLocalizedString(50001) + ", 7, " +
                                    icon + ")")
                # smartd started
        else:
            xbmc.log(consts.logHeader + "failed to start smartd",
                     xbmc.LOGERROR)
            xbmcgui.Dialog().ok(consts.dialogHeader,
                                addon.getLocalizedString(50024))


def stopService():
    smartd.stopDaemon()


startService()

while (not xbmc.abortRequested):
    xbmc.sleep(250)

stopService()
    def onClick(self, controlID):

        Logutil.log('onClick', util.LOG_LEVEL_INFO)

        if (controlID == CONTROL_BUTTON_EXIT):  # Close window button
            Logutil.log('close', util.LOG_LEVEL_INFO)
            self.close()
        #OK
        elif (controlID == CONTROL_BUTTON_SAVE):
            Logutil.log('save', util.LOG_LEVEL_INFO)
            #store selectedRomCollection
            if (self.selectedRomCollection != None):
                self.updateSelectedRomCollection()
                self.romCollections[
                    self.selectedRomCollection.id] = self.selectedRomCollection

            configWriter = ConfigXmlWriter(False)
            success, message = configWriter.writeRomCollections(
                self.romCollections, True)

            if not success:
                xbmcgui.Dialog().ok(util.localize(32021), message)
            self.close()

        #Cancel
        elif (controlID == CONTROL_BUTTON_CANCEL):
            self.close()
        #Rom Collection list
        elif (self.selectedControlId
              in (CONTROL_BUTTON_RC_DOWN, CONTROL_BUTTON_RC_UP)):
            if (self.selectedRomCollection != None):
                #save current values to selected Rom Collection
                self.updateSelectedRomCollection()
                #store previous selectedRomCollections state
                self.romCollections[
                    self.selectedRomCollection.id] = self.selectedRomCollection

            #HACK: add a little wait time as XBMC needs some ms to execute the MoveUp/MoveDown actions from the skin
            xbmc.sleep(util.WAITTIME_UPDATECONTROLS)
            self.updateRomCollectionControls()

        #Media Path
        elif (self.selectedControlId
              in (CONTROL_BUTTON_MEDIA_DOWN, CONTROL_BUTTON_MEDIA_UP)):
            #HACK: add a little wait time as XBMC needs some ms to execute the MoveUp/MoveDown actions from the skin
            xbmc.sleep(util.WAITTIME_UPDATECONTROLS)
            self.updateMediaPathControls()

        elif (controlID == CONTROL_BUTTON_GAMECLIENT):
            success, gameclient = helper.selectlibretrocore(
                self.selectedRomCollection.name)
            if success:
                self.selectedRomCollection.gameclient = gameclient

            control = self.getControlById(CONTROL_BUTTON_GAMECLIENT)
            if (gameclient == ""):
                control.setLabel("None")
            else:
                control.setLabel(gameclient)

        elif (controlID == CONTROL_BUTTON_EMUCMD):

            #maybe there is autoconfig support
            preconfiguredEmulator = None
            emulatorPath = ''
            dialog = xbmcgui.Dialog()

            if (self.selectedRomCollection.name == 'Linux'
                    or self.selectedRomCollection.name == 'Macintosh'
                    or self.selectedRomCollection.name == 'Windows'):
                emulatorPath = self.editTextProperty(CONTROL_BUTTON_EMUCMD,
                                                     util.localize(32624))
            else:
                if (xbmc.getCondVisibility('System.Platform.Android')):

                    autoconfig = EmulatorAutoconfig(
                        util.getEmuAutoConfigPath())

                    Logutil.log(
                        'Running on Android. Trying to find emulator per autoconfig.',
                        util.LOG_LEVEL_INFO)
                    emulators = autoconfig.findEmulators(
                        'Android', self.selectedRomCollection.name, True)
                    emulist = []
                    if (emulators):
                        for emulator in emulators:
                            if (emulator.isInstalled):
                                emulist.append(
                                    util.localize(32202) % emulator.name)
                            else:
                                emulist.append(emulator.name)
                    if (len(emulist) > 0):
                        emuIndex = dialog.select(util.localize(32203), emulist)
                        Logutil.log('emuIndex: ' + str(emuIndex),
                                    util.LOG_LEVEL_INFO)
                        if (emuIndex == -1):
                            Logutil.log('No Emulator selected.',
                                        util.LOG_LEVEL_INFO)
                        else:
                            preconfiguredEmulator = emulators[emuIndex]

                if (preconfiguredEmulator):
                    emulatorPath = preconfiguredEmulator.emuCmd
                    self.selectedRomCollection.emulatorParams = preconfiguredEmulator.emuParams
                    control = self.getControlById(CONTROL_BUTTON_PARAMS)
                    control.setLabel(self.selectedRomCollection.emulatorParams)
                else:
                    emulatorPath = dialog.browse(
                        1, '%s ' % self.selectedRomCollection.name +
                        util.localize(32139), 'files')
                    if (emulatorPath == ''):
                        return

            self.selectedRomCollection.emulatorCmd = emulatorPath
            control = self.getControlById(CONTROL_BUTTON_EMUCMD)
            control.setLabel(emulatorPath)

        elif (controlID == CONTROL_BUTTON_PARAMS):
            emulatorParams = self.editTextProperty(CONTROL_BUTTON_PARAMS,
                                                   util.localize(32625))
            self.selectedRomCollection.emulatorParams = emulatorParams

        elif (controlID == CONTROL_BUTTON_ROMPATH):
            self.editRomPath()

        elif (controlID == CONTROL_BUTTON_FILEMASK):
            self.editRomFileMask()

        elif (controlID == CONTROL_BUTTON_MEDIAPATH):
            self.editMediaPath()

        elif (controlID == CONTROL_BUTTON_MEDIAFILEMASK):
            self.editMediaFileMask()

        elif (controlID == CONTROL_BUTTON_ADDMEDIAPATH):
            self.addMediaPath()

        elif (controlID == CONTROL_BUTTON_REMOVEMEDIAPATH):
            self.removeMediaPath()

        elif (controlID == CONTROL_BUTTON_MAXFOLDERDEPTH):
            maxFolderDepth = self.editTextProperty(
                CONTROL_BUTTON_MAXFOLDERDEPTH, util.localize(32610))
            self.selectedRomCollection.maxFolderDepth = maxFolderDepth

        elif (controlID == CONTROL_BUTTON_DISKINDICATOR):
            diskIndicator = self.editTextProperty(CONTROL_BUTTON_DISKINDICATOR,
                                                  util.localize(32611))
            self.selectedRomCollection.diskPrefix = diskIndicator

        elif (controlID == CONTROL_BUTTON_SAVESTATEPATH):
            saveStatePathComplete = self.editPathWithFileMask(
                CONTROL_BUTTON_SAVESTATEPATH,
                '%s ' % self.selectedRomCollection.name + util.localize(32629),
                CONTROL_BUTTON_SAVESTATEMASK)
            if (saveStatePathComplete != ''):
                self.selectedRomCollection.saveStatePath = saveStatePathComplete

        elif (controlID == CONTROL_BUTTON_SAVESTATEMASK):
            self.selectedRomCollection.saveStatePath = self.editFilemask(
                CONTROL_BUTTON_SAVESTATEMASK, util.localize(32630),
                self.selectedRomCollection.saveStatePath)

        elif (controlID == CONTROL_BUTTON_SAVESTATEPARAMS):
            saveStateParams = self.editTextProperty(
                CONTROL_BUTTON_SAVESTATEPARAMS, util.localize(32631))
            self.selectedRomCollection.saveStateParams = saveStateParams

        elif (controlID == CONTROL_BUTTON_PRECMD):
            preCmd = self.editTextProperty(CONTROL_BUTTON_PRECMD,
                                           util.localize(32632))
            self.selectedRomCollection.preCmd = preCmd
            Logutil.log(
                'OnClick: precmd = ' + self.selectedRomCollection.preCmd,
                util.LOG_LEVEL_INFO)

        elif (controlID == CONTROL_BUTTON_POSTCMD):
            postCmd = self.editTextProperty(CONTROL_BUTTON_POSTCMD,
                                            util.localize(32633))
            self.selectedRomCollection.postCmd = postCmd
Esempio n. 38
0
def add_tvshow(item, channel=None):
    """
        Guarda contenido en la libreria de series. Este contenido puede ser uno de estos dos:
            - La serie con todos los capitulos incluidos en la lista episodelist.
            - Un solo capitulo descargado previamente en local.

        Para añadir episodios descargados en local, el item debe tener exclusivamente:
            - contentSerieName (o show): Titulo de la serie
            - contentTitle: titulo del episodio para extraer season_and_episode ("1x01 Piloto")
            - title: titulo a mostrar junto al listado de enlaces -findvideos- ("Reproducir video local")
            - infoLabels["tmdb_id"] o infoLabels["imdb_id"]
            - contentType != "movie"
            - channel = "downloads"
            - url : ruta local al video

        @type item: item
        @param item: item que representa la serie a guardar
        @type channel: modulo
        @param channel: canal desde el que se guardara la serie.
            Por defecto se importara item.from_channel o item.channel

    """
    logger.info("show=#" + item.show + "#")

    if item.channel == "downloads":
        itemlist = [item.clone()]

    else:
        # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
        item.action = item.extra
        if isinstance(item.extra, str) and "###" in item.extra:
            item.action = item.extra.split("###")[0]
            item.extra = item.extra.split("###")[1]

        if item.from_action:
            item.__dict__["action"] = item.__dict__.pop("from_action")
        if item.from_channel:
            item.__dict__["channel"] = item.__dict__.pop("from_channel")

        if not channel:
            try:
                channel = __import__('channels.%s' % item.channel, fromlist=["channels.%s" % item.channel])
            except ImportError:
                exec "import channels." + item.channel + " as channel"

        #Para desambiguar títulos, se provoca que TMDB pregunte por el título realmente deseado
        #El usuario puede seleccionar el título entre los ofrecidos en la primera pantalla
        #o puede cancelar e introducir un nuevo título en la segunda pantalla
        #Si lo hace en "Introducir otro nombre", TMDB buscará automáticamente el nuevo título
        #Si lo hace en "Completar Información", cambia parcialmente al nuevo título, pero no busca en TMDB.  Hay que hacerlo
        #Si se cancela la segunda pantalla, la variable "scraper_return" estará en False.  El usuario no quiere seguir
        
        item = generictools.update_title(item) #Llamamos al método que actualiza el título con tmdb.find_and_set_infoLabels
        #if item.tmdb_stat:
        #    del item.tmdb_stat          #Limpiamos el status para que no se grabe en la Videoteca
                
        # Obtiene el listado de episodios
        itemlist = getattr(channel, item.action)(item)
        
    insertados, sobreescritos, fallidos, path = save_tvshow(item, itemlist)

    if not insertados and not sobreescritos and not fallidos:
        platformtools.dialog_ok(config.get_localized_string(30131), config.get_localized_string(60067))
        logger.error("La serie %s no se ha podido añadir a la videoteca. No se ha podido obtener ningun episodio"
                     % item.show)

    elif fallidos == -1:
        platformtools.dialog_ok(config.get_localized_string(30131), config.get_localized_string(60068))
        logger.error("La serie %s no se ha podido añadir a la videoteca" % item.show)

    elif fallidos > 0:
        platformtools.dialog_ok(config.get_localized_string(30131), config.get_localized_string(60069))
        logger.error("No se han podido añadir %s episodios de la serie %s a la videoteca" % (fallidos, item.show))

    else:
        platformtools.dialog_ok(config.get_localized_string(30131), config.get_localized_string(60070))
        logger.info("Se han añadido %s episodios de la serie %s a la videoteca" %
                    (insertados, item.show))
        if config.is_xbmc():
            if config.get_setting("sync_trakt_new_tvshow", "videolibrary"):
                import xbmc
                from platformcode import xbmc_videolibrary
                if config.get_setting("sync_trakt_new_tvshow_wait", "videolibrary"):
                    # Comprobar que no se esta buscando contenido en la videoteca de Kodi
                    while xbmc.getCondVisibility('Library.IsScanningVideo()'):
                        xbmc.sleep(1000)
                # Se lanza la sincronizacion para la videoteca de Kodi
                xbmc_videolibrary.sync_trakt_kodi()
                # Se lanza la sincronización para la videoteca del addon
                xbmc_videolibrary.sync_trakt_addon(path)
Esempio n. 39
0
print CurrrentVersion
LatestVersion = re.findall('hackedtv\sversion=\"(.+?)\"',
                           net().http_GET(NewVersionUrl).content)[0]
print CurrrentVersion
print LatestVersion

if LatestVersion > CurrrentVersion:
    xbmc.log('hackermil HackedTV Updater')
    xbmc.log('Currently Installed: %s Latest Version Available: %s' %
             (CurrrentVersion, LatestVersion))
    xbmc.executebuiltin(
        "XBMC.Notification([COLOR aqua]HackedTV Information[/COLOR],[COLOR aqua]An Update Has Been Found And Will Be Downloaded And Installed[/COLOR],7000,"
        + os.path.join(art, 'hms.png') + ")")
    GA('TEST', 'CV: %s NV: %s' % (CurrrentVersion, LatestVersion))
    xbmc.sleep(4000)
    TextBox()
    downloadFile = os.path.join(downloadPath, UpdateName)
    try:
        os.remove(downloadFile)
    except:
        pass
    GA('TEST', 'DISPLAY CHANGELOG')
    print 'DL PATH: ' + str(downloadPath)
    print 'DF path: ' + str(downloadFile)
    QuietDownload(UpdateUrl, downloadPath, UpdateName, UpdateName)

#xbmc.log('hackermil HackedTV Updater')
#
#OLC_url = 'http://bitbucket.org/jas0npc_13/jas0npc-repo/raw/master/hackTest/hackedtvVersion.xml'
#newVersion = re.findall('hackedtv\sversion=\"(.+?)\"', net().http_GET(OLC_url).content)[0]
Esempio n. 40
0
def download(link, episode=""):
    log(__name__, "Download Subscene")
    subtitle_list = []
    exts = [".srt", ".sub", ".txt", ".smi", ".ssa", ".ass"]
    downloadlink_pattern = "...<a href=\"(.+?)\" rel=\"nofollow\" onclick=\"DownloadSubtitle"

    uid = uuid.uuid4()
    tempdir = os.path.join(TEMP, unicode(uid))
    xbmcvfs.mkdirs(tempdir)

    content, resp = geturl(link)
    match = re.compile(downloadlink_pattern).findall(content)
    if match:
        downloadlink = main_url + match[0]
        viewstate = 0
        previouspage = 0
        subtitleid = 0
        typeid = "zip"
        filmid = 0

        jsondata = {"url": downloadlink}
        data = json.dumps(jsondata)

        request = urllib2.Request("https://us-central1-kodi-thuongtin.cloudfunctions.net/subscene2", data , {'Content-Type': 'application/json', 'Content-Length': len(data)})
        response = urllib2.urlopen(request)

        if response.getcode() != 200:
            log(__name__, "Failed to download subtitle file")
            return subtitle_list
        local_tmp_file = os.path.join(tempdir, "subscene.xxx")
        packed = False

        try:
            log(__name__, "Saving subtitles to '%s'" % local_tmp_file)
            local_file_handle = xbmcvfs.File(local_tmp_file, "wb")
            local_file_handle.write(response.read())
            # local_file_handle.write(content)
            local_file_handle.close()

            # Check archive type (rar/zip/else) through the file header (rar=Rar!, zip=PK)
            myfile = xbmcvfs.File(local_tmp_file, "rb")
            myfile.seek(0,0)
            if myfile.read(1) == 'R':
                typeid = "rar"
                packed = True
                log(__name__, "Discovered RAR Archive")
            else:
                myfile.seek(0,0)
                if myfile.read(1) == 'P':
                    typeid = "zip"
                    packed = True
                    log(__name__, "Discovered ZIP Archive")
                else:
                    typeid = "srt"
                    packed = False
                    log(__name__, "Discovered a non-archive file")
            myfile.close()
            local_tmp_file = os.path.join(tempdir, "subscene." + typeid)
            xbmcvfs.rename(os.path.join(tempdir, "subscene.xxx"), local_tmp_file)
            log(__name__, "Saving to %s" % local_tmp_file)
        except:
            log(__name__, "Failed to save subtitle to %s" % local_tmp_file)

        if packed:
            xbmc.sleep(500)
            xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % (local_tmp_file, tempdir,)).encode('utf-8'), True)

        episode_pattern = None
        if episode != '':
            episode_pattern = re.compile(get_episode_pattern(episode), re.IGNORECASE)

        for dir in xbmcvfs.listdir(tempdir)[0]:
            for file in xbmcvfs.listdir(os.path.join(tempdir, dir))[1]:
                if os.path.splitext(file)[1] in exts:
                    log(__name__, 'match '+episode+' '+file)
                    if episode_pattern and not episode_pattern.search(file):
                        continue
                    log(__name__, "=== returning subtitle file %s" % file)
                    subtitle_list.append(os.path.join(tempdir, dir, file))

        for file in xbmcvfs.listdir(tempdir)[1]:
            if os.path.splitext(file)[1] in exts:
                log(__name__, 'match '+episode+' '+file)
                if episode_pattern and not episode_pattern.search(file):
                    continue
                log(__name__, "=== returning subtitle file %s" % file)
                subtitle_list.append(os.path.join(tempdir, file))

        if len(subtitle_list) == 0:
            if episode:
                _xbmc_notification(32002)
            else:
                _xbmc_notification(32003)

    return subtitle_list
Esempio n. 41
0
    def get(self, name, imdb, season, episode):
        try:
            if not control.setting('subtitles') == 'true': raise Exception()

            langDict = {
                'Afrikaans': 'afr',
                'Albanian': 'alb',
                'Arabic': 'ara',
                'Armenian': 'arm',
                'Basque': 'baq',
                'Bengali': 'ben',
                'Bosnian': 'bos',
                'Breton': 'bre',
                'Bulgarian': 'bul',
                'Burmese': 'bur',
                'Catalan': 'cat',
                'Chinese': 'chi',
                'Croatian': 'hrv',
                'Czech': 'cze',
                'Danish': 'dan',
                'Dutch': 'dut',
                'English': 'eng',
                'Esperanto': 'epo',
                'Estonian': 'est',
                'Finnish': 'fin',
                'French': 'fre',
                'Galician': 'glg',
                'Georgian': 'geo',
                'German': 'ger',
                'Greek': 'ell',
                'Hebrew': 'heb',
                'Hindi': 'hin',
                'Hungarian': 'hun',
                'Icelandic': 'ice',
                'Indonesian': 'ind',
                'Italian': 'ita',
                'Japanese': 'jpn',
                'Kazakh': 'kaz',
                'Khmer': 'khm',
                'Korean': 'kor',
                'Latvian': 'lav',
                'Lithuanian': 'lit',
                'Luxembourgish': 'ltz',
                'Macedonian': 'mac',
                'Malay': 'may',
                'Malayalam': 'mal',
                'Manipuri': 'mni',
                'Mongolian': 'mon',
                'Montenegrin': 'mne',
                'Norwegian': 'nor',
                'Occitan': 'oci',
                'Persian': 'per',
                'Polish': 'pol',
                'Portuguese': 'por,pob',
                'Portuguese(Brazil)': 'pob,por',
                'Romanian': 'rum',
                'Russian': 'rus',
                'Serbian': 'scc',
                'Sinhalese': 'sin',
                'Slovak': 'slo',
                'Slovenian': 'slv',
                'Spanish': 'spa',
                'Swahili': 'swa',
                'Swedish': 'swe',
                'Syriac': 'syr',
                'Tagalog': 'tgl',
                'Tamil': 'tam',
                'Telugu': 'tel',
                'Thai': 'tha',
                'Turkish': 'tur',
                'Ukrainian': 'ukr',
                'Urdu': 'urd'
            }

            codePageDict = {
                'ara': 'cp1256',
                'ar': 'cp1256',
                'ell': 'cp1253',
                'el': 'cp1253',
                'heb': 'cp1255',
                'he': 'cp1255',
                'tur': 'cp1254',
                'tr': 'cp1254',
                'rus': 'cp1251',
                'ru': 'cp1251'
            }

            quality = [
                'bluray', 'hdrip', 'brrip', 'bdrip', 'dvdrip', 'webrip', 'hdtv'
            ]

            langs = []
            try:
                try:
                    langs = langDict[control.setting(
                        'subtitles.lang.1')].split(',')
                except:
                    langs.append(langDict[control.setting('subtitles.lang.1')])
            except:
                pass
            try:
                try:
                    langs = langs + langDict[control.setting(
                        'subtitles.lang.2')].split(',')
                except:
                    langs.append(langDict[control.setting('subtitles.lang.2')])
            except:
                pass

            try:
                subLang = xbmc.Player().getSubtitles()
            except:
                subLang = ''
            if subLang == langs[0]: raise Exception()

            server = xmlrpclib.Server('http://api.opensubtitles.org/xml-rpc',
                                      verbose=0)
            token = server.LogIn('', '', 'en', 'XBMC_Subtitles_v1')['token']

            sublanguageid = ','.join(langs)
            imdbid = re.sub('[^0-9]', '', imdb)

            if not (season == None or episode == None):
                result = server.SearchSubtitles(token, [{
                    'sublanguageid': sublanguageid,
                    'imdbid': imdbid,
                    'season': season,
                    'episode': episode
                }])['data']
                fmt = ['hdtv']
            else:
                result = server.SearchSubtitles(token, [{
                    'sublanguageid': sublanguageid,
                    'imdbid': imdbid
                }])['data']
                try:
                    vidPath = xbmc.Player().getPlayingFile()
                except:
                    vidPath = ''
                fmt = re.split('\.|\(|\)|\[|\]|\s|\-', vidPath)
                fmt = [i.lower() for i in fmt]
                fmt = [i for i in fmt if i in quality]

            filter = []
            result = [i for i in result if i['SubSumCD'] == '1']

            for lang in langs:
                filter += [
                    i for i in result if i['SubLanguageID'] == lang and any(
                        x in i['MovieReleaseName'].lower() for x in fmt)
                ]
                filter += [
                    i for i in result if i['SubLanguageID'] == lang and any(
                        x in i['MovieReleaseName'].lower() for x in quality)
                ]
                filter += [i for i in result if i['SubLanguageID'] == lang]

            try:
                lang = xbmc.convertLanguage(filter[0]['SubLanguageID'],
                                            xbmc.ISO_639_1)
            except:
                lang = filter[0]['SubLanguageID']

            content = [
                filter[0]['IDSubtitleFile'],
            ]
            content = server.DownloadSubtitles(token, content)
            content = base64.b64decode(content['data'][0]['data'])
            content = str(
                zlib.decompressobj(16 + zlib.MAX_WBITS).decompress(content))

            subtitle = xbmc.translatePath('special://temp/')
            subtitle = os.path.join(subtitle, 'TemporarySubs.%s.srt' % lang)

            codepage = codePageDict.get(lang, '')
            if codepage and control.setting('subtitles.utf') == 'true':
                try:
                    content_encoded = codecs.decode(content, codepage)
                    content = codecs.encode(content_encoded, 'utf-8')
                except:
                    pass

            file = control.openFile(subtitle, 'w')
            file.write(str(content))
            file.close()

            xbmc.sleep(1000)
            xbmc.Player().setSubtitles(subtitle)
        except:
            pass
Esempio n. 42
0
 def __init__(self, *args, **kwargs):
     xbmc.executebuiltin("ActivateWindow(%d)" % (self.WINDOW, ))
     self.win = xbmcgui.Window(self.WINDOW)
     xbmc.sleep(1000)
     self.setControls()
Esempio n. 43
0
	def get(self, name, imdb, season, episode):
		try:
			import gzip, codecs
			from io import BytesIO
			import re, base64
			import xmlrpc.client as xmlrpc_client
		except:
			log_utils.error()
			return
		try:
			langDict = {'Afrikaans': 'afr', 'Albanian': 'alb', 'Arabic': 'ara', 'Armenian': 'arm', 'Basque': 'baq', 'Bengali': 'ben',
			'Bosnian': 'bos', 'Breton': 'bre', 'Bulgarian': 'bul', 'Burmese': 'bur', 'Catalan': 'cat', 'Chinese': 'chi', 'Croatian': 'hrv',
			'Czech': 'cze', 'Danish': 'dan', 'Dutch': 'dut', 'English': 'eng', 'Esperanto': 'epo', 'Estonian': 'est', 'Finnish': 'fin',
			'French': 'fre', 'Galician': 'glg', 'Georgian': 'geo', 'German': 'ger', 'Greek': 'ell', 'Hebrew': 'heb', 'Hindi': 'hin',
			'Hungarian': 'hun', 'Icelandic': 'ice', 'Indonesian': 'ind', 'Italian': 'ita', 'Japanese': 'jpn', 'Kazakh': 'kaz', 'Khmer': 'khm',
			'Korean': 'kor', 'Latvian': 'lav', 'Lithuanian': 'lit', 'Luxembourgish': 'ltz', 'Macedonian': 'mac', 'Malay': 'may',
			'Malayalam': 'mal', 'Manipuri': 'mni', 'Mongolian': 'mon', 'Montenegrin': 'mne', 'Norwegian': 'nor', 'Occitan': 'oci',
			'Persian': 'per', 'Polish': 'pol', 'Portuguese': 'por,pob', 'Portuguese(Brazil)': 'pob,por', 'Romanian': 'rum', 'Russian': 'rus',
			'Serbian': 'scc', 'Sinhalese': 'sin', 'Slovak': 'slo', 'Slovenian': 'slv', 'Spanish': 'spa', 'Swahili': 'swa', 'Swedish': 'swe',
			'Syriac': 'syr', 'Tagalog': 'tgl', 'Tamil': 'tam', 'Telugu': 'tel', 'Thai': 'tha', 'Turkish': 'tur', 'Ukrainian': 'ukr', 'Urdu': 'urd'}
			codePageDict = {'ara': 'cp1256', 'ar': 'cp1256', 'ell': 'cp1253', 'el': 'cp1253', 'heb': 'cp1255',
									'he': 'cp1255', 'tur': 'cp1254', 'tr': 'cp1254', 'rus': 'cp1251', 'ru': 'cp1251'}
			quality = ['bluray', 'hdrip', 'brrip', 'bdrip', 'dvdrip', 'webrip', 'hdtv']
			langs = []
			try:
				try: langs = langDict[control.setting('subtitles.lang.1')].split(',')
				except: langs.append(langDict[control.setting('subtitles.lang.1')])
			except: pass
			try:
				try: langs = langs + langDict[control.setting('subtitles.lang.2')].split(',')
				except: langs.append(langDict[control.setting('subtitles.lang.2')])
			except: pass
			try: subLang = xbmc.Player().getSubtitles()
			except: subLang = ''

			if subLang == langs[0]: raise Exception()
			server = xmlrpc_client.Server('https://api.opensubtitles.org/xml-rpc', verbose=0)
			# token = server.LogIn('', '', 'en', 'XBMC_Subtitles_v1')
			token = server.LogIn('', '', 'en', 'XBMC_Subtitles_Unofficial_v5.2.14') # service.subtitles.opensubtitles_by_opensubtitles
			if 'token' not in token:
				return log_utils.log('OpenSubtitles Login failed: token=%s' % token, level=log_utils.LOGWARNING)
			else: token = token['token']

			sublanguageid = ','.join(langs)
			imdbid = re.sub(r'[^0-9]', '', imdb)
			if not (season is None or episode is None):
				result = server.SearchSubtitles(token, [{'sublanguageid': sublanguageid, 'imdbid': imdbid, 'season': season, 'episode': episode}])['data']
				fmt = ['hdtv']
			else:
				result = server.SearchSubtitles(token, [{'sublanguageid': sublanguageid, 'imdbid': imdbid}])['data']
				try: vidPath = xbmc.Player().getPlayingFile()
				except: vidPath = ''
				fmt = re.split(r'\.|\(|\)|\[|\]|\s|\-', vidPath)
				fmt = [i.lower() for i in fmt]
				fmt = [i for i in fmt if i in quality]
			filter = []
			result = [i for i in result if i['SubSumCD'] == '1']
			for lang in langs:
				filter += [i for i in result if i['SubLanguageID'] == lang and any(x in i['MovieReleaseName'].lower() for x in fmt)]
				filter += [i for i in result if i['SubLanguageID'] == lang and any(x in i['MovieReleaseName'].lower() for x in quality)]
				filter += [i for i in result if i['SubLanguageID'] == lang]

			try: lang = xbmc.convertLanguage(filter[0]['SubLanguageID'], xbmc.ISO_639_1)
			except: lang = filter[0]['SubLanguageID']
			filename = filter[0]['SubFileName']
			log_utils.log('downloaded subtitle=%s' % filename, level=log_utils.LOGDEBUG)

			content = [filter[0]['IDSubtitleFile'],]
			content = server.DownloadSubtitles(token, content)
			content = base64.b64decode(content['data'][0]['data'])
			content = gzip.GzipFile(fileobj=BytesIO(content)).read()
			subtitle = control.transPath('special://temp/')
			subtitle = control.joinPath(subtitle, 'TemporarySubs.%s.srt' % lang)
			log_utils.log('subtitle file = %s' % subtitle, level=log_utils.LOGDEBUG)

			codepage = codePageDict.get(lang, '')
			if codepage and control.setting('subtitles.utf') == 'true':
				try:
					content_encoded = codecs.decode(content, codepage) # check for kodi 19?
					content = codecs.encode(content_encoded, 'utf-8') # check for kodi 19?
				except: pass

			file = control.openFile(subtitle, 'w')
			file.write(content)
			file.close()
			xbmc.sleep(1000)
			xbmc.Player().setSubtitles(subtitle)
			if control.setting('subtitles.notification') == 'true':
				if Player().isPlayback():
					control.sleep(500)
					control.notification(title=filename, message=control.lang(32191) % lang.upper())
		except:
			log_utils.error()
def doDownload(url, dest, title, image, headers):

    headers = json.loads(urllib.unquote_plus(headers))

    url = urllib.unquote_plus(url)

    title = urllib.unquote_plus(title)

    image = urllib.unquote_plus(image)

    dest = urllib.unquote_plus(dest)

    file = dest.rsplit(os.sep, 1)[-1]

    resp = getResponse(url, headers, 0)

    if not resp:
        xbmcgui.Dialog().ok(title, dest, 'Download fehlgeschlagen',
                            'Keine Antwort vom Server')
        return

    try:
        content = int(resp.headers['Content-Length'])
    except:
        content = 0

    try:
        resumable = 'bytes' in resp.headers['Accept-Ranges'].lower()
    except:
        resumable = False

    #print "Download Header"
    #print resp.headers
    if resumable:
        print "Download is resumable"

    if content < 1:
        xbmcgui.Dialog().ok(title, file, 'Unbekannte Dateigröße',
                            'Download nicht möglich')
        return

    size = 1024 * 1024
    mb = content / (1024 * 1024)

    if content < size:
        size = content

    total = 0
    notify = 0
    errors = 0
    count = 0
    resume = 0
    sleep = 0

    if xbmcgui.Dialog().yesno(title + ' - Download bestätigen', file,
                              'Dateigröße %dMB' % mb, 'Download fortsetzen?',
                              'Fortsetzen', 'Abbrechen') == 1:
        return

    print 'Download File Size : %dMB %s ' % (mb, dest)

    #f = open(dest, mode='wb')
    f = xbmcvfs.File(dest, 'w')

    chunks = []

    while True:
        downloaded = total
        for c in chunks:
            downloaded += len(c)
        percent = min(100 * downloaded / content, 100)
        if percent >= notify:
            xbmc.executebuiltin(
                "XBMC.Notification(%s,%s,%i,%s)" %
                (str(percent) + '%' + ' - ' + title, dest, 10000, image))

            print 'Download percent : %s %s %dMB downloaded : %sMB File Size : %sMB' % (
                str(percent) + '%', dest, mb, downloaded / 1000000,
                content / 1000000)

            notify += 10

        chunk = None
        error = False

        try:
            chunk = resp.read(size)
            if not chunk:
                if percent < 99:
                    error = True
                else:
                    while len(chunks) > 0:
                        c = chunks.pop(0)
                        f.write(c)
                        del c

                    f.close()
                    print '%s download complete' % (dest)
                    return done(title, dest, True)

        except Exception, e:
            print str(e)
            error = True
            sleep = 10
            errno = 0

            if hasattr(e, 'errno'):
                errno = e.errno

            if errno == 10035:  # 'A non-blocking socket operation could not be completed immediately'
                pass

            if errno == 10054:  #'An existing connection was forcibly closed by the remote host'
                errors = 10  #force resume
                sleep = 30

            if errno == 11001:  # 'getaddrinfo failed'
                errors = 10  #force resume
                sleep = 30

        if chunk:
            errors = 0
            chunks.append(chunk)
            if len(chunks) > 5:
                c = chunks.pop(0)
                f.write(c)
                total += len(c)
                del c

        if error:
            errors += 1
            count += 1
            print '%d Error(s) whilst downloading %s' % (count, dest)
            xbmc.sleep(sleep * 1000)

        if (resumable and errors > 0) or errors >= 10:
            if (not resumable and resume >= 50) or resume >= 500:
                #Give up!
                print '%s download canceled - too many error whilst downloading' % (
                    dest)
                return done(title, dest, False)

            resume += 1
            errors = 0
            if resumable:
                chunks = []
                #create new response
                print 'Download resumed (%d) %s' % (resume, dest)
                resp = getResponse(url, headers, total)
            else:
                #use existing response
                pass
Esempio n. 45
0
    alreadyRunning = xbmcgui.Window(10000).getProperty(
        "VideoScreensaverStarting")
    if alreadyRunning in ["", None]:
        xbmcgui.Window(10000).setProperty("VideoScreensaverStarting", "true")

        # Make a special check to see if TvTunes is running - as we want to give that time
        # to stop before we start trying to play the video
        maxTvTunesWait = 40
        while maxTvTunesWait > 0:
            maxTvTunesWait = maxTvTunesWait - 1
            # If TvTunes is not running then stop waiting
            if xbmcgui.Window(10025).getProperty("TvTunesIsRunning") in [
                    None, ""
            ]:
                break
            xbmc.sleep(100)

        try:
            # Stop TvTunes trying to start while we load the screensaver
            xbmcgui.Window(10025).setProperty("TvTunesIsRunning",
                                              "VideoScreensaver")

            # Give a little bit of time for everything to shake out before starting the screensaver
            # waiting another few seconds to start a screensaver is not going to make a difference
            # to the user
            xbmc.sleep(1000)

            # Check if media (Music or video) is playing already when the screensaver
            # starts, as the user may want to stop the screensaver running if they are
            # playing music
            if not (xbmc.Player().isPlaying()
Esempio n. 46
0
    def keepPlaybackAlive(self):
        pname = '%s.player.overlay' % control.addonInfo('id')
        control.window.clearProperty(pname)

        if self.content == 'movie':
            overlay = playcount.getMovieOverlay(playcount.getMovieIndicators(),
                                                self.imdb)

        elif self.content == 'episode':
            overlay = playcount.getEpisodeOverlay(
                playcount.getTVShowIndicators(), self.imdb, self.tvdb,
                self.season, self.episode)

        else:
            overlay = '6'

        for i in range(0, 240):
            if self.isPlayingVideo(): break
            xbmc.sleep(1000)

        if overlay == '7':

            while self.isPlayingVideo():
                try:
                    self.totalTime = self.getTotalTime()
                    self.currentTime = self.getTime()
                except:
                    pass
                xbmc.sleep(2000)

        elif self.content == 'movie':

            while self.isPlayingVideo():
                try:
                    self.totalTime = self.getTotalTime()
                    self.currentTime = self.getTime()

                    watcher = (self.currentTime / self.totalTime >= .9)
                    property = control.window.getProperty(pname)

                    if watcher == True and not property == '7':
                        control.window.setProperty(pname, '7')
                        playcount.markMovieDuringPlayback(self.imdb, '7')

                    elif watcher == False and not property == '6':
                        control.window.setProperty(pname, '6')
                        playcount.markMovieDuringPlayback(self.imdb, '6')
                except:
                    pass
                xbmc.sleep(2000)

        elif self.content == 'episode':

            while self.isPlayingVideo():
                try:
                    self.totalTime = self.getTotalTime()
                    self.currentTime = self.getTime()

                    watcher = (self.currentTime / self.totalTime >= .9)
                    property = control.window.getProperty(pname)

                    if watcher == True and not property == '7':
                        control.window.setProperty(pname, '7')
                        playcount.markEpisodeDuringPlayback(
                            self.imdb, self.tvdb, self.season, self.episode,
                            '7')

                    elif watcher == False and not property == '6':
                        control.window.setProperty(pname, '6')
                        playcount.markEpisodeDuringPlayback(
                            self.imdb, self.tvdb, self.season, self.episode,
                            '6')
                except:
                    pass
                xbmc.sleep(2000)

        control.window.clearProperty(pname)
Esempio n. 47
0
def showMovies(sSearch=''):
    oGui = cGui()
    oParser = cParser()

    if sSearch:

        bvalid, stoken, scookie = GetTokens()
        if bvalid:
            pdata = '_token=' + stoken + '&search=' + sSearch
            sUrl = URL_MAIN + 'search'
            UA = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:70.0) Gecko/20100101 Firefox/70.0'

            oRequestHandler = cRequestHandler(sUrl)
            oRequestHandler.setRequestType(1)
            oRequestHandler.addHeaderEntry('User-Agent', UA)
            oRequestHandler.addHeaderEntry('Referer', URL_MAIN)
            oRequestHandler.addHeaderEntry('Content-Type', 'application/x-www-form-urlencoded')
            oRequestHandler.addHeaderEntry('Cookie', scookie)
            oRequestHandler.addParametersLine(pdata)
            oRequestHandler.request()

            # constatation : on est oblige de faire 2 requetes
            # dans le cas ou le mot recherché est composé ?
            xbmc.sleep(500)
            oRequestHandler.setRequestType(1)
            oRequestHandler.addHeaderEntry('User-Agent', UA)
            oRequestHandler.addHeaderEntry('Referer', URL_MAIN)
            oRequestHandler.addHeaderEntry('Cookie', scookie)
            oRequestHandler.addParametersLine(pdata)

            sHtmlContent = oRequestHandler.request()

        else:
            oGui.addText(SITE_IDENTIFIER)
            return

    else:
        oInputParameterHandler = cInputParameterHandler()
        sUrl = oInputParameterHandler.getValue('siteUrl')
        oRequestHandler = cRequestHandler(sUrl)
        sHtmlContent = oRequestHandler.request()

    # title img year surl
    sPattern = '<article class.+?data-url.+?title="([^"]*).+?img src=([^\s]*).+?year">([^<]+).+?href="([^"]+)'

    aResult = oParser.parse(sHtmlContent, sPattern)

    if (aResult[0] == False):
        oGui.addText(SITE_IDENTIFIER)

    if (aResult[0] == True):
        total = len(aResult[1])
        progress_ = progress().VScreate(SITE_NAME)

        oOutputParameterHandler = cOutputParameterHandler()
        for aEntry in aResult[1]:
            progress_.VSupdate(progress_, total)
            if progress_.iscanceled():
                break

            sDesc = ''
            sTitle = aEntry[0]
            sThumb = aEntry[1]
            sYear = aEntry[2]
            sUrl2 = aEntry[3]
            sDisplayTitle = sTitle + '(' + sYear + ')'

            oOutputParameterHandler.addParameter('siteUrl', sUrl2)
            oOutputParameterHandler.addParameter('sMovieTitle', sTitle)
            oOutputParameterHandler.addParameter('sThumb', sThumb)
            oOutputParameterHandler.addParameter('sDesc', sDesc)
            oOutputParameterHandler.addParameter('sYear', sYear)

            if sSearch:
                oGui.addLink(SITE_IDENTIFIER, 'showSelectType', sDisplayTitle, sThumb, sDesc, oOutputParameterHandler)
            elif SERIE_NEWS[0] in sUrl:
                sDisplayTitle = sTitle
                oGui.addTV(SITE_IDENTIFIER, 'showSXE', sDisplayTitle, '', sThumb, sDesc, oOutputParameterHandler)
            else:
                oGui.addMovie(SITE_IDENTIFIER, 'showLink', sDisplayTitle, '', sThumb, sDesc, oOutputParameterHandler)

        progress_.VSclose(progress_)

    if not sSearch:
        sNextPage, sPaging = __checkForNextPage(sHtmlContent)
        if (sNextPage != False):
            oOutputParameterHandler = cOutputParameterHandler()
            oOutputParameterHandler.addParameter('siteUrl', sNextPage)
            oGui.addNext(SITE_IDENTIFIER, 'showMovies', 'Page ' + sPaging, oOutputParameterHandler)

        oGui.setEndOfDirectory()
Esempio n. 48
0
        # Uninitiallized: First Update -> update shall take place. 
        updateNeeded = True 


    os.system('rm %s' % destination_path) 
    return updateNeeded



dialog = xbmcgui.DialogProgress()
dialog.create('System Update', 'Checking For Updates')

if check_for_updates():
    dialog.update(100, 'Update Required')
    dialog.update(100, 'Restarting in 5...')
    xbmc.sleep(999)
    dialog.update(100, 'Restarting in 4...')
    xbmc.sleep(999)
    dialog.update(100, 'Restarting in 3...')
    xbmc.sleep(999)
    dialog.update(100, 'Restarting in 2...')
    xbmc.sleep(999)
    dialog.update(100, 'Restarting in 1...')
    xbmc.sleep(999)
    xbmc.restart()
else:
    dialog.update(100, 'System Is Up To Date')
    xbmc.sleep(500)
    dialog.close()
    exit()
    
Esempio n. 49
0
 def playPlaylist(self):
     self.play(self.playlist)
     while self.isPlaying(): 
         xbmc.sleep(500)
Esempio n. 50
0
    def runAsAService(self):
        logVideoLibraryNotShowing = True

        while not xbmc.Monitor().abortRequested():
            # Wait a little before starting the check each time
            xbmc.sleep(200)

            # Check the forced TV Tunes status at the start of the loop, if this is True
            # then we don't want to stop themes until the next iteration, this stops the case
            # where some checks are done and the value changes part was through a single
            # loop iteration
            isForcedTvTunesContinue = WindowShowing.isTvTunesOverrideContinuePlaying(
            )

            # Stop the theme if the shutdown menu appears - it normally means
            # we are about to shut the system down, so get ahead of the game
            if WindowShowing.isShutdownMenu():
                self.stop(fastFade=True)
                continue

            # NOTE: The screensaver kicking in will only be picked up if the option
            # "Use Visualization if Playing Audio" is disabled
            if WindowShowing.isScreensaver():
                if self.isAlive:
                    log("TunesBackend: Screensaver active")
                    self.stop(fastFade=True)

                    # It may be possible that we stopped for the screen-saver about to kick in
                    # If we are using Gotham or higher, it is possible for us to re-kick off the
                    # screen-saver, otherwise the action of us stopping the theme will reset the
                    # timeout and the user will have to wait longer
                    log("TunesBackend: Restarting screensaver that TvTunes stopped"
                        )
                    executebuiltin("ActivateScreensaver", True)
                continue

            # Check if TvTunes is blocked from playing any themes
            if xbmcgui.Window(10025).getProperty('TvTunesBlocked') not in [
                    None, ""
            ]:
                self.stop(fastFade=True)
                continue

            if (not WindowShowing.isVideoLibrary()) and (
                    not WindowShowing.isMusicSection()):
                log("TunesBackend: Video Library no longer visible",
                    logVideoLibraryNotShowing)
                logVideoLibraryNotShowing = False
                # End playing cleanly (including any fade out) and then stop everything
                self.stop()
                continue
            else:
                logVideoLibraryNotShowing = True

            # There is a valid page selected and there is currently nothing playing
            if self.isPlayingZone(
            ) and not WindowShowing.isTvTunesOverrideContinuePrevious():
                newThemes = self.getThemes()
                if self.newThemeFiles != newThemes:
                    self.newThemeFiles = newThemes

            # Check if the file path has changed, if so there is a new file to play
            if self.newThemeFiles != self.oldThemeFiles and self.newThemeFiles.hasThemes(
            ):
                log("TunesBackend: old path: %s" %
                    self.oldThemeFiles.getPath())
                log("TunesBackend: new path: %s" %
                    self.newThemeFiles.getPath())
                if self.start_playing():
                    # Now that playing has started, update the current themes that are being used
                    self.oldThemeFiles = self.newThemeFiles

            # Check the operations where we are currently running and we need to stop
            # playing the current theme
            if self.isAlive:
                if self.themePlayer.isPlayingTheme():
                    # There is no theme at this location, so make sure we are stopped
                    if not self.newThemeFiles.hasThemes():
                        log("TunesBackend: No themes to play for current item")
                        self.themePlayer.endPlaying()
                        self.oldThemeFiles.clear()
                        self.prevThemeFiles.clear()
                        self.delayedStart.clear()
                        self.isAlive = False
                else:
                    # This will occur when a theme has stopped playing, maybe is is not set to loop
                    # There can be a delay when playing between playlist items, so give it a little
                    # time to start playing the next one
                    themeIsStillPlaying = False
                    maxLoop = 500
                    while (maxLoop > 0) and (not themeIsStillPlaying):
                        maxLoop = maxLoop - 1
                        xbmc.sleep(1)
                        if self.themePlayer.isPlayingTheme():
                            themeIsStillPlaying = True
                            break

                    if not themeIsStillPlaying:
                        log("TunesBackend: playing ended, restoring settings")
                        self.themePlayer.restoreSettings()
                        self.isAlive = False

            # This is the case where the user has moved from within an area where the themes
            # to an area where the theme is no longer played, so it will trigger a stop and
            # reset everything to highlight that nothing is playing
            if (not self.isPlayingZone()) and (not isForcedTvTunesContinue):
                self.stop()
            else:
                # Check for the case where we are playing the trailer as a theme
                # video, if so we want to stop the trailer playing when the video
                # information screen is displayed. If we don't, when the trailer is
                # started then TvTunes will automatically stop it
                if Settings.useTrailers() and WindowShowing.isMovieInformation(
                ) and self.themePlayer.isPlayingTrailerTheme():
                    self.stop()

            # Check to see if the setting to restrict the theme duration is enabled
            # and if it is we need to stop the current theme playing
            self.themePlayer.checkEnding()

        # We have finished running, just make one last check to ensure
        # we do not need to stop any audio
        self.stop(True)
        del self.themePlayer
Esempio n. 51
0
def get_link(url, movie_title, thumb, media):
    hmf = urlresolver.HostedMediaFile(url)
    ##########################################
    if hmf:
        try:
            url = urlresolver.resolve(url)
            params = {'url': url, 'name': movie_title, 'thumb': thumb}
            addon.add_video_item(params, {'title': movie_title}, img=thumb)
            liz = xbmcgui.ListItem(movie_title,
                                   iconImage="DefaultFolder.png",
                                   thumbnailImage=thumb)
            xbmc.sleep(1000)
            liz.setPath(str(url))
            xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
            #xbmc.Player ().play(url, liz, False)
            movie_name = movie_title[:-6]
            movie_name = '"' + movie_name + '"'
            movie_year_full = movie_title[-6:]
            movie_year = movie_year_full.replace('(', '').replace(')', '')
            if kodi.get_setting('trakt_oauth_token'):
                xbmc.sleep(30000)
                print "Velocity: Movie Scrobble  Start"
                try:
                    trakt_auth.start_movie_watch(movie_name, movie_year)
                except Exception as e:
                    log_utils.log('Error [%s]  %s' % (str(e), ''),
                                  xbmc.LOGERROR)
                    if kodi.get_setting('error_notify') == "true":
                        kodi.notify(header='Scrobble not loggged',
                                    msg='%s  %s' % (str(e), ''),
                                    duration=5000,
                                    sound=None)
            xbmc.sleep(30000)
            if kodi.get_setting('trakt_oauth_token'):
                check_player(movie_name, movie_year)
        except Exception as e:
            log_utils.log('Error [%s]  %s' % (str(e), ''), xbmc.LOGERROR)
            kodi.notify(header='Try Another Source',
                        msg='Link Removed or Failed',
                        duration=4000,
                        sound=None)

    if not hmf:
        try:
            params = {'url': url, 'name': movie_title, 'thumb': thumb}
            addon.add_video_item(params, {'title': movie_title}, img=thumb)
            liz = xbmcgui.ListItem(movie_title,
                                   iconImage="DefaultFolder.png",
                                   thumbnailImage=thumb)
            xbmc.sleep(1000)
            liz.setPath(str(url))
            xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
            #xbmc.Player ().play(url, liz, False)
            movie_name = movie_title[:-6]
            movie_name = '"' + movie_name + '"'
            movie_year_full = movie_title[-6:]
            movie_year = movie_year_full.replace('(', '').replace(')', '')
            if kodi.get_setting('trakt_oauth_token'):
                xbmc.sleep(30000)
                print "Velocity: Movie Scrobble  Start"
                try:
                    trakt_auth.start_movie_watch(movie_name, movie_year)
                except Exception as e:
                    log_utils.log('Error [%s]  %s' % (str(e), ''),
                                  xbmc.LOGERROR)
                    if kodi.get_setting('error_notify') == "true":
                        kodi.notify(header='Scrobble not loggged',
                                    msg='%s  %s' % (str(e), ''),
                                    duration=5000,
                                    sound=None)

            xbmc.sleep(30000)
            if kodi.get_setting('trakt_oauth_token'):
                check_player(movie_name, movie_year)
        except Exception as e:
            log_utils.log('Error [%s]  %s' % (str(e), ''), xbmc.LOGERROR)
            kodi.notify(header='Try Another Source',
                        msg='Link Removed or Failed',
                        duration=4000,
                        sound=None)
Esempio n. 52
0
def HELPWIZARD(name, url, description, filetype):
    path = xbmc.translatePath(
        os.path.join('special://home', 'addons', 'packages'))
    confirm = xbmcgui.Dialog().yesno(
        "Please Confirm",
        "                Please confirm that you wish to automatically                     ",
        "            configure Kodi with all the best addons and tweaks!",
        "              ", "Cancel", "Install")
    filetype = filetype.lower()
    if confirm:
        path = xbmc.translatePath(
            os.path.join('special://home', 'addons', 'packages'))
        dp = xbmcgui.DialogProgress()
        dp.create(AddonTitle, " ", 'Downloading and Configuring ',
                  'Please Wait')
        lib = os.path.join(path, name + '.zip')
        try:
            os.remove(lib)
        except:
            pass
        ### ## ... ##
        # kodi.log(url)
        if str(url).endswith('[error]'):
            print url
            dialog = xbmcgui.Dialog()
            dialog.ok("Error!", url)
            return
        if '[error]' in url:
            print url
            dialog = xbmcgui.Dialog()
            dialog.ok("Error!", url)
            return
        downloader.download(url, lib, dp)
        if filetype == 'main':
            addonfolder = xbmc.translatePath('special://home')
        elif filetype == 'addon':
            addonfolder = xbmc.translatePath(
                os.path.join('special://home', 'addons'))
        else:
            print {'filetype': filetype}
            dialog = xbmcgui.Dialog()
            dialog.ok("Error!", 'filetype: "%s"' % str(filetype))
            return
        xbmc.sleep(4000)
        extract.all(lib, addonfolder, dp)
        xbmc.executebuiltin("XBMC.UpdateLocalAddons()")
        addon_able.setall_enable()
        try:
            os.remove(lib)
        except:
            pass
        if filetype == 'main':
            link = OPEN_URL(cutslink)
            shorts = re.compile('shortcut="(.+?)"').findall(link)
            for shortname in shorts:
                xEB('Skin.SetString(%s)' % shortname)
                enableBG16 = "UseCustomBackground,true"
                enableBG17 = "use_custom_bg,true"
                xEB('Skin.SetBool(%s)' % enableBG16)
                xEB('Skin.SetBool(%s)' % enableBG17)

        xbmc.sleep(4000)
        xbmc.executebuiltin('XBMC_UpdateLocalAddons()')
        addon_able.setall_enable()

        kodi.set_setting("wizardran", 'true')

        dialog = xbmcgui.Dialog()
        dialog.ok(TeamName, "Installation Complete!", "",
                  "Click OK to exit Kodi and then restart to complete .")
        xbmc.executebuiltin('ShutDown')
def sleep(sleep_time):
    mon = xbmc.Monitor()
    while not mon.abortRequested() and sleep_time > 0:
        sleep_time -= 100
        xbmc.sleep(99)
    def run(self):
        LOG.info("----===## Starting %s ##===----", self.__class__.__name__)

        counter = 0
        handshake_counter = 0
        stopped = self.stopped
        suspended = self.suspended
        while not stopped():
            # In the event the server goes offline
            while suspended():
                # Set in service.py
                if self.ws is not None:
                    self.ws.close()
                    self.ws = None
                if stopped():
                    # Abort was requested while waiting. We should exit
                    LOG.info("##===---- %s Stopped ----===##",
                             self.__class__.__name__)
                    return
                sleep(1000)
            try:
                self.process(*self.receive(self.ws))
            except websocket.WebSocketTimeoutException:
                # No worries if read timed out
                pass
            except websocket.WebSocketConnectionClosedException:
                LOG.info("%s: connection closed, (re)connecting",
                         self.__class__.__name__)
                uri, sslopt = self.getUri()
                try:
                    # Low timeout - let's us shut this thread down!
                    self.ws = websocket.create_connection(
                        uri, timeout=1, sslopt=sslopt, enable_multithread=True)
                except IOError:
                    # Server is probably offline
                    LOG.info("%s: Error connecting", self.__class__.__name__)
                    self.ws = None
                    counter += 1
                    if counter > 3:
                        counter = 0
                        self.IOError_response()
                    sleep(1000)
                except websocket.WebSocketTimeoutException:
                    LOG.info("%s: Timeout while connecting, trying again",
                             self.__class__.__name__)
                    self.ws = None
                    sleep(1000)
                except websocket.WebSocketException as e:
                    LOG.info('%s: WebSocketException: %s',
                             self.__class__.__name__, e)
                    if ('Handshake Status 401' in e.args
                            or 'Handshake Status 403' in e.args):
                        handshake_counter += 1
                        if handshake_counter >= 5:
                            LOG.info(
                                '%s: Error in handshake detected. '
                                'Stopping now', self.__class__.__name__)
                            break
                    self.ws = None
                    sleep(1000)
                except Exception as e:
                    LOG.error(
                        '%s: Unknown exception encountered when '
                        'connecting: %s', self.__class__.__name__, e)
                    import traceback
                    LOG.error("%s: Traceback:\n%s", self.__class__.__name__,
                              traceback.format_exc())
                    self.ws = None
                    sleep(1000)
                else:
                    counter = 0
                    handshake_counter = 0
            except Exception as e:
                LOG.error("%s: Unknown exception encountered: %s",
                          self.__class__.__name__, e)
                import traceback
                LOG.error("%s: Traceback:\n%s", self.__class__.__name__,
                          traceback.format_exc())
                if self.ws is not None:
                    self.ws.close()
                self.ws = None
        # Close websocket connection on shutdown
        if self.ws is not None:
            self.ws.close()
        LOG.info("##===---- %s Stopped ----===##", self.__class__.__name__)
Esempio n. 55
0
def download(link, episode=""):
    subtitle_list = []
    exts = [".srt", ".sub", ".txt", ".smi", ".ssa", ".ass"]
    downloadlink_pattern = "...<a href=\"(.+?)\" rel=\"nofollow\" onclick=\"DownloadSubtitle"

    uid = uuid.uuid4()
    tempdir = os.path.join(TEMP, unicode(uid))
    xbmcvfs.mkdirs(tempdir)

    content, response_url = geturl(link)
    match = re.compile(downloadlink_pattern).findall(content)
    if match:
        downloadlink = main_url + match[0]
        viewstate = 0
        previouspage = 0
        subtitleid = 0
        typeid = "zip"
        filmid = 0

        postparams = urllib.urlencode({
            '__EVENTTARGET': 's$lc$bcr$downloadLink',
            '__EVENTARGUMENT': '',
            '__VIEWSTATE': viewstate,
            '__PREVIOUSPAGE': previouspage,
            'subtitleId': subtitleid,
            'typeId': typeid,
            'filmId': filmid
        })

        useragent = (
            "User-Agent=Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) "
            "Gecko/20100401 Firefox/3.6.3 ( .NET CLR 3.5.30729)")
        headers = {'User-Agent': useragent, 'Referer': link}
        log(
            __name__,
            "Fetching subtitles using url '%s' with referer header '%s' and post parameters '%s'"
            % (downloadlink, link, postparams))
        request = urllib2.Request(downloadlink, postparams, headers)
        response = urllib2.urlopen(request)

        if response.getcode() != 200:
            log(__name__, "Failed to download subtitle file")
            return subtitle_list

        local_tmp_file = os.path.join(tempdir, "subscene.xxx")
        packed = False

        try:
            log(__name__, "Saving subtitles to '%s'" % local_tmp_file)
            local_file_handle = xbmcvfs.File(local_tmp_file, "wb")
            local_file_handle.write(response.read())
            local_file_handle.close()

            # Check archive type (rar/zip/else) through the file header (rar=Rar!, zip=PK)
            myfile = xbmcvfs.File(local_tmp_file, "rb")
            myfile.seek(0, 0)
            if myfile.read(1) == 'R':
                typeid = "rar"
                packed = True
                log(__name__, "Discovered RAR Archive")
            else:
                myfile.seek(0, 0)
                if myfile.read(1) == 'P':
                    typeid = "zip"
                    packed = True
                    log(__name__, "Discovered ZIP Archive")
                else:
                    typeid = "srt"
                    packed = False
                    log(__name__, "Discovered a non-archive file")
            myfile.close()
            local_tmp_file = os.path.join(tempdir, "subscene." + typeid)
            xbmcvfs.rename(os.path.join(tempdir, "subscene.xxx"),
                           local_tmp_file)
            log(__name__, "Saving to %s" % local_tmp_file)
        except:
            log(__name__, "Failed to save subtitle to %s" % local_tmp_file)

        if packed:
            xbmc.sleep(500)
            xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % (
                local_tmp_file,
                tempdir,
            )).encode('utf-8'), True)

        episode_pattern = None
        if episode != '':
            episode_pattern = re.compile(get_episode_pattern(episode),
                                         re.IGNORECASE)

        for dir in xbmcvfs.listdir(tempdir)[0]:
            for file in xbmcvfs.listdir(os.path.join(tempdir, dir))[1]:
                if os.path.splitext(file)[1] in exts:
                    log(__name__, 'match ' + episode + ' ' + file)
                    if episode_pattern and not episode_pattern.search(file):
                        continue
                    log(__name__, "=== returning subtitle file %s" % file)
                    subtitle_list.append(os.path.join(tempdir, dir, file))

        for file in xbmcvfs.listdir(tempdir)[1]:
            if os.path.splitext(file)[1] in exts:
                log(__name__, 'match ' + episode + ' ' + file)
                if episode_pattern and not episode_pattern.search(file):
                    continue
                log(__name__, "=== returning subtitle file %s" % file)
                subtitle_list.append(os.path.join(tempdir, file))

        if len(subtitle_list) == 0:
            if episode:
                _xbmc_notification(32002)
            else:
                _xbmc_notification(32003)

    return subtitle_list
Esempio n. 56
0
    def onAVStarted(self):
        xbmc.sleep(1000)
        self.type = None
        self.id = None

        # take the user start scrobble offset into account
        scrobbleStartOffset = kodiUtilities.getSettingAsInt(
            'scrobble_start_offset') * 60
        if scrobbleStartOffset > 0:
            waitFor = 10
            waitedFor = 0
            # check each 10 seconds if we can abort or proceed
            while scrobbleStartOffset > waitedFor:
                waitedFor += waitFor
                time.sleep(waitFor)
                if not self.isPlayingVideo():
                    logger.debug(
                        '[traktPlayer] Playback stopped before reaching the scrobble offset'
                    )
                    return

        # only do anything if we're playing a video
        if self.isPlayingVideo():
            # get item data from json rpc
            activePlayers = kodiUtilities.kodiJsonRequest({
                "jsonrpc": "2.0",
                "method": "Player.GetActivePlayers",
                "id": 1
            })
            logger.debug("[traktPlayer] onAVStarted() - activePlayers: %s" %
                         activePlayers)
            playerId = int(activePlayers[0]['playerid'])
            logger.debug(
                "[traktPlayer] onAVStarted() - Doing Player.GetItem kodiJsonRequest"
            )
            result = kodiUtilities.kodiJsonRequest({
                'jsonrpc': '2.0',
                'method': 'Player.GetItem',
                'params': {
                    'playerid': playerId
                },
                'id': 1
            })
            if result:
                logger.debug("[traktPlayer] onAVStarted() - %s" % result)
                # check for exclusion
                _filename = None
                try:
                    _filename = self.getPlayingFile()
                except:
                    logger.debug(
                        "[traktPlayer] onAVStarted() - Exception trying to get playing filename, player suddenly stopped."
                    )
                    return

                if kodiUtilities.checkExclusion(_filename):
                    logger.debug(
                        "[traktPlayer] onAVStarted() - '%s' is in exclusion settings, ignoring."
                        % _filename)
                    return

                if (kodiUtilities.getSettingAsBool('scrobble_mythtv_pvr')):
                    logger.debug(
                        '[traktPlayer] Setting is enabled to try scrobbling mythtv pvr recording, if necessary.'
                    )

                self.type = result['item']['type']
                data = {'action': 'started'}
                # check type of item
                if 'id' not in result['item'] or self.type == 'channel':
                    # get non-library details by infolabel (ie. PVR, plugins, etc.)
                    self.type, data = kodiUtilities.getInfoLabelDetails(result)
                elif self.type == 'episode' or self.type == 'movie':
                    # get library id
                    self.id = result['item']['id']
                    data['id'] = self.id
                    data['type'] = self.type

                    if self.type == 'episode':
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Doing multi-part episode check."
                        )
                        result = kodiUtilities.kodiJsonRequest({
                            'jsonrpc': '2.0',
                            'method': 'VideoLibrary.GetEpisodeDetails',
                            'params': {
                                'episodeid':
                                self.id,
                                'properties':
                                ['tvshowid', 'season', 'episode', 'file']
                            },
                            'id': 1
                        })
                        if result:
                            logger.debug("[traktPlayer] onAVStarted() - %s" %
                                         result)
                            tvshowid = int(
                                result['episodedetails']['tvshowid'])
                            season = int(result['episodedetails']['season'])
                            currentfile = result['episodedetails']['file']

                            result = kodiUtilities.kodiJsonRequest({
                                'jsonrpc': '2.0',
                                'method': 'VideoLibrary.GetEpisodes',
                                'params': {
                                    'tvshowid': tvshowid,
                                    'season': season,
                                    'properties': ['episode', 'file'],
                                    'sort': {
                                        'method': 'episode'
                                    }
                                },
                                'id': 1
                            })
                            if result:
                                logger.debug(
                                    "[traktPlayer] onAVStarted() - %s" %
                                    result)
                                # make sure episodes array exists in results
                                if 'episodes' in result:
                                    multi = []
                                    for i in range(result['limits']['start'],
                                                   result['limits']['total']):
                                        if currentfile == result['episodes'][
                                                i]['file']:
                                            multi.append(result['episodes'][i]
                                                         ['episodeid'])
                                    if len(multi) > 1:
                                        data['multi_episode_data'] = multi
                                        data['multi_episode_count'] = len(
                                            multi)
                                        logger.debug(
                                            "[traktPlayer] onAVStarted() - This episode is part of a multi-part episode."
                                        )
                                    else:
                                        logger.debug(
                                            "[traktPlayer] onAVStarted() - This is a single episode."
                                        )
                elif (kodiUtilities.getSettingAsBool('scrobble_mythtv_pvr')
                      and self.type == 'unknown' and result['item']['label']):
                    # If we have label/id but no show type, then this might be a PVR recording.

                    # DEBUG INFO: This code is useful when trying to figure out what info is available. Many of the fields
                    # that you'd expect (TVShowTitle, episode, season, etc) are always blank. In Kodi v15, we got the show
                    # and episode name in the VideoPlayer label. In v16, that's gone, but the Player.Filename infolabel
                    # is populated with several interesting things. If these things change in future versions, uncommenting
                    # this code will hopefully provide some useful info in the debug log.
                    # logger.debug("[traktPlayer] onAVStarted() - TEMP Checking all videoplayer infolabels.")
                    # for il in ['VideoPlayer.Time','VideoPlayer.TimeRemaining','VideoPlayer.TimeSpeed','VideoPlayer.Duration','VideoPlayer.Title','VideoPlayer.TVShowTitle','VideoPlayer.Season','VideoPlayer.Episode','VideoPlayer.Genre','VideoPlayer.Director','VideoPlayer.Country','VideoPlayer.Year','VideoPlayer.Rating','VideoPlayer.UserRating','VideoPlayer.Votes','VideoPlayer.RatingAndVotes','VideoPlayer.mpaa',VideoPlayer.EpisodeName','VideoPlayer.PlaylistPosition','VideoPlayer.PlaylistLength','VideoPlayer.Cast','VideoPlayer.CastAndRole','VideoPlayer.Album','VideoPlayer.Artist','VideoPlayer.Studio','VideoPlayer.Writer','VideoPlayer.Tagline','VideoPlayer.PlotOutline','VideoPlayer.Plot','VideoPlayer.LastPlayed','VideoPlayer.PlayCount','VideoPlayer.VideoCodec','VideoPlayer.VideoResolution','VideoPlayer.VideoAspect','VideoPlayer.AudioCodec','VideoPlayer.AudioChannels','VideoPlayer.AudioLanguage','VideoPlayer.SubtitlesLanguage','VideoPlayer.StereoscopicMode','VideoPlayer.EndTime','VideoPlayer.NextTitle','VideoPlayer.NextGenre','VideoPlayer.NextPlot','VideoPlayer.NextPlotOutline','VideoPlayer.NextStartTime','VideoPlayer.NextEndTime','VideoPlayer.NextDuration','VideoPlayer.ChannelName','VideoPlayer.ChannelNumber','VideoPlayer.SubChannelNumber','VideoPlayer.ChannelNumberLabel','VideoPlayer.ChannelGroup','VideoPlayer.ParentalRating','Player.FinishTime','Player.FinishTime(format)','Player.Chapter','Player.ChapterCount','Player.Time','Player.Time(format)','Player.TimeRemaining','Player.TimeRemaining(format)','Player.Duration','Player.Duration(format)','Player.SeekTime','Player.SeekOffset','Player.SeekOffset(format)','Player.SeekStepSize','Player.ProgressCache','Player.Folderpath','Player.Filenameandpath','Player.StartTime','Player.StartTime(format)','Player.Title','Player.Filename']:
                    #    logger.debug("[traktPlayer] TEMP %s : %s" % (il, xbmc.getInfoLabel(il)))
                    # for k,v in result.items():
                    #    logger.debug("[traktPlayer] onAVStarted() - result - %s : %s" % (k,v))
                    # for k,v in result['item'].items():
                    #    logger.debug("[traktPlayer] onAVStarted() - result.item - %s : %s" % (k,v))

                    # As of Kodi v17, many of the VideoPlayer labels are populated by the MythTV PVR addon, though sadly this
                    # does not include IMDB number. That means we're still stuck using the show title/episode name to look up
                    # IDs to feed to the scrobbler. Still, much easier than previous versions!
                    foundShowName = xbmc.getInfoLabel('VideoPlayer.Title')
                    logger.debug(
                        "[traktPlayer] onAVStarted() - Found VideoPlayer.Title: %s"
                        % foundShowName)
                    foundEpisodeName = xbmc.getInfoLabel(
                        'VideoPlayer.EpisodeName')
                    logger.debug(
                        "[traktPlayer] onAVStarted() - Found VideoPlayer.EpisodeName: %s"
                        % foundEpisodeName)
                    foundEpisodeYear = xbmc.getInfoLabel('VideoPlayer.Year')
                    logger.debug(
                        "[traktPlayer] onAVStarted() - Found VideoPlayer.Year: %s"
                        % foundEpisodeYear)
                    foundSeason = xbmc.getInfoLabel('VideoPlayer.Season')
                    logger.debug(
                        "[traktPlayer] onAVStarted() - Found VideoPlayer.Season: %s"
                        % foundSeason)
                    foundEpisode = xbmc.getInfoLabel('VideoPlayer.Episode')
                    logger.debug(
                        "[traktPlayer] onAVStarted() - Found VideoPlayer.Episode: %s"
                        % foundEpisode)
                    if (foundShowName and foundEpisodeName
                            and foundEpisodeYear):
                        # If the show/episode/year are populated, we can skip all the mess of trying to extract the info from the
                        # Player.Filename infolabel.
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Got info from VideoPlayer labels"
                        )
                    else:
                        logger.debug(
                            "[traktPlayer] onAVStarted() - No love from VideoPlayer labels, trying Player.Filename infolabel"
                        )
                        # If that didn't work, we can fall back on the Player.Filename infolabel. It shows up like this:
                        # (v16) ShowName [sXXeYY ](year) EpisodeName, channel, PVRFileName
                        # (v17) ShowName [sXXeYY ](year) EpisodeName, channel, date, PVRFileName
                        # The season and episode info may or may not be present. Also, sometimes there are some URL encodings
                        # (i.e. %20 instead of space) so those need removing. For example:
                        # Powerless s01e08 (2017)%20Green%20Furious, TV%20(WOOD%20TV), 20170414_003000, 1081_1492129800_4e1.pvr
                        # DC's Legends of Tomorrow (2016) Pilot, Part 2, TV (CW W MI), 20160129_010000, 1081_1492129800_4e1.pvr
                        foundLabel = urllib.parse.unquote(
                            xbmc.getInfoLabel('Player.Filename'))
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Found unknown video type with label: %s. Might be a PVR episode, searching Trakt for it."
                            % foundLabel)
                        logger.debug(
                            "[traktPlayer] onAVStarted() - After urllib.unquote: %s."
                            % foundLabel)
                        splitLabel = foundLabel.rsplit(", ", 3)
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Post-split of label: %s "
                            % splitLabel)
                        if len(splitLabel) != 4:
                            logger.debug(
                                "[traktPlayer] onAVStarted() - Label doesn't have the ShowName sXXeYY (year) EpisodeName, channel, date, PVRFileName format that was expected. Might be the v16 version with no date instead."
                            )
                            splitLabel = foundLabel.rsplit(", ", 2)
                            logger.debug(
                                "[traktPlayer] onAVStarted() - Post-split of label: %s "
                                % splitLabel)
                            if len(splitLabel) != 3:
                                logger.debug(
                                    "[traktPlayer] onAVStarted() - Label doesn't have the ShowName sXXeYY (year) EpisodeName, channel, PVRFileName format that was expected. Giving up."
                                )
                                return
                        foundShowAndEpInfo = splitLabel[0]
                        logger.debug(
                            "[traktPlayer] onAVStarted() - show plus episode info: %s"
                            % foundShowAndEpInfo)
                        splitShowAndEpInfo = re.split(
                            r' (s\d\de\d\d)? ?\((\d\d\d\d)\) ',
                            foundShowAndEpInfo, 1)
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Post-split of show plus episode info: %s "
                            % splitShowAndEpInfo)
                        if len(splitShowAndEpInfo) != 4:
                            logger.debug(
                                "[traktPlayer] onAVStarted() - Show plus episode info doesn't have the ShowName sXXeYY (year) EpisodeName format that was expected. Giving up."
                            )
                            return
                        foundShowName = splitShowAndEpInfo[0]
                        logger.debug(
                            "[traktPlayer] onAVStarted() - using show name: %s"
                            % foundShowName)
                        foundEpisodeName = splitShowAndEpInfo[3]
                        logger.debug(
                            "[traktPlayer] onAVStarted() - using episode name: %s"
                            % foundEpisodeName)
                        foundEpisodeYear = splitShowAndEpInfo[2]
                        logger.debug(
                            "[traktPlayer] onAVStarted() - using episode year: %s"
                            % foundEpisodeYear)
                    epYear = None
                    try:
                        epYear = int(foundEpisodeYear)
                    except ValueError:
                        epYear = None
                    logger.debug(
                        "[traktPlayer] onAVStarted() - verified episode year: %d"
                        % epYear)
                    # All right, now we have the show name, episode name, and (maybe) episode year. All good, but useless for
                    # scrobbling since Trakt only understands IDs, not names.
                    data['video_ids'] = None
                    data['season'] = None
                    data['episode'] = None
                    data['episodeTitle'] = None
                    # First thing to try, a text query to the Trakt DB looking for this episode. Note
                    # that we can't search for show and episode together, because the Trakt function gets confused and returns nothing.
                    newResp = globals.traktapi.getTextQuery(
                        foundEpisodeName, "episode", epYear)
                    if not newResp:
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Empty Response from getTextQuery, giving up"
                        )
                    else:
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Got Response from getTextQuery: %s"
                            % str(newResp))
                        # We got something back. See if one of the returned values is for the show we're looking for. Often it's
                        # not, but since there's no way to tell the search which show we want, this is all we can do.
                        rightResp = None
                        for thisResp in newResp:
                            compareShowName = thisResp.show.title
                            logger.debug(
                                "[traktPlayer] onAVStarted() - comparing show name: %s"
                                % compareShowName)
                            if thisResp.show.title == foundShowName:
                                logger.debug(
                                    "[traktPlayer] onAVStarted() - found the right show, using this response"
                                )
                                rightResp = thisResp
                                break
                        if rightResp is None:
                            logger.debug(
                                "[traktPlayer] onAVStarted() - Failed to find matching episode/show via text search."
                            )
                        else:
                            # OK, now we have a episode object to work with.
                            self.type = 'episode'
                            data['type'] = 'episode'
                            # You'd think we could just use the episode key that Trakt just returned to us, but the scrobbler
                            # function (see scrobber.py) only understands the show key plus season/episode values.
                            showKeys = {}
                            for eachKey in rightResp.show.keys:
                                showKeys[eachKey[0]] = eachKey[1]
                            data['video_ids'] = showKeys
                            # For some reason, the Trakt search call returns the season and episode as an array in the pk field.
                            # You'd think individual episode and season fields would be better, but whatever.
                            data['season'] = rightResp.pk[0]
                            data['episode'] = rightResp.pk[1]
                    # At this point if we haven't found the episode data yet, the episode-title-text-search method
                    # didn't work.
                    if (not data['season']):
                        # This text query API is basically the same as searching on the website. Works with alternative
                        # titles, unlike the scrobble function. Though we can't use the episode year since that would only
                        # match the show if we're dealing with season 1.
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Searching for show title via getTextQuery: %s"
                            % foundShowName)
                        newResp = globals.traktapi.getTextQuery(
                            foundShowName, "show", None)
                        if not newResp:
                            logger.debug(
                                "[traktPlayer] onAVStarted() - Empty Show Response from getTextQuery, falling back on episode text query"
                            )
                        else:
                            logger.debug(
                                "[traktPlayer] onAVStarted() - Got Show Response from getTextQuery: %s"
                                % str(newResp))
                            # We got something back. Have to assume the first show found is the right one; if there's more than
                            # one, there's no way to know which to use. Pull the ids from the show data, and store 'em for scrobbling.
                            showKeys = {}
                            for eachKey in newResp[0].keys:
                                showKeys[eachKey[0]] = eachKey[1]
                            data['video_ids'] = showKeys
                            # Now to find the episode. There's no search function to look for an episode within a show, but
                            # we can get all the episodes and look for the title.
                            while (not data['season']):
                                logger.debug(
                                    "[traktPlayer] onAVStarted() - Querying for all seasons/episodes of this show"
                                )
                                epQueryResp = globals.traktapi.getShowWithAllEpisodesList(
                                    data['video_ids']['trakt'])
                                if not epQueryResp:
                                    # Nothing returned. Giving up.
                                    logger.debug(
                                        "[traktPlayer] onAVStarted() - No response received"
                                    )
                                    break
                                else:
                                    # Got the list back. Go through each season.
                                    logger.debug(
                                        "[traktPlayer] onAVStarted() - Got response with seasons: %s"
                                        % str(epQueryResp))
                                    for eachSeason in epQueryResp:
                                        # For each season, check each episode.
                                        logger.debug(
                                            "[traktPlayer] onAVStarted() - Processing season: %s"
                                            % str(eachSeason))
                                        for eachEpisodeNumber in eachSeason.episodes:
                                            thisEpTitle = None
                                            # Get the title. The try block is here in case the title doesn't exist for some entries.
                                            try:
                                                thisEpTitle = eachSeason.episodes[
                                                    eachEpisodeNumber].title
                                            except:
                                                thisEpTitle = None
                                            logger.debug(
                                                "[traktPlayer] onAVStarted() - Checking episode number %d with title %s"
                                                % (eachEpisodeNumber,
                                                   thisEpTitle))
                                            if (foundEpisodeName == thisEpTitle
                                                ):
                                                # Found it! Save the data. The scrobbler wants season and episode number. Which for some
                                                # reason is stored as a pair in the first item in the keys array.
                                                data[
                                                    'season'] = eachSeason.episodes[
                                                        eachEpisodeNumber].keys[
                                                            0][0]
                                                data[
                                                    'episode'] = eachSeason.episodes[
                                                        eachEpisodeNumber].keys[
                                                            0][1]
                                                # Title too, just for the heck of it. Though it's not actually used.
                                                data[
                                                    'episodeTitle'] = thisEpTitle
                                                break
                                        # If we already found our data, no need to go through the rest of the seasons.
                                        if (data['season']):
                                            break
                    # Now we've done all we can.
                    if (data['season']):
                        # OK, that's everything. Data should be all set for scrobbling.
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Playing a non-library 'episode' : show trakt key %s, season: %d, episode: %d"
                            % (data['video_ids'], data['season'],
                               data['episode']))
                    else:
                        # Still no data? Too bad, have to give up.
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Did our best, but couldn't get info for this show and episode. Skipping."
                        )
                        return
                else:
                    logger.debug(
                        "[traktPlayer] onAVStarted() - Video type '%s' unrecognized, skipping."
                        % self.type)
                    return

                pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
                plSize = len(pl)
                if plSize > 1:
                    pos = pl.getposition()
                    if not self.plIndex is None:
                        logger.debug(
                            "[traktPlayer] onAVStarted() - User manually skipped to next (or previous) video, forcing playback ended event."
                        )
                        self.onPlayBackEnded()
                    self.plIndex = pos
                    logger.debug(
                        "[traktPlayer] onAVStarted() - Playlist contains %d item(s), and is currently on item %d"
                        % (plSize, (pos + 1)))

                self._playing = True

                # send dispatch
                self.action(data)
Esempio n. 57
0
 def __init__(self,*args,**kwargs):
   xbmc.executebuiltin("ActivateWindow(%d)" % (self.WINDOW, )) # activate the text viewer window
   self.win=xbmcgui.Window(self.WINDOW) # get window
   xbmc.sleep(500) # give window time to initialize
   self.setControls()
Esempio n. 58
0
def play(track_id, station_id=None):
    import re
    import play
    import xbmc

    track = rhapsody.tracks.detail(track_id)
    stream = rhapsody.streams.detail(track_id)

    item = helpers.get_track_item(track)
    if stream.url.startswith('rtmp://'):
        parts = [
            '/'.join(stream.url.split('/')[:5]),
            'app=' + '/'.join(stream.url.split('/')[3:5]),
            'playpath=' + 'mp3:' + '/'.join(stream.url.split('/')[5:])
        ]
        item['path'] = ' '.join(parts)
    else:
        item['path'] = stream.url

    notify = play.Notify(rhapsody, track, stream)
    player = play.Player(plugin=plugin, notify=notify)
    plugin.set_resolved_url(item)

    # add upcoming station tracks to playlist
    if station_id is not None:
        playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
        current_pos = playlist.getposition()
        playlist_target_size = current_pos + 5
        while playlist.size() <= playlist_target_size:
            next_tracks = rhapsody.stations.tracks(station_id).tracks[:5]
            if len(next_tracks) == 0:
                break
            for next_track in next_tracks:
                plugin.log.info(
                    'Preload: Adding next station track {0:d} of {1:d}'.format(
                        playlist.size(), current_pos + 5))
                next_item = helpers.get_track_item(next_track)
                next_item['path'] = plugin.url_for(
                    'stations_play',
                    station_id=station_id,
                    current_track_id=next_track.id)
                plugin.add_to_playlist([next_item], playlist='music')

    # query the next playlist item so it'll be added to the cache for seamless playback
    prefetch_enabled = plugin.get_setting('api_prefetch', converter=bool)
    if prefetch_enabled and rhapsody.ENABLE_CACHE:
        playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
        next_pos = playlist.getposition() + 1
        if next_pos >= playlist.size():
            next_pos = 0
        next_url = playlist[next_pos].getfilename()

        next_track_id = None
        url_patterns = [
            re.escape(plugin.url_for('play', track_id='-track_id-')).replace(
                re.escape('-track_id-'), '(?P<track_id>[^\/]+)'),
            re.escape(
                plugin.url_for('stations_play',
                               station_id='-station_id-',
                               current_track_id='-track_id-')).replace(
                                   re.escape('-station_id-'),
                                   '(?P<station_id>[^\/]+)').replace(
                                       re.escape('-track_id-'),
                                       '(?P<track_id>.+)')
        ]
        for url_pattern in url_patterns:
            match = re.match(url_pattern, next_url)
            if match is not None:
                next_track_id = match.group('track_id')

        if next_track_id is not None:
            plugin.log.info(
                'Preload: Caching next playlist position {0:d} ({1:s})'.format(
                    next_pos, next_track_id))
            rhapsody.tracks.detail(next_track_id)
            rhapsody.streams.detail(next_track_id)

    # wait for the current item to finish before exiting
    while not xbmc.abortRequested and not player.has_stopped:
        xbmc.sleep(10)

    plugin.log.info('Player: Exited')
    return plugin.finish()
Esempio n. 59
0
def do_My_TextSplash(
        msg='',
        img='http://www.tvaddons.ag/wp-content/uploads/2014/08/tvaddons_logo.png',
        HowLong=15,
        resize=False,
        L=0,
        T=0,
        W=1280,
        H=720,
        TxtColor='0xFFFFFFFF',
        Font='font14',
        BorderWidth=10):  #HowLong in seconds.
    class MyWindowCountDownWithText(xbmcgui.WindowDialog):
        scr = {}
        #scr['L']=0; scr['T']=0; scr['W']=1280; scr['H']=720;

        def __init__(self,
                     msg='',
                     bgArt='',
                     L=0,
                     T=0,
                     W=1280,
                     H=720,
                     TxtColor='0xFFFFFFFF',
                     Font='font14',
                     BorderWidth=10):
            self.background = bgArt
            self.scr['L'] = L
            self.scr['T'] = T
            self.scr['W'] = W
            self.scr['H'] = H
            image_path = os.path.join(_1CH.get_path(), 'resources', 'media',
                                      '1CHDialogBack.png')
            self.border = xbmcgui.ControlImage(self.scr['L'], self.scr['T'],
                                               self.scr['W'], self.scr['H'],
                                               image_path)
            self.addControl(self.border)
            self.BG = xbmcgui.ControlImage(self.scr['L'] + BorderWidth,
                                           self.scr['T'] + BorderWidth,
                                           self.scr['W'] - (BorderWidth * 2),
                                           self.scr['H'] - (BorderWidth * 2),
                                           self.background,
                                           aspectRatio=0,
                                           colorDiffuse='0x2FFFFFFF')
            self.addControl(self.BG)
            self.TxtMessage = xbmcgui.ControlTextBox(
                self.scr['L'] + BorderWidth,
                self.scr['T'] + BorderWidth,
                self.scr['W'] - (BorderWidth * 2),
                self.scr['H'] - (BorderWidth * 2),
                font=Font,
                textColor=TxtColor)
            self.addControl(self.TxtMessage)
            self.TxtMessage.setText(msg)
            counter_width = len(continue_msg) * 11
            self.counter = xbmcgui.ControlTextBox(L + (W - counter_width) / 2,
                                                  T + H - 30 - BorderWidth,
                                                  counter_width,
                                                  30,
                                                  font=Font,
                                                  textColor=TxtColor)
            self.addControl(self.counter)

        def see(self):
            self.show()

        def updateBG(self, bgArt=''):
            self.background = bgArt
            self.setImage(self.background)

        def updateY(self, x, y):
            self.BG.setPosition(x, y)
            self.scr['L'] = x
            self.scr['T'] = y

        def updateSize(self, w, h):
            self.BG.setWidth(w)
            self.BG.setHeight(h)
            self.scr['W'] = w
            self.scr['H'] = h

        def updateW(self, w):
            self.BG.setWidth(w)
            self.scr['W'] = w

        def updateH(self, h):
            self.BG.setHeight(h)
            self.scr['H'] = h

        #def onInit(self):
        #def onClick(self,control):
        #def onControl(self,control):
        #def onFocus(self,control):
        #def onAction(self,action):

    if resize == False:
        maxW = 1280
        maxH = 720
        W = maxW / 2
        H = maxH / 2
        L = maxW / 4
        T = maxH / 4
    continue_msg = 'Continuing in %d seconds...'
    TempWindow2 = MyWindowCountDownWithText(msg=msg,
                                            bgArt=img,
                                            L=L,
                                            T=T,
                                            W=W,
                                            H=H,
                                            TxtColor=TxtColor,
                                            Font=Font,
                                            BorderWidth=BorderWidth)
    StartTime = time.time()
    while (time.time() - StartTime) <= HowLong:
        wait = HowLong - (time.time() - StartTime)
        TempWindow2.counter.setText(continue_msg % (wait))
        TempWindow2.show()
        xbmc.sleep(500)
    try:
        del self.TempWindow2
    except:
        pass
def parse_movies(content_type,
                 list_type,
                 full_liz,
                 useCache,
                 plot_enable,
                 limit,
                 date_liz=None,
                 date_type=None):
    json_query = _get_data(content_type, useCache)
    while json_query == "LOADING":
        xbmc.sleep(100)
        json_query = _get_data(content_type, useCache)

    count = 0
    if json_query:
        json_query = json.loads(json_query)
        if "result" in json_query and "movies" in json_query['result']:
            for movie in json_query['result']['movies']:
                if "cast" in movie:
                    cast = _get_cast(movie['cast'])

                # create a list item
                liz = xbmcgui.ListItem(movie['title'])
                liz.setInfo(type="Video",
                            infoLabels={
                                "Title":
                                movie['title'],
                                "OriginalTitle":
                                movie['originaltitle'],
                                "Year":
                                movie['year'],
                                "Genre":
                                _get_joined_items(movie.get('genre', "")),
                                "Studio":
                                _get_first_item(movie.get('studio', "")),
                                "Country":
                                _get_first_item(movie.get('country', "")),
                                "Plot":
                                _get_plot(movie['plot'], plot_enable,
                                          movie['playcount']),
                                "PlotOutline":
                                movie['plotoutline'],
                                "Tagline":
                                movie['tagline'],
                                "Rating":
                                str(float(movie['rating'])),
                                "Votes":
                                movie['votes'],
                                "MPAA":
                                movie['mpaa'],
                                "Director":
                                _get_joined_items(movie.get('director', "")),
                                "Writer":
                                _get_joined_items(movie.get('writer', "")),
                                "Cast":
                                cast[0],
                                "CastAndRole":
                                cast[1],
                                "mediatype":
                                "movie",
                                "Trailer":
                                movie['trailer'],
                                "Playcount":
                                movie['playcount']
                            })
                liz.setProperty("resumetime", str(movie['resume']['position']))
                liz.setProperty("totaltime", str(movie['resume']['total']))
                liz.setProperty("type", ADDON_LANGUAGE(list_type))
                liz.setProperty("dbid", str(movie['movieid']))
                liz.setProperty("imdbnumber", str(movie['imdbnumber']))
                liz.setProperty("fanart_image", movie['art'].get('fanart', ''))
                liz.setProperty("cid", str(movie['movieid']))
                liz.setArt(movie['art'])
                liz.setThumbnailImage(movie['art'].get('poster', ''))
                liz.setIconImage('DefaultVideoCover.png')
                liz.setPath(movie.get("path", ""))
                hasVideo = False
                for key, value in movie['streamdetails'].iteritems():
                    for stream in value:
                        if 'video' in key:
                            hasVideo = True
                        liz.addStreamInfo(key, stream)

                # if duration wasnt in the streaminfo try adding the scraped one
                if not hasVideo:
                    stream = {'duration': movie['runtime']}
                    liz.addStreamInfo("video", stream)
                full_liz.append((movie['file'], liz, False))

                if date_type is not None:
                    date_liz.append(movie[date_type])

                count += 1
                if count == limit:
                    break

        del json_query