Beispiel #1
0
class Radioob(ReplApplication):
    APPNAME = 'radioob'
    VERSION = '0.e'
    COPYRIGHT = 'Copyright(C) 2010-2012 Romain Bignon'
    DESCRIPTION = 'Console application allowing to search for web radio stations, listen to them and get information ' \
                  'like the current song.'
    CAPS = ICapRadio
    EXTRA_FORMATTERS = {'radio_list': RadioListFormatter}
    COMMANDS_FORMATTERS = {'ls':     'radio_list',
                           'search': 'radio_list',
                          }
    COLLECTION_OBJECTS = (Radio, )

    def __init__(self, *args, **kwargs):
        ReplApplication.__init__(self, *args, **kwargs)
        self.player = MediaPlayer(self.logger)

    def main(self, argv):
        self.load_config()
        return ReplApplication.main(self, argv)

    def complete_play(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_object()

    def do_play(self, _id):
        """
        play ID

        Play a radio with a found player.
        """
        if not _id:
            print >>sys.stderr, 'This command takes an argument: %s' % self.get_command_help('play', short=True)
            return 2

        radio = self.get_object(_id, 'get_radio', ['streams'])
        if not radio:
            print >>sys.stderr, 'Radio not found:', _id
            return 1
        try:
            player_name = self.config.get('media_player')
            if not player_name:
                self.logger.debug(u'You can set the media_player key to the player you prefer in the radioob '
                                  'configuration file.')
            self.player.play(radio.streams[0], player_name=player_name)
        except (InvalidMediaPlayer, MediaPlayerNotFound), e:
            print '%s\nRadio URL: %s' % (e, radio.streams[0].url)
Beispiel #2
0
def video_info(url):
    """Fetch info about a video using youtube-dl

    :param url: URL of the web page containing the video
    :rtype: :class:`weboob.capabilities.video.Video`
    """

    if not MediaPlayer._find_in_path(os.environ['PATH'], 'youtube-dl'):
        raise Exception('Please install youtube-dl')

    try:
        j = json.loads(subprocess.check_output(['youtube-dl', '-f', 'best', '-J', url]))
    except subprocess.CalledProcessError:
        return

    v = BaseVideo(id=url)
    v.title = j.get('title') or NotAvailable
    v.ext = j.get('ext') or NotAvailable
    v.description = j.get('description') or NotAvailable
    v.url = j['url']
    v.duration = j.get('duration') or NotAvailable
    v.author = j.get('uploader') or NotAvailable
    v.rating = j.get('average_rating') or NotAvailable

    if j.get('thumbnail'):
        v.thumbnail = Thumbnail(j['thumbnail'])

    d = j.get('upload_date', j.get('release_date'))
    if d:
        v.date = parse_date(d)

    return v
Beispiel #3
0
def video_info(url):
    """Fetch info about a video using youtube-dl

    :param url: URL of the web page containing the video
    :rtype: :class:`weboob.capabilities.video.Video`
    """

    if not MediaPlayer._find_in_path(os.environ['PATH'], 'youtube-dl'):
        raise Exception('Please install youtube-dl')

    try:
        j = json.loads(
            subprocess.check_output(['youtube-dl', '-f', 'best', '-J', url]))
    except subprocess.CalledProcessError:
        return

    v = BaseVideo(id=url)
    v.title = j.get('title') or NotAvailable
    v.ext = j.get('ext') or NotAvailable
    v.description = j.get('description') or NotAvailable
    v.url = j['url']
    v.duration = j.get('duration') or NotAvailable
    v.author = j.get('uploader') or NotAvailable
    v.rating = j.get('average_rating') or NotAvailable

    if j.get('thumbnail'):
        v.thumbnail = Thumbnail(j['thumbnail'])

    d = j.get('upload_date', j.get('release_date'))
    if d:
        v.date = parse_date(d)

    return v
Beispiel #4
0
 def __init__(self, *args, **kwargs):
     ReplApplication.__init__(self, *args, **kwargs)
     self.player = MediaPlayer(self.logger)
Beispiel #5
0
class Radioob(ReplApplication):
    APPNAME = 'radioob'
    VERSION = '1.1'
    COPYRIGHT = 'Copyright(C) 2010-YEAR Romain Bignon\nCopyright(C) YEAR Pierre Maziere'
    DESCRIPTION = "Console application allowing to search for web radio stations, listen to them and get information " \
                  "like the current song."
    SHORT_DESCRIPTION = "search, show or listen to radio stations"
    CAPS = (CapRadio, CapAudio)
    EXTRA_FORMATTERS = {'radio_list': RadioListFormatter,
                        'song_list': SongListFormatter,
                        'album_tracks_list_info': AlbumTrackListInfoFormatter,
                        'playlist_tracks_list_info': PlaylistTrackListInfoFormatter,
                        }

    COMMANDS_FORMATTERS = {'ls': 'radio_list',
                           'playlist': 'radio_list',
                           }

    COLLECTION_OBJECTS = (Radio, BaseAudio, )
    PLAYLIST = []

    def __init__(self, *args, **kwargs):
        ReplApplication.__init__(self, *args, **kwargs)
        self.player = MediaPlayer(self.logger)

    def main(self, argv):
        self.load_config()
        return ReplApplication.main(self, argv)

    def complete_download(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_object()
        elif len(args) >= 3:
            return self.path_completer(args[2])

    def do_download(self, line):
        """
        download ID [FILENAME]

        Download an audio file
        """
        _id, dest = self.parse_command_args(line, 2, 1)
        audio = self.get_object(_id, 'get_audio', ['url'])
        if not audio:
            print('Audio file not found: %s' % _id, file=self.stderr)
            return 3

        if not audio.url:
            print('Error: the direct URL is not available.', file=self.stderr)
            return 4

        def check_exec(executable):
            with open('/dev/null', 'w') as devnull:
                process = subprocess.Popen(['which', executable], stdout=devnull)
                if process.wait() != 0:
                    print('Please install "%s"' % executable, file=self.stderr)
                    return False
            return True

        def audio_to_file(_audio):
            ext = _audio.ext
            if not ext:
                ext = 'audiofile'
            return '%s.%s' % (re.sub('[?:/]', '-', _audio.id), ext)

        if dest is not None and os.path.isdir(dest):
            dest += '/%s' % audio_to_file(audio)

        if dest is None:
            dest = audio_to_file(audio)

        if audio.url.startswith('rtmp'):
            if not check_exec('rtmpdump'):
                return 1
            args = ('rtmpdump', '-e', '-r', audio.url, '-o', dest)
        elif audio.url.startswith('mms'):
            if not check_exec('mimms'):
                return 1
            args = ('mimms', '-r', audio.url, dest)
        else:
            if check_exec('wget'):
                args = ('wget', '-c', audio.url, '-O', dest)
            elif check_exec('curl'):
                args = ('curl', '-C', '-', audio.url, '-o', dest)
            else:
                return 1

        os.spawnlp(os.P_WAIT, args[0], *args)

    def complete_play(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_object()

    def do_play(self, line):
        """
        play ID [stream_id]

        Play a radio or a audio file with a found player (optionnaly specify the wanted stream).
        """
        _id, stream_id = self.parse_command_args(line, 2, 1)
        if not _id:
            print('This command takes an argument: %s' % self.get_command_help('play', short=True), file=self.stderr)
            return 2

        try:
            stream_id = int(stream_id)
        except (ValueError, TypeError):
            stream_id = 0

        obj = self.retrieve_obj(_id)

        if obj is None:
            print('No object matches with this id:', _id, file=self.stderr)
            return 3

        if isinstance(obj, Radio):
            try:
                streams = [obj.streams[stream_id]]
            except IndexError:
                print('Stream %d not found' % stream_id, file=self.stderr)
                return 1
        elif isinstance(obj, BaseAudio):
            streams = [obj]

        else:
            streams = obj.tracks_list

        if len(streams) == 0:
            print('Radio or Audio file not found:', _id, file=self.stderr)
            return 3

        try:
            player_name = self.config.get('media_player')
            media_player_args = self.config.get('media_player_args')
            if not player_name:
                self.logger.debug(u'You can set the media_player key to the player you prefer in the radioob '
                                  'configuration file.')

            for stream in streams:
                if isinstance(stream, BaseAudio) and not stream.url:
                    stream = self.get_object(stream.id, 'get_audio')
                else:
                    r = requests.get(stream.url, stream=True)
                    buf = r.iter_content(512).next()
                    r.close()
                    playlistFormat = None
                    for line in buf.split("\n"):
                        if playlistFormat is None:
                            if line == "[playlist]":
                                playlistFormat = "pls"
                            elif line == "#EXTM3U":
                                playlistFormat = "m3u"
                            else:
                                break
                        elif playlistFormat == "pls":
                            if line.startswith('File'):
                                stream.url = line.split('=', 1).pop(1).strip()
                                break
                        elif playlistFormat == "m3u":
                            if line[0] != "#":
                                stream.url = line.strip()
                                break

                self.player.play(stream, player_name=player_name, player_args=media_player_args)

        except (InvalidMediaPlayer, MediaPlayerNotFound) as e:
            print('%s\nRadio URL: %s' % (e, stream.url))

    def retrieve_obj(self, _id):
        obj = None
        if self.interactive:
            try:
                obj = self.objects[int(_id) - 1]
                _id = obj.id
            except (IndexError, ValueError):
                pass

        m = CapAudio.get_object_method(_id)
        if m:
            obj = self.get_object(_id, m)

        return obj if obj is not None else self.get_object(_id, 'get_radio')

    def do_playlist(self, line):
        """
        playlist cmd [args]
        playlist add ID [ID2 ID3 ...]
        playlist remove ID [ID2 ID3 ...]
        playlist export [FILENAME]
        playlist display
        """

        if not line:
            print('This command takes an argument: %s' % self.get_command_help('playlist'), file=self.stderr)
            return 2

        cmd, args = self.parse_command_args(line, 2, req_n=1)
        if cmd == "add":
            _ids = args.strip().split(' ')
            for _id in _ids:
                audio = self.get_object(_id, 'get_audio')

                if not audio:
                    print('Audio file not found: %s' % _id, file=self.stderr)
                    return 3

                if not audio.url:
                    print('Error: the direct URL is not available.', file=self.stderr)
                    return 4

                self.PLAYLIST.append(audio)

        elif cmd == "remove":
            _ids = args.strip().split(' ')
            for _id in _ids:

                audio_to_remove = self.get_object(_id, 'get_audio')

                if not audio_to_remove:
                    print('Audio file not found: %s' % _id, file=self.stderr)
                    return 3

                if not audio_to_remove.url:
                    print('Error: the direct URL is not available.', file=self.stderr)
                    return 4

                for audio in self.PLAYLIST:
                    if audio.id == audio_to_remove.id:
                        self.PLAYLIST.remove(audio)
                        break

        elif cmd == "export":
            filename = "playlist.m3u"
            if args:
                filename = args

            file = open(filename, 'w')
            for audio in self.PLAYLIST:
                file.write('%s\r\n' % audio.url)
            file.close()

        elif cmd == "display":
            for audio in self.PLAYLIST:
                self.cached_format(audio)

        else:
            print('Playlist command only support "add", "remove", "display" and "export" arguments.', file=self.stderr)
            return 2

    def complete_info(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_object()

    def do_info(self, _id):
        """
        info ID

        Get information about a radio or an audio file.
        """
        if not _id:
            print('This command takes an argument: %s' % self.get_command_help('info', short=True), file=self.stderr)
            return 2

        obj = self.retrieve_obj(_id)

        if isinstance(obj, Album):
            self.set_formatter('album_tracks_list_info')
        elif isinstance(obj, Playlist):
            self.set_formatter('playlist_tracks_list_info')

        if obj is None:
            print('No object matches with this id:', _id, file=self.stderr)
            return 3

        self.format(obj)

    @defaultcount(10)
    def do_search(self, pattern=None):
        """
        search (radio|song|album|playlist) PATTERN

        List (radio|song|album|playlist) matching a PATTERN.

        If PATTERN is not given, this command will list all the (radio|song|album|playlist).
        """

        if not pattern:
            print('This command takes an argument: %s' % self.get_command_help('playlist'), file=self.stderr)
            return 2

        cmd, args = self.parse_command_args(pattern, 2, req_n=1)
        if not args:
            args = ""

        self.set_formatter_header(u'Search pattern: %s' % pattern if pattern else u'All radios')
        self.change_path([u'search'])

        if cmd == "radio":
            self.set_formatter('radio_list')
            for radio in self.do('iter_radios_search', pattern=args):
                self.add_object(radio)
                self.format(radio)

        elif cmd == "song":
            self.set_formatter('song_list')
            for audio in self.do('search_audio', pattern=args):
                self.add_object(audio)
                self.format(audio)

        elif cmd == "album":
            self.set_formatter('song_list')
            for album in self.do('search_album', pattern=args):
                self.add_object(album)
                self.format(album)

        elif cmd == "playlist":
            self.set_formatter('song_list')
            for playlist in self.do('search_playlist', pattern=args):
                self.add_object(playlist)
                self.format(playlist)

        else:
            print('Search command only supports "radio", "song", "album" and "playlist" arguments.', file=self.stderr)
            return 2

    def do_ls(self, line):
        """
        ls

        List radios
        """
        ret = super(Radioob, self).do_ls(line)
        return ret
Beispiel #6
0
class Radioob(ReplApplication):
    APPNAME = 'radioob'
    VERSION = '0.h'
    COPYRIGHT = 'Copyright(C) 2010-2012 Romain Bignon'
    DESCRIPTION = "Console application allowing to search for web radio stations, listen to them and get information " \
                  "like the current song."
    SHORT_DESCRIPTION = "search, show or listen to radio stations"
    CAPS = ICapRadio
    EXTRA_FORMATTERS = {'radio_list': RadioListFormatter}
    COMMANDS_FORMATTERS = {'ls':     'radio_list',
                           'search': 'radio_list',
                          }
    COLLECTION_OBJECTS = (Radio, )

    def __init__(self, *args, **kwargs):
        ReplApplication.__init__(self, *args, **kwargs)
        self.player = MediaPlayer(self.logger)

    def main(self, argv):
        self.load_config()
        return ReplApplication.main(self, argv)

    def complete_play(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_object()

    def do_play(self, _id):
        """
        play ID

        Play a radio with a found player.
        """
        if not _id:
            print >>sys.stderr, 'This command takes an argument: %s' % self.get_command_help('play', short=True)
            return 2

        radio = self.get_object(_id, 'get_radio', ['streams'])
        if not radio:
            print >>sys.stderr, 'Radio not found:', _id
            return 1
        try:
            player_name = self.config.get('media_player')
            media_player_args = self.config.get('media_player_args')
            if not player_name:
                self.logger.debug(u'You can set the media_player key to the player you prefer in the radioob '
                                  'configuration file.')
            self.player.play(radio.streams[0], player_name=player_name, player_args=media_player_args)
        except (InvalidMediaPlayer, MediaPlayerNotFound) as e:
            print '%s\nRadio URL: %s' % (e, radio.streams[0].url)

    def complete_info(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_object()

    def do_info(self, _id):
        """
        info ID

        Get information about a radio.
        """
        if not _id:
            print >>sys.stderr, 'This command takes an argument: %s' % self.get_command_help('info', short=True)
            return 2

        radio = self.get_object(_id, 'get_radio', ['streams', 'current'])
        if not radio:
            print >>sys.stderr, 'Radio not found:', _id
            return 3
        self.format(radio)

    @defaultcount(10)
    def do_search(self, pattern=None):
        """
        search PATTERN

        List radios matching a PATTERN.

        If PATTERN is not given, this command will list all the radios.
        """
        self.set_formatter_header(u'Search pattern: %s' % pattern if pattern else u'All radios')
        self.change_path([u'search'])
        for backend, radio in self.do('iter_radios_search', pattern=pattern):
            self.add_object(radio)
            self.format(radio)

    def do_ls(self, line):
        """
        ls

        List radios
        """
        ret = super(Radioob, self).do_ls(line)
        return ret
Beispiel #7
0
class Videoob(ReplApplication):
    APPNAME = 'videoob'
    VERSION = '1.2'
    COPYRIGHT = 'Copyright(C) 2010-YEAR Christophe Benz, Romain Bignon, John Obbele'
    DESCRIPTION = "Console application allowing to search for videos on various websites, " \
                  "play and download them and get information."
    SHORT_DESCRIPTION = "search and play videos"
    CAPS = CapVideo
    EXTRA_FORMATTERS = {'video_list': VideoListFormatter}
    COMMANDS_FORMATTERS = {'search': 'video_list',
                           'ls': 'video_list',
                           'playlist': 'video_list'}
    COLLECTION_OBJECTS = (BaseVideo, )
    PLAYLIST = []
    nsfw = True

    def __init__(self, *args, **kwargs):
        ReplApplication.__init__(self, *args, **kwargs)
        self.player = MediaPlayer(self.logger)

    def main(self, argv):
        self.load_config()
        return ReplApplication.main(self, argv)

    def download(self, video, dest, default=None):
        if not video.url:
            print('Error: the direct URL is not available.', file=self.stderr)
            return 4

        def check_exec(executable):
            with open(os.devnull, 'w') as devnull:
                process = subprocess.Popen(['which', executable], stdout=devnull)
                if process.wait() != 0:
                    print('Please install "%s"' % executable, file=self.stderr)
                    return False
            return True

        dest = self.obj_to_filename(video, dest, default)

        if video.url.startswith('rtmp'):
            if not check_exec('rtmpdump'):
                return 1
            args = ('rtmpdump', '-e', '-r', video.url, '-o', dest)
        elif video.url.startswith('mms'):
            if not check_exec('mimms'):
                return 1
            args = ('mimms', '-r', video.url, dest)
        elif u'm3u8' == video.ext:
            _dest, _ = os.path.splitext(dest)
            dest = u'%s.%s' % (_dest, 'mp4')
            content = tuple()
            parsed_uri = urlparse(video.url)
            baseurl = '{uri.scheme}://{uri.netloc}'.format(uri=parsed_uri)
            for line in self.read_url(video.url):
                if not line.startswith('#'):
                    if not line.startswith('http'):
                        line = u'%s%s' % (baseurl, line)
                    content += (line,)

            args = ('wget', '-nv',) + content + ('-O', dest)
        else:
            if check_exec('wget'):
                args = ('wget', '-c', video.url, '-O', dest)
            elif check_exec('curl'):
                args = ('curl', '-C', '-', video.url, '-o', dest)
            else:
                return 1

        self.logger.debug(' '.join(args))
        os.spawnlp(os.P_WAIT, args[0], *args)

    def read_url(self, url):
        r = requests.get(url, stream=True)
        return r.iter_lines()

    def complete_download(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_object()
        elif len(args) >= 3:
            return self.path_completer(args[2])

    def do_download(self, line):
        """
        download ID [FILENAME]

        Download a video

        Braces-enclosed tags are replaced with data fields. Use the 'info'
        command to see what fields are available on a given video.

        Example: download KdRRge4XYIo@youtube '{title}.{ext}'
        """
        _id, dest = self.parse_command_args(line, 2, 1)
        video = self.get_object(_id, 'get_video', ['url'])
        if not video:
            print('Video not found: %s' % _id, file=self.stderr)
            return 3

        return self.download(video, dest)

    def complete_play(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) >= 2:
            return self._complete_object()

    def do_play(self, line):
        """
        play ID

        Play a video with a found player.
        """
        if not line:
            print('This command takes an argument: %s' % self.get_command_help('play', short=True), file=self.stderr)
            return 2

        ret = 0
        for _id in line.split(' '):
            video = self.get_object(_id, 'get_video', ['url'])
            error = self.play(video, _id)
            if error is not None:
                ret = error

        return ret

    def play(self, video, _id):
        if not video:
            print('Video not found: %s' % _id, file=self.stderr)
            return 3
        if not video.url:
            print('Error: the direct URL is not available.', file=self.stderr)
            return 4
        try:
            player_name = self.config.get('media_player')
            media_player_args = self.config.get('media_player_args')
            if not player_name:
                self.logger.info(u'You can set the media_player key to the player you prefer in the videoob '
                                 'configuration file.')
            self.player.play(video, player_name=player_name, player_args=media_player_args)
        except (InvalidMediaPlayer, MediaPlayerNotFound) as e:
            print('%s\nVideo URL: %s' % (e, video.url))

    def complete_info(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) >= 2:
            return self._complete_object()

    def do_info(self, line):
        """
        info ID [ID2 [...]]

        Get information about a video.
        """
        if not line:
            print('This command takes an argument: %s' % self.get_command_help('info', short=True), file=self.stderr)
            return 2

        self.start_format()
        for _id in line.split(' '):
            video = self.get_object(_id, 'get_video')
            if not video:
                print('Video not found: %s' % _id, file=self.stderr)
                return 3

            self.format(video)

    def complete_playlist(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return ['play', 'add', 'remove', 'export', 'display', 'download']
        if len(args) >= 3:
            if args[1] in ('export', 'download'):
                return self.path_completer(args[2])
            if args[1] in ('add', 'remove'):
                return self._complete_object()

    def do_playlist(self, line):
        """
        playlist cmd [args]

        playlist add ID [ID2 ID3 ...]
        playlist remove ID [ID2 ID3 ...]
        playlist export [FILENAME]
        playlist display
        playlist download [PATH]
        playlist play
        """

        if not self.interactive:
            print('This command can be used only in interactive mode.', file=self.stderr)
            return 1

        if not line:
            print('This command takes an argument: %s' % self.get_command_help('playlist'), file=self.stderr)
            return 2

        cmd, args = self.parse_command_args(line, 2, req_n=1)
        if cmd == "add":
            _ids = args.strip().split(' ')
            for _id in _ids:
                video = self.get_object(_id, 'get_video')

                if not video:
                    print('Video not found: %s' % _id, file=self.stderr)
                    return 3

                if not video.url:
                    print('Error: the direct URL is not available.', file=self.stderr)
                    return 4

                self.PLAYLIST.append(video)
        elif cmd == "remove":
            _ids = args.strip().split(' ')
            for _id in _ids:
                video_to_remove = self.get_object(_id, 'get_video')

                if not video_to_remove:
                    print('Video not found: %s' % _id, file=self.stderr)
                    return 3

                if not video_to_remove.url:
                    print('Error: the direct URL is not available.', file=self.stderr)
                    return 4

                for video in self.PLAYLIST:
                    if video.id == video_to_remove.id:
                        self.PLAYLIST.remove(video)
                        break
        elif cmd == "export":
            filename = "playlist.m3u"
            if args:
                filename = args

            file = open(filename, 'w')
            for video in self.PLAYLIST:
                file.write('%s\r\n' % video.url)
            file.close()
        elif cmd == "display":
            for video in self.PLAYLIST:
                self.cached_format(video)
        elif cmd == "download":
            for i, video in enumerate(self.PLAYLIST):
                self.download(video, args, '%02d-{id}-{title}.{ext}' % (i+1))
        elif cmd == "play":
            for video in self.PLAYLIST:
                self.play(video, video.id)
        else:
            print('Playlist command only support "add", "remove", "display", "download" and "export" arguments.', file=self.stderr)
            return 2

    def complete_nsfw(self, text, line, begidx, endidx):
        return ['on', 'off']

    def do_nsfw(self, line):
        """
        nsfw [on | off]

        If argument is given, enable or disable the non-suitable for work behavior.

        If no argument is given, print the current behavior.
        """
        line = line.strip()
        if line:
            if line == 'on':
                self.nsfw = True
            elif line == 'off':
                self.nsfw = False
            else:
                print('Invalid argument "%s".' % line)
                return 2
        else:
            print("on" if self.nsfw else "off")

    @defaultcount()
    def do_search(self, pattern):
        """
        search PATTERN

        Search for videos matching a PATTERN.
        """
        if not pattern:
            print('This command takes an argument: %s' % self.get_command_help('search', short=True), file=self.stderr)
            return 2

        self.change_path([u'search'])
        self.start_format(pattern=pattern)
        for video in self.do('search_videos', pattern=pattern, nsfw=self.nsfw):
            self.cached_format(video)
Beispiel #8
0
class Videoob(ReplApplication):
    APPNAME = 'videoob'
    VERSION = '0.e'
    COPYRIGHT = 'Copyright(C) 2010-2011 Christophe Benz, Romain Bignon, John Obbele'
    DESCRIPTION = 'Console application allowing to search for videos on various websites, ' \
                  'play and download them and get information.'
    CAPS = ICapVideo
    EXTRA_FORMATTERS = {'video_list': VideoListFormatter}
    COMMANDS_FORMATTERS = {'search': 'video_list', 'ls': 'video_list'}
    COLLECTION_OBJECTS = (BaseVideo, )

    nsfw = True

    def __init__(self, *args, **kwargs):
        ReplApplication.__init__(self, *args, **kwargs)
        self.player = MediaPlayer(self.logger)

    def main(self, argv):
        self.load_config()
        return ReplApplication.main(self, argv)

    def complete_download(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_object()
        elif len(args) >= 3:
            return self.path_completer(args[2])

    def do_download(self, line):
        """
        download ID [FILENAME]

        Download a video
        """
        _id, dest = self.parse_command_args(line, 2, 1)
        video = self.get_object(_id, 'get_video', ['url'])
        if not video:
            print >> sys.stderr, 'Video not found: %s' % _id
            return 3

        if not video.url:
            print >> sys.stderr, 'Error: the direct URL is not available.'
            return 4

        def check_exec(executable):
            with open('/dev/null', 'w') as devnull:
                process = subprocess.Popen(['which', executable],
                                           stdout=devnull)
                if process.wait() != 0:
                    print >> sys.stderr, 'Please install "%s"' % executable
                    return False
            return True

        if dest is None:
            ext = video.ext
            if not ext:
                ext = 'avi'
            dest = '%s.%s' % (video.id, ext)

        if video.url.startswith('rtmp'):
            if not check_exec('rtmpdump'):
                return 1
            args = ('rtmpdump', '-e', '-r', video.url, '-o', dest)
        elif video.url.startswith('mms'):
            if not check_exec('mimms'):
                return 1
            args = ('mimms', video.url, dest)
        else:
            if not check_exec('wget'):
                return 1
            args = ('wget', video.url, '-O', dest)

        os.spawnlp(os.P_WAIT, args[0], *args)

    def complete_play(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_object()

    def do_play(self, _id):
        """
        play ID

        Play a video with a found player.
        """
        if not _id:
            print >> sys.stderr, 'This command takes an argument: %s' % self.get_command_help(
                'play', short=True)
            return 2

        video = self.get_object(_id, 'get_video', ['url'])
        if not video:
            print >> sys.stderr, 'Video not found: %s' % _id
            return 3
        if not video.url:
            print >> sys.stderr, 'Error: the direct URL is not available.'
            return 4
        try:
            player_name = self.config.get('media_player')
            if not player_name:
                self.logger.info(
                    u'You can set the media_player key to the player you prefer in the videoob '
                    'configuration file.')
            self.player.play(video, player_name=player_name)
        except (InvalidMediaPlayer, MediaPlayerNotFound), e:
            print '%s\nVideo URL: %s' % (e, video.url)
Beispiel #9
0
class Videoob(ReplApplication):
    APPNAME = 'videoob'
    VERSION = '1.2'
    COPYRIGHT = 'Copyright(C) 2010-YEAR Christophe Benz, Romain Bignon, John Obbele'
    DESCRIPTION = "Console application allowing to search for videos on various websites, " \
                  "play and download them and get information."
    SHORT_DESCRIPTION = "search and play videos"
    CAPS = CapVideo
    EXTRA_FORMATTERS = {'video_list': VideoListFormatter}
    COMMANDS_FORMATTERS = {
        'search': 'video_list',
        'ls': 'video_list',
        'playlist': 'video_list'
    }
    COLLECTION_OBJECTS = (BaseVideo, )
    PLAYLIST = []
    nsfw = True

    def __init__(self, *args, **kwargs):
        ReplApplication.__init__(self, *args, **kwargs)
        self.player = MediaPlayer(self.logger)

    def main(self, argv):
        self.load_config()
        return ReplApplication.main(self, argv)

    def download(self, video, dest, default=None):
        if not video.url:
            print('Error: the direct URL is not available.', file=self.stderr)
            return 4

        def check_exec(executable):
            with open(os.devnull, 'w') as devnull:
                process = subprocess.Popen(['which', executable],
                                           stdout=devnull)
                if process.wait() != 0:
                    print('Please install "%s"' % executable, file=self.stderr)
                    return False
            return True

        dest = self.obj_to_filename(video, dest, default)

        if video.url.startswith('rtmp'):
            if not check_exec('rtmpdump'):
                return 1
            args = ('rtmpdump', '-e', '-r', video.url, '-o', dest)
        elif video.url.startswith('mms'):
            if not check_exec('mimms'):
                return 1
            args = ('mimms', '-r', video.url, dest)
        elif u'm3u8' == video.ext:
            _dest, _ = os.path.splitext(dest)
            dest = u'%s.%s' % (_dest, 'mp4')
            content = tuple()
            baseurl = video.url.rpartition('/')[0]
            for line in self.read_url(video.url):
                if not line.startswith('#'):
                    if not line.startswith('http'):
                        line = u'%s/%s' % (baseurl, line)
                    content += (line, )

            args = (
                'wget',
                '-nv',
            ) + content + ('-O', dest)
        else:
            if check_exec('wget'):
                args = ('wget', '-c', video.url, '-O', dest)
            elif check_exec('curl'):
                args = ('curl', '-C', '-', video.url, '-o', dest)
            else:
                return 1

        self.logger.debug(' '.join(args))
        os.spawnlp(os.P_WAIT, args[0], *args)

    def read_url(self, url):
        r = requests.get(url, stream=True)
        return r.iter_lines()

    def complete_download(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_object()
        elif len(args) >= 3:
            return self.path_completer(args[2])

    def do_download(self, line):
        """
        download ID [FILENAME]

        Download a video

        Braces-enclosed tags are replaced with data fields. Use the 'info'
        command to see what fields are available on a given video.

        Example: download KdRRge4XYIo@youtube '{title}.{ext}'
        """
        _id, dest = self.parse_command_args(line, 2, 1)
        video = self.get_object(_id, 'get_video', ['url'])
        if not video:
            print('Video not found: %s' % _id, file=self.stderr)
            return 3

        return self.download(video, dest)

    def complete_play(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) >= 2:
            return self._complete_object()

    def do_play(self, line):
        """
        play ID

        Play a video with a found player.
        """
        if not line:
            print('This command takes an argument: %s' %
                  self.get_command_help('play', short=True),
                  file=self.stderr)
            return 2

        ret = 0
        for _id in line.split(' '):
            video = self.get_object(_id, 'get_video', ['url'])
            error = self.play(video, _id)
            if error is not None:
                ret = error

        return ret

    def play(self, video, _id):
        if not video:
            print('Video not found: %s' % _id, file=self.stderr)
            return 3
        if not video.url:
            print('Error: the direct URL is not available.', file=self.stderr)
            return 4
        try:
            player_name = self.config.get('media_player')
            media_player_args = self.config.get('media_player_args')
            if not player_name:
                self.logger.info(
                    u'You can set the media_player key to the player you prefer in the videoob '
                    'configuration file.')
            self.player.play(video,
                             player_name=player_name,
                             player_args=media_player_args)
        except (InvalidMediaPlayer, MediaPlayerNotFound) as e:
            print('%s\nVideo URL: %s' % (e, video.url))

    def complete_info(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) >= 2:
            return self._complete_object()

    def do_info(self, line):
        """
        info ID [ID2 [...]]

        Get information about a video.
        """
        if not line:
            print('This command takes an argument: %s' %
                  self.get_command_help('info', short=True),
                  file=self.stderr)
            return 2

        self.start_format()
        for _id in line.split(' '):
            video = self.get_object(_id, 'get_video')
            if not video:
                print('Video not found: %s' % _id, file=self.stderr)
                return 3

            self.format(video)

    def complete_playlist(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return ['play', 'add', 'remove', 'export', 'display', 'download']
        if len(args) >= 3:
            if args[1] in ('export', 'download'):
                return self.path_completer(args[2])
            if args[1] in ('add', 'remove'):
                return self._complete_object()

    def do_playlist(self, line):
        """
        playlist cmd [args]

        playlist add ID [ID2 ID3 ...]
        playlist remove ID [ID2 ID3 ...]
        playlist export [FILENAME]
        playlist display
        playlist download [PATH]
        playlist play
        """

        if not self.interactive:
            print('This command can be used only in interactive mode.',
                  file=self.stderr)
            return 1

        if not line:
            print('This command takes an argument: %s' %
                  self.get_command_help('playlist'),
                  file=self.stderr)
            return 2

        cmd, args = self.parse_command_args(line, 2, req_n=1)
        if cmd == "add":
            _ids = args.strip().split(' ')
            for _id in _ids:
                video = self.get_object(_id, 'get_video')

                if not video:
                    print('Video not found: %s' % _id, file=self.stderr)
                    return 3

                if not video.url:
                    print('Error: the direct URL is not available.',
                          file=self.stderr)
                    return 4

                self.PLAYLIST.append(video)
        elif cmd == "remove":
            _ids = args.strip().split(' ')
            for _id in _ids:
                video_to_remove = self.get_object(_id, 'get_video')

                if not video_to_remove:
                    print('Video not found: %s' % _id, file=self.stderr)
                    return 3

                if not video_to_remove.url:
                    print('Error: the direct URL is not available.',
                          file=self.stderr)
                    return 4

                for video in self.PLAYLIST:
                    if video.id == video_to_remove.id:
                        self.PLAYLIST.remove(video)
                        break
        elif cmd == "export":
            filename = "playlist.m3u"
            if args:
                filename = args

            file = open(filename, 'w')
            for video in self.PLAYLIST:
                file.write('%s\r\n' % video.url)
            file.close()
        elif cmd == "display":
            for video in self.PLAYLIST:
                self.cached_format(video)
        elif cmd == "download":
            for i, video in enumerate(self.PLAYLIST):
                self.download(video, args, '%02d-{id}-{title}.{ext}' % (i + 1))
        elif cmd == "play":
            for video in self.PLAYLIST:
                self.play(video, video.id)
        else:
            print(
                'Playlist command only support "add", "remove", "display", "download" and "export" arguments.',
                file=self.stderr)
            return 2

    def complete_nsfw(self, text, line, begidx, endidx):
        return ['on', 'off']

    def do_nsfw(self, line):
        """
        nsfw [on | off]

        If argument is given, enable or disable the non-suitable for work behavior.

        If no argument is given, print the current behavior.
        """
        line = line.strip()
        if line:
            if line == 'on':
                self.nsfw = True
            elif line == 'off':
                self.nsfw = False
            else:
                print('Invalid argument "%s".' % line)
                return 2
        else:
            print("on" if self.nsfw else "off")

    @defaultcount()
    def do_search(self, pattern):
        """
        search PATTERN

        Search for videos matching a PATTERN.
        """
        if not pattern:
            print('This command takes an argument: %s' %
                  self.get_command_help('search', short=True),
                  file=self.stderr)
            return 2

        self.change_path([u'search'])
        self.start_format(pattern=pattern)
        for video in self.do('search_videos', pattern=pattern, nsfw=self.nsfw):
            self.cached_format(video)
Beispiel #10
0
class Videoob(ReplApplication):
    APPNAME = 'videoob'
    VERSION = '0.4'
    COPYRIGHT = 'Copyright(C) 2010 Christophe Benz, Romain Bignon, John Obbele'
    CAPS = ICapVideo
    EXTRA_FORMATTERS = {'video_list': VideoListFormatter}
    COMMANDS_FORMATTERS = {'search': 'video_list'}

    nsfw = True
    videos = []

    def __init__(self, *args, **kwargs):
        ReplApplication.__init__(self, *args, **kwargs)
        self.player = MediaPlayer(self.logger)

    def main(self, argv):
        self.load_config()
        return ReplApplication.main(self, argv)

    def _get_video(self, _id, fields=None):
        if self.interactive:
            try:
                video = self.videos[int(_id) - 1]
            except (IndexError,ValueError):
                pass
            else:
                for backend, video in self.do('fillobj', video, fields, backends=[video.backend]):
                    if video:
                        return video
        _id, backend_name = self.parse_id(_id)
        backend_names = (backend_name,) if backend_name is not None else self.enabled_backends
        for backend, video in self.do('get_video', _id, backends=backend_names):
            if video:
                return video

    def _complete_id(self):
        return ['%s@%s' % (video.id, video.backend) for video in self.videos]

    def complete_play(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_id()

    def do_play(self, _id):
        """
        play ID

        Play a video with a found player.
        """
        if not _id:
            print 'This command takes an argument: %s' % self.get_command_help('play', short=True)
            return

        video = self._get_video(_id, ['url'])
        if not video:
            print 'Video not found: %s' %  _id
            return
        try:
            player_name = self.config.get('media_player')
            if not player_name:
                self.logger.debug(u'You can set the media_player key to the player you prefer in the videoob '
                                  'configuration file.')
            self.player.play(video, player_name=player_name)
        except (InvalidMediaPlayer, MediaPlayerNotFound), e:
            print '%s\nVideo URL: %s' % (e, video.url)
Beispiel #11
0
class Radioob(ReplApplication):
    APPNAME = 'radioob'
    VERSION = '0.4'
    COPYRIGHT = 'Copyright(C) 2010 Romain Bignon'
    CAPS = ICapRadio
    EXTRA_FORMATTERS = {'radio_list': RadioListFormatter}
    COMMANDS_FORMATTERS = {'list':    'radio_list'}

    radios = []

    def __init__(self, *args, **kwargs):
        ReplApplication.__init__(self, *args, **kwargs)
        self.player = MediaPlayer(self.logger)

    def main(self, argv):
        self.load_config()
        return ReplApplication.main(self, argv)

    def _get_radio(self, _id, fields=None):
        if self.interactive:
            try:
                radio = self.radios[int(_id) - 1]
            except (IndexError,ValueError):
                pass
            else:
                for backend, radio in self.do('fillobj', radio, fields, backends=[radio.backend]):
                    if radio:
                        return radio
        _id, backend_name = self.parse_id(_id)
        backend_names = (backend_name,) if backend_name is not None else self.enabled_backends
        for backend, radio in self.do('get_radio', _id, backends=backend_names):
            if radio:
                return radio

    def _complete_id(self):
        return ['%s@%s' % (radio.id, radio.backend) for radio in self.radios]

    def complete_play(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_id()

    def do_play(self, _id):
        """
        play ID

        Play a radio with a found player.
        """
        if not _id:
            print 'This command takes an argument: %s' % self.get_command_help('play', short=True)
            return

        radio = self._get_radio(_id, ['streams'])
        if not radio:
            print >>sys.stderr, 'Radio not found: ' % _id
            return
        try:
            player_name = self.config.get('media_player')
            if not player_name:
                self.logger.debug(u'You can set the media_player key to the player you prefer in the radioob '
                                  'configuration file.')
            self.player.play(radio.streams[0], player_name=player_name)
        except (InvalidMediaPlayer, MediaPlayerNotFound), e:
            print '%s\nVideo URL: %s' % (e, radio.streams[0].url)
Beispiel #12
0
class Radioob(ReplApplication):
    APPNAME = 'radioob'
    VERSION = '0.i'
    COPYRIGHT = 'Copyright(C) 2010-2013 Romain Bignon\nCopyright(C) 2013 Pierre Maziere'
    DESCRIPTION = "Console application allowing to search for web radio stations, listen to them and get information " \
                  "like the current song."
    SHORT_DESCRIPTION = "search, show or listen to radio stations"
    CAPS = (ICapRadio, ICapAudio)
    EXTRA_FORMATTERS = {'radio_list': RadioListFormatter}
    COMMANDS_FORMATTERS = {'ls':     'radio_list',
                           'search': 'radio_list',
                           'playlist': 'radio_list',
                          }
    COLLECTION_OBJECTS = (Radio, BaseAudio, )
    PLAYLIST = []

    def __init__(self, *args, **kwargs):
        ReplApplication.__init__(self, *args, **kwargs)
        self.player = MediaPlayer(self.logger)

    def main(self, argv):
        self.load_config()
        return ReplApplication.main(self, argv)

    def complete_download(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_object()
        elif len(args) >= 3:
            return self.path_completer(args[2])

    def do_download(self, line):
        """
        download ID [FILENAME]

        Download an audio file
        """
        _id, dest = self.parse_command_args(line, 2, 1)
        audio = self.get_object(_id, 'get_audio', ['url'])
        if not audio:
            print >>sys.stderr, 'Audio file not found: %s' % _id
            return 3

        if not audio.url:
            print >>sys.stderr, 'Error: the direct URL is not available.'
            return 4

        def check_exec(executable):
            with open('/dev/null', 'w') as devnull:
                process = subprocess.Popen(['which', executable], stdout=devnull)
                if process.wait() != 0:
                    print >>sys.stderr, 'Please install "%s"' % executable
                    return False
            return True

        def audio_to_file(_audio):
            ext = _audio.ext
            if not ext:
                ext = 'audiofile'
            return '%s.%s' % (re.sub('[?:/]', '-', _audio.id), ext)

        if dest is not None and os.path.isdir(dest):
            dest += '/%s' % audio_to_file(audio)

        if dest is None:
            dest = audio_to_file(audio)

        if audio.url.startswith('rtmp'):
            if not check_exec('rtmpdump'):
                return 1
            args = ('rtmpdump', '-e', '-r', audio.url, '-o', dest)
        elif audio.url.startswith('mms'):
            if not check_exec('mimms'):
                return 1
            args = ('mimms', '-r', audio.url, dest)
        else:
            if check_exec('wget'):
                args = ('wget', '-c', audio.url, '-O', dest)
            elif check_exec('curl'):
                args = ('curl', '-C', '-', audio.url, '-o', dest)
            else:
                return 1

        os.spawnlp(os.P_WAIT, args[0], *args)

    def complete_play(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_object()

    def do_play(self, line):
        """
        play ID [stream_id]

        Play a radio or a audio file with a found player (optionnaly specify the wanted stream).
        """
        _id, stream_id = self.parse_command_args(line, 2, 1)
        if not _id:
            print >>sys.stderr, 'This command takes an argument: %s' % self.get_command_help('play', short=True)
            return 2

        try:
            stream_id = int(stream_id)
        except (ValueError,TypeError):
            stream_id = 0

        radio = self.get_object(_id, 'get_radio')
        audio = self.get_object(_id, 'get_audio')

        if radio is None and audio is None:
            print >>sys.stderr, 'Radio or Audio file not found:', _id
            return 3

        if audio is None:
            try:
                stream = radio.streams[stream_id]
            except IndexError:
                print >>sys.stderr, 'Stream #%d not found' % stream_id
                return 1
        else:
            stream = audio

        try:
            player_name = self.config.get('media_player')
            media_player_args = self.config.get('media_player_args')
            if not player_name:
                self.logger.debug(u'You can set the media_player key to the player you prefer in the radioob '
                                  'configuration file.')
            self.player.play(stream, player_name=player_name, player_args=media_player_args)
        except (InvalidMediaPlayer, MediaPlayerNotFound) as e:
            print '%s\nRadio URL: %s' % (e, stream.url)

    def do_playlist(self, line):
        """
        playlist cmd [args]
        playlist add ID [ID2 ID3 ...]
        playlist remove ID [ID2 ID3 ...]
        playlist export [FILENAME]
        playlist display
        """

        if not line:
            print >>sys.stderr, 'This command takes an argument: %s' % self.get_command_help('playlist')
            return 2

        cmd, args = self.parse_command_args(line, 2, req_n=1)
        if cmd == "add":
            _ids = args.strip().split(' ')
            for _id in _ids:
                audio = self.get_object(_id, 'get_audio')

                if not audio:
                    print >>sys.stderr, 'Audio file not found: %s' % _id
                    return 3

                if not audio.url:
                    print >>sys.stderr, 'Error: the direct URL is not available.'
                    return 4

                self.PLAYLIST.append(audio)

        elif cmd == "remove":
            _ids = args.strip().split(' ')
            for _id in _ids:

                audio_to_remove = self.get_object(_id, 'get_audio')

                if not audio_to_remove:
                    print >>sys.stderr, 'Audio file not found: %s' % _id
                    return 3

                if not audio_to_remove.url:
                    print >>sys.stderr, 'Error: the direct URL is not available.'
                    return 4

                for audio in self.PLAYLIST:
                    if audio.id == audio_to_remove.id:
                        self.PLAYLIST.remove(audio)
                        break

        elif cmd == "export":
            filename = "playlist.m3u"
            if args:
                filename = args

            file = open(filename, 'w')
            for audio in self.PLAYLIST:
                file.write('%s\r\n' % audio.url)
            file.close()

        elif cmd == "display":
            for audio in self.PLAYLIST:
                self.cached_format(audio)

        else:
            print >>sys.stderr, 'Playlist command only support "add", "remove", "display" and "export" arguments.'
            return 2


    def complete_info(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_object()

    def do_info(self, _id):
        """
        info ID

        Get information about a radio or an audio file.
        """
        if not _id:
            print >>sys.stderr, 'This command takes an argument: %s' % self.get_command_help('info', short=True)
            return 2

        radio = self.get_object(_id, 'get_radio')
        audio = self.get_object(_id, 'get_audio')
        if radio is None and audio is None:
            print >>sys.stderr, 'Radio or Audio file not found:', _id
            return 3

        if audio is None:
            self.format(radio)
        else:
            self.format(audio)

    @defaultcount(10)
    def do_search(self, pattern=None):
        """
        search PATTERN

        List radios matching a PATTERN.

        If PATTERN is not given, this command will list all the radios.
        """
        self.set_formatter_header(u'Search pattern: %s' % pattern if pattern else u'All radios')
        self.change_path([u'search'])
        for backend, radio in self.do('iter_radios_search', pattern=pattern):
            self.add_object(radio)
            self.format(radio)
        for backend, audio in self.do('search_audio', pattern=pattern):
            self.add_object(audio)
            self.format(audio)


    def do_ls(self, line):
        """
        ls

        List radios
        """
        ret = super(Radioob, self).do_ls(line)
        return ret
Beispiel #13
0
class Videoob(ReplApplication):
    APPNAME = 'videoob'
    VERSION = '0.h'
    COPYRIGHT = 'Copyright(C) 2010-2011 Christophe Benz, Romain Bignon, John Obbele'
    DESCRIPTION = "Console application allowing to search for videos on various websites, " \
                  "play and download them and get information."
    SHORT_DESCRIPTION = "search and play videos"
    CAPS = ICapVideo
    EXTRA_FORMATTERS = {'video_list': VideoListFormatter}
    COMMANDS_FORMATTERS = {'search': 'video_list',
                           'ls': 'video_list'}
    COLLECTION_OBJECTS = (BaseVideo, )

    nsfw = True

    def __init__(self, *args, **kwargs):
        ReplApplication.__init__(self, *args, **kwargs)
        self.player = MediaPlayer(self.logger)

    def main(self, argv):
        self.load_config()
        return ReplApplication.main(self, argv)

    def complete_download(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_object()
        elif len(args) >= 3:
            return self.path_completer(args[2])

    def do_download(self, line):
        """
        download ID [FILENAME]

        Download a video
        """
        _id, dest = self.parse_command_args(line, 2, 1)
        video = self.get_object(_id, 'get_video', ['url'])
        if not video:
            print >>sys.stderr, 'Video not found: %s' % _id
            return 3

        if not video.url:
            print >>sys.stderr, 'Error: the direct URL is not available.'
            return 4

        def check_exec(executable):
            with open('/dev/null', 'w') as devnull:
                process = subprocess.Popen(['which', executable], stdout=devnull)
                if process.wait() != 0:
                    print >>sys.stderr, 'Please install "%s"' % executable
                    return False
            return True

        if dest is None:
            ext = video.ext
            if not ext:
                ext = 'avi'
            dest = '%s.%s' % (video.id, ext)

        if video.url.startswith('rtmp'):
            if not check_exec('rtmpdump'):
                return 1
            args = ('rtmpdump', '-e', '-r', video.url, '-o', dest)
        elif video.url.startswith('mms'):
            if not check_exec('mimms'):
                return 1
            args = ('mimms', '-r', video.url, dest)
        else:
            if not check_exec('wget'):
                return 1
            args = ('wget', '-c', video.url, '-O', dest)

        os.spawnlp(os.P_WAIT, args[0], *args)

    def complete_play(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_object()

    def do_play(self, _id):
        """
        play ID

        Play a video with a found player.
        """
        if not _id:
            print >>sys.stderr, 'This command takes an argument: %s' % self.get_command_help('play', short=True)
            return 2

        video = self.get_object(_id, 'get_video', ['url'])
        if not video:
            print >>sys.stderr, 'Video not found: %s' % _id
            return 3
        if not video.url:
            print >>sys.stderr, 'Error: the direct URL is not available.'
            return 4
        try:
            player_name = self.config.get('media_player')
            media_player_args = self.config.get('media_player_args')
            if not player_name:
                self.logger.info(u'You can set the media_player key to the player you prefer in the videoob '
                                  'configuration file.')
            self.player.play(video, player_name=player_name, player_args=media_player_args)
        except (InvalidMediaPlayer, MediaPlayerNotFound) as e:
            print '%s\nVideo URL: %s' % (e, video.url)

    def complete_info(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_object()

    def do_info(self, _id):
        """
        info ID

        Get information about a video.
        """
        if not _id:
            print >>sys.stderr, 'This command takes an argument: %s' % self.get_command_help('info', short=True)
            return 2

        video = self.get_object(_id, 'get_video')
        if not video:
            print >>sys.stderr, 'Video not found: %s' % _id
            return 3

        self.start_format()
        self.format(video)

    def complete_nsfw(self, text, line, begidx, endidx):
        return ['on', 'off']

    def do_nsfw(self, line):
        """
        nsfw [on | off]

        If argument is given, enable or disable the non-suitable for work behavior.

        If no argument is given, print the current behavior.
        """
        line = line.strip()
        if line:
            if line == 'on':
                self.nsfw = True
            elif line == 'off':
                self.nsfw = False
            else:
                print 'Invalid argument "%s".' % line
                return 2
        else:
            print "on" if self.nsfw else "off"

    @defaultcount()
    def do_search(self, pattern):
        """
        search PATTERN

        Search for videos matching a PATTERN.
        """
        if not pattern:
            print >>sys.stderr, 'This command takes an argument: %s' % self.get_command_help('search', short=True)
            return 2

        self.change_path([u'search'])
        self.start_format(pattern=pattern)
        for backend, video in self.do('search_videos', pattern=pattern, nsfw=self.nsfw):
            self.cached_format(video)
Beispiel #14
0
 def __init__(self, *args, **kwargs):
     super(Videoob, self).__init__(*args, **kwargs)
     self.player = MediaPlayer(self.logger)
Beispiel #15
0
class Radioob(ReplApplication):
    APPNAME = 'radioob'
    VERSION = '1.4'
    COPYRIGHT = 'Copyright(C) 2010-YEAR Romain Bignon\nCopyright(C) YEAR Pierre Maziere'
    DESCRIPTION = "Console application allowing to search for web radio stations, listen to them and get information " \
                  "like the current song."
    SHORT_DESCRIPTION = "search, show or listen to radio stations"
    CAPS = (CapRadio, CapAudio)
    EXTRA_FORMATTERS = {
        'radio_list': RadioListFormatter,
        'song_list': SongListFormatter,
        'album_tracks_list_info': AlbumTrackListInfoFormatter,
        'playlist_tracks_list_info': PlaylistTrackListInfoFormatter,
    }

    COMMANDS_FORMATTERS = {
        'ls': 'radio_list',
        'playlist': 'radio_list',
    }

    COLLECTION_OBJECTS = (
        Radio,
        BaseAudio,
    )
    PLAYLIST = []

    def __init__(self, *args, **kwargs):
        super(Radioob, self).__init__(*args, **kwargs)
        self.player = MediaPlayer(self.logger)

    def main(self, argv):
        self.load_config()
        return ReplApplication.main(self, argv)

    def complete_download(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_object()
        elif len(args) >= 3:
            return self.path_completer(args[2])

    def do_download(self, line):
        """
        download ID [DIRECTORY]

        Download an audio file
        """
        _id, dest = self.parse_command_args(line, 2, 1)

        obj = self.retrieve_obj(_id)

        if obj is None:
            print('No object matches with this id:', _id, file=self.stderr)
            return 3

        if isinstance(obj, BaseAudio):
            streams = [obj]

        else:
            streams = obj.tracks_list

        if len(streams) == 0:
            print('Radio or Audio file not found:', _id, file=self.stderr)
            return 3

        for stream in streams:
            self.download_file(stream, dest)

    def download_file(self, audio, dest):
        _obj = self.get_object(audio.id, 'get_audio', ['url', 'title'])
        if not _obj:
            print('Audio file not found: %s' % audio.id, file=self.stderr)
            return 3

        if not _obj.url:
            print('Error: the direct URL is not available.', file=self.stderr)
            return 4

        audio.url = _obj.url

        def check_exec(executable):
            with open(os.devnull, 'w') as devnull:
                process = subprocess.Popen(['which', executable],
                                           stdout=devnull)
                if process.wait() != 0:
                    print('Please install "%s"' % executable, file=self.stderr)
                    return False
            return True

        def audio_to_file(_audio):
            ext = _audio.ext
            if not ext:
                ext = 'audiofile'
            title = _audio.title if _audio.title else _audio.id
            return '%s.%s' % (re.sub('[?:/]', '-', title), ext)

        if dest is not None and os.path.isdir(dest):
            dest += '/%s' % audio_to_file(audio)

        if dest is None:
            dest = audio_to_file(audio)

        if audio.url.startswith('rtmp'):
            if not check_exec('rtmpdump'):
                return 1
            args = ('rtmpdump', '-e', '-r', audio.url, '-o', dest)
        elif audio.url.startswith('mms'):
            if not check_exec('mimms'):
                return 1
            args = ('mimms', '-r', audio.url, dest)
        else:
            if check_exec('wget'):
                args = ('wget', '-c', audio.url, '-O', dest)
            elif check_exec('curl'):
                args = ('curl', '-C', '-', audio.url, '-o', dest)
            else:
                return 1

        os.spawnlp(os.P_WAIT, args[0], *args)

    def complete_play(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_object()

    def do_play(self, line):
        """
        play ID [stream_id]

        Play a radio or a audio file with a found player (optionnaly specify the wanted stream).
        """
        _id, stream_id = self.parse_command_args(line, 2, 1)
        if not _id:
            print('This command takes an argument: %s' %
                  self.get_command_help('play', short=True),
                  file=self.stderr)
            return 2

        try:
            stream_id = int(stream_id)
        except (ValueError, TypeError):
            stream_id = 0

        obj = self.retrieve_obj(_id)

        if obj is None:
            print('No object matches with this id:', _id, file=self.stderr)
            return 3

        if isinstance(obj, Radio):
            try:
                streams = [obj.streams[stream_id]]
            except IndexError:
                print('Stream %d not found' % stream_id, file=self.stderr)
                return 1
        elif isinstance(obj, BaseAudio):
            streams = [obj]

        else:
            streams = obj.tracks_list

        if len(streams) == 0:
            print('Radio or Audio file not found:', _id, file=self.stderr)
            return 3

        try:
            player_name = self.config.get('media_player')
            media_player_args = self.config.get('media_player_args')
            if not player_name:
                self.logger.debug(
                    u'You can set the media_player key to the player you prefer in the radioob '
                    'configuration file.')

            for stream in streams:
                if isinstance(stream, BaseAudio) and not stream.url:
                    stream = self.get_object(stream.id, 'get_audio')
                else:
                    r = requests.get(stream.url, stream=True)
                    buf = next(r.iter_content(512)).decode('utf-8', 'replace')
                    r.close()
                    playlistFormat = None
                    for line in buf.split("\n"):
                        if playlistFormat is None:
                            if line == "[playlist]":
                                playlistFormat = "pls"
                            elif line == "#EXTM3U":
                                playlistFormat = "m3u"
                            else:
                                break
                        elif playlistFormat == "pls":
                            if line.startswith('File'):
                                stream.url = line.split('=', 1).pop(1).strip()
                                break
                        elif playlistFormat == "m3u":
                            if line[0] != "#":
                                stream.url = line.strip()
                                break

                self.player.play(stream,
                                 player_name=player_name,
                                 player_args=media_player_args)

        except (InvalidMediaPlayer, MediaPlayerNotFound) as e:
            print('%s\nRadio URL: %s' % (e, stream.url))

    def retrieve_obj(self, _id):
        obj = None
        if self.interactive:
            try:
                obj = self.objects[int(_id) - 1]
                _id = obj.id
            except (IndexError, ValueError):
                pass

        m = CapAudio.get_object_method(_id)
        if m:
            obj = self.get_object(_id, m)

        return obj if obj is not None else self.get_object(_id, 'get_radio')

    def do_playlist(self, line):
        """
        playlist cmd [args]
        playlist add ID [ID2 ID3 ...]
        playlist remove ID [ID2 ID3 ...]
        playlist export [FILENAME]
        playlist display
        """

        if not line:
            print('This command takes an argument: %s' %
                  self.get_command_help('playlist'),
                  file=self.stderr)
            return 2

        cmd, args = self.parse_command_args(line, 2, req_n=1)
        if cmd == "add":
            _ids = args.strip().split(' ')
            for _id in _ids:
                audio = self.get_object(_id, 'get_audio')

                if not audio:
                    print('Audio file not found: %s' % _id, file=self.stderr)
                    return 3

                if not audio.url:
                    print('Error: the direct URL is not available.',
                          file=self.stderr)
                    return 4

                self.PLAYLIST.append(audio)

        elif cmd == "remove":
            _ids = args.strip().split(' ')
            for _id in _ids:

                audio_to_remove = self.get_object(_id, 'get_audio')

                if not audio_to_remove:
                    print('Audio file not found: %s' % _id, file=self.stderr)
                    return 3

                if not audio_to_remove.url:
                    print('Error: the direct URL is not available.',
                          file=self.stderr)
                    return 4

                for audio in self.PLAYLIST:
                    if audio.id == audio_to_remove.id:
                        self.PLAYLIST.remove(audio)
                        break

        elif cmd == "export":
            filename = "playlist.m3u"
            if args:
                filename = args

            file = open(filename, 'w')
            for audio in self.PLAYLIST:
                file.write('%s\r\n' % audio.url)
            file.close()

        elif cmd == "display":
            for audio in self.PLAYLIST:
                self.cached_format(audio)

        else:
            print(
                'Playlist command only support "add", "remove", "display" and "export" arguments.',
                file=self.stderr)
            return 2

    def complete_info(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_object()

    def do_info(self, _id):
        """
        info ID

        Get information about a radio or an audio file.
        """
        if not _id:
            print('This command takes an argument: %s' %
                  self.get_command_help('info', short=True),
                  file=self.stderr)
            return 2

        obj = self.retrieve_obj(_id)

        if isinstance(obj, Album):
            self.set_formatter('album_tracks_list_info')
        elif isinstance(obj, Playlist):
            self.set_formatter('playlist_tracks_list_info')

        if obj is None:
            print('No object matches with this id:', _id, file=self.stderr)
            return 3

        self.format(obj)

    @defaultcount(10)
    def do_search(self, pattern=None):
        """
        search (radio|song|file|album|playlist) PATTERN

        List (radio|song|file|album|playlist) matching a PATTERN.

        If PATTERN is not given, this command will list all the (radio|song|album|playlist).
        """

        if not pattern:
            print('This command takes an argument: %s' %
                  self.get_command_help('playlist'),
                  file=self.stderr)
            return 2

        cmd, args = self.parse_command_args(pattern, 2, req_n=1)
        if not args:
            args = ""

        self.set_formatter_header(u'Search pattern: %s' %
                                  pattern if pattern else u'All radios')
        self.change_path([u'search'])

        if cmd == "radio":
            self.set_formatter('radio_list')
            for radio in self.do('iter_radios_search', pattern=args):
                self.add_object(radio)
                self.format(radio)

        elif cmd == "song" or cmd == "file":
            self.set_formatter('song_list')
            for audio in self.do('search_audio', pattern=args):
                self.add_object(audio)
                self.format(audio)

        elif cmd == "album":
            self.set_formatter('song_list')
            for album in self.do('search_album', pattern=args):
                self.add_object(album)
                self.format(album)

        elif cmd == "playlist":
            self.set_formatter('song_list')
            for playlist in self.do('search_playlist', pattern=args):
                self.add_object(playlist)
                self.format(playlist)

        else:
            print(
                'Search command only supports "radio", "song", "file", "album" and "playlist" arguments.',
                file=self.stderr)
            return 2

    def do_ls(self, line):
        """
        ls

        List radios
        """
        ret = super(Radioob, self).do_ls(line)
        return ret
Beispiel #16
0
 def __init__(self, *args, **kwargs):
     super(Radioob, self).__init__(*args, **kwargs)
     self.player = MediaPlayer(self.logger)
Beispiel #17
0
class Radioob(ReplApplication):
    APPNAME = "radioob"
    VERSION = "0.h"
    COPYRIGHT = "Copyright(C) 2010-2012 Romain Bignon"
    DESCRIPTION = (
        "Console application allowing to search for web radio stations, listen to them and get information "
        "like the current song."
    )
    SHORT_DESCRIPTION = "search, show or listen to radio stations"
    CAPS = ICapRadio
    EXTRA_FORMATTERS = {"radio_list": RadioListFormatter}
    COMMANDS_FORMATTERS = {"ls": "radio_list", "search": "radio_list"}
    COLLECTION_OBJECTS = (Radio,)

    def __init__(self, *args, **kwargs):
        ReplApplication.__init__(self, *args, **kwargs)
        self.player = MediaPlayer(self.logger)

    def main(self, argv):
        self.load_config()
        return ReplApplication.main(self, argv)

    def complete_play(self, text, line, *ignored):
        args = line.split(" ")
        if len(args) == 2:
            return self._complete_object()

    def do_play(self, line):
        """
        play ID [stream_id]

        Play a radio with a found player (optionnaly specify the wanted stream).
        """
        _id, stream_id = self.parse_command_args(line, 2, 1)
        if not _id:
            print >> sys.stderr, "This command takes an argument: %s" % self.get_command_help("play", short=True)
            return 2

        try:
            stream_id = int(stream_id)
        except (ValueError, TypeError):
            stream_id = 0

        radio = self.get_object(_id, "get_radio", ["streams"])
        if not radio:
            print >> sys.stderr, "Radio not found:", _id
            return 1

        try:
            stream = radio.streams[stream_id]
        except IndexError:
            print >> sys.stderr, "Stream #%d not found" % stream_id
            return 1

        try:
            player_name = self.config.get("media_player")
            media_player_args = self.config.get("media_player_args")
            if not player_name:
                self.logger.debug(
                    u"You can set the media_player key to the player you prefer in the radioob " "configuration file."
                )
            self.player.play(stream, player_name=player_name, player_args=media_player_args)
        except (InvalidMediaPlayer, MediaPlayerNotFound) as e:
            print "%s\nRadio URL: %s" % (e, stream.url)

    def complete_info(self, text, line, *ignored):
        args = line.split(" ")
        if len(args) == 2:
            return self._complete_object()

    def do_info(self, _id):
        """
        info ID

        Get information about a radio.
        """
        if not _id:
            print >> sys.stderr, "This command takes an argument: %s" % self.get_command_help("info", short=True)
            return 2

        radio = self.get_object(_id, "get_radio", ["streams", "current"])
        if not radio:
            print >> sys.stderr, "Radio not found:", _id
            return 3
        self.format(radio)

    @defaultcount(10)
    def do_search(self, pattern=None):
        """
        search PATTERN

        List radios matching a PATTERN.

        If PATTERN is not given, this command will list all the radios.
        """
        self.set_formatter_header(u"Search pattern: %s" % pattern if pattern else u"All radios")
        self.change_path([u"search"])
        for backend, radio in self.do("iter_radios_search", pattern=pattern):
            self.add_object(radio)
            self.format(radio)

    def do_ls(self, line):
        """
        ls

        List radios
        """
        ret = super(Radioob, self).do_ls(line)
        return ret
Beispiel #18
0
 def __init__(self, *args, **kwargs):
     ReplApplication.__init__(self, *args, **kwargs)
     self.player = MediaPlayer(self.logger)
Beispiel #19
0
class Videoob(ReplApplication):
    APPNAME = 'videoob'
    VERSION = '0.e'
    COPYRIGHT = 'Copyright(C) 2010-2011 Christophe Benz, Romain Bignon, John Obbele'
    DESCRIPTION = 'Console application allowing to search for videos on various websites, ' \
                  'play and download them and get information.'
    CAPS = ICapVideo
    EXTRA_FORMATTERS = {'video_list': VideoListFormatter}
    COMMANDS_FORMATTERS = {'search': 'video_list',
                           'ls': 'video_list'}
    COLLECTION_OBJECTS = (BaseVideo, )

    nsfw = True

    def __init__(self, *args, **kwargs):
        ReplApplication.__init__(self, *args, **kwargs)
        self.player = MediaPlayer(self.logger)

    def main(self, argv):
        self.load_config()
        return ReplApplication.main(self, argv)

    def complete_download(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_object()
        elif len(args) >= 3:
            return self.path_completer(args[2])

    def do_download(self, line):
        """
        download ID [FILENAME]

        Download a video
        """
        _id, dest = self.parse_command_args(line, 2, 1)
        video = self.get_object(_id, 'get_video', ['url'])
        if not video:
            print >>sys.stderr, 'Video not found: %s' % _id
            return 3

        if not video.url:
            print >>sys.stderr, 'Error: the direct URL is not available.'
            return 4

        def check_exec(executable):
            with open('/dev/null', 'w') as devnull:
                process = subprocess.Popen(['which', executable], stdout=devnull)
                if process.wait() != 0:
                    print >>sys.stderr, 'Please install "%s"' % executable
                    return False
            return True

        if dest is None:
            ext = video.ext
            if not ext:
                ext = 'avi'
            dest = '%s.%s' % (video.id, ext)

        if video.url.startswith('rtmp'):
            if not check_exec('rtmpdump'):
                return 1
            args = ('rtmpdump', '-e', '-r', video.url, '-o', dest)
        elif video.url.startswith('mms'):
            if not check_exec('mimms'):
                return 1
            args = ('mimms', video.url, dest)
        else:
            if not check_exec('wget'):
                return 1
            args = ('wget', video.url, '-O', dest)

        os.spawnlp(os.P_WAIT, args[0], *args)

    def complete_play(self, text, line, *ignored):
        args = line.split(' ')
        if len(args) == 2:
            return self._complete_object()

    def do_play(self, _id):
        """
        play ID

        Play a video with a found player.
        """
        if not _id:
            print >>sys.stderr, 'This command takes an argument: %s' % self.get_command_help('play', short=True)
            return 2

        video = self.get_object(_id, 'get_video', ['url'])
        if not video:
            print >>sys.stderr, 'Video not found: %s' % _id
            return 3
        if not video.url:
            print >>sys.stderr, 'Error: the direct URL is not available.'
            return 4
        try:
            player_name = self.config.get('media_player')
            if not player_name:
                self.logger.info(u'You can set the media_player key to the player you prefer in the videoob '
                                  'configuration file.')
            self.player.play(video, player_name=player_name)
        except (InvalidMediaPlayer, MediaPlayerNotFound), e:
            print '%s\nVideo URL: %s' % (e, video.url)