Ejemplo n.º 1
0
 def run(self) -> None:
     from ba import _lang
     from ba._general import Call
     try:
         _ba.set_thread_name('BA_PickFolderSongThread')
         all_files: List[str] = []
         valid_extensions = ['.' + x for x in self._valid_extensions]
         for root, _subdirs, filenames in os.walk(self._path):
             for fname in filenames:
                 if any(fname.lower().endswith(ext)
                        for ext in valid_extensions):
                     all_files.insert(random.randrange(len(all_files) + 1),
                                      root + '/' + fname)
         if not all_files:
             raise Exception(
                 _lang.Lstr(resource='internal.noMusicFilesInFolderText').
                 evaluate())
         _ba.pushcall(Call(self._callback, all_files, None),
                      from_other_thread=True)
     except Exception as exc:
         from ba import _error
         _error.print_exception()
         try:
             err_str = str(exc)
         except Exception:
             err_str = '<ENCERR4523>'
         _ba.pushcall(Call(self._callback, self._path, err_str),
                      from_other_thread=True)
Ejemplo n.º 2
0
    def run(self) -> None:
        import urllib.request
        import urllib.error
        import json
        from ba import _general
        try:
            self._data = _general.utf8_all(self._data)
            _ba.set_thread_name("BA_ServerCallThread")

            # Seems pycharm doesn't know about urllib.parse.
            # noinspection PyUnresolvedReferences
            parse = urllib.parse
            if self._request_type == 'get':
                response = urllib.request.urlopen(
                    urllib.request.Request(
                        (_ba.get_master_server_address() + '/' +
                         self._request + '?' + parse.urlencode(self._data)),
                        None, {'User-Agent': _ba.app.user_agent_string}))
            elif self._request_type == 'post':
                response = urllib.request.urlopen(
                    urllib.request.Request(
                        _ba.get_master_server_address() + '/' + self._request,
                        parse.urlencode(self._data).encode(),
                        {'User-Agent': _ba.app.user_agent_string}))
            else:
                raise Exception("Invalid request_type: " + self._request_type)

            # If html request failed.
            if response.getcode() != 200:
                response_data = None
            elif self._response_type == ServerResponseType.JSON:
                raw_data = response.read()

                # Empty string here means something failed server side.
                if raw_data == b'':
                    response_data = None
                else:
                    # Json.loads requires str in python < 3.6.
                    raw_data_s = raw_data.decode()
                    response_data = json.loads(raw_data_s)
            else:
                raise Exception(f'invalid responsetype: {self._response_type}')
        except (urllib.error.URLError, ConnectionError):
            # Server rejected us, broken pipe, etc.  It happens. Ignoring.
            response_data = None
        except Exception as exc:
            # Any other error here is unexpected, so let's make a note of it.
            print('Exc in ServerCallThread:', exc)
            import traceback
            traceback.print_exc()
            response_data = None

        if self._callback is not None:
            _ba.pushcall(_general.Call(self._run_callback, response_data),
                         from_other_thread=True)
Ejemplo n.º 3
0
    def run(self) -> None:
        """Run the Music.app thread."""
        from ba._general import Call
        from ba._lang import Lstr
        from ba._enums import TimeType
        _ba.set_thread_name("BA_MacMusicAppThread")
        _ba.mac_music_app_init()

        # Let's mention to the user we're launching Music.app in case
        # it causes any funny business (this used to background the app
        # sometimes, though I think that is fixed now)
        def do_print() -> None:
            _ba.timer(1.0,
                      Call(_ba.screenmessage, Lstr(resource='usingItunesText'),
                           (0, 1, 0)),
                      timetype=TimeType.REAL)

        _ba.pushcall(do_print, from_other_thread=True)

        # Here we grab this to force the actual launch.
        _ba.mac_music_app_get_volume()
        _ba.mac_music_app_get_library_source()
        done = False
        while not done:
            self._commands_available.wait()
            self._commands_available.clear()

            # We're not protecting this list with a mutex but we're
            # just using it as a simple queue so it should be fine.
            while self._commands:
                cmd = self._commands.pop(0)
                if cmd[0] == 'DIE':

                    self._handle_die_command()
                    done = True
                    break
                if cmd[0] == 'PLAY':
                    self._handle_play_command(target=cmd[1])
                elif cmd[0] == 'GET_PLAYLISTS':
                    self._handle_get_playlists_command(target=cmd[1])

                del cmd  # Allows the command data/callback/etc to be freed.
Ejemplo n.º 4
0
    def run(self) -> None:
        # pylint: disable=too-many-branches
        import urllib.request
        import urllib.error
        import json
        import http.client
        from ba import _general
        try:
            self._data = _general.utf8_all(self._data)
            _ba.set_thread_name('BA_ServerCallThread')
            parse = urllib.parse
            if self._request_type == 'get':
                response = urllib.request.urlopen(
                    urllib.request.Request(
                        (_ba.get_master_server_address() + '/' +
                         self._request + '?' + parse.urlencode(self._data)),
                        None, {'User-Agent': _ba.app.user_agent_string}))
            elif self._request_type == 'post':
                response = urllib.request.urlopen(
                    urllib.request.Request(
                        _ba.get_master_server_address() + '/' + self._request,
                        parse.urlencode(self._data).encode(),
                        {'User-Agent': _ba.app.user_agent_string}))
            else:
                raise TypeError('Invalid request_type: ' + self._request_type)

            # If html request failed.
            if response.getcode() != 200:
                response_data = None
            elif self._response_type == ServerResponseType.JSON:
                raw_data = response.read()

                # Empty string here means something failed server side.
                if raw_data == b'':
                    response_data = None
                else:
                    # Json.loads requires str in python < 3.6.
                    raw_data_s = raw_data.decode()
                    response_data = json.loads(raw_data_s)
            else:
                raise TypeError(f'invalid responsetype: {self._response_type}')

        except Exception as exc:
            import errno
            do_print = False
            response_data = None

            # Ignore common network errors; note unexpected ones.
            if isinstance(
                    exc,
                (urllib.error.URLError, ConnectionError,
                 http.client.IncompleteRead, http.client.BadStatusLine)):
                pass
            elif isinstance(exc, OSError):
                if exc.errno == 10051:  # Windows unreachable network error.
                    pass
                elif exc.errno in [
                        errno.ETIMEDOUT, errno.EHOSTUNREACH, errno.ENETUNREACH
                ]:
                    pass
                else:
                    do_print = True
            elif (self._response_type == ServerResponseType.JSON
                  and isinstance(exc, json.decoder.JSONDecodeError)):
                pass
            else:
                do_print = True

            if do_print:
                # Any other error here is unexpected,
                # so let's make a note of it,
                print(f'Error in ServerCallThread'
                      f' (response-type={self._response_type},'
                      f' response-data={response_data}):')
                import traceback
                traceback.print_exc()

        if self._callback is not None:
            _ba.pushcall(_general.Call(self._run_callback, response_data),
                         from_other_thread=True)
Ejemplo n.º 5
0
    def run(self) -> None:
        # pylint: disable=too-many-branches, consider-using-with
        import urllib.request
        import urllib.error
        import json

        from efro.net import is_urllib_network_error
        from ba import _general
        try:
            self._data = _general.utf8_all(self._data)
            _ba.set_thread_name('BA_ServerCallThread')
            parse = urllib.parse
            if self._request_type == 'get':
                response = urllib.request.urlopen(
                    urllib.request.Request(
                        (_ba.get_master_server_address() + '/' +
                         self._request + '?' + parse.urlencode(self._data)),
                        None, {'User-Agent': _ba.app.user_agent_string}),
                    timeout=DEFAULT_REQUEST_TIMEOUT_SECONDS)
            elif self._request_type == 'post':
                response = urllib.request.urlopen(
                    urllib.request.Request(
                        _ba.get_master_server_address() + '/' + self._request,
                        parse.urlencode(self._data).encode(),
                        {'User-Agent': _ba.app.user_agent_string}),
                    timeout=DEFAULT_REQUEST_TIMEOUT_SECONDS)
            else:
                raise TypeError('Invalid request_type: ' + self._request_type)

            # If html request failed.
            if response.getcode() != 200:
                response_data = None
            elif self._response_type == MasterServerResponseType.JSON:
                raw_data = response.read()

                # Empty string here means something failed server side.
                if raw_data == b'':
                    response_data = None
                else:
                    response_data = json.loads(raw_data)
            else:
                raise TypeError(f'invalid responsetype: {self._response_type}')

        except Exception as exc:
            do_print = False
            response_data = None

            # Ignore common network errors; note unexpected ones.
            if is_urllib_network_error(exc):
                pass
            elif (self._response_type == MasterServerResponseType.JSON
                  and isinstance(exc, json.decoder.JSONDecodeError)):
                # FIXME: should handle this better; could mean either the
                # server sent us bad data or it got corrupted along the way.
                pass
            else:
                do_print = True

            if do_print:
                # Any other error here is unexpected,
                # so let's make a note of it,
                print(f'Error in MasterServerCallThread'
                      f' (response-type={self._response_type},'
                      f' response-data={response_data}):')
                import traceback
                traceback.print_exc()

        if self._callback is not None:
            _ba.pushcall(_general.Call(self._run_callback, response_data),
                         from_other_thread=True)