Beispiel #1
0
def monitor_daemon():
    f = open("/tmp/mkchromecast.pid", "rb")
    pidnumber = int(pickle.load(f))
    print(colors.options("PID of main process:") + " " + str(pidnumber))

    localpid = getpid()
    print(colors.options("PID of streaming process:") + " " + str(localpid))

    while psutil.pid_exists(localpid) is True:
        try:
            time.sleep(0.5)
            # With this I ensure that if the main app fails, everything# With
            # this I ensure that if the main app fails, everything
            # will get back to normal
            if psutil.pid_exists(pidnumber) is False:
                if platform == "Darwin":
                    inputint()
                    outputint()
                else:
                    from mkchromecast.pulseaudio import remove_sink

                    remove_sink()
                parent = psutil.Process(localpid)
                for child in parent.children(recursive=True):
                    child.kill()
                parent.kill()
        except KeyboardInterrupt:
            print("Ctrl-c was requested")
            sys.exit(0)
        except IOError:
            print("I/O Error")
            sys.exit(0)
        except OSError:
            print("OSError")
            sys.exit(0)
Beispiel #2
0
def monitor_daemon():
    f = open('/tmp/mkchromecast.pid', 'rb')
    pidnumber = int(pickle.load(f))
    print(colors.options('PID of main process:') + ' ' + str(pidnumber))

    localpid = getpid()
    print(colors.options('PID of streaming process:') + ' ' + str(localpid))

    while psutil.pid_exists(localpid) == True:
        try:
            time.sleep(0.5)
            if psutil.pid_exists(
                    pidnumber
            ) == False:  # With this I ensure that if the main app fails, everything
                if platform == 'Darwin':  # will get back to normal
                    inputint()
                    outputint()
                else:
                    from mkchromecast.pulseaudio import remove_sink
                    remove_sink()
                parent = psutil.Process(localpid)
                for child in parent.children(
                        recursive=True
                ):  # or parent.children() for recursive=False
                    child.kill()
                parent.kill()
        except KeyboardInterrupt:
            print('Ctrl-c was requested')
            sys.exit(0)
        except IOError:
            print('I/O Error')
            sys.exit(0)
        except OSError:
            print('OSError')
            sys.exit(0)
Beispiel #3
0
 def controls_msg(self):
     """Messages shown when controls is True"""
     print('')
     print(colors.important('Controls:'))
     print(colors.important('========='))
     print('')
     print(colors.options('Volume Up:') + ' u')
     print(colors.options('Volume Down:') + ' d')
     if videoarg == True:
         print(colors.options('Pause Casting:') + ' p')
         print(colors.options('Resume Casting:') + ' r')
     print(colors.options('Quit the Application:') + ' q or Ctrl-C')
     print('')
Beispiel #4
0
def bitrate_default(bitrate):
    """Bitrate messages
    Printing default bitrate message
    """
    if source_url is None:
        print(colors.options('Default bitrate used:') + ' ' + bitrate)
    return
Beispiel #5
0
def samplerate_default(samplerate):
    """Sample rate messages
    Printing default sample rate message"""
    if source_url is None:
        print(colors.options('Default sample rate used:') + ' ' +
              samplerate + 'Hz.')
    return
Beispiel #6
0
def bitrate_default(bitrate):
    """Bitrate messages
    Printing default bitrate message
    """
    if source_url is None:
        print(colors.options("Default bitrate used:") + " " + bitrate)
    return
def samplerate_default(samplerate):
    """Sample rate messages
    Printing default sample rate message"""
    if sourceurl is None:
        print(colors.options('Default sample rate used:') + ' ' +
              samplerate + 'Hz.')
    return
def bitrate_default(bitrate):
    """Bitrate messages
    Printing default bitrate message
    """
    if sourceurl is None:
        print(colors.options('Default bitrate used:') + ' ' + bitrate)
    return
Beispiel #9
0
 def inp_cc(self):
     while True:
         try:
             pickle.dump(self.index, self.tf)
             self.tf.close()
             self.cast_to = self.cclist[int(self.index)][1]
             print(' ')
             print(colors.options('Casting to:') + ' ' +
                   colors.success(self.cast_to))
             print(' ')
         except TypeError:
             print(colors.options('Casting to:') + ' ' +
                   colors.success(self.cast_to.player_name))
         except IndexError:
             checkmktmp()
             self.tf = open('/tmp/mkchromecast.tmp', 'wb')
             self.sel_cc()
             continue
         break
Beispiel #10
0
 def input_device(self, write_to_pickle=True):
     while True:
         try:
             if write_to_pickle:
                 pickle.dump(self.index, self.tf)
                 self.tf.close()
             self.cast_to = self.cclist[int(self.index)][1]
             print(' ')
             print(colors.options('Casting to:') + ' ' +
                   colors.success(self.cast_to))
             print(' ')
         except TypeError:
             print(colors.options('Casting to:') + ' ' +
                   colors.success(self.cast_to.player_name))
         except IndexError:
             checkmktmp()
             self.tf = open('/tmp/mkchromecast.tmp', 'wb')
             self.select_device()
             continue
         break
Beispiel #11
0
 def input_device(self, write_to_pickle=True):
     while True:
         try:
             if write_to_pickle:
                 pickle.dump(self.index, self.tf)
                 self.tf.close()
             self.cast_to = self.cclist[int(self.index)][1]
             print(" ")
             print(
                 colors.options("Casting to:") + " " +
                 colors.success(self.cast_to))
             print(" ")
         except TypeError:
             print(
                 colors.options("Casting to:") + " " +
                 colors.success(self.cast_to.player_name))
         except IndexError:
             checkmktmp()
             self.tf = open("/tmp/mkchromecast.tmp", "wb")
             self.select_device()
             continue
         break
Beispiel #12
0
def streaming():
    """
    Configuration files
    """
    platform = mkchromecast.__init__.platform
    tray = mkchromecast.__init__.tray
    debug = mkchromecast.__init__.debug
    config = ConfigParser.RawConfigParser()
    configurations = config_manager()  # Class from mkchromecast.config
    configf = configurations.configf

    if os.path.exists(configf) and tray == True:
        configurations.chk_config()
        print(colors.warning('Configuration file exists'))
        print(colors.warning('Using defaults set there'))
        config.read(configf)
        backend = ConfigSectionMap('settings')['backend']
        rcodec = ConfigSectionMap('settings')['codec']
        bitrate = ConfigSectionMap('settings')['bitrate']
        samplerate = ConfigSectionMap('settings')['samplerate']
        notifications = ConfigSectionMap('settings')['notifications']
    else:
        backend = mkchromecast.__init__.backend
        rcodec = mkchromecast.__init__.rcodec
        codec = mkchromecast.__init__.codec
        bitrate = str(mkchromecast.__init__.bitrate)
        samplerate = str(mkchromecast.__init__.samplerate)
        notifications = mkchromecast.__init__.notifications

    print(colors.options('Selected backend:') + ' ' + backend)

    if debug == True:
        print(':::node::: variables', backend, rcodec, bitrate, samplerate,
              notifications)

    try:
        youtubeurl = mkchromecast.__init__.youtubeurl
    except AttributeError:
        youtubeurl = None

    if youtubeurl == None:
        if backend == 'node' and rcodec != 'mp3':
            print(
                colors.warning('Codec ' + rcodec +
                               ' is not supported by the node server!'))
            print('Using ' + codec + ' as default.')

        if backend == 'node':
            if int(bitrate) == 192:
                print(
                    colors.options('Default bitrate used:') + ' ' + bitrate +
                    'k')
            elif int(bitrate) > 320:
                print(
                    colors.warning('Maximum bitrate supported by ' + codec +
                                   ' is:') + ' ' + str(320) + 'k')
                bitrate = '320'
                print(colors.warning('Bitrate has been set to maximum!'))
            else:
                print(colors.options('Selected bitrate: ') + bitrate + 'k')

            if samplerate == '44100':
                print(
                    colors.options('Default sample rate used:') + ' ' +
                    samplerate + 'Hz')
            else:
                codecs_sr = ['mp3', 'ogg', 'aac', 'wav', 'flac']
                '''
                The codecs below do not support 96000Hz
                '''
                no96k = ['mp3', 'ogg']

                if codec in codecs_sr and int(samplerate) > 22000 and int(
                        samplerate) <= 27050:
                    samplerate = '22050'
                    msg.samplerate_no96(codec)

                if codec in codecs_sr and int(samplerate) > 27050 and int(
                        samplerate) <= 32000:
                    samplerate = '32000'
                    msg.samplerate_no96(codec)

                elif codec in codecs_sr and int(samplerate) > 32000 and int(
                        samplerate) <= 36000:
                    samplerate = '32000'
                    msg.samplerate_no96(codec)

                elif codec in codecs_sr and int(samplerate) > 36000 and int(
                        samplerate) <= 43000:
                    samplerate = '44100'
                    msg.samplerate_no96(codec)
                    print(
                        colors.warning('Sample rate has been set to default!'))

                elif codec in codecs_sr and int(samplerate) > 43000 and int(
                        samplerate) <= 72000:
                    samplerate = '48000'
                    msg.samplerate_no96(codec)

                elif codec in codecs_sr and int(samplerate) > 72000:
                    if codec in no96k:
                        msg.samplerate_no96(codec)
                        samplerate = '48000'
                    print(
                        colors.warning('Sample rate has been set to maximum!'))

                print(
                    colors.options('Sample rate set to:') + ' ' + samplerate +
                    'Hz')
    """
    Node section
    """
    if os.path.exists('./bin/node') == True:
        webcast = [
            './bin/node',
            './nodejs/node_modules/webcast-osx-audio/bin/webcast.js', '-b',
            bitrate, '-s', samplerate, '-p', '5000', '-u', 'stream'
        ]
    else:
        webcast = [
            './nodejs/bin/node',
            './nodejs/node_modules/webcast-osx-audio/bin/webcast.js', '-b',
            bitrate, '-s', samplerate, '-p', '5000', '-u', 'stream'
        ]
    p = subprocess.Popen(webcast)
    if debug == True:
        print(':::node::: node command', webcast)

    f = open('/tmp/mkchromecast.pid', 'rb')
    pidnumber = int(pickle.load(f))
    print(colors.options('PID of main process:') + ' ' + str(pidnumber))

    localpid = getpid()
    print(colors.options('PID of streaming process:') + ' ' + str(localpid))

    while p.poll() is None:
        try:
            time.sleep(0.5)
            if psutil.pid_exists(
                    pidnumber
            ) == False:  # With this I ensure that if the main app fails, everything
                inputint()  # will get back to normal
                outputint()
                parent = psutil.Process(localpid)
                for child in parent.children(
                        recursive=True
                ):  # or parent.children() for recursive=False
                    child.kill()
                parent.kill()
        except KeyboardInterrupt:
            print('Ctrl-c was requested')
            sys.exit(0)
        except IOError:
            print('I/O Error')
            sys.exit(0)
        except OSError:
            print('OSError')
            sys.exit(0)
    else:
        print(colors.warning('Reconnecting node streaming...'))
        if platform == 'Darwin' and notifications == 'enabled':
            if os.path.exists('images/google.icns') == True:
                noticon = 'images/google.icns'
            else:
                noticon = 'google.icns'
        if debug == True:
            print(':::node::: platform, tray, notifications', platform, tray,
                  notifications)

        if platform == 'Darwin' and tray == True and notifications == 'enabled':
            reconnecting = [
                './notifier/terminal-notifier.app/Contents/MacOS/terminal-notifier',
                '-group', 'cast', '-contentImage', noticon, '-title',
                'mkchromecast', '-subtitle', 'node server failed', '-message',
                'Reconnecting...'
            ]
            subprocess.Popen(reconnecting)

            if debug == True:
                print(':::node::: reconnecting notifier command', reconnecting)
        relaunch(stream, recasting, kill)
    return
Beispiel #13
0
    def play_cast(self):
        if self.debug is True:
            print('def play_cast(self):')
        localip = self.ip

        try:
            print(colors.options('The IP of ') +
                  colors.success(self.cast_to) + colors.options(' is:') +
                  ' ' + self.cast.host)
        except TypeError:
            print(colors.options('The IP of ') +
                  colors.success(self.cast_to.player_name) +
                  colors.options(' is:') + ' ' + self.cast_to.ip_address)
        except AttributeError:
            for _ in self.sonos_list:
                if self.cast_to == _.player_name:
                    self.cast_to = _
            print(colors.options('The IP of ') +
                  colors.success(self.cast_to.player_name) +
                  colors.options(' is:') + ' ' + self.cast_to.ip_address)

        if self.host is None:
            print(colors.options('Your local IP is:') + ' ' + localip)
        else:
            print(colors.options('Your manually entered local IP is:') +
                  ' ' + localip)

        try:
            media_controller = self.cast.media_controller

            if self.tray is True:
                config = ConfigParser.RawConfigParser()
                # Class from mkchromecast.config
                from mkchromecast.config import config_manager
                configurations = config_manager()
                configf = configurations.configf

                if os.path.exists(configf) and self.tray is True:
                    print(self.tray)
                    print(colors.warning('Configuration file exists'))
                    print(colors.warning('Using defaults set there'))
                    config.read(configf)
                    self.backend = ConfigSectionMap('settings')['backend']

            if self.source_url is not None:
                if args.video is True:
                    import mkchromecast.video
                    mtype = mkchromecast.video.mtype
                else:
                    import mkchromecast.audio
                    mtype = mkchromecast.audio.mtype
                print(' ')
                print(colors.options('Casting from stream URL:') + ' ' +
                      self.source_url)
                print(colors.options('Using media type:') + ' ' +
                      mtype)
                media_controller.play_media(
                        self.source_url,
                        mtype,
                        title=self.title,
                        stream_type='LIVE'
                        )
                media_controller.play()
            elif (self.backend == 'ffmpeg' or self.backend == 'node' or
                    self.backend == 'avconv' or self.backend == 'parec' or
                    self.backend == 'gstreamer' and self.source_url is None):
                if args.video is True:
                    import mkchromecast.video
                    mtype = mkchromecast.video.mtype
                else:
                    import mkchromecast.audio
                    mtype = mkchromecast.audio.mtype
                print(' ')
                print(colors.options('The media type string used is:') +
                      ' ' + mtype)
                media_controller.play_media(
                        'http://' + localip + ':' + self.port + '/stream',
                        mtype,
                        title=self.title,
                        stream_type='LIVE'
                        )

            if media_controller.is_active:
                import time
                time.sleep(2)
                media_controller.play()

            print(' ')
            print(colors.important('Cast media controller status'))
            print(' ')
            print(self.cast.status)
            print(' ')
            if self.hijack is True:
                self.r = Thread(target=self.hijack_cc)
                # This has to be set to True so that we catch
                # KeyboardInterrupt.
                self.r.daemon = True
                self.r.start()
        except AttributeError:
            self.sonos = self.cast_to
            self.sonos.play_uri('x-rincon-mp3radio://' + localip +
                                ':' + self.port + '/stream',
                                title=self.title)
            if self.tray is True:
                self.cast = self.sonos
Beispiel #14
0
    print(':::audio::: chunk_size: ', chunk_size)
debug = mkchromecast.__init__.debug
sourceurl = mkchromecast.__init__.sourceurl
config = ConfigParser.RawConfigParser()
configurations = config_manager()  # Class from mkchromecast.config
configf = configurations.configf
appendtourl = 'stream'

try:
    youtubeurl = mkchromecast.__init__.youtubeurl
except AttributeError:
    youtubeurl = None

# This is to take the youtube URL
if youtubeurl != None:
    print(colors.options('The Youtube URL chosen:') + ' ' + youtubeurl)

    try:
        import urlparse
        url_data = urlparse.urlparse(youtubeurl)
        query = urlparse.parse_qs(url_data.query)
    except ImportError:
        import urllib.parse
        url_data = urllib.parse.urlparse(youtubeurl)
        query = urllib.parse.parse_qs(url_data.query)
    video = query['v'][0]
    print(colors.options('Playing video:') + ' ' + video)
    command = ['youtube-dl', '-o', '-', youtubeurl]
    mtype = 'audio/mp4'
else:
    if os.path.exists(configf) and tray == True:
Beispiel #15
0
codecs = ['mp3', 'ogg', 'aac', 'wav', 'flac']

if backend == 'node' and args.codec != 'mp3' and sourceurl == None:
    rcodec = args.codec
    codec = 'mp3'
elif backend == 'node' and args.codec == 'mp3' and sourceurl == None:
    rcodec = args.codec
    codec = 'mp3'
elif sourceurl != None:
    codec = args.codec
else:
    rcodec = None
    if backend != 'node' and args.codec in codecs:
        codec = args.codec
    else:
        print(colors.options('Selected audio codec: ') + args.codec)
        print(colors.error('Supported audio codecs are: '))
        for codec in codecs:
            print('-', codec)
        sys.exit(0)
"""
Resolution
"""
resolutions = ['480p', '720p', '1080p', '2K', 'UHD', '4K']

_resolutions = [r.lower() for r in resolutions]

if args.resolution == None:
    resolution = args.resolution
elif args.resolution.lower() in _resolutions:
    resolution = args.resolution.lower()
Beispiel #16
0
    def initialize_cast(self):
        # This fixes the `No handlers could be found for logger
        # "pychromecast.socket_client` warning"`.
        # See commit 18005ebd4c96faccd69757bf3d126eb145687e0d.
        if chromecast:
            from pychromecast import socket_client
            self.cclist = self._get_chromecasts()
            self.cclist = [[i, _, 'Gcast'] for i, _ in enumerate(self.cclist)]
        else:
            self.cclist = []

        if sonos:
            try:
                self.sonos_list = list(soco.discover())
                for self.index, device in enumerate(self.sonos_list):
                    add_sonos = [self.index, device, 'Sonos']
                    self.cclist.append(add_sonos)
            except TypeError:
                pass

        if self.debug is True:
            print('self.cclist', self.cclist)

        if (len(self.cclist) != 0 and self.select_device is False and
                self.device_name is None):
            if self.debug is True:
                print('if len(self.cclist) != 0 and self.select_device == False:')
            print(' ')
            print_available_devices(self.available_devices())
            print(' ')
            if self.discover is False:
                print(colors.important('Casting to first device shown above!'))
                print(colors.important('Select devices by using the -s flag.'))
                print(' ')
                self.cast_to = self.cclist[0][1]
                if self.cclist[0][2] == 'Sonos':
                    print(colors.success(self.cast_to.player_name))
                else:
                    print(colors.success(self.cast_to))
                print(' ')

        elif (len(self.cclist) != 0 and self.select_device is True and
                self.tray is False and self.device_name is None):
            if self.debug is True:
                print('elif len(self.cclist) != 0 and self.select_device == True'
                      ' and self.tray == False:')
            if os.path.exists('/tmp/mkchromecast.tmp') is False:
                self.tf = open('/tmp/mkchromecast.tmp', 'wb')
                print(' ')
                print_available_devices(self.available_devices())
            else:
                if self.debug is True:
                    print('else:')
                self.tf = open('/tmp/mkchromecast.tmp', 'rb')
                self.index = pickle.load(self.tf)
                self.cast_to = self.cclist[int(self.index)]
                print(' ')
                print(colors.options('Casting to:') + ' ' +
                      colors.success(self.cast_to))
                print(' ')

        elif (len(self.cclist) != 0 and self.select_device is True and
                self.tray is True):
            if self.debug is True:
                print('elif len(self.cclist) != 0 and self.select_device == True'
                      '  and self.tray == True:')
            if os.path.exists('/tmp/mkchromecast.tmp') is False:
                self.tf = open('/tmp/mkchromecast.tmp', 'wb')
                print(' ')
                print_available_devices(self.available_devices())
            else:
                if self.debug is True:
                    print('else:')
                self.tf = open('/tmp/mkchromecast.tmp', 'rb')
                self.cast_to = pickle.load(self.tf)
                print_available_devices(self.available_devices())
                print(' ')
                print(colors.options('Casting to:') + ' ' +
                      colors.success(self.cast_to))
                print(' ')

        elif len(self.cclist) == 0 and self.tray is False:
            if self.debug is True:
                print('elif len(self.cclist) == 0 and self.tray == False:')
            print(colors.error('No devices found!'))
            if self.platform == 'Linux' and self.adevice is None:
                remove_sink()
            elif self.platform == 'Darwin':
                inputint()
                outputint()
            terminate()
            exit()

        elif len(self.cclist) == 0 and self.tray is True:
            print(colors.error(':::Tray::: No devices found!'))
            self.available_devices = []
Beispiel #17
0
    def initialize_cast(self):
        import mkchromecast.__init__            # This is to verify against some needed variables.
        from pychromecast import socket_client  # This fixes the `No handlers could be found for logger "pychromecast.socket_client` warning"`.
                                                # See commit 18005ebd4c96faccd69757bf3d126eb145687e0d.
        self.cclist = self._get_chromecasts()
        if self.debug == True:
            print('self.cclist', self.cclist)

        """
        This block was used for casting youtube with pychromecast, but it does not work
        """
        """
        try:
            self.youtubeurl = mkchromecast.__init__.youtubeurl
        except AttributeError:
            self.youtubeurl = None
        """

        if len(self.cclist) != 0 and self.select_cc == False and self.ccname == None:
            if self.debug == True:
                print('if len(self.cclist) != 0 and self.select_cc == False:')
            print(' ')
            print(colors.important('List of Google Cast devices available in your network:'))
            print(colors.important('------------------------------------------------------'))
            print(' ')
            print(colors.important('Index   Friendly name'))
            print(colors.important('=====   ============= '))
            for self.index,device in enumerate(self.cclist):
                try:
                    print(str(self.index)+'      ', str(device))
                except UnicodeEncodeError:
                    print(str(self.index)+'      ', str(unicode(device).encode("utf-8")))
            print(' ')
            if self.discover == False:
                print(colors.important('We will cast to first device in the list above!'))
                print(' ')
                self.cast_to = self.cclist[0]
                print(colors.success(self.cast_to))
                print(' ')

        elif len(self.cclist) != 0 and self.select_cc == True and self.tray == False and self.ccname == None:
            if self.debug == True:
                print('elif len(self.cclist) != 0 and self.select_cc == True and self.tray == False:')
            if os.path.exists('/tmp/mkchromecast.tmp') == False:
                self.tf = open('/tmp/mkchromecast.tmp', 'wb')
                print(' ')
                print(colors.important('List of Google Cast devices available in your network:'))
                print(colors.important('------------------------------------------------------'))
                print(' ')
                print(colors.important('Index   Friendly name'))
                print(colors.important('=====   ============= '))
                self.availablecc()
            else:
                if self.debug == True:
                    print('else:')
                self.tf = open('/tmp/mkchromecast.tmp', 'rb')
                self.index=pickle.load(self.tf)
                self.cast_to = self.cclist[int(self.index)]
                print(' ')
                print(colors.options('Casting to:')+' '+colors.success(self.cast_to))
                print(' ')

        elif len(self.cclist) != 0 and self.select_cc == True and self.tray == True:
            if self.debug == True:
                print('elif len(self.cclist) != 0 and self.select_cc == True and self.tray == True:')
            if os.path.exists('/tmp/mkchromecast.tmp') == False:
                self.tf = open('/tmp/mkchromecast.tmp', 'wb')
                print(' ')
                print(colors.important('List of Google Cast devices available in your network:'))
                print(colors.important('------------------------------------------------------'))
                print(' ')
                print(colors.important('Index   Friendly name'))
                print(colors.important('=====   ============= '))
                self.availablecc()
            else:
                if self.debug == True:
                    print('else:')
                self.tf = open('/tmp/mkchromecast.tmp', 'rb')
                self.cast_to=pickle.load(self.tf)
                self.availablecc()
                print(' ')
                print(colors.options('Casting to:')+' '+colors.success(self.cast_to))
                print(' ')

        elif len(self.cclist) == 0 and self.tray == False:
            if self.debug == True:
                print('elif len(self.cclist) == 0 and self.tray == False:')
            print(colors.error('No devices found!'))
            if self.platform == 'Linux' and self.adevice == None:
                from mkchromecast.pulseaudio import remove_sink
                remove_sink()
            elif self.platform == 'Darwin':
                inputint()
                outputint()
            terminate()
            exit()

        elif len(self.cclist) == 0 and self.tray == True:
            print(colors.error(':::Tray::: No devices found!'))
            self.availablecc = []
Beispiel #18
0
    def play_cast(self):
        if self.debug == True:
            print('def play_cast(self):')
        localip = self.ip

        print(colors.options('The IP of ')+colors.success(self.cast_to)+colors.options(' is:')+' '+self.cast.host)
        if self.host == None:
            print(colors.options('Your local IP is:')+' '+localip)
        else:
            print(colors.options('Your manually entered local IP is:')+' '+localip)

        """
        if self.youtubeurl != None:
            print(colors.options('The Youtube URL chosen:')+' '+self.youtubeurl)
            import pychromecast.controllers.youtube as youtube
            yt = youtube.YouTubeController()
            self.cast.register_handler(yt)

            try:
                import urlparse
                url_data = urlparse.urlparse(self.youtubeurl)
                query = urlparse.parse_qs(url_data.query)
            except ImportError:
                import urllib.parse
                url_data = urllib.parse.urlparse(self.youtubeurl)
                query = urllib.parse.parse_qs(url_data.query)
            video = query["v"][0]
            print(colors.options('Playing video:')+' '+video)
            yt.play_video(video)
        else:
        """
        media_controller = self.cast.media_controller

        if self.tray == True:
            config = ConfigParser.RawConfigParser()
            configurations = config_manager()    # Class from mkchromecast.config
            configf = configurations.configf

            if os.path.exists(configf) and self.tray == True:
                print(tray)
                print(colors.warning('Configuration file exists'))
                print(colors.warning('Using defaults set there'))
                config.read(configf)
                self.backend = ConfigSectionMap('settings')['backend']

        if self.sourceurl != None:
            if args.video == True:
                import mkchromecast.video
                mtype = mkchromecast.video.mtype
            else:
                import mkchromecast.audio
                mtype = mkchromecast.audio.mtype
            print(' ')
            print(colors.options('Casting from stream URL:')+' '+self.sourceurl)
            print(colors.options('Using media type:')+' '+mtype)
            media_controller.play_media(self.sourceurl, mtype, title = self.title)
        elif (self.backend == 'ffmpeg' or self.backend == 'node' or self.backend == 'avconv' or
                self.backend == 'parec' or self.backend == 'gstreamer' and self.sourceurl == None):
            if args.video == True:
                import mkchromecast.video
                mtype = mkchromecast.video.mtype
            else:
                import mkchromecast.audio
                mtype = mkchromecast.audio.mtype
            print(' ')
            print(colors.options('The media type string used is:')+' '+mtype)
            media_controller.play_media('http://'+localip+':5000/stream', mtype, title = self.title)
        print(' ')
        print(colors.important('Cast media controller status'))
        print(' ')
        print(self.cast.status)
        print(' ')
        if self.reconnect == True:
            self.r = Thread(target = self.reconnect_cc)
            self.r.daemon = True   # This has to be set to True so that we catch KeyboardInterrupt.
            self.r.start()
Beispiel #19
0
codecs = ['mp3', 'ogg', 'aac', 'opus', 'wav', 'flac']

if backend == 'node' and args.codec != 'mp3' and source_url is None:
    rcodec = args.codec
    codec = 'mp3'
elif backend == 'node' and args.codec == 'mp3' and source_url is None:
    rcodec = args.codec
    codec = 'mp3'
elif source_url is not None:
    codec = args.codec
else:
    rcodec = None
    if backend != 'node' and args.codec in codecs:
        codec = args.codec
    else:
        print(colors.options('Selected audio codec: %s.') % args.codec)
        print(colors.error('Supported audio codecs are: '))
        for codec in codecs:
            print('- %s.' % codec)
        sys.exit(0)
"""
Loop
"""
loop = args.loop

if args.loop is True and args.video is True:
    print(
        colors.warning('The %s backend is not supported.') %
        args.encoder_backend)
"""
Command
Beispiel #20
0
codecs = ["mp3", "ogg", "aac", "opus", "wav", "flac"]

if backend == "node" and args.codec != "mp3" and source_url is None:
    rcodec = args.codec
    codec = "mp3"
elif backend == "node" and args.codec == "mp3" and source_url is None:
    rcodec = args.codec
    codec = "mp3"
elif source_url is not None:
    codec = args.codec
else:
    rcodec = None
    if backend != "node" and args.codec in codecs:
        codec = args.codec
    else:
        print(colors.options("Selected audio codec: %s.") % args.codec)
        print(colors.error("Supported audio codecs are: "))
        for codec in codecs:
            print("- %s." % codec)
        sys.exit(0)

"""
Loop
"""
loop = args.loop

if args.loop is True and args.video is True:
    print(colors.warning("The %s backend is not supported.") % args.encoder_backend)

"""
Command
Beispiel #21
0
    ]

if backend == 'node' and args.codec != 'mp3' and source_url is None:
    rcodec = args.codec
    codec = 'mp3'
elif backend == 'node' and args.codec == 'mp3' and source_url is None:
    rcodec = args.codec
    codec = 'mp3'
elif source_url is not None:
    codec = args.codec
else:
    rcodec = None
    if backend != 'node' and args.codec in codecs:
        codec = args.codec
    else:
        print(colors.options('Selected audio codec: %s.') % args.codec)
        print(colors.error('Supported audio codecs are: '))
        for codec in codecs:
            print('- %s.' % codec)
        sys.exit(0)

"""
Loop
"""
loop = args.loop

if args.loop is True and args.video is True:
    print(colors.warning('The %s backend is not supported.')
          % args.encoder_backend)

"""
Beispiel #22
0
def samplerate_default(samplerate):
    """Sample rate messages
    Printing default sample rate message"""
    if source_url is None:
        print(colors.options("Default sample rate used:") + " " + samplerate + "Hz.")
    return
Beispiel #23
0
    def play_cast(self):
        if self.debug is True:
            print("def play_cast(self):")
        localip = self.ip

        try:
            print(
                colors.options("The IP of ") + colors.success(self.cast_to) +
                colors.options(" is:") + " " + self.cast.host)
        except TypeError:
            print(
                colors.options("The IP of ") +
                colors.success(self.cast_to.player_name) +
                colors.options(" is:") + " " + self.cast_to.ip_address)
        except AttributeError:
            for _ in self.sonos_list:
                if self.cast_to == _.coordinator.player_name:
                    self.cast_to = _
            print(
                colors.options("The IP of ") +
                colors.success(self.cast_to.coordinator.player_name) +
                colors.options(" is:") + " " +
                self.cast_to.coordinator.ip_address)

        if self.host is None:
            print(colors.options("Your local IP is:") + " " + localip)
        else:
            print(
                colors.options("Your manually entered local IP is:") + " " +
                localip)

        try:
            media_controller = self.cast.media_controller

            if self.tray is True:
                config = ConfigParser.RawConfigParser()
                # Class from mkchromecast.config
                from mkchromecast.config import config_manager

                configurations = config_manager()
                configf = configurations.configf

                if os.path.exists(configf) and self.tray is True:
                    print(self.tray)
                    print(colors.warning("Configuration file exists"))
                    print(colors.warning("Using defaults set there"))
                    config.read(configf)
                    self.backend = ConfigSectionMap("settings")["backend"]

            if self.source_url is not None:
                if args.video is True:
                    import mkchromecast.video

                    mtype = mkchromecast.video.mtype
                else:
                    import mkchromecast.audio

                    mtype = mkchromecast.audio.mtype
                print(" ")
                print(
                    colors.options("Casting from stream URL:") + " " +
                    self.source_url)
                print(colors.options("Using media type:") + " " + mtype)
                media_controller.play_media(self.source_url,
                                            mtype,
                                            title=self.title,
                                            stream_type="LIVE")
                media_controller.play()
            elif (self.backend == "ffmpeg" or self.backend == "node"
                  or self.backend == "avconv" or self.backend == "parec"
                  or self.backend == "gstreamer" and self.source_url is None):
                if args.video is True:
                    import mkchromecast.video

                    mtype = mkchromecast.video.mtype
                else:
                    import mkchromecast.audio

                    mtype = mkchromecast.audio.mtype
                print(" ")
                print(
                    colors.options("The media type string used is:") + " " +
                    mtype)
                media_controller.play_media(
                    "http://" + localip + ":" + self.port + "/stream",
                    mtype,
                    title=self.title,
                    stream_type="LIVE",
                )

            if media_controller.is_active:
                media_controller.play()

            print(" ")
            print(colors.important("Cast media controller status"))
            print(" ")
            print(self.cast.status)
            print(" ")

            time.sleep(5.0)
            media_controller.play()

            if self.hijack is True:
                self.r = Thread(target=self.hijack_cc)
                # This has to be set to True so that we catch
                # KeyboardInterrupt.
                self.r.daemon = True
                self.r.start()

        except AttributeError:
            self.sonos = self.cast_to
            self.sonos.coordinator.play_uri(
                "x-rincon-mp3radio://" + localip + ":" + self.port + "/stream",
                title=self.title,
            )
            if self.tray is True:
                self.cast = self.sonos
Beispiel #24
0
def streaming():
    """
    Configuration files
    """
    platform = mkchromecast.__init__.platform
    tray = mkchromecast.__init__.tray
    debug = mkchromecast.__init__.debug
    config = ConfigParser.RawConfigParser()
    # Class from mkchromecast.config
    configurations = config_manager()
    configf = configurations.configf

    if os.path.exists(configf) and tray is True:
        configurations.chk_config()
        print(colors.warning("Configuration file exists"))
        print(colors.warning("Using defaults set there"))
        config.read(configf)
        backend = ConfigSectionMap("settings")["backend"]
        rcodec = ConfigSectionMap("settings")["codec"]
        bitrate = ConfigSectionMap("settings")["bitrate"]
        samplerate = ConfigSectionMap("settings")["samplerate"]
        notifications = ConfigSectionMap("settings")["notifications"]
    else:
        backend = mkchromecast.__init__.backend
        rcodec = mkchromecast.__init__.rcodec
        codec = mkchromecast.__init__.codec
        bitrate = str(mkchromecast.__init__.bitrate)
        samplerate = str(mkchromecast.__init__.samplerate)
        notifications = mkchromecast.__init__.notifications

    print(colors.options("Selected backend:") + " " + backend)

    if debug is True:
        print(
            ":::node::: variables %s, %s, %s, %s, %s"
            % (backend, rcodec, bitrate, samplerate, notifications)
        )

    try:
        youtube_url = mkchromecast.__init__.youtube_url
    except AttributeError:
        youtube_url = None

    if youtube_url is None:
        if backend == "node" and rcodec != "mp3":
            print(
                colors.warning(
                    "Codec " + rcodec + " is not supported by the node server!"
                )
            )
            print("Using " + codec + " as default.")

        if backend == "node":
            if int(bitrate) == 192:
                print(colors.options("Default bitrate used:") + " " + bitrate + "k.")
            elif int(bitrate) > 500:
                print(
                    colors.warning("Maximum bitrate supported by " + codec + " is:")
                    + " "
                    + str(500)
                    + "k."
                )
                bitrate = "500"
                print(colors.warning("Bitrate has been set to maximum!"))
            else:
                print(colors.options("Selected bitrate: ") + bitrate + "k.")

            if samplerate == "44100":
                print(
                    colors.options("Default sample rate used:")
                    + " "
                    + samplerate
                    + "Hz."
                )
            else:
                codecs_sr = ["mp3", "ogg", "aac", "wav", "flac"]

                """
                The codecs below do not support 96000Hz
                """
                no96k = ["mp3", "ogg"]

                if (
                    codec in codecs_sr
                    and int(samplerate) > 22000
                    and int(samplerate) <= 27050
                ):
                    samplerate = "22050"
                    msg.samplerate_no96(codec)

                if (
                    codec in codecs_sr
                    and int(samplerate) > 27050
                    and int(samplerate) <= 32000
                ):
                    samplerate = "32000"
                    msg.samplerate_no96(codec)

                elif (
                    codec in codecs_sr
                    and int(samplerate) > 32000
                    and int(samplerate) <= 36000
                ):
                    samplerate = "32000"
                    msg.samplerate_no96(codec)

                elif (
                    codec in codecs_sr
                    and int(samplerate) > 36000
                    and int(samplerate) <= 43000
                ):
                    samplerate = "44100"
                    msg.samplerate_no96(codec)
                    print(
                        colors.warning(
                            "Sample rate has been set to \
                        default!"
                        )
                    )

                elif (
                    codec in codecs_sr
                    and int(samplerate) > 43000
                    and int(samplerate) <= 72000
                ):
                    samplerate = "48000"
                    msg.samplerate_no96(codec)

                elif codec in codecs_sr and int(samplerate) > 72000:
                    if codec in no96k:
                        msg.samplerate_no96(codec)
                        samplerate = "48000"
                    print(
                        colors.warning(
                            "Sample rate has been set to \
                        maximum!"
                        )
                    )

                print(colors.options("Sample rate set to:") + " " + samplerate + "Hz.")

    """
    Node section
    """
    paths = ["/usr/local/bin/node", "./bin/node", "./nodejs/bin/node"]

    for path in paths:
        if os.path.exists(path) is True:
            webcast = [
                path,
                "./nodejs/node_modules/webcast-osx-audio/bin/webcast.js",
                "-b",
                bitrate,
                "-s",
                samplerate,
                "-p",
                "5000",
                "-u",
                "stream",
            ]
            break
    else:
        webcast = None
        print(colors.warning("Node is not installed..."))
        print(
            colors.warning("Use your package manager or their official " "installer...")
        )
        pass

    if webcast is not None:
        p = subprocess.Popen(webcast)

        if debug is True:
            print(":::node::: node command: %s." % webcast)

        f = open("/tmp/mkchromecast.pid", "rb")
        pidnumber = int(pickle.load(f))
        print(colors.options("PID of main process:") + " " + str(pidnumber))

        localpid = getpid()
        print(colors.options("PID of streaming process: ") + str(localpid))

        while p.poll() is None:
            try:
                time.sleep(0.5)
                # With this I ensure that if the main app fails, everything
                # will get back to normal
                if psutil.pid_exists(pidnumber) is False:
                    inputint()
                    outputint()
                    parent = psutil.Process(localpid)
                    # or parent.children() for recursive=False
                    for child in parent.children(recursive=True):
                        child.kill()
                    parent.kill()
            except KeyboardInterrupt:
                print("Ctrl-c was requested")
                sys.exit(0)
            except IOError:
                print("I/O Error")
                sys.exit(0)
            except OSError:
                print("OSError")
                sys.exit(0)
        else:
            print(colors.warning("Reconnecting node streaming..."))
            if platform == "Darwin" and notifications == "enabled":
                if os.path.exists("images/google.icns") is True:
                    noticon = "images/google.icns"
                else:
                    noticon = "google.icns"
            if debug is True:
                print(
                    ":::node::: platform, tray, notifications: %s, %s, %s."
                    % (platform, tray, notifications)
                )

            if platform == "Darwin" and tray is True and notifications == "enabled":
                reconnecting = [
                    "./notifier/terminal-notifier.app/Contents/MacOS/terminal-notifier",
                    "-group",
                    "cast",
                    "-contentImage",
                    noticon,
                    "-title",
                    "mkchromecast",
                    "-subtitle",
                    "node server failed",
                    "-message",
                    "Reconnecting...",
                ]
                subprocess.Popen(reconnecting)

                if debug is True:
                    print(
                        ":::node::: reconnecting notifier command: %s." % reconnecting
                    )
            relaunch(stream, recasting, kill)
        return
Beispiel #25
0
    print(":::audio::: chunk_size, frame_size, buffer_size: %s, %s, %s" %
          (chunk_size, frame_size, buffer_size))
source_url = mkchromecast.__init__.source_url
config = ConfigParser.RawConfigParser()
configurations = config_manager()  # Class from mkchromecast.config
configf = configurations.configf
appendtourl = "stream"

try:
    youtube_url = mkchromecast.__init__.youtube_url
except AttributeError:
    youtube_url = None

# This is to take the youtube URL
if youtube_url is not None:
    print(colors.options("The Youtube URL chosen: ") + youtube_url)

    try:
        import urlparse

        url_data = urlparse.urlparse(youtube_url)
        query = urlparse.parse_qs(url_data.query)
    except ImportError:
        import urllib.parse

        url_data = urllib.parse.urlparse(youtube_url)
        query = urllib.parse.parse_qs(url_data.query)
    video = query["v"][0]
    print(colors.options("Playing video:") + " " + video)
    command = ["youtube-dl", "-o", "-", youtube_url]
    mtype = "audio/mp4"
Beispiel #26
0
    def initialize_cast(self):
        # This fixes the `No handlers could be found for logger
        # "pychromecast.socket_client` warning"`.
        # See commit 18005ebd4c96faccd69757bf3d126eb145687e0d.
        from pychromecast import socket_client
        self.cclist = self._get_chromecasts()
        self.cclist = [[i, _, 'Gcast'] for i, _ in enumerate(self.cclist)]

        if sonos is True:
            try:
                self.sonos_list = list(soco.discover())
                for self.index, device in enumerate(self.sonos_list):
                    add_sonos = [self.index, device, 'Sonos']
                    self.cclist.append(add_sonos)
            except TypeError:
                pass

        if self.debug is True:
            print('self.cclist', self.cclist)

        if (len(self.cclist) != 0 and self.select_cc is False
                and self.ccname is None):
            if self.debug is True:
                print('if len(self.cclist) != 0 and self.select_cc == False:')
            print(' ')
            print(colors.important('List of Devices Available in Network:'))
            print(colors.important('-------------------------------------\n'))
            print(colors.important('Index   Types   Friendly Name '))
            print(colors.important('=====   =====   ============= '))
            self.availablecc()
            print(' ')
            if self.discover is False:
                print(colors.important('Casting to first device shown above!'))
                print(colors.important('Select devices by using the -s flag.'))
                print(' ')
                self.cast_to = self.cclist[0][1]
                if self.cclist[0][2] == 'Sonos':
                    print(colors.success(self.cast_to.player_name))
                else:
                    print(colors.success(self.cast_to))
                print(' ')

        elif (len(self.cclist) != 0 and self.select_cc is True
              and self.tray is False and self.ccname is None):
            if self.debug is True:
                print('elif len(self.cclist) != 0 and self.select_cc == True'
                      ' and self.tray == False:')
            if os.path.exists('/tmp/mkchromecast.tmp') is False:
                self.tf = open('/tmp/mkchromecast.tmp', 'wb')
                print(' ')
                print(
                    colors.important('List of Devices Available in Network:'))
                print(
                    colors.important(
                        '-------------------------------------\n'))
                print(colors.important('Index   Types   Friendly Name '))
                print(colors.important('=====   =====   ============= '))
                self.availablecc()
            else:
                if self.debug is True:
                    print('else:')
                self.tf = open('/tmp/mkchromecast.tmp', 'rb')
                self.index = pickle.load(self.tf)
                self.cast_to = self.cclist[int(self.index)]
                print(' ')
                print(
                    colors.options('Casting to:') + ' ' +
                    colors.success(self.cast_to))
                print(' ')

        elif (len(self.cclist) != 0 and self.select_cc is True
              and self.tray is True):
            if self.debug is True:
                print('elif len(self.cclist) != 0 and self.select_cc == True'
                      '  and self.tray == True:')
            if os.path.exists('/tmp/mkchromecast.tmp') is False:
                self.tf = open('/tmp/mkchromecast.tmp', 'wb')
                print(' ')
                print(
                    colors.important('List of Devices Available in Network:'))
                print(
                    colors.important(
                        '-------------------------------------\n'))
                print(colors.important('Index   Types   Friendly Name '))
                print(colors.important('=====   =====   ============= '))
                self.availablecc()
            else:
                if self.debug is True:
                    print('else:')
                self.tf = open('/tmp/mkchromecast.tmp', 'rb')
                self.cast_to = pickle.load(self.tf)
                self.availablecc()
                print(' ')
                print(
                    colors.options('Casting to:') + ' ' +
                    colors.success(self.cast_to))
                print(' ')

        elif len(self.cclist) == 0 and self.tray is False:
            if self.debug is True:
                print('elif len(self.cclist) == 0 and self.tray == False:')
            print(colors.error('No devices found!'))
            if self.platform == 'Linux' and self.adevice is None:
                remove_sink()
            elif self.platform == 'Darwin':
                inputint()
                outputint()
            terminate()
            exit()

        elif len(self.cclist) == 0 and self.tray is True:
            print(colors.error(':::Tray::: No devices found!'))
            self.availablecc = []
Beispiel #27
0
    def play_cast(self):
        if self.debug is True:
            print('def play_cast(self):')
        localip = self.ip

        try:
            print(
                colors.options('The IP of ') + colors.success(self.cast_to) +
                colors.options(' is:') + ' ' + self.cast.host)
        except TypeError:
            print(
                colors.options('The IP of ') +
                colors.success(self.cast_to.player_name) +
                colors.options(' is:') + ' ' + self.cast_to.ip_address)
        except AttributeError:
            for _ in self.sonos_list:
                if self.cast_to in _.player_name:
                    self.cast_to = _
            print(
                colors.options('The IP of ') +
                colors.success(self.cast_to.player_name) +
                colors.options(' is:') + ' ' + self.cast_to.ip_address)

        if self.host is None:
            print(colors.options('Your local IP is:') + ' ' + localip)
        else:
            print(
                colors.options('Your manually entered local IP is:') + ' ' +
                localip)

        try:
            media_controller = self.cast.media_controller

            if self.tray is True:
                config = ConfigParser.RawConfigParser()
                # Class from mkchromecast.config
                from mkchromecast.config import config_manager
                configurations = config_manager()
                configf = configurations.configf

                if os.path.exists(configf) and self.tray is True:
                    print(self.tray)
                    print(colors.warning('Configuration file exists'))
                    print(colors.warning('Using defaults set there'))
                    config.read(configf)
                    self.backend = ConfigSectionMap('settings')['backend']

            if self.sourceurl is not None:
                if args.video is True:
                    import mkchromecast.video
                    mtype = mkchromecast.video.mtype
                else:
                    import mkchromecast.audio
                    mtype = mkchromecast.audio.mtype
                print(' ')
                print(
                    colors.options('Casting from stream URL:') + ' ' +
                    self.sourceurl)
                print(colors.options('Using media type:') + ' ' + mtype)
                media_controller.play_media(self.sourceurl,
                                            mtype,
                                            title=self.title)
            elif (self.backend == 'ffmpeg' or self.backend == 'node'
                  or self.backend == 'avconv' or self.backend == 'parec'
                  or self.backend == 'gstreamer' and self.sourceurl is None):
                if args.video is True:
                    import mkchromecast.video
                    mtype = mkchromecast.video.mtype
                else:
                    import mkchromecast.audio
                    mtype = mkchromecast.audio.mtype
                print(' ')
                print(
                    colors.options('The media type string used is:') + ' ' +
                    mtype)
                media_controller.play_media('http://' + localip + ':' +
                                            self.port + '/stream',
                                            mtype,
                                            title=self.title)
            print(' ')
            print(colors.important('Cast media controller status'))
            print(' ')
            print(self.cast.status)
            print(' ')
            if self.hijack is True:
                self.r = Thread(target=self.hijack_cc)
                # This has to be set to True so that we catch
                # KeyboardInterrupt.
                self.r.daemon = True
                self.r.start()
        except AttributeError:
            self.sonos = self.cast_to
            self.sonos.play_uri('x-rincon-mp3radio://' + localip + ':' +
                                self.port + '/stream',
                                title=self.title)
            if self.tray is True:
                self.cast = self.sonos
Beispiel #28
0
    def initialize_cast(self):
        # This fixes the `No handlers could be found for logger
        # "pychromecast.socket_client` warning"`.
        # See commit 18005ebd4c96faccd69757bf3d126eb145687e0d.
        if chromecast:
            from pychromecast import socket_client

            self.cclist = self._get_chromecasts()
            self.cclist = [[i, _, "Gcast"] for i, _ in enumerate(self.cclist)]
        else:
            self.cclist = []

        if sonos:
            try:
                # Checking groups
                zone = soco.discovery.any_soco()

                self.sonos_list = zone.all_groups

                for self.index, group in enumerate(self.sonos_list):
                    add_sonos = [self.index, group.coordinator, "Sonos"]
                    self.cclist.append(add_sonos)
            except (TypeError, AttributeError):
                pass

        if self.debug is True:
            print("self.cclist", self.cclist)

        if (len(self.cclist) != 0 and self.select_device is False
                and self.device_name is None):
            if self.debug is True:
                print(
                    "if len(self.cclist) != 0 and self.select_device == False:"
                )
            print(" ")
            print_available_devices(self.available_devices())
            print(" ")
            if self.discover is False:
                print(colors.important("Casting to first device shown above!"))
                print(colors.important("Select devices by using the -s flag."))
                print(" ")
                self.cast_to = self.cclist[0][1]
                if self.cclist[0][2] == "Sonos":
                    print(colors.success(self.cast_to.coordinator.player_name))
                else:
                    print(colors.success(self.cast_to))
                print(" ")

        elif (len(self.cclist) != 0 and self.select_device is True
              and self.tray is False and self.device_name is None):
            if self.debug is True:
                print(
                    "elif len(self.cclist) != 0 and self.select_device == True"
                    " and self.tray == False:")
            if os.path.exists("/tmp/mkchromecast.tmp") is False:
                self.tf = open("/tmp/mkchromecast.tmp", "wb")
                print(" ")
                print_available_devices(self.available_devices())
            else:
                if self.debug is True:
                    print("else:")
                self.tf = open("/tmp/mkchromecast.tmp", "rb")
                self.index = pickle.load(self.tf)
                self.cast_to = self.cclist[int(self.index)]
                print(" ")
                print(
                    colors.options("Casting to:") + " " +
                    colors.success(self.cast_to))
                print(" ")

        elif len(self.cclist
                 ) != 0 and self.select_device is True and self.tray is True:
            if self.debug is True:
                print(
                    "elif len(self.cclist) != 0 and self.select_device == True"
                    "  and self.tray == True:")
            if os.path.exists("/tmp/mkchromecast.tmp") is False:
                self.tf = open("/tmp/mkchromecast.tmp", "wb")
                print(" ")
                print_available_devices(self.available_devices())
            else:
                if self.debug is True:
                    print("else:")
                self.tf = open("/tmp/mkchromecast.tmp", "rb")
                self.cast_to = pickle.load(self.tf)
                print_available_devices(self.available_devices())
                print(" ")
                print(
                    colors.options("Casting to:") + " " +
                    colors.success(self.cast_to))
                print(" ")

        elif len(self.cclist) == 0 and self.tray is False:
            if self.debug is True:
                print("elif len(self.cclist) == 0 and self.tray == False:")
            print(colors.error("No devices found!"))
            if self.platform == "Linux" and self.adevice is None:
                remove_sink()
            elif self.platform == "Darwin":
                inputint()
                outputint()
            terminate()
            exit()

        elif len(self.cclist) == 0 and self.tray is True:
            print(colors.error(":::Tray::: No devices found!"))
            self.available_devices = []
Beispiel #29
0
    def initialize_cast(self):
        import mkchromecast.__init__  # This is to verify against some needed variables.
        from pychromecast import socket_client  # This fixes the `No handlers could be found for logger "pychromecast.socket_client` warning"`.
        # See commit 18005ebd4c96faccd69757bf3d126eb145687e0d.
        self.cclist = self._get_chromecasts()
        self.cclist = [[index, _, 'Gcast']
                       for index, _ in enumerate(self.cclist)]

        if sonos == True:
            try:
                self.sonos_list = list(soco.discover())
                length = len(self.cclist)
                for self.index, device in enumerate(self.sonos_list):
                    add_sonos = [self.index, device, 'Sonos']
                    self.cclist.append(add_sonos)
            except TypeError:
                pass

        if self.debug == True:
            print('self.cclist', self.cclist)
        """
        This block was used for casting youtube with pychromecast, but it does not work
        """
        """
        try:
            self.youtubeurl = mkchromecast.__init__.youtubeurl
        except AttributeError:
            self.youtubeurl = None
        """

        if (len(self.cclist) != 0 and self.select_cc == False
                and self.ccname == None):
            if self.debug == True:
                print('if len(self.cclist) != 0 and self.select_cc == False:')
            print(' ')
            print(
                colors.important('List of Devices Available in your Network:'))
            print(
                colors.important(
                    '------------------------------------------\n'))
            print(colors.important('Index \tTypes \tFriendly Name '))
            print(colors.important('===== \t===== \t============= '))
            self.availablecc()
            print(' ')
            if self.discover == False:
                print(
                    colors.important(
                        'We will cast to first device in the list above!'))
                print(' ')
                self.cast_to = self.cclist[0][1]
                print(colors.success(self.cast_to))
                print(' ')

        elif (len(self.cclist) != 0 and self.select_cc == True
              and self.tray == False and self.ccname == None):
            if self.debug == True:
                print(
                    'elif len(self.cclist) != 0 and self.select_cc == True and self.tray == False:'
                )
            if os.path.exists('/tmp/mkchromecast.tmp') == False:
                self.tf = open('/tmp/mkchromecast.tmp', 'wb')
                print(' ')
                print(
                    colors.important(
                        'List of Devices Available in your Network:'))
                print(
                    colors.important(
                        '------------------------------------------\n'))
                print(colors.important('Index \tTypes \tFriendly Name '))
                print(colors.important('===== \t===== \t============= '))
                self.availablecc()
            else:
                if self.debug == True:
                    print('else:')
                self.tf = open('/tmp/mkchromecast.tmp', 'rb')
                self.index = pickle.load(self.tf)
                self.cast_to = self.cclist[int(self.index)]
                print(' ')
                print(
                    colors.options('Casting to:') + ' ' +
                    colors.success(self.cast_to))
                print(' ')

        elif (len(self.cclist) != 0 and self.select_cc == True
              and self.tray == True):
            if self.debug == True:
                print(
                    'elif len(self.cclist) != 0 and self.select_cc == True and self.tray == True:'
                )
            if os.path.exists('/tmp/mkchromecast.tmp') == False:
                self.tf = open('/tmp/mkchromecast.tmp', 'wb')
                print(' ')
                print(
                    colors.important(
                        'List of Devices Available in your Network:'))
                print(
                    colors.important(
                        '------------------------------------------\n'))
                print(colors.important('Index \tTypes \tFriendly Name '))
                print(colors.important('===== \t===== \t============= '))
                self.availablecc()
            else:
                if self.debug == True:
                    print('else:')
                self.tf = open('/tmp/mkchromecast.tmp', 'rb')
                self.cast_to = pickle.load(self.tf)
                self.availablecc()
                print(' ')
                print(
                    colors.options('Casting to:') + ' ' +
                    colors.success(self.cast_to))
                print(' ')

        elif len(self.cclist) == 0 and self.tray == False:
            if self.debug == True:
                print('elif len(self.cclist) == 0 and self.tray == False:')
            print(colors.error('No devices found!'))
            if self.platform == 'Linux' and self.adevice == None:
                remove_sink()
            elif self.platform == 'Darwin':
                inputint()
                outputint()
            terminate()
            exit()

        elif len(self.cclist) == 0 and self.tray == True:
            print(colors.error(':::Tray::: No devices found!'))
            self.availablecc = []