Esempio n. 1
0
def build_sub_directory(url, name, slug, offset, daily_info):
    if slug == None:
        dialog = xbmcgui.Dialog()
        ok = dialog.ok(plugin, settings.getLocalizedString(30029))
        build_main_directory(BASE + 'getShows' + KEY)
        return
    saveurl = url
    data = json.loads(getUrl(url + '&offset=' + str(offset * 25)))
    if len(data['episodes']) == 0:
        dialog = xbmcgui.Dialog()
        ok = dialog.ok(plugin,
                       settings.getLocalizedString(30026) + ' ' + name + '.')
        return
    if slug != 'None':
        try:
            downloads = 'http://testtube.com/' + slug + '/' + slug + '_downloads'
            fresult = getPage(downloads)['content']
            match = re.compile('<a href="(.+?)" target="_blank">1920x1200</a>'
                               ).findall(fresult)
            if len(match) > 1:
                fanart = match[1]
            else:
                fanart = match[0]
            settings.setSetting(slug, fanart)
        except:
            fanart = 'http://videos.testtube.com/revision3/images/shows/%s/%s_hero.jpg' % (
                slug, slug)
            if getPage(fanart)['error'] == 'HTTP Error 404: Not Found':
                fanart = fanart_bg
                settings.setSetting(slug, fanart)
            else:
                settings.setSetting(slug, fanart)
    else:
        fanart = fanart_bg
    if daily_info != 'None' and settings.getSetting('daily') == 'true':
        daily_info = ast.literal_eval(daily_info)
        u = {
            'mode': '1',
            'name': daily_info['name'],
            'url': daily_info['url'],
            'slug': slug,
            'daily_info': 'None'
        }
        infoLabels = {"Title": daily_info['name'], "Plot": daily_info['plot']}
        addListItem('[ ' + daily_info['name'] + ' ]', daily_info['thumb'], u,
                    True, 0, infoLabels, fanart)
    if settings.getSetting('download') == '' or settings.getSetting(
            'download') == 'false':
        if settings.getSetting('playall') == 'true':
            playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
            playlist.clear()
            u = {'mode': '6'}
            infoLabels = {
                "Title": settings.getLocalizedString(30030),
                "Plot": settings.getLocalizedString(30031)
            }
            addListItem('* ' + settings.getLocalizedString(30030) + ' *',
                        play_thumb, u, True, 0, infoLabels, fanart)
    for episode in data['episodes']:
        studio = episode['show']['name']
        thumb = episode['images']['medium']
        url = episode['media']
        plot = episode['summary'].encode('ascii', 'ignore')
        name = episode['name'].encode('ascii', 'ignore')
        episodenum = episode['number']
        date = episode['published'].rsplit('T')[0]
        duration = int(episode['duration'])
        infoLabels = {
            "Title": name,
            "Studio": studio,
            "Plot": plot,
            "Episode": int(episodenum),
            "Aired": date
        }
        u = {
            'mode': '2',
            'name': name,
            'url': url,
            'plot': plot,
            'studio': studio,
            'episode': episodenum,
            'thumb': thumb,
            'date': date
        }
        addListItem(plot, thumb, u, False, len(data['episodes']), infoLabels,
                    fanart, duration)
    if (int(data['total']) - ((offset + 1) * 25)) > 0:
        u = {
            'mode': '1',
            'name': studio,
            'url': saveurl,
            'slug': slug,
            'offset': offset + 1,
            'daily_info': 'None'
        }
        infoLabels = {
            "Title": settings.getLocalizedString(30016),
            "Plot": settings.getLocalizedString(30016)
        }
        addListItem(
            settings.getLocalizedString(30016) + ' (' + str(offset + 2) + ')',
            next_thumb, u, True, 0, infoLabels, fanart)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_UNSORTED)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_EPISODE)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_STUDIO)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_VIDEO_RUNTIME)
    setViewMode("503")
    xbmcplugin.endOfDirectory(int(sys.argv[1]))
Esempio n. 2
0
	def playbackStarted(self, data):
		Debug("[Scrobbler] playbackStarted(data: %s)" % data)
		if not data:
			return
		self.curVideo = data
		self.curVideoInfo = None
		# {"jsonrpc":"2.0","method":"Player.OnPlay","params":{"data":{"item":{"type":"movie"},"player":{"playerid":1,"speed":1},"title":"Shooter","year":2007},"sender":"xbmc"}}
		# {"jsonrpc":"2.0","method":"Player.OnPlay","params":{"data":{"episode":3,"item":{"type":"episode"},"player":{"playerid":1,"speed":1},"season":4,"showtitle":"24","title":"9:00 A.M. - 10:00 A.M."},"sender":"xbmc"}}
		if 'type' in self.curVideo:
			Debug("[Scrobbler] Watching: %s" % self.curVideo['type'])
			if not xbmc.Player().isPlayingVideo():
				Debug("[Scrobbler] Suddenly stopped watching item")
				return
			xbmc.sleep(1000) # Wait for possible silent seek (caused by resuming)
			try:
				self.watchedTime = xbmc.Player().getTime()
				self.videoDuration = xbmc.Player().getTotalTime()
			except Exception, e:
				Debug("[Scrobbler] Suddenly stopped watching item: %s" % e.message)
				self.curVideo = None
				return

			if self.videoDuration == 0:
				if utilities.isMovie(self.curVideo['type']):
					self.videoDuration = 90
				elif utilities.isEpisode(self.curVideo['type']):
					self.videoDuration = 30
				else:
					self.videoDuration = 1

			self.playlistLength = len(xbmc.PlayList(xbmc.PLAYLIST_VIDEO))
			self.playlistIndex = xbmc.PlayList(xbmc.PLAYLIST_VIDEO).getposition()
			if (self.playlistLength == 0):
				Debug("[Scrobbler] Warning: Cant find playlist length, assuming that this item is by itself")
				self.playlistLength = 1

			self.traktSummaryInfo = None
			self.isMultiPartEpisode = False
			if utilities.isMovie(self.curVideo['type']):
				if 'id' in self.curVideo:
					self.curVideoInfo = utilities.getMovieDetailsFromXbmc(self.curVideo['id'], ['imdbnumber', 'title', 'year'])
					if utilities.getSettingAsBool('rate_movie'):
						# pre-get sumamry information, for faster rating dialog.
						Debug("[Scrobbler] Movie rating is enabled, pre-fetching summary information.")
						imdb_id = self.curVideoInfo['imdbnumber']
						if imdb_id.startswith("tt") or imdb_id.isdigit():
							self.traktSummaryInfo = self.traktapi.getMovieSummary(self.curVideoInfo['imdbnumber'])
							self.traktSummaryInfo['xbmc_id'] = self.curVideo['id']
						else:
							self.curVideoInfo['imdbnumber'] = None
							Debug("[Scrobbler] Can not get summary information for '%s (%d)' as is has no valid id, will retry during a watching call." % (self.curVideoInfo['title'], self.curVideoInfo['year']))
				elif 'title' in self.curVideo and 'year' in self.curVideo:
					self.curVideoInfo = {}
					self.curVideoInfo['imdbnumber'] = None
					self.curVideoInfo['title'] = self.curVideo['title']
					self.curVideoInfo['year'] = self.curVideo['year']

			elif utilities.isEpisode(self.curVideo['type']):
				if 'id' in self.curVideo:
					self.curVideoInfo = utilities.getEpisodeDetailsFromXbmc(self.curVideo['id'], ['showtitle', 'season', 'episode', 'tvshowid', 'uniqueid'])
					if not self.curVideoInfo: # getEpisodeDetailsFromXbmc was empty
						Debug("[Scrobbler] Episode details from XBMC was empty, ID (%d) seems invalid, aborting further scrobbling of this episode." % self.curVideo['id'])
						self.curVideo = None
						self.isPlaying = False
						self.watchedTime = 0
						return
					if utilities.getSettingAsBool('rate_episode'):
						# pre-get sumamry information, for faster rating dialog.
						Debug("[Scrobbler] Episode rating is enabled, pre-fetching summary information.")
						tvdb_id = self.curVideoInfo['tvdb_id']
						if tvdb_id.isdigit() or tvdb_id.startswith("tt"):
							self.traktSummaryInfo = self.traktapi.getEpisodeSummary(tvdb_id, self.curVideoInfo['season'], self.curVideoInfo['episode'])
						else:
							self.curVideoInfo['tvdb_id'] = None
							Debug("[Scrobbler] Can not get summary information for '%s - S%02dE%02d' as it has no valid id, will retry during a watching call." % (self.curVideoInfo['showtitle'], self.curVideoInfo['season'], self.curVideoInfo['episode']))
				elif 'showtitle' in self.curVideo and 'season' in self.curVideo and 'episode' in self.curVideo:
					self.curVideoInfo = {}
					self.curVideoInfo['tvdb_id'] = None
					self.curVideoInfo['year'] = None
					if 'year' in self.curVideo:
						self.curVideoInfo['year'] = self.curVideo['year']
					self.curVideoInfo['showtitle'] = self.curVideo['showtitle']
					self.curVideoInfo['season'] = self.curVideo['season']
					self.curVideoInfo['episode'] = self.curVideo['episode']

				if 'multi_episode_count' in self.curVideo:
					self.isMultiPartEpisode = True
					self.markedAsWatched = []
					episode_count = self.curVideo['multi_episode_count']
					for i in range(episode_count):
						self.markedAsWatched.append(False)

			self.isPlaying = True
			self.isPaused = False
			self.watching()
Esempio n. 3
0
    def playbackStarted(self, data):
        logger.debug("playbackStarted(data: %s)" % data)
        if not data:
            return
        self.curVideo = data
        self.curVideoInfo = None
        self.videosToRate = []

        if not utilities.getSettingAsBool(
                'scrobble_fallback'
        ) and 'id' not in self.curVideo and 'video_ids' not in self.curVideo:
            logger.debug('Aborting scrobble to avoid fallback: %s' %
                         (self.curVideo))
            return

        if 'type' in self.curVideo:
            logger.debug("Watching: %s" % self.curVideo['type'])
            if not xbmc.Player().isPlayingVideo():
                logger.debug("Suddenly stopped watching item")
                return
            xbmc.sleep(
                1000)  # Wait for possible silent seek (caused by resuming)
            try:
                self.watchedTime = xbmc.Player().getTime()
                self.videoDuration = xbmc.Player().getTotalTime()
            except Exception as e:
                logger.debug("Suddenly stopped watching item: %s" % e.message)
                self.curVideo = None
                return

            if self.videoDuration == 0:
                if utilities.isMovie(self.curVideo['type']):
                    self.videoDuration = 90
                elif utilities.isEpisode(self.curVideo['type']):
                    self.videoDuration = 30
                else:
                    self.videoDuration = 1

            self.playlistLength = len(xbmc.PlayList(xbmc.PLAYLIST_VIDEO))
            self.playlistIndex = xbmc.PlayList(
                xbmc.PLAYLIST_VIDEO).getposition()
            if self.playlistLength == 0:
                logger.debug(
                    "Warning: Cant find playlist length, assuming that this item is by itself"
                )
                self.playlistLength = 1

            self.isMultiPartEpisode = False
            if utilities.isMovie(self.curVideo['type']):
                if 'id' in self.curVideo:
                    self.curVideoInfo = utilities.kodiRpcToTraktMediaObject(
                        'movie',
                        utilities.getMovieDetailsFromKodi(
                            self.curVideo['id'], [
                                'imdbnumber', 'title', 'year', 'file',
                                'lastplayed', 'playcount'
                            ]))
                elif 'video_ids' in self.curVideo:
                    self.curVideoInfo = {
                        'ids': self.curVideo['video_ids'],
                        'title': self.curVideo['title'],
                        'year': self.curVideo['year']
                    }
                elif 'title' in self.curVideo and 'year' in self.curVideo:
                    self.curVideoInfo = {
                        'title': self.curVideo['title'],
                        'year': self.curVideo['year']
                    }

            elif utilities.isEpisode(self.curVideo['type']):
                if 'id' in self.curVideo:
                    episodeDetailsKodi = utilities.getEpisodeDetailsFromKodi(
                        self.curVideo['id'], [
                            'showtitle', 'season', 'episode', 'tvshowid',
                            'uniqueid', 'file', 'playcount'
                        ])
                    tvdb = episodeDetailsKodi['imdbnumber']
                    title, year = utilities.regex_year(
                        episodeDetailsKodi['showtitle'])
                    if not year:
                        self.traktShowSummary = {
                            'title': episodeDetailsKodi['showtitle'],
                            'year': episodeDetailsKodi['year']
                        }
                    else:
                        self.traktShowSummary = {'title': title, 'year': year}
                    if tvdb:
                        self.traktShowSummary['ids'] = {'tvdb': tvdb}
                    self.curVideoInfo = utilities.kodiRpcToTraktMediaObject(
                        'episode', episodeDetailsKodi)
                    if not self.curVideoInfo:  # getEpisodeDetailsFromKodi was empty
                        logger.debug(
                            "Episode details from Kodi was empty, ID (%d) seems invalid, aborting further scrobbling of this episode."
                            % self.curVideo['id'])
                        self.curVideo = None
                        self.isPlaying = False
                        self.watchedTime = 0
                        return
                elif 'video_ids' in self.curVideo and 'season' in self.curVideo and 'episode' in self.curVideo:
                    self.curVideoInfo = {
                        'title': self.curVideo['title'],
                        'season': self.curVideo['season'],
                        'number': self.curVideo['episode']
                    }
                    self.traktShowSummary = {'ids': self.curVideo['video_ids']}
                elif 'title' in self.curVideo and 'season' in self.curVideo and 'episode' in self.curVideo:
                    self.curVideoInfo = {
                        'title': self.curVideo['title'],
                        'season': self.curVideo['season'],
                        'number': self.curVideo['episode']
                    }

                    title, year = utilities.regex_year(
                        self.curVideo['showtitle'])
                    if not year:
                        self.traktShowSummary = {
                            'title': self.curVideo['showtitle']
                        }
                    else:
                        self.traktShowSummary = {'title': title, 'year': year}

                    if 'year' in self.curVideo:
                        self.traktShowSummary['year'] = self.curVideo['year']

                if 'multi_episode_count' in self.curVideo and self.curVideo[
                        'multi_episode_count'] > 1:
                    self.isMultiPartEpisode = True

            self.isPlaying = True
            self.isPaused = False

            if utilities.getSettingAsBool(
                    'scrobble_movie') or utilities.getSettingAsBool(
                        'scrobble_episode'):
                result = self.__scrobble('start')
            elif utilities.getSettingAsBool(
                    'rate_movie') and utilities.isMovie(self.curVideo['type']):
                result = {
                    'movie':
                    self.traktapi.getMovieSummary(
                        self.curVideoInfo['ids']['imdb']).to_dict()
                }
            elif utilities.getSettingAsBool(
                    'rate_episode') and utilities.isEpisode(
                        self.curVideo['type']):
                data, id_type = utilities.parseIdToTraktIds(
                    str(self.traktShowSummary['ids']['tvdb']),
                    self.curVideo['type'])
                ids = self.traktapi.getIdLookup(data[id_type], id_type)
                trakt_id = dict(ids[0].keys)['trakt']
                result = {
                    'show':
                    self.traktapi.getShowSummary(trakt_id).to_dict(),
                    'episode':
                    self.traktapi.getEpisodeSummary(
                        trakt_id, self.curVideoInfo['season'],
                        self.curVideoInfo['number']).to_dict()
                }

            self.__preFetchUserRatings(result)
Esempio n. 4
0
    def update(self, forceCheck=False):
        if not xbmc.Player().isPlayingVideo():
            return

        if self.isPlaying:
            t = xbmc.Player().getTime()
            l = xbmc.PlayList(xbmc.PLAYLIST_VIDEO).getposition()
            if self.playlistIndex == l:
                self.watchedTime = t
            else:
                logger.debug(
                    "Current playlist item changed! Not updating time! (%d -> %d)"
                    % (self.playlistIndex, l))

            if 'id' in self.curVideo and self.isMultiPartEpisode:
                # do transition check every minute
                if (time.time() > (self.lastMPCheck + 60)) or forceCheck:
                    self.lastMPCheck = time.time()
                    watchedPercent = (self.watchedTime /
                                      self.videoDuration) * 100
                    epIndex = self._currentEpisode(
                        watchedPercent, self.curVideo['multi_episode_count'])
                    if self.curMPEpisode != epIndex:
                        # current episode in multi-part episode has changed
                        logger.debug(
                            "Attempting to stop scrobble episode part %d of %d."
                            % (self.curMPEpisode + 1,
                               self.curVideo['multi_episode_count']))

                        # recalculate watchedPercent and duration for multi-part, and scrobble
                        adjustedDuration = int(
                            self.videoDuration /
                            self.curVideo['multi_episode_count'])
                        watchedPercent = (
                            (self.watchedTime -
                             (adjustedDuration * self.curMPEpisode)) /
                            adjustedDuration) * 100
                        response = self.traktapi.scrobbleEpisode(
                            self.traktShowSummary, self.curVideoInfo,
                            watchedPercent, 'stop')
                        if response is not None:
                            logger.debug("Scrobble response: %s" %
                                         str(response))

                        # update current information
                        self.curMPEpisode = epIndex
                        self.curVideoInfo = utilities.kodiRpcToTraktMediaObject(
                            'episode',
                            utilities.getEpisodeDetailsFromKodi(
                                self.curVideo['multi_episode_data']
                                [self.curMPEpisode], [
                                    'showtitle', 'season', 'episode',
                                    'tvshowid', 'uniqueid', 'file', 'playcount'
                                ]))

                        if not forceCheck:
                            logger.debug(
                                "Attempting to start scrobble episode part %d of %d."
                                % (self.curMPEpisode + 1,
                                   self.curVideo['multi_episode_count']))
                            response = self.traktapi.scrobbleEpisode(
                                self.traktShowSummary, self.curVideoInfo, 0,
                                'start')
                            if response is not None:
                                logger.debug("Scrobble response: %s" %
                                             str(response))
Esempio n. 5
0
def run():
    url = urllib.parse.urlparse(sys.argv[0])
    path = url.path
    handle = int(sys.argv[1])
    args = urllib.parse.parse_qs(sys.argv[2][1:])
    xbmcplugin.setContent(handle, "songs")

    if path == PATH_ROOT:
        action = args.get("action", None)
        if action is None:
            items = listItems.root()
            xbmcplugin.addDirectoryItems(handle, items, len(items))
            xbmcplugin.endOfDirectory(handle)
        elif "call" in action:
            collection = listItems.from_collection(
                api.call(args.get("call")[0]))
            xbmcplugin.addDirectoryItems(handle, collection, len(collection))
            xbmcplugin.endOfDirectory(handle)
        elif "settings" in action:
            addon.openSettings()
        else:
            xbmc.log("Invalid root action", xbmc.LOGERROR)

    elif path == PATH_CHARTS:
        action = args.get("action", [None])[0]
        genre = args.get("genre", ["soundcloud:genres:all-music"])[0]
        if action is None:
            items = listItems.charts()
            xbmcplugin.addDirectoryItems(handle, items, len(items))
            xbmcplugin.endOfDirectory(handle)
        else:
            api_result = api.charts({
                "kind": action,
                "genre": genre,
                "limit": 50
            })
            collection = listItems.from_collection(api_result)
            xbmcplugin.addDirectoryItems(handle, collection, len(collection))
            xbmcplugin.endOfDirectory(handle)

    elif path == PATH_DISCOVER:
        selection = args.get("selection", [None])[0]
        collection = listItems.from_collection(api.discover(selection))
        xbmcplugin.addDirectoryItems(handle, collection, len(collection))
        xbmcplugin.endOfDirectory(handle)

    elif path == PATH_PLAY:
        # Public params
        track_id = args.get("track_id", [None])[0]
        playlist_id = args.get("playlist_id", [None])[0]
        url = args.get("url", [None])[0]

        # Public legacy params (@deprecated)
        audio_id_legacy = args.get("audio_id", [None])[0]
        track_id = audio_id_legacy if audio_id_legacy else track_id

        # Private params
        media_url = args.get("media_url", [None])[0]

        if media_url:
            resolved_url = api.resolve_media_url(media_url)
            item = xbmcgui.ListItem(path=resolved_url)
            xbmcplugin.setResolvedUrl(handle, succeeded=True, listitem=item)
        elif track_id:
            collection = listItems.from_collection(api.resolve_id(track_id))
            playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
            resolve_list_item(handle, collection[0][1])
            playlist.add(url=collection[0][0], listitem=collection[0][1])
        elif playlist_id:
            call = "/playlists/{id}".format(id=playlist_id)
            collection = listItems.from_collection(api.call(call))
            playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
            for item in collection:
                resolve_list_item(handle, item[1])
                playlist.add(url=item[0], listitem=item[1])
        elif url:
            collection = listItems.from_collection(api.resolve_url(url))
            playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
            for item in collection:
                resolve_list_item(handle, item[1])
                playlist.add(url=item[0], listitem=item[1])
        else:
            xbmc.log("Invalid play param", xbmc.LOGERROR)

    elif path == PATH_SEARCH:
        action = args.get("action", None)
        query = args.get("query", [""])[0]
        if query:
            if action is None:
                search(handle, query)
            elif "people" in action:
                xbmcplugin.setContent(handle, "artists")
                collection = listItems.from_collection(
                    api.search(query, "users"))
                xbmcplugin.addDirectoryItems(handle, collection,
                                             len(collection))
                xbmcplugin.endOfDirectory(handle)
            elif "albums" in action:
                xbmcplugin.setContent(handle, "albums")
                collection = listItems.from_collection(
                    api.search(query, "albums"))
                xbmcplugin.addDirectoryItems(handle, collection,
                                             len(collection))
                xbmcplugin.endOfDirectory(handle)
            elif "playlists" in action:
                xbmcplugin.setContent(handle, "albums")
                collection = listItems.from_collection(
                    api.search(query, "playlists_without_albums"))
                xbmcplugin.addDirectoryItems(handle, collection,
                                             len(collection))
                xbmcplugin.endOfDirectory(handle)
            else:
                xbmc.log("Invalid search action", xbmc.LOGERROR)
        else:
            if action is None:
                items = listItems.search()
                xbmcplugin.addDirectoryItems(handle, items, len(items))
                xbmcplugin.endOfDirectory(handle)
            elif "new" in action:
                query = xbmcgui.Dialog().input(addon.getLocalizedString(30101))
                search_history.add(query)
                search(handle, query)
            else:
                xbmc.log("Invalid search action", xbmc.LOGERROR)

    # Legacy search query used by Chorus2 (@deprecated)
    elif path == PATH_SEARCH_LEGACY:
        query = args.get("q", [""])[0]
        collection = listItems.from_collection(api.search(query))
        xbmcplugin.addDirectoryItems(handle, collection, len(collection))
        xbmcplugin.endOfDirectory(handle)

    elif path == PATH_USER:
        user_id = args.get("id")[0]
        default_action = args.get("call")[0]
        if user_id:
            items = listItems.user(user_id)
            collection = listItems.from_collection(api.call(default_action))
            xbmcplugin.addDirectoryItems(handle, items, len(items))
            xbmcplugin.addDirectoryItems(handle, collection, len(collection))
            xbmcplugin.endOfDirectory(handle)
        else:
            xbmc.log("Invalid user action", xbmc.LOGERROR)

    elif path == PATH_SETTINGS_CACHE_CLEAR:
        vfs_cache.destroy()
        dialog = xbmcgui.Dialog()
        dialog.ok("SoundCloud", addon.getLocalizedString(30501))

    else:
        xbmc.log("Path not found", xbmc.LOGERROR)
Esempio n. 6
0
def play_file(play_info, monitor):
    item_id = play_info.get("item_id")

    home_window = HomeWindow()
    last_url = home_window.get_property("last_content_url")
    if last_url:
        home_window.set_property("skip_cache_for_" + last_url, "true")

    action = play_info.get("action", "play")
    if action == "add_to_playlist":
        add_to_playlist(play_info, monitor)
        return

    # if this is a list of items them add them all to the play list
    if isinstance(item_id, list):
        return play_list_of_items(item_id, monitor)

    auto_resume = play_info.get("auto_resume", "-1")
    force_transcode = play_info.get("force_transcode", False)
    media_source_id = play_info.get("media_source_id", "")
    subtitle_stream_index = play_info.get("subtitle_stream_index", None)
    audio_stream_index = play_info.get("audio_stream_index", None)

    log.debug("playFile id({0}) resume({1}) force_transcode({2})", item_id,
              auto_resume, force_transcode)

    settings = xbmcaddon.Addon()
    addon_path = settings.getAddonInfo('path')
    force_auto_resume = settings.getSetting('forceAutoResume') == 'true'
    jump_back_amount = int(settings.getSetting("jump_back_amount"))
    play_cinema_intros = settings.getSetting('play_cinema_intros') == 'true'

    server = download_utils.get_server()

    url = "{server}/Users/{userid}/Items/%s?format=json" % (item_id, )
    data_manager = DataManager()
    result = data_manager.get_content(url)
    log.debug("Playfile item: {0}", result)

    if result is None:
        log.debug("Playfile item was None, so can not play!")
        return

    # if this is a season, playlist or album then play all items in that parent
    if result.get("Type") in ["Season", "MusicAlbum", "Playlist"]:
        log.debug("PlayAllFiles for parent item id: {0}", item_id)
        url = ('{server}/Users/{userid}/items' + '?ParentId=%s' +
               '&Fields=MediaSources' + '&format=json')
        url = url % (item_id, )
        result = data_manager.get_content(url)
        log.debug("PlayAllFiles items: {0}", result)

        # process each item
        items = result["Items"]
        if items is None:
            items = []
        return play_all_files(items, monitor)

    # if this is a program from live tv epg then play the actual channel
    if result.get("Type") == "Program":
        channel_id = result.get("ChannelId")
        url = "{server}/Users/{userid}/Items/%s?format=json" % (channel_id, )
        result = data_manager.get_content(url)
        item_id = result["Id"]

    if result.get("Type") == "Photo":
        play_url = "%s/Items/%s/Images/Primary"
        play_url = play_url % (server, item_id)

        plugin_path = xbmc.translatePath(
            os.path.join(xbmcaddon.Addon().getAddonInfo('path')))
        action_menu = PictureViewer("PictureViewer.xml", plugin_path,
                                    "default", "720p")
        action_menu.setPicture(play_url)
        action_menu.doModal()
        return

    # get playback info from the server using the device profile
    playback_info = download_utils.get_item_playback_info(
        item_id, force_transcode)
    if playback_info is None:
        log.debug(
            "playback_info was None, could not get MediaSources so can not play!"
        )
        return
    if playback_info.get("ErrorCode") is not None:
        error_string = playback_info.get("ErrorCode")
        xbmcgui.Dialog().notification(
            string_load(30316),
            error_string,
            icon="special://home/addons/plugin.video.jellycon/icon.png")
        return

    play_session_id = playback_info.get("PlaySessionId")

    # select the media source to use
    media_sources = playback_info.get('MediaSources')
    selected_media_source = None

    if media_sources is None or len(media_sources) == 0:
        log.debug("Play Failed! There is no MediaSources data!")
        return

    elif len(media_sources) == 1:
        selected_media_source = media_sources[0]

    elif media_source_id != "":
        for source in media_sources:
            if source.get("Id", "na") == media_source_id:
                selected_media_source = source
                break

    elif len(media_sources) > 1:
        items = []
        for source in media_sources:
            label = source.get("Name", "na")
            label2 = __build_label2_from(source)
            items.append(xbmcgui.ListItem(label=label, label2=label2))
        dialog = xbmcgui.Dialog()
        resp = dialog.select(string_load(30309), items, useDetails=True)
        if resp > -1:
            selected_media_source = media_sources[resp]
        else:
            log.debug("Play Aborted, user did not select a MediaSource")
            return

    if selected_media_source is None:
        log.debug("Play Aborted, MediaSource was None")
        return

    source_id = selected_media_source.get("Id")
    seek_time = 0
    auto_resume = int(auto_resume)

    # process user data for resume points
    if auto_resume != -1:
        seek_time = (auto_resume / 1000) / 10000

    elif force_auto_resume:
        user_data = result.get("UserData")
        reasonable_ticks = int(user_data.get("PlaybackPositionTicks")) / 1000
        seek_time = reasonable_ticks / 10000

    else:
        user_data = result.get("UserData")
        if user_data.get("PlaybackPositionTicks") != 0:

            reasonable_ticks = int(
                user_data.get("PlaybackPositionTicks")) / 1000
            seek_time = reasonable_ticks / 10000
            display_time = str(timedelta(seconds=seek_time))

            resume_dialog = ResumeDialog("ResumeDialog.xml", addon_path,
                                         "default", "720p")
            resume_dialog.setResumeTime("Resume from " + display_time)
            resume_dialog.doModal()
            resume_result = resume_dialog.getResumeAction()
            del resume_dialog
            log.debug("Resume Dialog Result: {0}", resume_result)

            # check system settings for play action
            # if prompt is set ask to set it to auto resume
            # remove for now as the context dialog is now handeled in the monitor thread
            # params = {"setting": "myvideos.selectaction"}
            # setting_result = json_rpc('Settings.getSettingValue').execute(params)
            # log.debug("Current Setting (myvideos.selectaction): {0}", setting_result)
            # current_value = setting_result.get("result", None)
            # if current_value is not None:
            #     current_value = current_value.get("value", -1)
            # if current_value not in (2,3):
            #     return_value = xbmcgui.Dialog().yesno(string_load(30276), string_load(30277))
            #     if return_value:
            #         params = {"setting": "myvideos.selectaction", "value": 2}
            #         json_rpc_result = json_rpc('Settings.setSettingValue').execute(params)
            #         log.debug("Save Setting (myvideos.selectaction): {0}", json_rpc_result)

            if resume_result == 1:
                seek_time = 0
            elif resume_result == -1:
                return

    log.debug("play_session_id: {0}", play_session_id)
    playurl, playback_type, listitem_props = PlayUtils().get_play_url(
        selected_media_source, play_session_id)
    log.info("Play URL: {0} Playback Type: {1} ListItem Properties: {2}",
             playurl, playback_type, listitem_props)

    if playurl is None:
        return

    playback_type_string = "DirectPlay"
    if playback_type == "2":
        playback_type_string = "Transcode"
    elif playback_type == "1":
        playback_type_string = "DirectStream"

    # add the playback type into the overview
    if result.get("Overview", None) is not None:
        result["Overview"] = playback_type_string + "\n" + result.get(
            "Overview")
    else:
        result["Overview"] = playback_type_string

    # add title decoration is needed
    item_title = result.get("Name", string_load(30280))

    # extract item info from result
    gui_options = {}
    gui_options["server"] = server
    gui_options["name_format"] = None
    gui_options["name_format_type"] = ""
    item_details = extract_item_info(result, gui_options)

    # create ListItem
    display_options = {}
    display_options["addCounts"] = False
    display_options["addResumePercent"] = False
    display_options["addSubtitleAvailable"] = False
    display_options["addUserRatings"] = False

    gui_item = add_gui_item("", item_details, display_options, False)
    list_item = gui_item[1]

    if playback_type == "2":  # if transcoding then prompt for audio and subtitle
        playurl = audio_subs_pref(playurl, list_item, selected_media_source,
                                  item_id, audio_stream_index,
                                  subtitle_stream_index)
        log.debug("New playurl for transcoding: {0}", playurl)

    elif playback_type == "1":  # for direct stream add any streamable subtitles
        external_subs(selected_media_source, list_item, item_id)

    # add playurl and data to the monitor
    data = {}
    data["item_id"] = item_id
    data["source_id"] = source_id
    data["playback_type"] = playback_type_string
    data["play_session_id"] = play_session_id
    data["play_action_type"] = "play"
    data["item_type"] = result.get("Type", None)
    data["can_delete"] = result.get("CanDelete", False)
    monitor.played_information[playurl] = data
    log.debug("Add to played_information: {0}", monitor.played_information)

    list_item.setPath(playurl)
    list_item = set_list_item_props(item_id, list_item, result, server,
                                    listitem_props, item_title)

    player = xbmc.Player()

    intro_items = []
    if play_cinema_intros and seek_time == 0:
        intro_items = get_playback_intros(item_id)

    if len(intro_items) > 0:
        playlist = play_all_files(intro_items, monitor, play_items=False)
        playlist.add(playurl, list_item)
    else:
        playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
        playlist.clear()
        playlist.add(playurl, list_item)

    player.play(playlist)

    if seek_time != 0:
        player.pause()
        monitor = xbmc.Monitor()
        count = 0
        while not player.isPlaying() and not monitor.abortRequested(
        ) and count != 100:
            count = count + 1
            xbmc.sleep(100)

        if count == 100 or not player.isPlaying() or monitor.abortRequested():
            log.info(
                "PlaybackResumrAction : Playback item did not get to a play state in 10 seconds so exiting"
            )
            player.stop()
            return

        log.info("PlaybackResumrAction : Playback is Running")

        seek_to_time = seek_time - jump_back_amount
        target_seek = (seek_to_time - 10)

        count = 0
        max_loops = 2 * 120
        while not monitor.abortRequested() and player.isPlaying(
        ) and count < max_loops:
            log.info("PlaybackResumrAction : Seeking to : {0}", seek_to_time)
            player.seekTime(seek_to_time)
            current_position = player.getTime()
            if current_position >= target_seek:
                break
            log.info("PlaybackResumrAction : target:{0} current:{1}",
                     target_seek, current_position)
            count = count + 1
            xbmc.sleep(500)

        if count == max_loops:
            log.info(
                "PlaybackResumrAction : Playback could not seek to required position"
            )
            player.stop()
        else:
            count = 0
            while bool(xbmc.getCondVisibility("Player.Paused")) and count < 10:
                log.info("PlaybackResumrAction : Unpausing playback")
                player.pause()
                xbmc.sleep(1000)
                count = count + 1

            if count == 10:
                log.info("PlaybackResumrAction : Could not unpause")
            else:
                log.info("PlaybackResumrAction : Playback resumed")

    next_episode = get_next_episode(result)
    data["next_episode"] = next_episode
    send_next_episode_details(result, next_episode)
Esempio n. 7
0
def lersinopse():
    mensagemprogresso.create('wareztuga.tv', 'A carregar...')
    link = clean(abrir_url_cookie(urlficheiro, False))
    #try:
    text = re.compile(
        '<span id="movie-synopsis-aux" class="movie-synopsis-aux">(.+?)</span>'
    ).findall(link)[0]
    text = text.decode('string-escape')
    trechos = []
    i = 0
    partido = splitCount(text, 99)
    #print partido
    for pedacos in partido:
        #print pedacos
        i = i + 1
        nomeficheiro = 'temp%s.mp3' % (str(i))
        temp = os.path.join(pastaperfil, nomeficheiro)
        trechos.append(temp)
        #limit = min(100, len(text))#100 characters is the current limit.
        #text = text[0:limit]
        url = "http://translate.google.com/translate_tts?tl=pt&q=%s" % (
            urllib.quote(pedacos))
        #values = urllib.urlencode({"q": pedacos, "textlen": len(pedacos), "tl": 'pt'})
        hrs = {
            "User-Agent":
            "Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7"
        }
        #req = urllib2.Request(url, data=values, headers=hrs)
        req = urllib2.Request(url, headers=hrs)
        p = urllib2.urlopen(req)
        f = open(temp, 'wb')
        f.write(p.read())
        f.close()
        xbmc.sleep(250)

    #import wave
    outfile = os.path.join(pastaperfil, 'final.mp3')
    try:
        os.remove(outfile)
    except:
        pass
    import shutil
    destination = open(outfile, 'wb')
    for filename in trechos:
        shutil.copyfileobj(open(filename, 'rb'), destination)
        try:
            os.remove(filename)
        except:
            pass
    destination.close()

    playlist = xbmc.PlayList(1)
    playlist.clear()
    listitem = xbmcgui.ListItem(traducao(40347),
                                iconImage="DefaultVideo.png",
                                thumbnailImage='')
    listitem.setInfo("Video", {"Title": traducao(40347)})
    playlist.add(outfile, listitem)

    #listitem.setProperty('mimetype', 'video/x-msvideo')
    #listitem.setProperty('IsPlayable', 'true')
    mensagemprogresso.close()
    xbmc.Player(xbmc.PLAYER_CORE_DVDPLAYER).play(playlist)
Esempio n. 8
0
def progList(name, type, cat, filtrs, page, listpage):
    if page is None: page = 1
    # p_url = 'http://list.funshion.com/%s/pg-%s%s/'
    ## p_url = 'http://www.funshion.com/list/%s/pg-%s%s/'

    if (name in SERIES_LIST) or (name in MOVIE_LIST):
        p_url = "http://www.fun.tv/retrieve/%s.n-e5bdb1e78987%s.pg-%s"
    else:
        p_url = "http://www.fun.tv/retrieve/%s%s.pg-%s"

    if (listpage == None):
        url = p_url % (type, '', page)
        link = getHttpData(url)

        match = re.compile('<div class="ls-nav" id="ls-nav">(.+?</div>)</div>',
                           re.DOTALL).findall(link)
        if match:
            listpage = match[0]
        match = re.compile('<div class="ls-sort" id="ls-sort">(.+?</div>)',
                           re.DOTALL).findall(link)
        if len(match):
            listpage += match[0]
        cat = updateListSEL(name, type, cat, filtrs, 0, listpage)
    else:
        url = p_url % (type, filtrs, page)
        link = getHttpData(url)

    # Fetch & build video titles list for user selection, highlight user selected filtrs
    li = xbmcgui.ListItem(name + '(第' + str(page) + '页)【' + cat + '】(按此选择)')
    u = sys.argv[0] + "?mode=10&name=" + urllib.quote_plus(
        name) + "&type=" + type + "&cat=" + urllib.quote_plus(
            cat) + "&filtrs=" + urllib.quote_plus(
                filtrs) + "&page=1" + "&listpage=" + urllib.quote_plus(
                    listpage)
    xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, True)

    if link == None: return
    # Movie, Video, Series, Variety & Music types need different routines
    if name in SERIES_LIST:
        isdir = True
        mode = 2
    elif name in MOVIE_LIST:
        isdir = False
        mode = 3
    else:  # 娱乐,新闻,体育,搞笑,时尚,生活,旅游,科技
        isdir = False
        mode = 4
        playlist = xbmc.PlayList(0)  # use Music playlist for temporary storage
        playlist.clear()

    match = re.compile('<div class="mod-vd-i.+?>(.+?)</div></div>',
                       re.DOTALL).findall(link)
    totalItems = len(match) + 1

    # COLOR_LIST = ['[COLOR FFFF0000]','[COLOR FF00FF00]','[COLOR FFFFFF00]','[COLOR FF00FFFF]','[COLOR FFFF00FF]']
    for i in range(0, len(match)):
        match1 = re.compile("/vplay/[a-z]+-(.+?)/").findall(match[i])
        p_id = match1[0]

        match1 = re.compile(
            '<img src=.+?_lazysrc=[\'|"]+(.*?)[\'|"]+.+?alt="(.+?)"').findall(
                match[i])
        p_thumb = match1[0][0]
        p_name = match1[0][1].replace('&quot;', '"')

        p_name1 = str(i + 1) + '. ' + p_name + ' '
        match1 = re.compile('<span>(.+?)</span>').findall(match[i])
        if len(match1):
            p_name1 += '[COLOR FF00FFFF](' + match1[0] + ')[/COLOR] '

        match1 = re.compile('<b class="score">(.+?)</b>').findall(match[i])
        if len(match1):
            p_rating = match1[0]
            p_name1 += '[COLOR FFFF00FF][' + p_rating + '][/COLOR]'

        if match[i].find("class='ico-dvd spdvd'") > 0:
            p_name1 += ' [COLOR FFFFFF00][超清][/COLOR]'
        elif match[i].find("class='ico-dvd hdvd'") > 0:
            p_name1 += ' [COLOR FF00FFFF][高清][/COLOR]'

        match1 = re.compile('<i class="tip">(.+?)</i>').findall(match[i])
        if len(match1):
            p_duration = match1[0]
            p_name1 += ' [COLOR FF00FF00][' + p_duration + '][/COLOR]'

        match1 = re.compile('<p class="desc">(.+?)</p>').findall(match[i])
        if len(match1):
            p_desp = match1[0]
            p_name1 += ' (' + p_desp + ')'

        li = xbmcgui.ListItem(p_name1, iconImage='', thumbnailImage=p_thumb)
        u = sys.argv[0] + "?mode=" + str(mode) + "&name=" + urllib.quote_plus(
            p_name1) + "&id=" + urllib.quote_plus(
                p_id) + "&thumb=" + urllib.quote_plus(
                    p_thumb) + "&type=" + urllib.quote_plus(type)
        li.setInfo(type="Video", infoLabels={"Title": p_name})
        xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, isdir, totalItems)
        if (mode == 4): playlist.add(p_id, li)

    # Construct page selection
    match = re.compile('<div class="pager-wrap fix">(.+?)</div>',
                       re.DOTALL).findall(link)
    if match:
        match1 = re.compile("<a[\s]+?href='.+?'>(\d+)</a>",
                            re.DOTALL).findall(match[0])
        plist = [str(page)]
        for num in match1:
            if (num not in plist):
                plist.append(num)
                li = xbmcgui.ListItem("... 第" + num + "页")
                u = sys.argv[0] + "?mode=1&name=" + urllib.quote_plus(
                    name) + "&type=" + urllib.quote_plus(
                        type) + "&cat=" + urllib.quote_plus(
                            cat
                        ) + "&filtrs=" + urllib.quote_plus(
                            filtrs
                        ) + "&page=" + num + "&listpage=" + urllib.quote_plus(
                            listpage)
                xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, True,
                                            totalItems)

    xbmcplugin.setContent(int(sys.argv[1]), 'movies')
    xbmcplugin.endOfDirectory(int(sys.argv[1]))
Esempio n. 9
0
def PlayVideo2(name, id, thumb, type):
    videoplaycont = __addon__.getSetting('video_vplaycont')

    playlistA = xbmc.PlayList(0)
    playlist = xbmc.PlayList(1)
    playlist.clear()

    v_pos = int(name.split('.')[0]) - 1
    psize = playlistA.size()
    ERR_MAX = psize - 1
    TRIAL = 1
    errcnt = 0
    k = 0

    pDialog = xbmcgui.DialogProgress()
    ret = pDialog.create('匹配视频', '请耐心等候! 尝试匹配视频文件 ...')
    pDialog.update(0)

    for x in range(psize):
        # abort if ERR_MAX or more access failures and no video playback
        if (errcnt >= ERR_MAX and k == 0):
            pDialog.close()
            dialog = xbmcgui.Dialog()
            ok = dialog.ok(__addonname__, '无法播放:多次未匹配到视频文件,请选择其它视频')
            break

        if x < v_pos: continue
        p_item = playlistA.__getitem__(x)
        p_url = p_item.getfilename(x)
        p_list = p_item.getdescription(x)

        li = p_item  # pass all li items including the embedded thumb image
        li.setInfo(type="Video", infoLabels={"Title": p_list})

        if not re.search('http://', p_url):  #fresh search
            if type == 'video':
                url = 'http://api.funshion.com/ajax/get_media_data/ugc/%s' % (
                    p_url)
            else:
                url = 'http://api.funshion.com/ajax/get_media_data/video/%s' % (
                    p_url)

            if (pDialog.iscanceled()):
                pDialog.close()
                x = psize  # quickily terminate any old thread
                err_cnt = 0
                return
            pDialog.update(errcnt * 100 / ERR_MAX + 100 / ERR_MAX / TRIAL * 1)

            link = getHttpData(url)
            try:
                json_response = simplejson.loads(link)
                hashid = json_response['data']['hashid'].encode('utf-8')
                filename = json_response['data']['filename'].encode('utf-8')
            except:
                errcnt += 1  # increment consequetive unsuccessful access
                continue
            url = 'http://jobsfe.funshion.com/query/v1/mp4/%s.json?file=%s' % (
                hashid, filename)

            link = getHttpData(url)
            try:  # prevent system occassion throw error
                json_response = simplejson.loads(link)
                status = json_response['return'].encode('utf-8')
            except:
                errcnt += 1  # increment consequetive unsuccessful access
                continue
            if status == 'succ':
                v_url = json_response['playlist'][0]['urls'][0]
                playlistA.remove(p_url)  # remove old url
                playlistA.add(v_url, li,
                              x)  # keep a copy of v_url in Audio Playlist
            else:
                errcnt += 1  # increment consequetive unsuccessful access
                continue
        else:
            v_url = p_url

        err_cnt = 0  # reset error count
        playlist.add(v_url, li, k)
        k += 1
        if k == 1:
            pDialog.close()
            xbmc.Player(1).play(playlist)
        if videoplaycont == 'false': break
Esempio n. 10
0
    def onClick( self, controlID ):
        try:
            if controlID == 5:
                if self.getControl( 5 ).getLabel() == LangXBMC( 207 ):
                    self.getControl( 5 ).setLabel( LangXBMC( 206 ) )
                    self.getControl( 150 ).setVisible( 0 )
                else:
                    self.getControl( 5 ).setLabel( LangXBMC( 207 ) )
                    self.getControl( 150 ).setVisible( 1 )

            elif controlID == 6:
                self._close_dialog()
                xbmc.executebuiltin( "RunScript(script.moviesets,manager)" )

            elif controlID == 8:
                self._close_dialog()
                xbmc.executebuiltin( "Container.Update(videodb://1/7/%s/,replace)" % self.idset )

            elif controlID == 11:
                # create our playlist
                playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
                # clear any possible entries
                playlist.clear()
                # set title
                #title = "%s (%s)" % ( xbmc.getInfoLabel( "ListItem.Label" ), LangXBMC( 20410 ) )
                #self.listitem.setInfo( "video", { "title": title } )
                # enum trailers
                #for trailer in xbmc.getInfoLabel( "ListItem.Trailer" ).replace( "stack://", "" ).split( " , " ):
                #    # add item to our playlist
                #    playlist.add( trailer, self.listitem )
                # get trailers
                for i in range( 1, 11 ):
                    title = _unicode( xbmc.getInfoLabel( "ListItem.Property(movie.%i.Title)" % i ) )
                    if not title: break
                    trailer = xbmc.getInfoLabel( "ListItem.Property(movie.%i.Trailer)" % i )
                    if not trailer: continue
                    title = "%s (%s)" % ( title, LangXBMC( 20410 ) )
                    # update title
                    self.listitem.setInfo( "video", { "title": title } )
                    # add item to our playlist
                    playlist.add( trailer, self.listitem )
                # if movie in playlist play item
                if playlist.size():
                    self._close_dialog()
                    # play item
                    xbmc.Player( xbmc.PLAYER_CORE_AUTO ).play( playlist )

            elif controlID in [ 10, 12 ]:
                self.setfocus = controlID
                # **attrs: Set movieset fanart or Set movieset thumb
                self.browser_attrs = {
                    "idset": self.idset,
                    "heading": xbmc.getInfoLabel( "ListItem.Label" ),
                    "type": ( "fanart", "thumb" )[ self.setfocus == 10 ]
                    }
                self._close_dialog()

            elif controlID == 150:
                actor_name = xbmc.getInfoLabel( "Container(150).ListItem.Title" )
                if actor_name:
                    xbmc.executebuiltin( "RunScript(script.metadata.actors,%s)" % actor_name )
        except:
            LOGGER.error.print_exc()
Esempio n. 11
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)
if __name__ == '__main__':
    log("Started")
    monitor = xbmc.Monitor()
    settings = xbmcaddon.Addon("plugin.yandex-music")
    token = settings.getSetting('token')

    log(sys.argv)
    type_ = sys.argv[1]
    radio_type_ = sys.argv[2]
    station_key_ = sys.argv[3]

    # get stations info
    auth, client = checkLogin(settings)

    # init playlist
    pl = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
    pl.clear()

    # init player
    player = MyPlayer()

    if type_ == "custom":
        player.start("%s:%s" % (radio_type_, station_key_), radio_type_)
    else:
        stations = radio.make_structure(client)
        stations["dashboard"] = radio.make_dashboard(client)
        station = stations[radio_type_][station_key_]
        player.start(station.getId(), station.source.station.id_for_from)

    sleep(5)
    while not monitor.abortRequested():
Esempio n. 13
0
def playall():
    playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    xbmc.Player().play(playlist)
    return
Esempio n. 14
0
def build_networks_sub_directory(url, offset):
    saveurl = url
    html = getUrl('http://testtube.com' + url +
                  '/episodePage?limit=25&offset=' + str(offset * 25))
    networkItem = common.parseDOM(html, "li", attrs={"class": "networkItem"})
    if len(networkItem) == 0:
        dialog = xbmcgui.Dialog()
        ok = dialog.ok(plugin,
                       settings.getLocalizedString(30026) + ' this page.')
        return
    if settings.getSetting('download') == '' or settings.getSetting(
            'download') == 'false':
        if settings.getSetting('playall') == 'true':
            playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
            playlist.clear()
            u = {'mode': '6'}
            infoLabels = {
                "Title": settings.getLocalizedString(30030),
                "Plot": settings.getLocalizedString(30031)
            }
            addListItem('* ' + settings.getLocalizedString(30030) + ' *',
                        play_thumb, u, True, 0, infoLabels, fanart_bg)
    for item in networkItem:
        url = common.parseDOM(item,
                              "a",
                              attrs={"class": "playlistPlay clear"},
                              ret="href")[0][1:]
        thumbnail = common.parseDOM(item, "div", attrs={"class": "thumbnail"})
        image = common.parseDOM(thumbnail, "img",
                                ret="src")[0].replace('small.thumb.jpg',
                                                      'medium.thumb.jpg')
        meta = common.parseDOM(item, "div", attrs={"class": "meta"})
        name = common.parseDOM(meta, "div",
                               attrs={"class":
                                      "title"})[0].encode('ascii', 'ignore')
        studio = common.parseDOM(meta, "div", attrs={"class": "showtitle"})[0]
        plot = common.parseDOM(meta, "div",
                               attrs={"class": "itemPreview"
                                      })[0].encode('ascii', 'ignore')
        infoLabels = {"Title": name, "Studio": studio, "Plot": plot}
        u = {
            'mode': '2',
            'name': name,
            'url': url,
            'plot': plot,
            'studio': studio,
            'episode': '0',
            'thumb': image,
            'date': '0000-00-00'
        }
        addListItem(name, image, u, False, len(networkItem), infoLabels,
                    fanart_bg)
    if len(networkItem) == 25:
        u = {'mode': '5', 'url': saveurl, 'offset': offset + 1}
        infoLabels = {
            "Title": settings.getLocalizedString(30016),
            "Plot": settings.getLocalizedString(30016)
        }
        addListItem(
            settings.getLocalizedString(30016) + ' (' + str(offset + 2) + ')',
            next_thumb, u, True, 0, infoLabels, fanart_bg)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_UNSORTED)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_EPISODE)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_STUDIO)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_VIDEO_RUNTIME)
    setViewMode("503")
    xbmcplugin.endOfDirectory(int(sys.argv[1]))
Esempio n. 15
0
def playvideoEx(canal, server, url, category, title, thumbnail, plot,
                desdefavoritos, desdedescargados):

    xbmc.output("[xbmctools.py] playvideo")
    xbmc.output("[xbmctools.py] playvideo canal=" + canal)
    xbmc.output("[xbmctools.py] playvideo server=" + server)
    xbmc.output("[xbmctools.py] playvideo url=" + url)
    xbmc.output("[xbmctools.py] playvideo category=" + category)

    # Abre el diálogo de selección
    if (server == "Megavideo" or server == "Megaupload"
        ) and xbmcplugin.getSetting("megavideopremium") == "true":
        opciones = []
        opciones.append("Ver en calidad alta [Megavideo]")
        opciones.append("Ver en calidad baja [Megavideo]")
        if desdefavoritos:
            opciones.append("Quitar de favoritos")
        else:
            opciones.append("Añadir a favoritos")

        dia = xbmcgui.Dialog()
        seleccion = dia.select("Elige una opción", opciones)
        xbmc.output("seleccion=%d" % seleccion)

        if seleccion == -1:
            return
        if seleccion == 0:
            if server == "Megaupload":
                mediaurl = servertools.getmegauploadhigh(url)
            else:
                mediaurl = servertools.getmegavideohigh(url)
        elif seleccion == 1:
            #advertencia = xbmcgui.Dialog()
            #resultado = advertencia.ok('Megavideo tiene un límite de reproducción de 72 minutos' , 'Aunque tengas una cuenta Premium el límite sigue existiendo' , 'cuando ves los vídeos en calidad baja')
            if server == "Megaupload":
                mediaurl = servertools.getmegauploadlow(url)
            else:
                mediaurl = servertools.getmegavideolow(url)
        elif seleccion == 2:
            if desdefavoritos:
                # La categoría es el nombre del fichero en favoritos
                os.remove(urllib.unquote_plus(category))
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok('Vídeo quitado de favoritos',
                                           title, 'Se ha quitado de favoritos')
            else:
                keyboard = xbmc.Keyboard(
                    downloadtools.limpia_nombre_excepto_1(title))
                keyboard.doModal()
                if (keyboard.isConfirmed()):
                    title = keyboard.getText()
                favoritos.savebookmark(title, url, thumbnail, server, plot)
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok('Nuevo vídeo en favoritos', title,
                                           'se ha añadido a favoritos')
            return

    else:
        opciones = []
        opciones.append("Ver [" + server + "]")
        if desdefavoritos:
            opciones.append("Quitar de favoritos")
        else:
            opciones.append("Añadir a favoritos")

        dia = xbmcgui.Dialog()
        seleccion = dia.select("Elige una opción", opciones)
        xbmc.output("seleccion=%d" % seleccion)

        if seleccion == -1:
            return
        if seleccion == 0:
            if server == "Megavideo":
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok(
                    'Megavideo tiene un límite de reproducción de 72 minutos',
                    'Para evitar que los vídeos se corten pasado ese tiempo',
                    'necesitas una cuenta Premium')
            mediaurl = servertools.findurl(url, server)
        elif seleccion == 1:
            if desdefavoritos:
                # La categoría es el nombre del fichero en favoritos
                os.remove(urllib.unquote_plus(category))
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok('Vídeo quitado de favoritos',
                                           title, 'Se ha quitado de favoritos')
            else:
                keyboard = xbmc.Keyboard(
                    downloadtools.limpia_nombre_excepto_1(title))
                keyboard.doModal()
                if (keyboard.isConfirmed()):
                    title = keyboard.getText()
                favoritos.savebookmark(title, url, thumbnail, server, plot)
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok('Nuevo vídeo en favoritos', title,
                                           'se ha añadido a favoritos')
            return

    xbmc.output("[xbmctools.py] mediaurl=" + mediaurl)

    if mediaurl == "":
        alertnodisponibleserver(server)
        return

    # Abre dialogo
    dialogWait = xbmcgui.DialogProgress()
    dialogWait.create('Accediendo al video...', title)

    # Playlist vacia
    playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    playlist.clear()

    # Crea la entrada y la añade al playlist
    listitem = xbmcgui.ListItem(title,
                                iconImage="DefaultVideo.png",
                                thumbnailImage=thumbnail)
    listitem.setInfo("video", {
        "Title": title,
        "Plot": plot,
        "Studio": canal,
        "Genre": category
    })
    playlist.add(mediaurl, listitem)

    # Cierra dialogo
    dialogWait.close()
    del dialogWait

    # Reproduce
    xbmcPlayer = xbmc.Player(xbmc.PLAYER_CORE_DVDPLAYER)
    xbmcPlayer.play(playlist)
Esempio n. 16
0
def add_related_video_to_playlist(context, video_id, demo=False):
    def _get_related(_video_id, _page_token, _current_items):
        _item = None

        if demo:
            _item = VIDEO_SEARCH

        else:
            try:
                payload = context.api.related_videos(
                    _video_id,
                    page_token=_page_token,
                    max_results=17,
                    fields='items(kind,id(videoId),snippet(title))')
                result_items = payload.get('items', [])
                _page_token = payload.get('nextPageToken', '')

            except:  # pylint: disable=bare-except
                result_items = []

            if result_items:
                _item = next((item for item in result_items if not any(
                    (item.get('id', {}).get('videoId') in playlist_item.get(
                        'file') or
                     (unescape(item.get('snippet', {}).get('title', '')) ==
                      playlist_item.get('label')))
                    for playlist_item in _current_items)), None)

        return _item, _page_token

    def _metadata(_video_id):
        if demo:
            cached_video = VIDEO_ITEM

        else:
            cached_payload = get_cached(context, context.api.videos,
                                        [_video_id])
            cached_video = cached_payload.get(_video_id, {})

        cached_snippet = cached_video.get('snippet', {})
        cached_content_details = cached_video.get('contentDetails', {})
        cached_statistics = cached_video.get('statistics', {})

        channel_id = cached_snippet.get('channelId', '')
        channel_name = unescape(cached_snippet.get('channelTitle', ''))

        video_title = unescape(cached_snippet.get('title', ''))

        published_arrow = None
        live_details = cached_video.get('liveStreamingDetails')

        if live_details:
            actual_start = live_details.get('actualStartTime')
            actual_end = live_details.get('actualEndTime')
            scheduled_start = live_details.get('scheduledStartTime')

            published = actual_end or actual_start or scheduled_start
            if published:
                published_arrow = arrow.get(published).to('local')

        if not published_arrow:
            published_arrow = arrow.get(
                cached_snippet['publishedAt']).to('local')

        likes = int(cached_statistics.get('likeCount', '0'))
        dislikes = int(cached_statistics.get('dislikeCount', '0'))
        votes = likes + dislikes
        try:
            rating = '%0.1f' % ((likes / votes) * 10)
        except ZeroDivisionError:
            rating = '0.0'

        data = {
            'video_id': _video_id,
            'channel_id': channel_id,
            'title': video_title,
            'description': unescape(cached_snippet.get('description', '')),
            'channel_name': channel_name,
            'year': published_arrow.year,
            'premiered': published_arrow.format('YYYY-MM-DD'),
            'dateadded': published_arrow.format('YYYY-MM-DD HH:mm:ss'),
            'tag': cached_snippet.get('tags', ''),
            'rating': rating,
            'votes': votes,
            'like_count': likes,
            'dislike_count': dislikes,
            'view_count': int(cached_statistics.get('viewCount', 0)),
            'comment_count': int(cached_statistics.get('commentCount', 0)),
            'thumbnail': get_thumbnail(cached_snippet),
        }

        duration = iso8601_duration_to_seconds(
            cached_content_details.get('duration', ''))
        if duration:
            data['duration'] = duration

        return data

    playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    metadata = {}

    if playlist.size() <= 999:
        pages = 0
        next_item = None
        page_token = ''
        current_items = playlist_items(playlist.getPlayListId())

        while not next_item and pages <= 2:
            pages += 1

            next_item, page_token = _get_related(video_id, page_token,
                                                 current_items)
            if not next_item and page_token:
                continue

            if next_item:
                metadata = _metadata(next_item.get('id', {}).get('videoId'))

                generated = list(video_generator(context, [next_item]))
                path, list_item, _ = generated[0]
                playlist.add(path, list_item)
                break

            if not page_token:
                break

    return metadata
Esempio n. 17
0
def add_to_playlist(play_info, monitor):
    log.debug("Adding item to playlist : {0}", play_info)

    playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    server = download_utils.get_server()

    item_id = play_info.get("item_id")

    url = "{server}/Users/{userid}/Items/%s?format=json"
    url = url % (item_id, )
    data_manager = DataManager()
    item = data_manager.get_content(url)
    if item is None:
        log.debug("Playfile item was None, so can not play!")
        return

    # get playback info
    playback_info = download_utils.get_item_playback_info(item_id, False)
    if playback_info is None:
        log.debug(
            "playback_info was None, could not get MediaSources so can not play!"
        )
        return
    if playback_info.get("ErrorCode") is not None:
        error_string = playback_info.get("ErrorCode")
        xbmcgui.Dialog().notification(
            string_load(30316),
            error_string,
            icon="special://home/addons/plugin.video.jellycon/icon.png")
        return

    # play_session_id = id_generator()
    play_session_id = playback_info.get("PlaySessionId")

    # select the media source to use
    # sources = item.get("MediaSources")
    sources = playback_info.get('MediaSources')

    selected_media_source = sources[0]
    source_id = selected_media_source.get("Id")

    playurl, playback_type, listitem_props = PlayUtils().get_play_url(
        selected_media_source, play_session_id)
    log.info("Play URL: {0} PlaybackType: {1} ListItem Properties: {2}",
             playurl, playback_type, listitem_props)

    if playurl is None:
        return

    playback_type_string = "DirectPlay"
    if playback_type == "2":
        playback_type_string = "Transcode"
    elif playback_type == "1":
        playback_type_string = "DirectStream"

    # add the playback type into the overview
    if item.get("Overview", None) is not None:
        item["Overview"] = playback_type_string + "\n" + item.get("Overview")
    else:
        item["Overview"] = playback_type_string

    # add title decoration is needed
    item_title = item.get("Name", string_load(30280))
    list_item = xbmcgui.ListItem(label=item_title)

    # add playurl and data to the monitor
    data = {}
    data["item_id"] = item_id
    data["source_id"] = source_id
    data["playback_type"] = playback_type_string
    data["play_session_id"] = play_session_id
    data["play_action_type"] = "play_all"
    monitor.played_information[playurl] = data
    log.debug("Add to played_information: {0}", monitor.played_information)

    list_item.setPath(playurl)
    list_item = set_list_item_props(item_id, list_item, item, server,
                                    listitem_props, item_title)

    playlist.add(playurl, list_item)
Esempio n. 18
0
import time, xbmc
try:
    while True:
        time.sleep(1)
        if xbmc.Player().isPlayingVideo():
            pass
        else:
            break
    if xbmc.getCondVisibility('Skin.HasSetting(Use_Startup_Playback)'):
        time.sleep(0.5)
        xbmc.executebuiltin(
            'PlayMedia(' +
            xbmc.getInfoLabel('Skin.String(Startup_Playback_Path)') + ')')
        xbmc.PlayList(0).shuffle()
        xbmc.executebuiltin('playercontrol(RepeatAll)')
except:
    pass
Esempio n. 19
0
def play_all_files(items, monitor, play_items=True):
    log.debug("playAllFiles called with items: {0}", items)
    server = download_utils.get_server()

    playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    playlist.clear()

    for item in items:

        item_id = item.get("Id")

        # get playback info
        playback_info = download_utils.get_item_playback_info(item_id, False)
        if playback_info is None:
            log.debug(
                "playback_info was None, could not get MediaSources so can not play!"
            )
            return
        if playback_info.get("ErrorCode") is not None:
            error_string = playback_info.get("ErrorCode")
            xbmcgui.Dialog().notification(
                string_load(30316),
                error_string,
                icon="special://home/addons/plugin.video.jellycon/icon.png")
            return

        play_session_id = playback_info.get("PlaySessionId")

        # select the media source to use
        sources = playback_info.get('MediaSources')

        selected_media_source = sources[0]
        source_id = selected_media_source.get("Id")

        playurl, playback_type, listitem_props = PlayUtils().get_play_url(
            selected_media_source, play_session_id)
        log.info("Play URL: {0} PlaybackType: {1} ListItem Properties: {2}",
                 playurl, playback_type, listitem_props)

        if playurl is None:
            return

        playback_type_string = "DirectPlay"
        if playback_type == "2":
            playback_type_string = "Transcode"
        elif playback_type == "1":
            playback_type_string = "DirectStream"

        # add the playback type into the overview
        if item.get("Overview", None) is not None:
            item["Overview"] = playback_type_string + "\n" + item.get(
                "Overview")
        else:
            item["Overview"] = playback_type_string

        # add title decoration is needed
        item_title = item.get("Name", string_load(30280))
        list_item = xbmcgui.ListItem(label=item_title)

        # add playurl and data to the monitor
        data = {}
        data["item_id"] = item_id
        data["source_id"] = source_id
        data["playback_type"] = playback_type_string
        data["play_session_id"] = play_session_id
        data["play_action_type"] = "play_all"
        monitor.played_information[playurl] = data
        log.debug("Add to played_information: {0}", monitor.played_information)

        list_item.setPath(playurl)
        list_item = set_list_item_props(item_id, list_item, item, server,
                                        listitem_props, item_title)

        playlist.add(playurl, list_item)

    if play_items:
        xbmc.Player().play(playlist)
        return None
    else:
        return playlist
Esempio n. 20
0
 def PlayVideo(self, url, resume=False):
     print "PLAYVIDEO"
     #check if intro needed
     isIntro = False
     if not resume and self.intro and self.introtime:
         isIntro = True
     #chargement des infos
     icone = ''
     try:
         icone = self.infos['Thumb']
     except:
         icone = ''
     listitem = xbmcgui.ListItem(self.infos['Title'],
                                 iconImage="DefaultVideo.png",
                                 thumbnailImage=icone)
     listitem.setInfo(type='video', infoLabels=self.infos)
     #chargement de la playlist
     playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
     playlist.clear()
     if isIntro:
         playlist.add(self.intro)
     playlist.add(url, listitem=listitem)
     #lecture de la video
     xbmc.Player().play(playlist)
     #Tant que le film est en lecture
     notplaying = True
     while notplaying:
         if xbmc.Player().isPlaying():
             notplaying = False
         time.sleep(0.1)
     if isIntro:
         time.sleep(int(self.introtime))
     if resume:
         xbmc.Player().seekTime(self.videotimewatched)
     notnotif = False
     if self.mode == 'local':
         notnotif = True
     if xbmc.Player().isPlaying():
         self.videototaltime = xbmc.Player().getTotalTime()
         while xbmc.Player().isPlaying():
             self.videotimewatched = xbmc.Player().getTime(
             )  #recup la durée  visionnée
             if self.videototaltime == 0:
                 self.videototaltime = xbmc.Player().getTotalTime(
                 )  #recup la durée totale de la video (répond 0.0 si on le met plus tôt)
             if notnotif and self.mode == 'local':
                 try:
                     download_info = self.downloader.getInfos()
                     if download_info['status'] == FINISHED:
                         xbmc.executebuiltin(
                             'XBMC.Notification("StreamLauncher","Téléchargement terminé",10000,'
                             + __OkLogo__ + ')')
                         notnotif = False
                 except:
                     pass
             time.sleep(0.5)
     #La lecture du film est stoppée
     print 'Player stopped'
     #si on est en mode local, on gère la suite :
     if self.mode == 'local':
         download_info = self.downloader.getInfos()
         for item in download_info.items():
             print str(item[0]) + ' : ' + str(item[1])
         #Si le film est complet
         if download_info['status'] == FINISHED:
             if not self.KeepDownloadedFile:
                 if not xbmcgui.Dialog().yesno(
                         "StreamLauncher",
                         "Fichier complet : \"" + self.infos['Title'] +
                         "\"\nSouhaitez-vous le conserver ?"):
                     shutil.rmtree(self.videolocalfolder)
         #Sinon si le film est incomplet, on demande quoi faire
         elif download_info['status'] == DOWNLOADING:
             #Si relance de la lecture
             if xbmcgui.Dialog().yesno(
                     "StreamLauncher", "Fichier incomplet : \"" +
                     self.infos['Title'] + "\"\nRelancer la lecture ?"):
                 self.PlayVideo(url, resume=True)
             #Sinon on demande si on continue le téléchargement
             else:
                 #Si on ne continue pas
                 if not xbmcgui.Dialog().yesno(
                         "StreamLauncher",
                         "Fichier incomplet : \"" + self.infos['Title'] +
                         "\"\nSouhaitez-vous poursuivre le téléchargement ?"
                 ):
                     self.downloader.stop()
                     notremove = True
                     while notremove:
                         try:
                             shutil.rmtree(self.videolocalfolder)
                             notremove = False
                         except:
                             pass
                             time.sleep(0.1)
                 #Sinon si on continue le téléchargement jusqu'à la fin ou l'annulation
                 else:
                     caching1 = True
                     progress1 = xbmcgui.DialogProgress()
                     progress1.create(
                         'Téléchargement',
                         'Si vous annulez, le fichier en cache sera supprimé'
                     )
                     while caching1:
                         download_info = self.downloader.getInfos()
                         if download_info['status'] == DOWNLOADING:
                             progress1.update(
                                 int(download_info['downloaded']) * 100 /
                                 int(download_info['size']),
                                 'Téléchargement en cours...\nSi vous annulez, le fichier en cache sera supprimé'
                             )
                             time.sleep(0.5)
                         elif download_info['status'] == FINISHED:
                             caching1 = False
                             progress1.close()
                             xbmcgui.Dialog().ok('StreamLauncher',
                                                 'Téléchargement terminé')
                             time.sleep(0.1)
                         if progress1.iscanceled():
                             caching1 = False
                             progress1.close()
                             self.downloader.stop()
                             notremove = True
                             while notremove:
                                 try:
                                     shutil.rmtree(self.videolocalfolder)
                                     notremove = False
                                 except:
                                     pass
                             time.sleep(0.1)
         #Sinon si le téléchargement est en erreur
         else:
             xbmcgui.Dialog().ok(
                 'StreamLauncher',
                 'Erreur pendant le téléchargement\nLe Fichier en cache sera supprimé'
             )
             try:
                 self.downloader.stop()
             except:
                 pass
             notremove = True
             while notremove:
                 try:
                     shutil.rmtree(self.videolocalfolder)
                     notremove = False
                 except:
                     pass
Esempio n. 21
0
    def playbackStarted(self, data):
        logger.debug("playbackStarted(data: %s)" % data)
        if not data:
            return
        self.curVideo = data
        self.curVideoInfo = None

        if 'type' in self.curVideo:
            logger.debug("Watching: %s" % self.curVideo['type'])
            if not xbmc.Player().isPlayingVideo():
                logger.debug("Suddenly stopped watching item")
                return
            xbmc.sleep(
                1000)  # Wait for possible silent seek (caused by resuming)
            try:
                self.watchedTime = xbmc.Player().getTime()
                self.videoDuration = xbmc.Player().getTotalTime()
            except Exception as e:
                logger.debug("Suddenly stopped watching item: %s" % e.message)
                self.curVideo = None
                return

            if self.videoDuration == 0:
                if utilities.isMovie(self.curVideo['type']):
                    self.videoDuration = 90
                elif utilities.isEpisode(self.curVideo['type']):
                    self.videoDuration = 30
                else:
                    self.videoDuration = 1

            self.playlistLength = len(xbmc.PlayList(xbmc.PLAYLIST_VIDEO))
            self.playlistIndex = xbmc.PlayList(
                xbmc.PLAYLIST_VIDEO).getposition()
            if self.playlistLength == 0:
                logger.debug(
                    "Warning: Cant find playlist length, assuming that this item is by itself"
                )
                self.playlistLength = 1

            self.isMultiPartEpisode = False
            if utilities.isMovie(self.curVideo['type']):
                if 'id' in self.curVideo:
                    self.curVideoInfo = utilities.kodiRpcToTraktMediaObject(
                        'movie',
                        utilities.getMovieDetailsFromKodi(
                            self.curVideo['id'], [
                                'imdbnumber', 'title', 'year', 'file',
                                'lastplayed', 'playcount'
                            ]))
                elif 'title' in self.curVideo and 'year' in self.curVideo:
                    self.curVideoInfo = {
                        'title': self.curVideo['title'],
                        'year': self.curVideo['year']
                    }

            elif utilities.isEpisode(self.curVideo['type']):
                if 'id' in self.curVideo:
                    episodeDetailsKodi = utilities.getEpisodeDetailsFromKodi(
                        self.curVideo['id'], [
                            'showtitle', 'season', 'episode', 'tvshowid',
                            'uniqueid', 'file', 'playcount'
                        ])
                    tvdb = episodeDetailsKodi['imdbnumber']
                    title, year = utilities.regex_year(
                        episodeDetailsKodi['showtitle'])
                    if not year:
                        self.traktShowSummary = {
                            'title': episodeDetailsKodi['showtitle'],
                            'year': episodeDetailsKodi['year']
                        }
                    else:
                        self.traktShowSummary = {'title': title, 'year': year}
                    if tvdb:
                        self.traktShowSummary['ids'] = {'tvdb': tvdb}
                    self.curVideoInfo = utilities.kodiRpcToTraktMediaObject(
                        'episode', episodeDetailsKodi)
                    if not self.curVideoInfo:  # getEpisodeDetailsFromKodi was empty
                        logger.debug(
                            "Episode details from Kodi was empty, ID (%d) seems invalid, aborting further scrobbling of this episode."
                            % self.curVideo['id'])
                        self.curVideo = None
                        self.isPlaying = False
                        self.watchedTime = 0
                        return
                elif 'title' in self.curVideo and 'season' in self.curVideo and 'episode' in self.curVideo:
                    self.curVideoInfo = {
                        'title': self.curVideo['title'],
                        'season': self.curVideo['season'],
                        'number': self.curVideo['episode']
                    }

                    title, year = utilities.regex_year(
                        self.curVideo['showtitle'])
                    if not year:
                        self.traktShowSummary = {
                            'title': self.curVideo['showtitle']
                        }
                    else:
                        self.traktShowSummary = {'title': title, 'year': year}

                    if 'year' in self.curVideo:
                        self.traktShowSummary['year'] = self.curVideo['year']

                if 'multi_episode_count' in self.curVideo:
                    self.isMultiPartEpisode = True

            self.isPlaying = True
            self.isPaused = False
            result = self.__scrobble('start')
            if result:
                if utilities.isMovie(
                        self.curVideo['type']) and utilities.getSettingAsBool(
                            'rate_movie'):
                    # pre-get sumamry information, for faster rating dialog.
                    logger.debug(
                        "Movie rating is enabled, pre-fetching summary information."
                    )
                    if result['movie']['ids']['imdb']:
                        self.curVideoInfo['user'] = {
                            'ratings':
                            self.traktapi.getMovieRatingForUser(
                                result['movie']['ids']['imdb'])
                        }
                        self.curVideoInfo['ids'] = result['movie']['ids']
                    else:
                        logger.debug(
                            "'%s (%d)' has no valid id, can't get rating." %
                            (self.curVideoInfo['title'],
                             self.curVideoInfo['year']))
                elif utilities.isEpisode(
                        self.curVideo['type']) and utilities.getSettingAsBool(
                            'rate_episode'):
                    # pre-get sumamry information, for faster rating dialog.
                    logger.debug(
                        "Episode rating is enabled, pre-fetching summary information."
                    )

                    if result['show']['ids']['tvdb']:
                        self.curVideoInfo['user'] = {
                            'ratings':
                            self.traktapi.getEpisodeRatingForUser(
                                result['show']['ids']['tvdb'],
                                self.curVideoInfo['season'],
                                self.curVideoInfo['number'])
                        }
                        self.curVideoInfo['ids'] = result['episode']['ids']
                    else:
                        logger.debug(
                            "'%s - S%02dE%02d' has no valid id, can't get rating."
                            % (self.curVideoInfo['showtitle'],
                               self.curVideoInfo['season'],
                               self.curVideoInfo['episode']))
Esempio n. 22
0
def play_video(item, itemSeleccion=-1):
    mediaurl = itemSeleccion.url[1]
    if len(itemSeleccion.url) > 2:
        wait_time = itemSeleccion.url[2]
    else:
        wait_time = 0

    if wait_time > 0:
        handle_wait(wait_time, server, "Cargando vídeo...")
    if item.fulltitle: item.title = item.fulltitle
    xlistitem = xbmcgui.ListItem(item.title,
                                 iconImage="DefaultVideo.png",
                                 thumbnailImage=item.thumbnail,
                                 path=mediaurl)
    xlistitem.setInfo(
        "video", {
            "Title": item.title,
            "Plot": item.plot,
            "Studio": item.channel,
            "Genre": item.category
        })

    if item.subtitle != "":
        import os
        ficherosubtitulo = os.path.join(config.get_data_path(),
                                        'subtitulo.srt')
        if os.path.exists(ficherosubtitulo):
            os.remove(ficherosubtitulo)

        from core import scrapertools
        data = scrapertools.cache_page(item.subtitle)
        fichero = open(ficherosubtitulo, "w")
        fichero.write(data)
        fichero.close()

    if item.channel == "library":  #Si es un fichero strm no hace falta el play
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xlistitem)

    else:
        if config.get_setting("player_mode") == "3":  #download_and_play
            import download_and_play
            download_and_play.download_and_play(
                mediaurl, "download_and_play.tmp",
                config.get_setting("downloadpath"))

        elif config.get_setting("player_mode") == "0" or (
                config.get_setting("player_mode") == "3"
                and mediaurl.startswith("rtmp")):  #Direct

            playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
            playlist.clear()
            playlist.add(mediaurl, xlistitem)
            playersettings = config.get_setting('player_type')
            player_type = xbmc.PLAYER_CORE_AUTO
            if playersettings == "0":
                player_type = xbmc.PLAYER_CORE_AUTO
                logger.info("[xbmctools.py] PLAYER_CORE_AUTO")
            elif playersettings == "1":
                player_type = xbmc.PLAYER_CORE_MPLAYER
                logger.info("[xbmctools.py] PLAYER_CORE_MPLAYER")
            elif playersettings == "2":
                player_type = xbmc.PLAYER_CORE_DVDPLAYER
                logger.info("[xbmctools.py] PLAYER_CORE_DVDPLAYER")
            xbmcPlayer = xbmc.Player(player_type)
            xbmcPlayer.play(playlist)

        elif config.get_setting("player_mode") == "1":  #setResolvedUrl
            xbmcplugin.setResolvedUrl(int(sys.argv[1]), True,
                                      xbmcgui.ListItem(path=mediaurl))

        elif config.get_setting("player_mode") == "2":  #Built-in
            xbmc.executebuiltin("PlayMedia(" + mediaurl + ")")
Esempio n. 23
0
def play(item):
    import xbmc
    import xbmcgui

    logger.info("[turbonick.py] play")

    # Abre dialogo
    dialogWait = xbmcgui.DialogProgress()
    dialogWait.create('Descargando datos del vídeo...', item.title)

    # --------------------------------------------------------
    # Descarga pagina detalle
    # --------------------------------------------------------
    data = scrapertools.cachePage(item.url)
    patron = '<src>([^<]+)</src>'
    matches = re.compile(patron, re.DOTALL).findall(data)
    scrapertools.printMatches(matches)
    url = matches[0]
    #rtmp://cp35019.edgefcs.net/ondemand/mtviestor/_!/intlnick/es/AVATAR/AVATAR1A_OD_640.flv
    #DEBUG: Protocol : RTMP
    #DEBUG: Hostname : cp35019.edgefcs.net
    #DEBUG: Port     : 1935
    #DEBUG: Playpath : mtviestor/_!/intlnick/es/AVATAR/AVATAR1A_OD_640
    #DEBUG: tcUrl    : rtmp://cp35019.edgefcs.net:1935/ondemand
    #DEBUG: app      : ondemand
    #DEBUG: flashVer : LNX 9,0,124,0
    #DEBUG: live     : no
    #DEBUG: timeout  : 300 sec
    cabecera = url[:35]
    logger.info("cabecera=" + cabecera)
    finplaypath = url.rfind(".")
    playpath = url[35:finplaypath]
    logger.info("playpath=" + playpath)

    logger.info("url=" + url)

    # Playlist vacia
    playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    playlist.clear()

    # Crea la entrada y la añade al playlist
    url = cabecera
    listitem = xbmcgui.ListItem(item.title,
                                iconImage="DefaultVideo.png",
                                thumbnailImage=item.thumbnail)
    listitem.setProperty(
        "SWFPlayer",
        "http://es.turbonick.nick.com/global/apps/broadband/swf/bb_flv_player.swf"
    )
    #listitem.setProperty("Playpath","14314/plus/plustv/PO778395")
    listitem.setProperty("Playpath", playpath)
    listitem.setProperty("Hostname", "cp35019.edgefcs.net")
    listitem.setProperty("Port", "1935")
    #listitem.setProperty("tcUrl","rtmp://od.flash.plus.es/ondemand")
    listitem.setProperty("tcUrl", cabecera)
    listitem.setProperty("app", "ondemand")
    listitem.setProperty("flashVer", "LNX 9,0,124,0")
    #listitem.setProperty("pageUrl","LNX 9,0,124,0")

    listitem.setInfo(
        "video", {
            "Title": item.title,
            "Plot": item.plot,
            "Studio": CHANNELNAME,
            "Genre": item.category
        })
    playlist.add(url, listitem)

    # Cierra dialogo
    dialogWait.close()
    del dialogWait

    # Reproduce
    xbmcPlayer = xbmc.Player(xbmc.PLAYER_CORE_AUTO)
    xbmcPlayer.play(playlist)

    return []
Esempio n. 24
0
 def run(self, url=None):
     params = dict(parse_qsl(sys.argv[2].replace('?', '')))
     rootname = params.get('rootname', '')
     url = url if url else params.get("url") if 'url' in params else None
     url = unquote(url)
     if not url: return
     try:
         if rootname in ('video', 'music'):
             p_list = xbmc.PLAYLIST_VIDEO if rootname == 'video' else xbmc.PLAYLIST_MUSIC
             playlist = xbmc.PlayList(p_list)
             playlist.clear()
             listitem = xbmcgui.ListItem()
             listitem.setInfo(type=rootname, infoLabels={})
             playlist.add(url, listitem)
             return self.play(playlist)
         self.meta = json.loads(window.getProperty('fen_media_meta'))
         rootname = self.meta['rootname'] if 'rootname' in self.meta else ''
         bookmark = self.bookmarkChoice()
         if bookmark == -1: return
         self.meta.update({'url': url, 'bookmark': bookmark})
         listitem = xbmcgui.ListItem(path=url)
         try:
             if self.meta.get('use_animated_poster', False):
                 poster = self.meta.get('gif_poster')
             else:
                 poster = self.meta.get('poster')
             listitem.setProperty('StartPercent',
                                  str(self.meta.get('bookmark')))
             listitem.setArt({
                 'poster': poster,
                 'fanart': self.meta.get('fanart'),
                 'banner': self.meta.get('banner'),
                 'clearart': self.meta.get('clearart'),
                 'clearlogo': self.meta.get('clearlogo'),
                 'landscape': self.meta.get('landscape'),
                 'discart': self.meta.get('discart')
             })
             listitem.setCast(self.meta['cast'])
             if self.meta['vid_type'] == 'movie':
                 listitem.setUniqueIDs({
                     'imdb': str(self.meta['imdb_id']),
                     'tmdb': str(self.meta['tmdb_id'])
                 })
                 listitem.setInfo(
                     'video', {
                         'mediatype': 'movie',
                         'trailer': str(self.meta['trailer']),
                         'title': self.meta['title'],
                         'size': '0',
                         'duration': self.meta['duration'],
                         'plot': self.meta['plot'],
                         'rating': self.meta['rating'],
                         'premiered': self.meta['premiered'],
                         'studio': self.meta['studio'],
                         'year': self.meta['year'],
                         'genre': self.meta['genre'],
                         'tagline': self.meta['tagline'],
                         'code': self.meta['imdb_id'],
                         'imdbnumber': self.meta['imdb_id'],
                         'director': self.meta['director'],
                         'writer': self.meta['writer'],
                         'votes': self.meta['votes']
                     })
             elif self.meta['vid_type'] == 'episode':
                 listitem.setUniqueIDs({
                     'imdb': str(self.meta['imdb_id']),
                     'tmdb': str(self.meta['tmdb_id']),
                     'tvdb': str(self.meta['tvdb_id'])
                 })
                 listitem.setInfo(
                     'video', {
                         'mediatype': 'episode',
                         'trailer': str(self.meta['trailer']),
                         'title': self.meta['ep_name'],
                         'imdbnumber': self.meta['imdb_id'],
                         'tvshowtitle': self.meta['title'],
                         'size': '0',
                         'plot': self.meta['plot'],
                         'year': self.meta['year'],
                         'votes': self.meta['votes'],
                         'premiered': self.meta['premiered'],
                         'studio': self.meta['studio'],
                         'genre': self.meta['genre'],
                         'season': int(self.meta['season']),
                         'episode': int(self.meta['episode']),
                         'duration': str(self.meta['duration']),
                         'rating': self.meta['rating']
                     })
         except Exception as e:
             from modules.utils import logger
             logger('exception in meta set code', e)
             pass
         library_item = True if 'from_library' in self.meta else False
         if library_item:
             xbmcplugin.setResolvedUrl(__handle__, True, listitem)
         else:
             self.play(url, listitem)
         self.monitor()
     except Exception as e:
         from modules.utils import logger
         logger('exception in main code', e)
         return
Esempio n. 25
0
def direct_play(url,title=""):
    _log("direct_play ["+url+"]")
    try: xlistitem=xbmcgui.ListItem(title,iconImage="DefaultVideo.png",path=url)
    except: xlistitem=xbmcgui.ListItem(title,iconImage="DefaultVideo.png",)
    xlistitem.setInfo("video",{"Title":title}); playlist=xbmc.PlayList(xbmc.PLAYLIST_VIDEO); playlist.clear(); playlist.add(url,xlistitem); player_type=xbmc.PLAYER_CORE_AUTO; xbmcPlayer=xbmc.Player(player_type); xbmcPlayer.play(playlist)
Esempio n. 26
0
 def item_random_play(self):
     playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
     playlist.clear()
     xbmc.executebuiltin('Action(Queue)')
     playlist.shuffle()
     xbmc.Player().play(playlist)
Esempio n. 27
0
            dp.close()
            dp_cerrado = True
            if not bkg_user:
                is_view = "Ok"
            else:
                remove_files(download, torrent_file, video_file, ses, h,
                             ren_video_file)
                return

        if is_view == "Ok":
            # -- Esperando a que termine otra reproducción --------------------------
            while xbmc.Player().isPlaying():
                xbmc.sleep(3000)

            # -- Player - Ver el vídeo --------------------------
            playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
            playlist.clear()

            ren_video_file = os.path.join(save_path_videos, video_file)
            try:
                playlist.add(ren_video_file, xlistitem)
            except:
                playlist.add(ren_video_file)

            if xbmc_version < 17:
                player = play_video(xbmc.PLAYER_CORE_AUTO)
            else:
                player = play_video()
            player.play(playlist)

            # -- Contador de cancelaciones para la ventana de   -
Esempio n. 28
0
def queueVideo(url, name, thumb):
    playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    listitem = xbmcgui.ListItem(name, iconImage=thumb, thumbnailImage=thumb)
    playlist.add(url, listitem)
Esempio n. 29
0
 def onPlayBackEnded(self):
     pl = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
     if pl.getposition() < 0:
         xbmc.executebuiltin('SetFocus(212)')
Esempio n. 30
0
def play(params):
    playmode = params['playmode']

    try:
        url1 = urllib.unquote_plus(params['url'])
    except:
        pass

    playList = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
    playList.clear()

    if playmode == '2':  #wma затем mp3
        asx = Get_url(url['playasxstation'] % (params['id']))
        lst = ParseAsx(asx)
        for uri in lst:
            playList.add(uri, NewListItem())

        js = Get_url(url['playstation'] % (params['id']), JSON=True)
        if (js and len(js['playlist']) > 1):
            entry = js['playlist'][0]
            if playList.size() > 1:
                playList.add(entry['url'], NewListItem(), 1)
            else:
                playList.add(entry['url'], NewListItem())
            entry = js['playlist'][1]
            if playList.size() > 3:
                playList.add(entry['url'], NewListItem(), 3)
            else:
                playList.add(entry['url'], NewListItem())
    elif playmode == '3':  #mp3 затем wma
        js = Get_url(url['playstation'] % (params['id']), JSON=True)
        if js:
            for i in js['playlist']:
                playList.add(i['url'], NewListItem())
        asx = Get_url(url['playasxstation'] % (params['id']))
        lst = ParseAsx(asx)
        if len(lst) > 1:
            hc = HeadAsx_url(lst[0].replace('mms', 'http'))
            #xbmc.log('hc=%d'%hc, xbmc.LOGDEBUG);
            if hc == 200:
                if playList.size() > 1:
                    playList.add(lst[0], NewListItem(), 1)
                else:
                    playList.add(lst[0], NewListItem())
                if playList.size() > 3:
                    playList.add(lst[1], NewListItem(), 3)
                else:
                    playList.add(lst[1], NewListItem())
    elif playmode == '1':  #только wma
        asx = Get_url(url['playasxstation'] % (params['id']))
        #xbmc.log(asx, xbmc.LOGDEBUG);
        lst = ParseAsx(asx)
        for uri in lst:
            playList.add(uri, NewListItem())
    elif playmode == '0':  #только mp3
        js = Get_url(url['playstation'] % (params['id']), JSON=True)
        if js:
            for i in js['playlist']:
                playList.add(i['url'], NewListItem())
    elif playmode == 'track':
        playList.add(url1, NewListItem())
    elif playmode == 'rtmp':

        header1 = '|Referer=' + urllib.quote_plus('www.101.ru')
        header2 = '&Range=' + urllib.quote_plus('')

        Url_ = 'rtmp://wz7.101.ru/pradio22/' + params[
            'id'] + '///main' + header1 + header2
        playpath = 'main'
        swfUrl = "http://101.ru/static/js/uppod/uppod.swf"

        item = NewListItem()
        item.setProperty('PlayPath', playpath)
        item.setProperty('swfUrl', swfUrl)
        item.setProperty('mimetype', 'video/flv')

        playList.add(Url_, item)

    if playList.size() > 0:
        xbmc.Player().play(playList)