Esempio n. 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)
Esempio n. 2
0
 def get_devices(self):
     if self.debug is True:
         print("def get_devices(self):")
     if chromecast:
         try:
             if self.device_name is not None:
                 self.cast_to = self.device_name
             self.cast = self._get_chromecast(self.cast_to)
             # Wait for cast device to be ready
             self.cast.wait()
             print(" ")
             print(
                 colors.important("Information about ")
                 + " "
                 + colors.success(self.cast_to)
             )
             print(" ")
             print(self.cast.device)
             print(" ")
             print(
                 colors.important("Status of device ")
                 + " "
                 + colors.success(self.cast_to)
             )
             print(" ")
             print(self.cast.status)
             print(" ")
         except pychromecast.error.NoChromecastFoundError:
             print(
                 colors.error(
                     "No Chromecasts matching filter criteria" " were found!"
                 )
             )
             if self.platform == "Darwin":
                 inputint()
                 outputint()
             elif self.platform == "Linux":
                 remove_sink()
             # In the case that the tray is used, we don't kill the
             # application
             if self.tray is False:
                 print(colors.error("Finishing the application..."))
                 terminate()
                 exit()
             else:
                 self.stop_cast()
         except AttributeError:
             pass
         except KeyError:
             pass
Esempio n. 3
0
 def get_cc(self):
     if self.debug is True:
         print('def get_cc(self):')
     try:
         if self.ccname is not None:
             self.cast_to = self.ccname
         self.cast = self._get_chromecast(self.cast_to)
         # Wait for cast device to be ready
         self.cast.wait()
         print(' ')
         print(
             colors.important('Information about ') + ' ' +
             colors.success(self.cast_to))
         print(' ')
         print(self.cast.device)
         print(' ')
         print(
             colors.important('Status of device ') + ' ' +
             colors.success(self.cast_to))
         print(' ')
         print(self.cast.status)
         print(' ')
     except pychromecast.error.NoChromecastFoundError:
         print(
             colors.error('No Chromecasts matching filter criteria'
                          ' were found!'))
         if self.platform == 'Darwin':
             inputint()
             outputint()
         elif self.platform == 'Linux':
             remove_sink()
         # In the case that the tray is used, we don't kill the application
         if self.tray is False:
             print(colors.error('Finishing the application...'))
             terminate()
             exit()
         else:
             self.stop_cast()
     except AttributeError:
         pass
     except KeyError:
         pass
Esempio n. 4
0
    def hijack_cc(self):
        """Dummy method to call  _hijack_cc_().

        In the cast that the self.r thread is alive, we check that the
        chromecast is connected. If it is connected, we check again in
        5 seconds.
        """
        try:
            while self.r.is_alive():
                self._hijack_cc_()
                # FIXME: I think that this has to be set by users.
                time.sleep(5)
        except KeyboardInterrupt:
            self.stop_cast()
            if self.platform == "Darwin":
                inputint()
                outputint()
            elif self.platform == "Linux" and self.adevice is None:
                remove_sink()
            terminate()
Esempio n. 5
0
    def hijack_cc(self):
        """Dummy method to call  _hijack_cc_().

        In the cast that the self.r thread is alive, we check that the
        chromecast is connected. If it is connected, we check again in
        5 seconds.
        """
        try:
            while self.r.is_alive():
                self._hijack_cc_()
                # FIXME: I think that this has to be set by users.
                time.sleep(5)
        except KeyboardInterrupt:
            self.stop_cast()
            if self.platform == 'Darwin':
                inputint()
                outputint()
            elif self.platform == 'Linux' and self.adevice is None:
                remove_sink()
            terminate()
Esempio n. 6
0
 def get_devices(self):
     if self.debug is True:
         print('def get_devices(self):')
     if chromecast:
         try:
             if self.device_name is not None:
                 self.cast_to = self.device_name
             self.cast = self._get_chromecast(self.cast_to)
             # Wait for cast device to be ready
             self.cast.wait()
             print(' ')
             print(colors.important('Information about ') + ' ' +
                   colors.success(self.cast_to))
             print(' ')
             print(self.cast.device)
             print(' ')
             print(colors.important('Status of device ') + ' ' +
                   colors.success(self.cast_to))
             print(' ')
             print(self.cast.status)
             print(' ')
         except pychromecast.error.NoChromecastFoundError:
             print(colors.error('No Chromecasts matching filter criteria'
                                ' were found!'))
             if self.platform == 'Darwin':
                 inputint()
                 outputint()
             elif self.platform == 'Linux':
                 remove_sink()
             # In the case that the tray is used, we don't kill the
             # application
             if self.tray is False:
                 print(colors.error('Finishing the application...'))
                 terminate()
                 exit()
             else:
                 self.stop_cast()
         except AttributeError:
             pass
         except KeyError:
             pass
Esempio n. 7
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 = []
Esempio n. 8
0
sonos_device = args.sonos_device
port = args.port


if debug is True:
    print("Google Cast name: %s." % device_name)

"""
Check that input file exists
"""
if input_file != None and os.path.isfile(input_file) is False:
    if platform == "Darwin":
        from mkchromecast.audio_devices import inputint, outputint

        inputint()
        outputint()
    else:
        from mkchromecast.pulseaudio import remove_sink

        remove_sink()

    print(colors.warning("File not found!"))
    terminate()

"""
Media-Type
"""
mtype = args.mtype

if args.mtype is not None and args.video is False:
    print(
Esempio n. 9
0
hijack = args.hijack
device_name = args.name
port = args.port


if debug is True:
    print('Google Cast name: %s.' % device_name)

"""
Check that input file exists
"""
if input_file != None and os.path.isfile(input_file) is False:
    if platform == 'Darwin':
        from mkchromecast.audio_devices import inputint, outputint
        inputint()
        outputint()
    else:
        from mkchromecast.pulseaudio import remove_sink
        remove_sink()

    print(colors.warning('File not found!'))
    terminate()

"""
Media-Type
"""
mtype = args.mtype

if args.mtype is not None and args.video is False:
    print(colors.warning('The media type is not supported for audio.')
          % args.encoder_backend)
Esempio n. 10
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 = []
Esempio n. 11
0
 def reset_audio(self):
     if platform == 'Darwin':
         inputint()
         outputint()
     else:
         remove_sink()
Esempio n. 12
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
Esempio n. 13
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
Esempio n. 14
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 = []
Esempio n. 15
0
 def reset_audio(self):
     if platform == 'Darwin':
         inputint()
         outputint()
     else:
         remove_sink()