Example #1
0
 def __init__(self):
     if path.isfile(self.ini): self.cfg.read(self.ini)
     else:
         self.cfg['general'] = {
             "cfgversion": "1",
             "debug": "False",
             "enabled": "True"
         }
         self.cfg['autoban'] = {"enabled": "True"}
         self.cfg['automod'] = {"enabled": "True", "autotp": "True"}
         self.cfg['antirecord'] = {"enabled": "True"}
         self.cfg['autokickonban'] = {"enabled": "True"}
         self.cfg['groups'] = {
             "banned": ["BAN", "NOT WELCOME"],
             "mod": ["MOD", "OPERATOR"],
             "admin": ["ADMIN"]
         }
         with open(self.ini, 'w') as configfile:
             self.cfg.write(configfile)
     self.db = QSqlDatabase.addDatabase("QSQLITE", "channelWatcher")
     self.db.setDatabaseName(ts3lib.getConfigPath() + "settings.db")
     if self.db.isValid(): self.db.open()
     schid = ts3lib.getCurrentschid()
     if schid:
         self.requested = True
         ts3lib.requestChannelGroupList(schid)
         (error, ownID) = ts3lib.getClientID(schid)
         (error, cid) = ts3lib.getChannelOfClient(schid, ownID)
         self.ownchannels.extend([cid])
     if self.debug:
         ts3lib.printMessageToCurrentTab(
             "{0}[color=orange]{1}[/color] Plugin for pyTSon by [url=https://github.com/{2}]{2}[/url] loaded."
             .format(self.timestamp(), self.name, self.author))
    def contactStatus(self, uid):
        """
        checks contact status of a given uid. Returns friend=0, blocked=1, neutral=2
        """
        db = QSqlDatabase.addDatabase("QSQLITE", "pyTSon_example")
        db.setDatabaseName(ts3lib.getConfigPath() + "settings.db")

        if not db.isValid():
            raise Exception("Database not valid")

        if not db.open():
            raise Exception("Database could not be opened")

        q = self.settings.query(
            "SELECT * FROM contacts WHERE value LIKE '%%IDS=%s%%'" % uid)
        ret = 2

        if q.next():
            val = q.value("value")

            for l in val.split('\n'):
                if l.startswith('Friend='):
                    ret = int(l[-1])

        return ret
Example #3
0
def getConfigPath(*args):
    """
    Returns pyTSon's configpath, that is, the subdirectory 'pyTSon' in the
    TeamSpeak 3 config directory.
    @param args: path fields joined to the result as list of strings
    @type args: list[str]
    @return: The accumulated path
    @rtype: str
    """
    return os.path.join(ts3lib.getConfigPath(), "pyTSon", *args)
Example #4
0
def getConfigPath(*args):
    """
    Returns pyTSon's configpath, that is, the subdirectory 'pyTSon' in the
    TeamSpeak 3 config directory.
    @param args: path fields joined to the result as list of strings
    @type args: list[str]
    @return: The accumulated path
    @rtype: str
    """
    return os.path.join(ts3lib.getConfigPath(), "pyTSon", *args)
Example #5
0
        def __init__(self):
            self.db = QSqlDatabase.addDatabase("QSQLITE", "__pyTSon_config__")
            self.db.setDatabaseName(
                os.path.join(ts3lib.getConfigPath(), "settings.db"))

            if not self.db.isValid():
                raise Exception("Database not valid")

            if not self.db.open():
                raise Exception("Database could not be opened")
Example #6
0
        def __init__(self):
            self.db = QSqlDatabase.addDatabase("QSQLITE", "__pyTSon_config__")
            self.db.setDatabaseName(os.path.join(ts3lib.getConfigPath(),
                                                 "settings.db"))

            if not self.db.isValid():
                raise Exception("Database not valid")

            if not self.db.open():
                raise Exception("Database could not be opened")
Example #7
0
 def __init__(self):
     event_handler = LoggingEventHandler()
     self.observer = Observer()
     self.observer.schedule(event_handler, ts3lib.getConfigPath(), recursive=True)
     self.observer.start()
     try:
         while True:
             time.sleep(1)
     except KeyboardInterrupt:
         self.observer.stop()
         self.observer.join()
     if PluginHost.cfg.getboolean("general", "verbose"): ts3lib.printMessageToCurrentTab("{0}[color=orange]{1}[/color] Plugin for pyTSon by [url=https://github.com/{2}]{2}[/url] loaded.".format(timestamp(), self.name, self.author))
Example #8
0
    def __init__(self, schid):
        """
        Instantiates a new ServerCache object referenced by the server
        connection handler id (an Exception is raised if the path in the
        filesystem could not be located).
        @param schid: the ID of the serverconnection
        @type schid: int
        """
        err, uid = (ts3lib.getServerVariableAsString(schid,
                    ts3defines.VirtualServerProperties.
                    VIRTUALSERVER_UNIQUE_IDENTIFIER))

        if err != ts3defines.ERROR_ok:
            raise Exception("Error getting Server unique identifier: %s" % err)

        self.path = os.path.join(ts3lib.getConfigPath(), "cache",
                                 base64.b64encode(
                                 uid.encode("utf-8")).decode("utf-8"))
        if not os.path.isdir(self.path):
            raise Exception("No such file or directory: %s" % self.path)
Example #9
0
    def __init__(self, schid):
        """
        Instantiates a new ServerCache object referenced by the server
        connection handler id (an Exception is raised if the path in the
        filesystem could not be located).
        @param schid: the ID of the serverconnection
        @type schid: int
        """
        err, uid = (ts3lib.getServerVariableAsString(
            schid,
            ts3defines.VirtualServerProperties.VIRTUALSERVER_UNIQUE_IDENTIFIER)
                    )

        if err != ts3defines.ERROR_ok:
            raise Exception("Error getting Server unique identifier: %s" % err)

        self.path = os.path.join(
            ts3lib.getConfigPath(), "cache",
            base64.b64encode(uid.encode("utf-8")).decode("utf-8"))
        if not os.path.isdir(self.path):
            raise Exception("No such file or directory: %s" % self.path)
Example #10
0
 def onTextMessageEvent(self, schid, targetMode, toID, fromID, fromName,
                        fromUniqueIdentifier, message, ffIgnored):
     if ffIgnored: return False
     if targetMode != ts3defines.TextMessageTargetMode.TextMessageTarget_CLIENT:
         return False
     err, ownID = ts3lib.getClientID(schid)
     if fromID == ownID: return False
     err, uid = ts3lib.getClientVariable(
         schid, fromID,
         ts3defines.ClientProperties.CLIENT_UNIQUE_IDENTIFIER)
     if getContactStatus(uid) == ContactStatus.FRIEND: return False
     uid_encoded = b64encode(uid.encode()).decode()
     (err, suid) = ts3lib.getServerVariable(
         schid,
         ts3defines.VirtualServerProperties.VIRTUALSERVER_UNIQUE_IDENTIFIER)
     suid_encoded = b64encode(suid.encode()).decode()
     _path = path.join(ts3lib.getConfigPath(), "chats", suid_encoded,
                       "clients", uid_encoded)
     if PluginHost.cfg.getboolean("general", "verbose"):
         print(self.name, ">", "path:", _path)
     if path.exists("{}.html".format(_path)): return False
     if path.exists("{}.txt".format(_path)): return False
     return True
Example #11
0
    def __init__(self):           

        # --------------------------------------------
        # Database
        # --------------------------------------------

        # Database connect for plugin main.db
        self.db = QSqlDatabase.addDatabase("QSQLITE", "pyTSon_contactmanager")
        self.db.setDatabaseName(path.join(self.directory, "main.db"))

        if not self.db.isValid(): raise Exception("Database main.db is invalid")
        if not self.db.open(): raise Exception("Could not open Database main.db")

        # Database connect for internal teamspeak settings.db
        self.db_c = QSqlDatabase.addDatabase("QSQLITE","pyTSon_contacts")
        self.db_c.setDatabaseName(ts3.getConfigPath() + "settings.db")

        if not self.db_c.isValid(): raise Exception("Database settings.db is invalid")
        if not self.db_c.open(): raise Exception("Could not open Database settings.db")

        # --------------------------------------------
        # Load General Settings
        # --------------------------------------------
        
        s = self.db.exec_("SELECT * FROM settings LIMIT 1")
        if not self.db.lastError().isValid():
            if s.next():
                self.settings["f_channelgroup"]     = bool(s.value("db_f_channelgroup"))
                self.settings["f_talkpower"]        = bool(s.value("db_f_talkpower"))
                self.settings["f_message"]          = bool(s.value("db_f_message"))
                self.settings["f_message_message"]  = s.value("db_f_message_message")
                self.settings["b_channelgroup"]     = bool(s.value("db_b_channelgroup"))
                self.settings["b_kick"]             = bool(s.value("db_b_kick"))
                self.settings["b_kick_message"]     = s.value("db_b_kick_message")
                self.settings["b_message"]          = bool(s.value("db_b_message"))
                self.settings["b_message_message"]  = s.value("db_b_message_message")
Example #12
0
class nowPlaying(ts3plugin):
    name = "Now Playing"
    apiVersion = 22
    requestAutoload = False
    version = "1.0"
    author = "Bluscream"
    description = "Now playing plugin in pyTSon"
    offersConfigure = True
    commandKeyword = "info"
    infoTitle = "[b]"+name+":[/b]"
    menuItems = [(ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL, 0, "Toggle Now Playing", "")]
    hotkeys = []
    ini = path.join(ts3lib.getConfigPath(), "plugins", "pyTSon", "scripts", "nowPlaying", "settings.ini")
    cfg = configparser.ConfigParser()
    cfg.optionxform = str
    timer = None
    schid = 0
    prefix = ""
    suffix = ""
    interval = 10000
    enabled = False

    def __init__(self):
        self.dlg = None
        if path.isfile(self.ini):
            self.cfg.read(self.ini)
        else:
            self.cfg['general'] = { "Debug": "False" }
            self.cfg['nowplaying'] = { "client_nickname": "{title}" }
            with open(self.ini, 'w') as configfile:
                self.cfg.write(configfile)
        # self.timer.timeout.connect(self.tick)
        if self.cfg.getboolean('general', 'Debug'):
            ts3lib.printMessageToCurrentTab("{0}[color=orange]{1}[/color] Plugin for pyTSon by [url=https://github.com/{2}]{2}[/url] loaded.".format(timestamp(), self.name, self.author))

    def onConnectStatusChangeEvent(self, schid, newStatus, errorNumber):
        if not self.enabled: return
        if newStatus == ts3defines.ConnectStatus.STATUS_CONNECTION_ESTABLISHED:
            self.schid = schid;self.timer.start(self.interval)
        elif newStatus == ts3defines.ConnectStatus.STATUS_DISCONNECTED:
            self.schid = 0;self.timer.stop()

    def onMenuItemEvent(self, schid, atype, menuItemID, selectedItemID):
        if menuItemID == 0:
            if self.timer is None:
                self.timer = QTimer()
                self.timer.timeout.connect(self.tick)
            if self.timer.isActive():
                self.timer.timeout.disconnect(self.tick)
                self.timer.stop()
                self.timer = None
                del self.timer
                ts3lib.printMessageToCurrentTab('Timer stopped!')
            else:
                self.timer.start(self.interval)
                ts3lib.printMessageToCurrentTab('Timer started!')
            self.enabled = not self.enabled
            ts3lib.printMessageToCurrentTab("{0}Set {1} to [color=yellow]{2}[/color]".format(self.timestamp(),self.name,self.toggle))

    def buildString(self, value):
        return "{0}{1}{2}".format(self.prefix, value.replace('{title}',spotilib.song()).replace('{artist}',spotilib.artist()).replace('{artists}',spotimeta.artists()), self.suffix)

    def getString(self, value):
        return self.cfg.get('nowplaying', value)

    def tick(self):
        if self.getString('client_nickname') != "":
            ts3lib.setClientSelfVariableAsString(self.schid, ts3defines.ClientProperties.CLIENT_NICKNAME, self.buildString(self.getString('client_nickname')))
            ts3lib.flushClientSelfUpdates(self.schid)

    def configDialogClosed(self, r, vals):
        try:
            ts3lib.printMessageToCurrentTab("vals: "+str(vals))
            if r == QDialog.Accepted:
                for name, val in vals.items():
                    try:
                        if not val == self.cfg.getboolean('general', name):
                            self.cfg.set('general', str(name), str(val))
                    except:
                        from traceback import format_exc
                        ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "PyTSon", 0)
                with open(self.ini, 'w') as configfile:
                    self.cfg.write(configfile)
        except:
            from traceback import format_exc
            ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "PyTSon", 0)

    def configure(self, qParentWidget):
        try:
            if not self.dlg:
                self.dlg = SettingsDialog(self)
            self.dlg.show()
            self.dlg.raise_()
            self.dlg.activateWindow()
        except:
            from traceback import format_exc
            ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "PyTSon", 0)
Example #13
0
 def getAvatar(serverConnectionHandlerID, clientID):
     avatar = ts3lib.getAvatar(serverConnectionHandlerID, clientID)
     if avatar[0] != 0:
         return ""
     else:
         return path.relpath(avatar[1], ts3lib.getConfigPath())
Example #14
0
class info(ts3plugin):
    name = "Extended Info"
    apiVersion = 22
    requestAutoload = False
    version = "1.0"
    author = "Bluscream"
    description = "Shows you more informations.\nBest to use together with a Extended Info Theme.\nClick on \"Settings\" to select what items you want to see :)\n\nHomepage: https://github.com/Bluscream/Extended-Info-Plugin\n\n\nCheck out https://r4p3.net/forums/plugins.68/ for more plugins."
    offersConfigure = True
    commandKeyword = "info"
    infoTitle = "[b]Extendend Info[/b]"
    menuItems = [
        (PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL, 0, "Set Meta Data", ""),
        (PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL, 1, "Set Avatar Flag", "")
    ]
    hotkeys = []
    ini = os.path.join(ts3.getConfigPath(), "plugins", "pyTSon", "scripts",
                       "info", "settings.ini")
    cfg = ConfigParser()
    cfg.optionxform = str
    runs = 0
    requested = []
    requestedCLIDS = []

    def __init__(self):
        self.dlg = None
        if os.path.isfile(self.ini):
            self.cfg.read(self.ini)
        else:
            self.cfg['general'] = {
                "Debug": "False",
                "Colored": "False",
                "Autorequest Server Variables": "False",
                "Autorequest Client Variables": "False"
            }
            self.cfg.add_section('VirtualServerProperties')
            self.cfg.add_section('VirtualServerPropertiesRare')
            self.cfg.add_section('ChannelProperties')
            self.cfg.add_section('ChannelPropertiesRare')
            self.cfg.add_section('ClientProperties')
            self.cfg.add_section('ClientPropertiesRare')
            self.cfg.add_section('ConnectionProperties')
            self.cfg.add_section('ConnectionPropertiesRare')
            self.cfg.set("VirtualServerProperties", "LAST_REQUESTED", "True")
            self.cfg.set("VirtualServerProperties", "TYPE", "True")
            for name, value in getmembers(VirtualServerProperties):
                if not name.startswith(
                        '__') and not '_DUMMY_' in name and not name.endswith(
                            '_ENDMARKER'):
                    self.cfg.set("VirtualServerProperties", name, "False")
            for name, value in getmembers(VirtualServerPropertiesRare):
                if not name.startswith(
                        '__') and not '_DUMMY_' in name and not name.endswith(
                            '_ENDMARKER_RARE'):
                    self.cfg.set("VirtualServerPropertiesRare", name, "False")
            self.cfg.set("ChannelProperties", "LAST_REQUESTED", "True")
            self.cfg.set("ChannelProperties", "TYPE", "True")
            self.cfg.set("ChannelProperties", "ID", "True")
            for name, value in getmembers(ChannelProperties):
                if not name.startswith(
                        '__') and not '_DUMMY_' in name and not name.endswith(
                            '_ENDMARKER'):
                    self.cfg.set("ChannelProperties", name, "False")
            for name, value in getmembers(ChannelPropertiesRare):
                if not name.startswith(
                        '__') and not '_DUMMY_' in name and not name.endswith(
                            '_ENDMARKER_RARE'):
                    self.cfg.set("ChannelPropertiesRare", name, "False")
            self.cfg.set("ClientProperties", "LAST_REQUESTED", "True")
            self.cfg.set("ClientProperties", "TYPE", "True")
            self.cfg.set("ClientProperties", "ID", "True")
            self.cfg.set("ClientProperties", "DISPLAYNAME", "True")
            for name, value in getmembers(ClientProperties):
                if not name.startswith(
                        '__') and not '_DUMMY_' in name and not name.endswith(
                            '_ENDMARKER'):
                    self.cfg.set("ClientProperties", name, "False")
            for name, value in getmembers(ClientPropertiesRare):
                if not name.startswith(
                        '__') and not '_DUMMY_' in name and not name.endswith(
                            '_ENDMARKER_RARE'):
                    self.cfg.set("ClientPropertiesRare", name, "False")
            for name, value in getmembers(ConnectionProperties):
                if not name.startswith(
                        '__') and not '_DUMMY_' in name and not name.endswith(
                            '_ENDMARKER'):
                    self.cfg.set("ConnectionProperties", name, "False")
            for name, value in getmembers(ConnectionPropertiesRare):
                if not name.startswith(
                        '__') and not '_DUMMY_' in name and not name.endswith(
                            '_ENDMARKER_RARE'):
                    self.cfg.set('ConnectionPropertiesRare', name, 'False')
            with open(self.ini, 'w') as configfile:
                self.cfg.write(configfile)
        if self.cfg.getboolean('general', 'Debug'):
            ts3.printMessageToCurrentTab(
                "{0}[color=orange]{1}[/color] Plugin for pyTSon by [url=https://github.com/{2}]{2}[/url] loaded."
                .format(timestamp(), self.name, self.author))

    def configDialogClosed(self, r, vals):
        try:
            if r == QDialog.Accepted:
                for name, val in vals.items():
                    try:
                        if not val == self.cfg.getboolean('general', name):
                            self.cfg.set('general', str(name), str(val))
                    except:
                        if self.cfg.getboolean('general', 'Debug'):
                            from traceback import format_exc
                            ts3.logMessage(format_exc(),
                                           LogLevel.LogLevel_ERROR, "PyTSon",
                                           0)
                with open(self.ini, 'w') as configfile:
                    self.cfg.write(configfile)
        except:
            if self.cfg.getboolean('general', 'Debug'):
                from traceback import format_exc
                ts3.logMessage(format_exc(), LogLevel.LogLevel_ERROR, "PyTSon",
                               0)

    def configure(self, qParentWidget):
        try:
            if not self.dlg:
                self.dlg = SettingsDialog(self)
            self.dlg.show()
            self.dlg.raise_()
            self.dlg.activateWindow()
        except:
            if self.cfg.getboolean('general', 'Debug'):
                from traceback import format_exc
                ts3.logMessage(format_exc(), LogLevel.LogLevel_ERROR, "PyTSon",
                               0)

    def processCommand(self, schid, cmd):
        cmd = cmd.split(' ', 1)
        command = cmd[0].lower()
        if command == "client":
            clid = int(cmd[1])
            (err, cid) = ts3.getChannelOfClient(schid, clid)
            ts3.printMessageToCurrentTab(
                "<{0}> Client {1} in channel {2}".format(
                    Time(), clientURL(schid, clid), channelURL(schid, cid)))
        return 1

    def onMenuItemEvent(self, schid, atype, menuItemID, selectedItemID):
        if atype == PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL:
            if menuItemID == 0:
                error, ownid = ts3.getClientID(schid)
                if error == ERROR_ok:
                    error, meta = ts3.getClientVariableAsString(
                        schid, ownid, ClientProperties.CLIENT_META_DATA)
                    if error == ERROR_ok:
                        x = QWidget()
                        _meta = QInputDialog.getMultiLineText(
                            x, "Change own Meta Data", "Meta Data:", meta)
                        if _meta == meta: return
                        error = ts3.setClientSelfVariableAsString(
                            schid, ClientProperties.CLIENT_META_DATA, _meta)
                        if not error == ERROR_ok:
                            _t = QMessageBox(QMessageBox.Critical,
                                             "Error #%s" % error,
                                             "Unable to set own meta data!")
                            _t.show()
            elif menuItemID == 1:
                error, ownid = ts3.getClientID(schid)
                if error == ERROR_ok:
                    error, flag = ts3.getClientVariableAsString(
                        schid, ownid, ClientPropertiesRare.CLIENT_FLAG_AVATAR)
                    ts3.printMessageToCurrentTab(
                        "Your current avatar flag is: %s" % flag)
                    if error == ERROR_ok:
                        x = QWidget()
                        _flag = QInputDialog.getText(x,
                                                     "Change own Avatar Flag",
                                                     "Avatar File MD5:")
                        if _flag == "x" or _flag.strip() == flag.strip():
                            return
                        error = ts3.setClientSelfVariableAsString(
                            schid, ClientPropertiesRare.CLIENT_FLAG_AVATAR,
                            _flag)
                        error2 = ts3.flushClientSelfUpdates(schid)
                        if not error == ERROR_ok or not error2 == ERROR_ok:
                            _t = QMessageBox(QMessageBox.Critical, "Error",
                                             "Unable to set own avatar flag!")
                            _t.show()

    def getInfo(self, schid, selectedItemID, lists):
        i = []
        for lst in lists:
            for name, var in getItems(lst):
                (name, var) = self.preProcessVar(schid, selectedItemID, name,
                                                 var, lst)
                if var is None: continue
                if lst in [
                        VirtualServerProperties, VirtualServerPropertiesRare
                ]:
                    (err, var) = ts3.getServerVariable(schid, var)
                elif lst in [ChannelProperties, ChannelPropertiesRare]:
                    (err,
                     var) = ts3.getChannelVariable(schid, selectedItemID, var)
                elif lst in [ConnectionProperties, ConnectionPropertiesRare]:
                    (err,
                     var) = ts3.getConnectionVariable(schid, selectedItemID,
                                                      var)
                else:
                    (err, var) = ts3.getClientVariable(schid, selectedItemID,
                                                       var)
                if err != ERROR_ok or var == "" or var == 0: continue
                if isinstance(var, map): var = ", ".join(map(str, var))
                if name in ["VIRTUALSERVER_IP", "CONNECTION_CLIENT_IP"]:
                    i.extend(self.ipInfo(var))
                (name, var) = self.postProcessVar(schid, selectedItemID, name,
                                                  var, lst)
                i.append('{0}: {1}'.format(name, var))
        return i

    def preProcessVar(self, schid, id, name, var, lst):
        if name == "CLIENT_META_DATA":
            (err, ownID) = ts3.getClientID(schid)
            if id == ownID: return name, None
        elif name == "CHANNEL_PASSWORD": return name, None
        return name, var

    def postProcessVar(self, schid, id, name, val, lst):
        if name in [
                "VIRTUALSERVER_CREATED", "CLIENT_LAST_VAR_REQUEST",
                "CLIENT_CREATED", "CLIENT_LASTCONNECTED"
        ]:
            pass  # val = date().fromtimestamp(val).strftime('%Y-%m-%d %H:%M:%S ({0})'.format(val))
        elif name in [
                "VIRTUALSERVER_UPTIME", "VIRTUALSERVER_COMPLAIN_AUTOBAN_TIME",
                "VIRTUALSERVER_COMPLAIN_REMOVE_TIME", "CHANNEL_DELETE_DELAY",
                "CLIENT_IDLE_TIME", "CONNECTION_CONNECTED_TIME",
                "CONNECTION_IDLE_TIME"
        ]:
            val = '{0} ({1})'.format(timedelta(milliseconds=val), val)
        elif name == "TYPE":
            (t, val) = getItemType(lst)
        elif name == "ID":
            return name, id
        elif name == "DISPLAYNAME":
            (err, val) = ts3.getClientDisplayName(schid, id)
        if lst in [VirtualServerProperties, VirtualServerPropertiesRare]:
            name = name.replace("VIRTUALSERVER_", "")
        elif lst in [ChannelProperties, ChannelPropertiesRare]:
            name = name.replace("CHANNEL_", "")
        elif lst in [ConnectionProperties, ConnectionPropertiesRare]:
            name = name.replace("CONNECTION_", "")
        elif list in [ClientProperties, ClientPropertiesRare]:
            name = name.replace("CLIENT_", "")
        name = name.replace("_", " ").title()
        return name, val

    def onServerUpdatedEvent(self, schid):
        if schid in self.requested: return
        self.requested.append(schid)
        ts3.requestInfoUpdate(schid, PluginItemType.PLUGIN_SERVER, schid)

    def onConnectionInfoEvent(self, schid, clid):
        if clid in self.requestedCLIDS: return
        self.requestedCLIDS.append(clid)
        ts3.requestInfoUpdate(schid, PluginItemType.PLUGIN_CLIENT, schid)

    def onUpdateClientEvent(self, schid, clid, invokerID, invokerName,
                            invokerUniqueIdentifier):
        if clid in self.requestedCLIDS: return
        self.requestedCLIDS.append(clid)
        ts3.requestInfoUpdate(schid, PluginItemType.PLUGIN_CLIENT, schid)

    def ipInfo(self, ip):
        url = 'http://ip-api.com/json/{0}'.format(ip)
        print('Requesting {0}'.format(url))
        i = []
        r = requests.get(url)
        if r.status_code != requests.codes.ok: return i
        for k, v in r.json().items():
            if v is None or v == "" or k in ["status", "query", "message"]:
                continue
            i.append('{0}: {1}'.format(k.title(), v))
        return i
        # self.nwmc = QNetworkAccessManager()
        # self.nwmc.connect("finished(QNetworkReply*)", self.ipReply)
        # self.nwmc.get(QNetworkRequest(QUrl(url)))

    def ipReply(self, reply):
        i = []
        r = json.loads(reply.readAll().data().decode('utf-8'))
        for n, v in r:
            i.append('{0}: {1}'.format(n.title(), v))
        return i if len(i) > 0 else None

    def getServerInfo(self, schid):
        i = []
        (err, host, port, password) = ts3.getServerConnectInfo(schid)
        i.append('Host: {0}'.format(host))
        if port: i.append('Port: {0}'.format(port))
        if password != "": i.append('Password: {0}'.format(password))
        i.extend(
            self.getInfo(
                schid, None,
                [VirtualServerProperties, VirtualServerPropertiesRare]))
        return i if len(i) > 0 else None

    def getChannelInfo(self, schid, cid):
        i = []
        (err, path, password) = ts3.getChannelConnectInfo(schid, cid)
        (err, name) = ts3.getChannelVariable(schid, cid,
                                             ChannelProperties.CHANNEL_NAME)
        if path != name: i.append('Path: {0}'.format(path))
        if password != "": i.append('Password: {0}'.format(password))
        i.extend(
            self.getInfo(schid, cid,
                         [ChannelProperties, ChannelPropertiesRare]))
        return i if len(i) > 0 else None

    def getClientInfo(self, schid, clid):
        i = []
        i.extend(
            self.getInfo(schid, clid, [
                ClientProperties, ClientPropertiesRare, ConnectionProperties,
                ConnectionPropertiesRare
            ]))
        return i if len(i) > 0 else None

    def infoData(self, schid, id, atype):
        if not self.cfg.getboolean('general', 'InfoData'): return
        if atype == PluginItemType.PLUGIN_SERVER:
            if not schid in self.requested:
                ts3.requestServerVariables(schid)
            return self.getServerInfo(schid)
        elif atype == PluginItemType.PLUGIN_CHANNEL:
            return self.getChannelInfo(schid, id)
        elif atype == PluginItemType.PLUGIN_CLIENT:
            if not id in self.requestedCLIDS:
                ts3.requestConnectionInfo(schid, id)
            return self.getClientInfo(schid, id)
        return None
Example #15
0
class customBadges(ts3plugin):
    name = "Custom Badges"
    try: apiVersion = getCurrentApiVersion()
    except: apiVersion = 21
    requestAutoload = False
    version = "0.9.3.1"
    author = "Bluscream"
    description = "Automatically sets some badges for you :)"
    offersConfigure = True
    commandKeyword = ""
    infoTitle = "[b]Badges[/b]"
    menuItems = [
        (ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL, 0, "Change " + name, "")#,
        #(ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL, 1, "Generate Badge UIDs", "")
    ]
    hotkeys = []
    icons = path.join(ts3lib.getConfigPath(), "cache", "badges")
    ini = path.join(getPluginPath(), "scripts", "customBadges", "settings.ini")
    ui = path.join(getPluginPath(), "scripts", "customBadges", "badges.ui")
    badges_ext = path.join(getPluginPath(), "include", "badges_ext.json")
    badges_ext_remote = "https://raw.githubusercontent.com/R4P3-NET/CustomBadges/master/badges.json"
    cfg = ConfigParser()
    dlg = None
    cfg["general"] = {
        "cfgversion": "1",
        "debug": "False",
        "enabled": "True",
        "badges": "",
        "overwolf": "False",
        "lastnotice": ""
    }
    badges = {}
    extbadges = {}
    notice = QTimer()
    notice_nwmc = QNetworkAccessManager()

    def __init__(self):
        try:
            loadCfg(self.ini, self.cfg)
            (tstamp, self.badges, array) = loadBadges()
            self.requestBadgesExt()
            self.notice.timeout.connect(self.checkNotice)
            self.notice.start(30*1000) # 180
            if PluginHost.cfg.getboolean("general", "verbose"): ts3lib.printMessageToCurrentTab("{0}[color=orange]{1}[/color] Plugin for pyTSon by [url=https://github.com/{2}]{2}[/url] loaded.".format(timestamp(), self.name, self.author))
        except: ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)

    def infoData(self, schid, id, atype):
        if atype != ts3defines.PluginItemType.PLUGIN_CLIENT: return None
        (err, ownID) = ts3lib.getClientID(schid)
        if ownID != id: return None
        # overwolf = self.cfg.getboolean('general', 'overwolf')
        # badges = self.cfg.get('general', 'badges').split(',')
        (err, badges) = ts3lib.getClientVariable(schid, id, ts3defines.ClientPropertiesRare.CLIENT_BADGES)
        (overwolf, badges) = parseBadges(badges)
        _return = ["Overwolf: {0}".format("[color=green]Yes[/color]" if overwolf else "[color=red]No[/color]")]
        # i = []
        # for badge in badges:
            # if badge
        for badge in badges:
            lst = self.badges
            if badge in self.extbadges: lst = self.extbadges
            _return.append("{} {}".format(
                "[img]https://badges-content.teamspeak.com/{}/{}.svg[/img]".format(badge, lst[badge]["filename"] if badge in lst else "unknown"),
                self.badgeNameByUID(badge, lst) if badge in lst else badge
            ))
        return _return

    def saveBadges(self, external):
        db = ts3client.Config()
        query = QSqlQuery(db)
        (timestamp, internal, array) = loadBadges()
        delimiter = array.mid(0, 12)
        delimiter1 = 0;delimiter2 = 0;delimiter3 = 0;delimiter4 = 0
        guid_len = 0;guid = ""
        name_len = 0;name = ""
        url_len = 0;url = ""
        desc_len = 0;desc = ""
        for i in range(0, array.size()):
            if i == 12: #guid_len
                guid_len = int(array.at(i))
                guid = str(array.mid(i+1, guid_len))
            elif i == (12 + 1 + guid_len + 1):
                delimiter1 = array.mid(i - 1,i - 1)
                name_len = int(array.at(i))
                name = str(array.mid(i+1, name_len))
            elif i == (12 + 1 + guid_len + 1 + name_len + 2):
                delimiter2 = array.mid(i - 1,i - 1)
                url_len = int(array.at(i))
                url = str(array.mid(i+1, url_len))
            elif i == (12 + 1 + guid_len + 1 + name_len + 2 + url_len + 2):
                delimiter3 = array.mid(i - 3,i - 3)
                delimiter4 = array.mid(i+desc_len,i+desc_len)
                desc_len = int(array.at(i))
                desc = str(array.mid(i+1, desc_len))
                break
        print("delimiter:", delimiter.toHex())
        print("delimiter1:", delimiter1.toHex())
        print("delimiter2:", delimiter2.toHex())
        print("delimiter3:", delimiter3.toHex())
        print("delimiter4:", delimiter4.toHex())
        print("array:", array.toHex())
        # query.prepare( "UPDATE Badges (BadgesListData) VALUES (:byteArray)" );
        # query.bindValue( ":imageData", array);

    def badgeNameByUID(self, uid, lst=badges):
        for badge in lst:
            if badge == uid: return lst[badge]["name"]

    def requestBadgesExt(self):
        try:
            with open(self.badges_ext, encoding='utf-8-sig') as json_file:
                self.extbadges = load(json_file)
        except:
            self.nwmc_ext = QNetworkAccessManager()
            self.nwmc_ext.connect("finished(QNetworkReply*)", self.loadBadgesExt)
            self.nwmc_ext.get(QNetworkRequest(QUrl(self.badges_ext_remote)))

    def loadBadgesExt(self, reply):
        try:
            data = reply.readAll().data().decode('utf-8')
            self.extbadges = loads(data)
        except: ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)

    def checkNotice(self):
        self.notice_nwmc.connect("finished(QNetworkReply*)", self.loadNotice)
        self.notice_nwmc.get(QNetworkRequest(QUrl("https://raw.githubusercontent.com/R4P3-NET/CustomBadges/master/notice")))

    def loadNotice(self, reply):
        data = reply.readAll().data().decode('utf-8')
        if data.strip() == "" or data == self.cfg.get('general', 'lastnotice'): return
        msgBox(data, 0, "{} Notice!".format(self.name))
        self.cfg.set('general', 'lastnotice', data)

    def stop(self):
        saveCfg(self.ini, self.cfg)
        self.notice.stop()

    def configure(self, qParentWidget):
        self.openDialog()

    def onMenuItemEvent(self, schid, atype, menuItemID, selectedItemID):
        if atype != ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL: return
        if menuItemID == 0: self.openDialog()
        elif menuItemID == 1:
            self.saveBadges(self.extbadges)
            for i in range(0,3):
                # 0c4u2snt-ao1m-7b5a-d0gq-e3s3shceript
                uid = [random_string(size=8, chars=string.ascii_lowercase + string.digits)]
                for _i in range(0,3):
                    uid.append(random_string(size=4, chars=string.ascii_lowercase + string.digits))
                uid.append(random_string(size=12, chars=string.ascii_lowercase + string.digits))
                ts3lib.printMessageToCurrentTab("[color=red]Random UID #{}: [b]{}".format(i, '-'.join(uid)))

    def onConnectStatusChangeEvent(self, schid, newStatus, errorNumber):
        if newStatus == ts3defines.ConnectStatus.STATUS_CONNECTION_ESTABLISHED:
            self.setCustomBadges()

    def setCustomBadges(self):
        try:
            overwolf = self.cfg.getboolean('general', 'overwolf')
            badges = self.cfg.get('general', 'badges').split(",")
            # if len(badges) > 0: badges += ['0c4u2snt-ao1m-7b5a-d0gq-e3s3shceript']
            (err, schids) = ts3lib.getServerConnectionHandlerList()
            for schid in schids:
                sendCommand(self.name, buildBadges(badges, overwolf), schid)
        except: ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)

    def openDialog(self):
        if not self.dlg: self.dlg = BadgesDialog(self)
        self.dlg.show()
        self.dlg.raise_()
        self.dlg.activateWindow()
Example #16
0
class customBadges(ts3plugin):
    name = "Custom Badges"
    apiVersion = 21
    requestAutoload = True
    version = "0.9"
    author = "Bluscream"
    description = "Automatically sets some badges for you :)"
    offersConfigure = True
    commandKeyword = ""
    infoTitle = "[b]Badges[/b]"
    menuItems = [(ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL, 0,
                  "Change " + name, ""),
                 (ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL, 1,
                  "Generate Badge UIDs", "")]
    hotkeys = []
    icons = path.join(ts3lib.getConfigPath(), "cache", "badges")
    ini = path.join(getPluginPath(), "scripts", "customBadges", "settings.ini")
    ui = path.join(getPluginPath(), "scripts", "customBadges", "badges.ui")
    badges_local = path.join(getPluginPath(), "include", "badges.json")
    badges_ext = path.join(getPluginPath(), "include", "badges_ext.json")
    badges_remote = "https://gist.githubusercontent.com/Bluscream/29b838f11adc409feac9874267b43b1e/raw"
    badges_ext_remote = "https://raw.githubusercontent.com/R4P3-NET/CustomBadges/master/badges.json"
    cfg = ConfigParser()
    dlg = None
    cfg["general"] = {
        "cfgversion": "1",
        "debug": "False",
        "enabled": "True",
        "badges": "",
        "overwolf": "False",
    }
    badges = {}
    extbadges = {}

    def __init__(self):
        try:
            loadCfg(self.ini, self.cfg)
            self.requestBadges()
            self.requestBadgesExt()
            if PluginHost.cfg.getboolean("general", "verbose"):
                ts3lib.printMessageToCurrentTab(
                    "{0}[color=orange]{1}[/color] Plugin for pyTSon by [url=https://github.com/{2}]{2}[/url] loaded."
                    .format(timestamp(), self.name, self.author))
        except:
            ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                              "pyTSon", 0)

    def infoData(self, schid, id, atype):
        if atype != ts3defines.PluginItemType.PLUGIN_CLIENT: return None
        (err, ownID) = ts3lib.getClientID(schid)
        if ownID != id: return None
        # overwolf = self.cfg.getboolean('general', 'overwolf')
        # badges = self.cfg.get('general', 'badges').split(',')
        (err, badges) = ts3lib.getClientVariable(
            schid, id, ts3defines.ClientPropertiesRare.CLIENT_BADGES)
        (overwolf, badges) = parseBadges(badges)
        _return = [
            "Overwolf: {0}".format("[color=green]Yes[/color]"
                                   if overwolf else "[color=red]No[/color]")
        ]
        # i = []
        # for badge in badges:
        # if badge
        for badge in badges:
            lst = self.badges
            if badge in self.extbadges: lst = self.extbadges
            _return.append("{} {}".format(
                "[img]https://badges-content.teamspeak.com/{}/{}.svg[/img]".
                format(badge,
                       lst[badge]["filename"] if badge in lst else "unknown"),
                self.badgeNameByUID(badge, lst) if badge in lst else badge))
        return _return

    def badgeNameByUID(self, uid, lst=badges):
        for badge in lst:
            if badge == uid: return lst[badge]["name"]

    def requestBadges(self):
        try:
            with open(self.badges_local, encoding='utf-8-sig') as json_file:
                self.badges = load(json_file)
        except:
            self.nwmc = QNetworkAccessManager()
            self.nwmc.connect("finished(QNetworkReply*)", self.loadBadges)
            self.nwmc.get(QNetworkRequest(QUrl(self.badges_remote)))

    def requestBadgesExt(self):
        try:
            with open(self.badges_ext, encoding='utf-8-sig') as json_file:
                self.extbadges = load(json_file)
        except:
            self.nwmc_ext = QNetworkAccessManager()
            self.nwmc_ext.connect("finished(QNetworkReply*)",
                                  self.loadBadgesExt)
            self.nwmc_ext.get(QNetworkRequest(QUrl(self.badges_ext_remote)))

    def loadBadgesExt(self, reply):
        try:
            data = reply.readAll().data().decode('utf-8')
            self.extbadges = loads(data)
            print("extbadges: {}".format(self.extbadges))
            if PluginHost.cfg.getboolean("general", "verbose"):
                ts3lib.printMessageToCurrentTab("{}".format(self.badges))
        except:
            ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                              "pyTSon", 0)

    def loadBadges(self, reply):
        try:
            # print(reply)
            _reason = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
            _reasonmsg = reply.attribute(
                QNetworkRequest.HttpReasonPhraseAttribute)
            print('reason={}|reasonmsg={}'.format(_reason, _reasonmsg))
            data = reply.readAll().data().decode('utf-8')
            self.badges = loads(data)
            print("badges: {}".format(self.badges))
            if PluginHost.cfg.getboolean("general", "verbose"):
                ts3lib.printMessageToCurrentTab("{}".format(self.badges))
        except:
            ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                              "pyTSon", 0)

    def stop(self):
        saveCfg(self.ini, self.cfg)

    def configure(self, qParentWidget):
        self.openDialog()

    def onMenuItemEvent(self, schid, atype, menuItemID, selectedItemID):
        if atype != ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL: return
        if menuItemID == 0: self.openDialog()
        elif menuItemID == 1:
            for i in range(0, 3):
                # 0c4u2snt-ao1m-7b5a-d0gq-e3s3shceript
                uid = [
                    random_string(size=8,
                                  chars=string.ascii_lowercase + string.digits)
                ]
                for _i in range(0, 3):
                    uid.append(
                        random_string(size=4,
                                      chars=string.ascii_lowercase +
                                      string.digits))
                uid.append(
                    random_string(size=12,
                                  chars=string.ascii_lowercase +
                                  string.digits))
                ts3lib.printMessageToCurrentTab(
                    "[color=red]Random UID #{}: [b]{}".format(
                        i, '-'.join(uid)))

    def onConnectStatusChangeEvent(self, schid, newStatus, errorNumber):
        if newStatus == ts3defines.ConnectStatus.STATUS_CONNECTION_ESTABLISHED:
            self.setCustomBadges()

    def setCustomBadges(self):
        try:
            overwolf = self.cfg.getboolean('general', 'overwolf')
            badges = self.cfg.get('general', 'badges').split(",")
            # if len(badges) > 0: badges += ['0c4u2snt-ao1m-7b5a-d0gq-e3s3shceript']
            (err, schids) = ts3lib.getServerConnectionHandlerList()
            for schid in schids:
                sendCommand(self.name, buildBadges(badges, overwolf), schid)
        except:
            ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                              "pyTSon", 0)

    def openDialog(self):
        if not self.dlg: self.dlg = BadgesDialog(self)
        self.dlg.show()
        self.dlg.raise_()
        self.dlg.activateWindow()
Example #17
0
class customBadges(ts3plugin):
    __path__ = getScriptPath(__name__)
    name = "Custom Badges"
    try:
        apiVersion = getCurrentApiVersion()
    except:
        apiVersion = 21
    requestAutoload = True
    version = "0.9.5.1"
    author = "Bluscream"
    description = "Automatically sets some badges for you :)"
    offersConfigure = True
    commandKeyword = ""
    infoTitle = "[b]Badges[/b]"
    menuItems = [
        (ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL, 0,
         "Change " + name, "")  # ,
        # (ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL, 1, "Generate Badge UIDs", "")
    ]
    hotkeys = []
    ini = path.join(__path__, "settings.ini")
    txt = path.join(__path__, "notice")
    ui = path.join(__path__, "badges.ui")
    icons = path.join(ts3lib.getConfigPath(), "cache", "badges")
    # icons_ext = path.join(icons, "external")
    badges_ext_remote = "https://raw.githubusercontent.com/R4P3-NET/CustomBadges/master/badges.json"
    badges_remote = "https://badges-content.teamspeak.com/list"
    cfg = ConfigParser()
    dlg = None
    cfg["general"] = {
        "cfgversion": "1",
        "debug": "False",
        "enabled": "True",
        "badges": "",
        "overwolf": "False"
    }
    badges = {}
    extbadges = {}
    notice = QTimer()
    notice_nwmc = QNetworkAccessManager()
    mode = HookMode.NONE

    def __init__(self):
        if getAddonStatus("tspatch",
                          "TS Patch").value > AddonStatus.INSTALLED.value:
            self.mode = HookMode.TSPATCH
        elif getAddonStatus("TS3Hook",
                            "TS3Hook").value > AddonStatus.INSTALLED.value:
            self.mode = HookMode.TS3HOOK
        loadCfg(self.ini, self.cfg)
        self.requestBadges()
        self.requestBadgesExt()
        self.notice.timeout.connect(self.checkNotice)
        self.notice.start(30 * 1000)
        if PluginHost.cfg.getboolean("general", "verbose"):
            ts3lib.printMessageToCurrentTab(
                "{0}[color=orange]{1}[/color] Plugin for pyTSon by [url=https://github.com/{2}]{2}[/url] loaded."
                .format(timestamp(), self.name, self.author))

    def infoData(self, schid, id, atype):
        if atype != ts3defines.PluginItemType.PLUGIN_CLIENT: return None
        (err, ownID) = ts3lib.getClientID(schid)
        if ownID != id: return None
        # overwolf = self.cfg.getboolean('general', 'overwolf')
        # badges = self.cfg.get('general', 'badges').split(',')
        (err, badges) = ts3lib.getClientVariable(
            schid, id, ts3defines.ClientPropertiesRare.CLIENT_BADGES)
        (overwolf, badges) = parseBadges(badges)
        _return = [
            "Overwolf: {0}".format("[color=green]Yes[/color]"
                                   if overwolf else "[color=red]No[/color]")
        ]
        # i = []
        # for badge in badges:
        # if badge
        for badge in badges:
            lst = self.badges
            if badge in self.extbadges: lst = self.extbadges
            _return.append("{} {}".format(
                # "[img]data://image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAACp0lEQVR42qXSW0jTURwH8O/5/93mLm460alFXrKLqQ8aNUzRB6NWhOYG9ZDYlYiSHgoCs4d6qIwIiuipIOmtqClYUZEIhlDgbTIvealR7T6bm3Nz2///P/2bEURlRQd+L79zzuf8+HII/nOR5TYnduw+zjGMuuSJue2fgcltdRfT9BvO0kgY9pEPl8pedLb+NTCztb5cWZo3oM0GGI8PDi+B2xXauOl55+AfAZuhQQZ58pCudl0RlSiBJCmY0QFYJ4LjvEDK9M86ossDVQZjanXxI0VBOiSHWxI97vp5eF9bMOXjTTXdXebfAk5Dg4pZqZtPXasAL0+DvPlcoh+5eRns2zFMeHmE4kJKZcf90C8Be239Xc2eqgPEOQOiy4f82JlEP3ThFBjLMGJqHd5Me9sNfd0HfwKc2435is3F76TZFLHeV2BzC6Fsu5PYCx4yguvtgUq3Av2TPszMLhQ00dD7HwBX9c6+lNq8Lfz4EDi7ExJ9DVRX25eA5n3gerohS88BNx/H4yl7b+OCv+Y74JRkmGT1+oeyXBacKwAhMAd21Rqk3HqQAAL7d0KwWEEVadDwBFbHHPpn/aYjkaA5AXhyi9zKE9WZ/MgYaJIMiAsQnB+B1JzEC9zoINisQtAonyg1R2C22YN75/0a4ma0JxWnG26A84EGwqACheD1gl29Hqpr90Aog8BRE4RhCyDXgC7yUHHAp0AEXS53C/FXVMakxlIJb50Wvx0B5UXAaUdSeSVUbbe/ZdAkZvBSnCgDNMwDUQ5agcVTlwfkc0UVTW4qA52yAQJA4xwYsQSHGGRdI4hKjciVViRn5YFGqHhZABFLGiPocjiWQvQWl1CqlYVonAf3dQLxXDy6iLjNJpo8hMwcUFaGOMeD5wRxSgHu8KJql99DvgBZsjDj7AAlKgAAAABJRU5ErkJggg==[/img]",
                # "[img]file:///C:/Users/blusc/AppData/Roaming/TS3Client/styles/dark/apply.svg[/img]",
                "[img]https://badges-content.teamspeak.com/{}/{}.svg[/img]".
                format(badge,
                       lst[badge]["filename"] if badge in lst else "unknown"),
                self.badgeNameByUID(badge, lst) if badge in lst else badge))
        return _return

    def saveBadges(self, external):
        db = ts3client.Config()
        query = QSqlQuery(db)
        (timestamp, internal, array) = loadBadges()
        delimiter = array.mid(0, 12)
        delimiter1 = 0
        delimiter2 = 0
        delimiter3 = 0
        delimiter4 = 0
        guid_len = 0
        guid = ""
        name_len = 0
        name = ""
        url_len = 0
        url = ""
        desc_len = 0
        desc = ""
        for i in range(0, array.size()):
            if i == 12:  #guid_len
                guid_len = int(array.at(i))
                guid = str(array.mid(i + 1, guid_len))
            elif i == (12 + 1 + guid_len + 1):
                delimiter1 = array.mid(i - 1, i - 1)
                name_len = int(array.at(i))
                name = str(array.mid(i + 1, name_len))
            elif i == (12 + 1 + guid_len + 1 + name_len + 2):
                delimiter2 = array.mid(i - 1, i - 1)
                url_len = int(array.at(i))
                url = str(array.mid(i + 1, url_len))
            elif i == (12 + 1 + guid_len + 1 + name_len + 2 + url_len + 2):
                delimiter3 = array.mid(i - 3, i - 3)
                delimiter4 = array.mid(i + desc_len, i + desc_len)
                desc_len = int(array.at(i))
                desc = str(array.mid(i + 1, desc_len))
                break
        print("delimiter:", delimiter.toHex())
        print("delimiter1:", delimiter1.toHex())
        print("delimiter2:", delimiter2.toHex())
        print("delimiter3:", delimiter3.toHex())
        print("delimiter4:", delimiter4.toHex())
        print("array:", array.toHex())
        # query.prepare( "UPDATE Badges (BadgesListData) VALUES (:byteArray)" );
        # query.bindValue( ":imageData", array);

    def badgeNameByUID(self, uid, lst=badges):
        for badge in lst:
            if badge == uid: return lst[badge]["name"]

    def requestBadges(self):
        self.nwmc_badges = QNetworkAccessManager()
        self.nwmc_badges.connect("finished(QNetworkReply*)", self.loadBadges)
        self.nwmc_badges.get(QNetworkRequest(QUrl(self.badges_remote)))

    def loadBadges(self, reply):
        try:
            data = reply.readAll().data()  # .decode('utf-8')
            self.badges = parseBadgesBlob(QByteArray(data))[0]
        except:
            ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                              "pyTSon", 0)
            (tstamp, self.badges, array) = loadBadges()
        del self.nwmc_badges

    def requestBadgesExt(self):
        self.nwmc_ext = QNetworkAccessManager()
        self.nwmc_ext.connect("finished(QNetworkReply*)", self.loadBadgesExt)
        self.nwmc_ext.get(QNetworkRequest(QUrl(self.badges_ext_remote)))

    def loadBadgesExt(self, reply):
        try:
            data = reply.readAll().data().decode('utf-8')
            self.extbadges = loads(data)
            self.nwmc_exti = {}
            self.tmpfile = {}
            for badge in self.extbadges:
                _name = self.extbadges[badge]["filename"]
                _path = path.join(self.icons, _name)
                if path.exists(_path) and path.getsize(_path) > 0: continue
                self.requestExtIcon(_name)
                self.requestExtIcon("{}_details".format(_name))
        except:
            ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                              "pyTSon", 0)
        del self.nwmc_exti

    def requestExtIcon(self, filename):
        self.nwmc_exti[filename] = QNetworkAccessManager()
        self.nwmc_exti[filename].connect("finished(QNetworkReply*)",
                                         self.loadExtIcon)
        self.tmpfile[filename] = QFile()
        self.tmpfile[filename].setFileName(path.join(self.icons, filename))
        self.tmpfile[filename].open(QIODevice.WriteOnly)
        url = "https://raw.githubusercontent.com/R4P3-NET/CustomBadges/master/img/{}".format(
            filename)
        self.nwmc_exti[filename].get(QNetworkRequest(QUrl(url)))

    def loadExtIcon(self, reply):
        try:
            if reply.error() != QNetworkReply.NoError:
                ts3lib.logMessage(
                    "Requesting \"{}\" failed:\n{}".format(
                        reply.url().toString(), reply.errorString()),
                    ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)
                return
            name = reply.url().fileName()
            self.tmpfile[name].write(reply.readAll())
            if self.tmpfile[name].isOpen():
                self.tmpfile[name].close()
                self.tmpfile[name].deleteLater()
        except:
            ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                              "pyTSon", 0)

    def checkNotice(self):
        self.notice_nwmc.connect("finished(QNetworkReply*)", self.loadNotice)
        self.notice_nwmc.get(
            QNetworkRequest(
                QUrl(
                    "https://raw.githubusercontent.com/R4P3-NET/CustomBadges/master/notice"
                )))

    def loadNotice(self, reply):
        data = reply.readAll().data().decode('utf-8')
        if not path.isfile(self.txt):
            with open(self.txt, 'w'):
                pass
        data_local = ""
        with open(self.txt, 'r') as myfile:
            data_local = myfile.read()
            myfile.close()
        data = data.strip()
        # print("data:", data)
        # print("data_local:", data_local)
        if data == "" or data == data_local.strip():
            return  # self.cfg.get('general', 'lastnotice')
        with open(self.txt, "w") as text_file:
            text_file.write(data)
            text_file.close()
        # self.cfg.set('general', 'lastnotice', data)
        title = "{} Notice!".format(self.name)
        msgBox(data, 0, title)
        ts3lib.printMessageToCurrentTab("{}\n\n{}".format(title, data))

    def stop(self):
        saveCfg(self.ini, self.cfg)
        self.notice.stop()

    def configure(self, qParentWidget):
        self.openDialog()

    def onMenuItemEvent(self, schid, atype, menuItemID, selectedItemID):
        if atype != ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL: return
        if menuItemID == 0: self.openDialog()
        elif menuItemID == 1:
            self.saveBadges(self.extbadges)
            for i in range(0, 3):
                # 0c4u2snt-ao1m-7b5a-d0gq-e3s3shceript
                uid = [
                    random_string(8, string.ascii_lowercase + string.digits)
                ]
                for _i in range(0, 3):
                    uid.append(
                        random_string(4,
                                      string.ascii_lowercase + string.digits))
                uid.append(
                    random_string(12, string.ascii_lowercase + string.digits))
                ts3lib.printMessageToCurrentTab(
                    "[color=red]Random UID #{}: [b]{}".format(
                        i, '-'.join(uid)))

    def onConnectStatusChangeEvent(self, schid, newStatus, errorNumber):
        if newStatus == ts3defines.ConnectStatus.STATUS_CONNECTION_ESTABLISHED:
            self.setCustomBadges()

    def setCustomBadges(self):
        # try:
        if self.mode == HookMode.NONE: return
        overwolf = self.cfg.getboolean('general', 'overwolf')
        badges = self.cfg.get('general', 'badges').split(",")
        # if len(badges) > 0: badges += ['0c4u2snt-ao1m-7b5a-d0gq-e3s3shceript']
        (err, schids) = ts3lib.getServerConnectionHandlerList()
        reg = compile('3(?:\.\d+)* \[Build: \d+\]')
        for schid in schids:
            _badges = badges
            err, ver = ts3lib.getServerVariable(
                schid,
                ts3defines.VirtualServerProperties.VIRTUALSERVER_VERSION)
            err, platform = ts3lib.getServerVariable(
                schid,
                ts3defines.VirtualServerProperties.VIRTUALSERVER_PLATFORM)
            if getServerType(schid, reg) in [
                    ServerInstanceType.TEASPEAK, ServerInstanceType.UNKNOWN
            ]:
                _badges = [x for x in badges if not x in self.extbadges][:3]
            _badges = buildBadges(_badges, overwolf)
            sendCommand(name=self.name,
                        cmd=_badges,
                        schid=schid,
                        mode=self.mode)
        # except: ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)

    def openDialog(self):
        if not self.dlg: self.dlg = BadgesDialog(self)
        self.dlg.show()
        self.dlg.raise_()
        self.dlg.activateWindow()
Example #18
0
(_e, owncid) = getChannelOfClient(schid, ownid)
cid = owncid
ownCID = owncid
#if "aaa_ts3Ext" in PluginHost.active: ts3host = PluginHost.active["aaa_ts3Ext"].ts3host
#else: ts3host = ts3Ext.ts3SessionHost(next(iter(PluginHost.active.values())))

print('(pyTSon v{} on {} | Console started at: {:%Y-%m-%d %H:%M:%S})'.format(
    pytson.getVersion(), pytson.platformstr(), datetime.now()))
print("Client curAPI: {} | LibVer: {} | LibVerNum: {}".format(
    pytson.getCurrentApiVersion(), ts3lib.getClientLibVersion(),
    ts3lib.getClientLibVersionNumber()))
print("Python {} {} API: {}".format(sys.platform, sys.version,
                                    sys.api_version))
print("sys.executable: %s" % sys.executable)
print("ts3lib.getAppPath(): %s" % ts3lib.getAppPath())
print("ts3lib.getConfigPath(): %s" % ts3lib.getConfigPath())
print("ts3lib.getResourcesPath(): %s" % ts3lib.getResourcesPath())
print("ts3lib.getPluginPath(): %s" % ts3lib.getPluginPath())
print("pytson.getConfigPath(): %s" % pytson.getConfigPath())
print("pytson.getPluginPath(): %s" % pytson.getPluginPath())
print("bluscream.getScriptPath(): %s" % getScriptPath("console"))
i = 0
for item in sys.path:
    print('sys.path[{}]"{}"'.format(i, item))
    i += 1
print("")
print(sys.flags)
print("")


class testClass(object):
Example #19
0
class BadgesDialog(QWidget):
    listen = False
    icons = path.join(ts3lib.getConfigPath(), "cache", "badges")

    def __init__(self, customBadges, parent=None):
        super(QWidget, self).__init__(parent)
        self.listen = False
        setupUi(self, customBadges.ui)
        self.cfg = customBadges.cfg
        self.badges = customBadges.badges
        self.setCustomBadges = customBadges.setCustomBadges
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowTitle("Customize Badges")
        self.setupList()
        self.listen = True

    def badgeItem(self, badge, alt=False):
        item = QListWidgetItem(self.badges[badge]["name"])
        item.setData(Qt.UserRole, badge)
        item.setToolTip(self.badges[badge]["description"])
        item.setIcon(
            QIcon("{}\\{}{}".format(self.icons, self.badges[badge]["filename"],
                                    "_details" if alt else "")))
        return item

    def setupList(self):
        self.chk_overwolf.setChecked(
            True if self.cfg.getboolean('general', 'overwolf') else False)
        for badge in self.badges:
            self.lst_available.addItem(self.badgeItem(badge))
        badges = self.cfg.get('general', 'badges').split(",")
        if len(badges) < 1: return
        i = 0
        for badge in badges:
            if not badge: return
            i += 1
            if i == 1:
                self.badge1.setPixmap(
                    QPixmap("{}\\{}_details".format(
                        self.icons, self.badges[badge]["filename"])))
            elif i == 2:
                self.badge2.setPixmap(
                    QPixmap("{}\\{}_details".format(
                        self.icons, self.badges[badge]["filename"])))
            elif i == 3:
                self.badge3.setPixmap(
                    QPixmap("{}\\{}_details".format(
                        self.icons, self.badges[badge]["filename"])))
            self.lst_active.addItem(self.badgeItem(badge))

    def updateBadges(self):
        items = []
        self.badge1.clear()
        self.badge2.clear()
        self.badge3.clear()
        for i in range(self.lst_active.count):
            uid = self.lst_active.item(index).data(Qt.UserRole)
            items.append(uid)
            if i == 0:
                self.badge1.setPixmap(
                    QPixmap("{}\\{}_details".format(
                        self.icons, self.badges[uid]["filename"])))
            elif i == 1:
                self.badge2.setPixmap(
                    QPixmap("{}\\{}_details".format(
                        self.icons, self.badges[uid]["filename"])))
            elif i == 2:
                self.badge3.setPixmap(
                    QPixmap("{}\\{}_details".format(
                        self.icons, self.badges[uid]["filename"])))
        self.cfg.set('general', 'badges', ','.join(items))
        self.setCustomBadges()

    def addActive(self):
        item = self.lst_available.currentItem()
        self.lst_active.addItem(self.badgeItem(item.data(Qt.UserRole)))
        self.updateBadges()

    def delActive(self):
        row = self.lst_active.currentRow
        self.lst_active.takeItem(row)
        self.updateBadges()

    def on_lst_available_doubleClicked(self, mi):
        if not self.listen: return
        self.addActive()

    def on_btn_addactive_clicked(self):
        if not self.listen: return
        self.addActive()

    def on_lst_active_doubleClicked(self, mi):
        if not self.listen: return
        self.delActive()

    def on_btn_removeactive_clicked(self):
        if not self.listen: return
        self.delActive()

    def on_chk_overwolf_stateChanged(self, mi):
        if not self.listen: return
        self.cfg.set('general', 'overwolf',
                     "True" if mi == Qt.Checked else "False")
        self.updateBadges()

    def on_lst_active_indexesMoved(self, mi):
        self.updateBadges()

    def on_lst_active_itemChanged(self, mi):
        self.updateBadges()

    def on_btn_apply_clicked(self):
        self.updateBadges()
Example #20
0
    def __init__(self, *, info=None, name=None):
        """
        Instantiates a new IconPack object referenced by its name or the
        internal info string (an Exception is raised if the iconpack could
        not be located).
        @param info: the info string used in the settings.db
        @type info: str
        @param name: the name of the iconpack
        @type name: str
        """
        if name:
            cfg = Config()
            q = cfg.query("SELECT value FROM addons WHERE value LIKE "
                          "'%%name=%s%%'" % name)

            if not q.next():
                del cfg
                raise Exception("No iconpack with name %s found in database" %
                                name)

            for l in q.value(0).split(' '):
                if l.startswith("info="):
                    self.info = l.split('=')[1]
                    break

            del cfg

            if self.info == "default.zip":
                self.info = "default"
            elif not self.info:
                raise Exception("Unknown settings format in database")
        elif info:
            self.info = info
        else:
            raise Exception("No info or name given")

        self.path = None
        self.zip = False
        self.emos = {}

        if info[-4:].lower() == ".zip":
            self.zip = True

            if os.path.isfile(
                    os.path.join(ts3lib.getResourcesPath(), "gfx", info)):
                self.path = os.path.join(ts3lib.getResourcesPath(), "gfx",
                                         info)
            elif os.path.isfile(
                    os.path.join(ts3lib.getConfigPath(), "gfx", info)):
                self.path = os.path.join(ts3lib.getConfigPath(), "gfx", info)
        else:
            if os.path.isdir(
                    os.path.join(ts3lib.getResourcesPath(), "gfx", info)):
                self.path = os.path.join(ts3lib.getResourcesPath(), "gfx",
                                         info)
            elif os.path.isfile(
                    os.path.join(ts3lib.getResourcesPath(), "gfx",
                                 info + ".zip")):
                self.zip = True
                self.path = os.path.join(ts3lib.getResourcesPath(), "gfx",
                                         info + ".zip")
            elif os.path.isdir(
                    os.path.join(ts3lib.getConfigPath(), "gfx", info)):
                self.path = os.path.join(ts3lib.getConfigPath(), "gfx", info)
            elif os.path.isfile(
                    os.path.join(ts3lib.getConfigPath(), "gfx",
                                 info + ".zip")):
                self.zip = True
                self.path = os.path.join(ts3lib.getConfigPath(), "gfx",
                                         info + ".zip")

        if not self.path:
            raise Exception("Iconpack %s not found" % info)
Example #21
0
    def __init__(self, *, info=None, name=None):
        """
        Instantiates a new IconPack object referenced by its name or the
        internal info string (an Exception is raised if the iconpack could
        not be located).
        @param info: the info string used in the settings.db
        @type info: str
        @param name: the name of the iconpack
        @type name: str
        """
        if name:
            cfg = Config()
            q = cfg.query("SELECT value FROM addons WHERE value LIKE "
                          "'%%name=%s%%'" % name)

            if not q.next():
                del cfg
                raise Exception("No iconpack with name %s found in database" %
                                name)

            for l in q.value(0).split(' '):
                if l.startswith("info="):
                    self.info = l.split('=')[1]
                    break

            del cfg

            if self.info == "default.zip":
                self.info = "default"
            elif not self.info:
                raise Exception("Unknown settings format in database")
        elif info:
            self.info = info
        else:
            raise Exception("No info or name given")

        self.path = None
        self.zip = False
        self.emos = {}

        if info[-4:].lower() == ".zip":
            self.zip = True

            if os.path.isfile(os.path.join(ts3lib.getResourcesPath(),
                                           "gfx", info)):
                self.path = os.path.join(ts3lib.getResourcesPath(),
                                         "gfx", info)
            elif os.path.isfile(os.path.join(ts3lib.getConfigPath(), "gfx",
                                             info)):
                self.path = os.path.join(ts3lib.getConfigPath(), "gfx", info)
        else:
            if os.path.isdir(os.path.join(ts3lib.getResourcesPath(), "gfx",
                                          info)):
                self.path = os.path.join(ts3lib.getResourcesPath(), "gfx",
                                         info)
            elif os.path.isfile(os.path.join(ts3lib.getResourcesPath(), "gfx",
                                             info + ".zip")):
                self.zip = True
                self.path = os.path.join(ts3lib.getResourcesPath(), "gfx",
                                         info + ".zip")
            elif os.path.isdir(os.path.join(ts3lib.getConfigPath(), "gfx",
                                            info)):
                self.path = os.path.join(ts3lib.getConfigPath(), "gfx", info)
            elif os.path.isfile(os.path.join(ts3lib.getConfigPath(), "gfx",
                                             info + ".zip")):
                self.zip = True
                self.path = os.path.join(ts3lib.getConfigPath(), "gfx",
                                         info + ".zip")

        if not self.path:
            raise Exception("Iconpack %s not found" % info)