Example #1
0
class BanDialog(QDialog):
    moveBeforeBan = False
    clid = 0
    def __init__(self, script, schid, clid, uid, name, ip, parent=None):
        try:
            super(QDialog, self).__init__(parent)
            setupUi(self, "%s/ban.ui"%script.path)
            self.setAttribute(Qt.WA_DeleteOnClose)
            self.cfg = script.cfg
            self.ini = script.ini
            self.schid = schid
            self.templates = script.templates
            self.whitelist = script.whitelist
            self.name = script.name
            if script.cfg.getboolean("last", "expanded"):
                self.disableReasons(True)
            height = script.cfg.get("last", "height")
            if height: self.resize(self.width, int(height))
            else: self.disableReasons()
            alt = script.cfg.getboolean("last", "alternate")
            if alt: self.chk_alternate.setChecked(True)
            dblclick = script.cfg.getboolean("last", "ban on doubleclick")
            if dblclick: self.chk_doubleclick.setChecked(True)
            for reason in script.templates:
                self.lst_reasons.addItem(reason)
                self.box_reason.addItem(reason)
            self.box_reason.setEditText(script.cfg.get("last", "reason")) # setItemText(0, )
            self.setup(script, schid, clid, uid, name, ip)
        except: ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)

    def setup(self, script, schid, clid, uid, name, ip):
        self.setWindowTitle("Ban \"{}\" ({})".format(name, clid))
        self.clid = clid
        url = script.cfg.getboolean("general", "ipapi")
        if url:
            self.nwmc_ip = QNetworkAccessManager()
            self.nwmc_ip.connect("finished(QNetworkReply*)", self.checkIP)
            self.countries = CountryFlags()
            self.countries.open()
        self.disableISP()
        self.grp_ip.setChecked(script.cfg.getboolean("last", "ip"))
        if ip: self.txt_ip.setText(ip)
        self.grp_name.setChecked(script.cfg.getboolean("last", "name"))
        if name: self.txt_name.setText(name)
        self.grp_uid.setChecked(script.cfg.getboolean("last", "uid"))
        if uid: self.txt_uid.setText(uid)
        self.int_duration.setValue(script.cfg.getint("last", "duration"))

    def disableReasons(self, enable=False):
        for item in [self.lst_reasons,self.line,self.chk_alternate,self.chk_doubleclick,self.chk_keep]:
            item.setVisible(enable)
        if enable:
            self.btn_reasons.setText("Reasons <")
            self.setFixedWidth(675) # self.resize(675, self.height)
        else:
            self.btn_reasons.setText("Reasons >")
            self.setFixedWidth(320) # self.resize(320, self.height)

    def disableISP(self, enable=False):
        # if not enable and self.txt_loc.isVisible(): return
        # elif enable and not self.txt_loc.isVisible(): return
        for item in [self.lbl_isp,self.txt_isp,self.lbl_flag,self.txt_loc]:
            item.setVisible(enable)

    def disableAlt(self, enable=False):
        self.lst_reasons.setAlternatingRowColors(enable)
        self.lst_reasons.setStyleSheet(self.cfg.get("general", "stylesheet") if enable else "")

    def checkIP(self, reply):
        try:
            data = reply.readAll().data().decode('utf-8')
            # if PluginHost.cfg.getboolean("general", "verbose"): print(self.name,"> checkIP() data:",data)
            data = loads(data)
            if PluginHost.cfg.getboolean("general", "verbose"): print(self.name, "> Resolved IP ", self.txt_ip.text,":", data)
            if data["status"] != "success": self.disableISP(); return
            self.txt_isp.setText(data["isp"])
            self.txt_loc.setText("{}, {}, {}".format(data["city"], data["regionName"], data["country"]))
            code = data["countryCode"]
            self.lbl_flag.setToolTip(code)
            self.lbl_flag.setPixmap(self.countries.flag(code))
            if not self.txt_isp.isVisible(): self.disableISP(True)
        except: ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)

    def on_txt_ip_textChanged(self, text):
        try:
            if not hasattr(self, "nwmc_ip"): self.disableISP(); return
            if not text: self.disableISP(); return
            if len(text) < 7: self.disableISP(); return
            ip = QHostAddress(text)
            if ip.isNull() or ip.isLoopback() or ip.isMulticast(): self.disableISP(); return
            if text.strip() in ["127.0.0.1", "0.0.0.0", "255.255.255"]: self.disableISP(); return
            self.nwmc_ip.get(QNetworkRequest(QUrl("http://ip-api.com/json/{ip}".format(ip=text))))
        except: ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)

    def on_box_reason_currentTextChanged(self, text):
        if not text in self.templates: return
        self.int_duration.setValue(self.templates[text])

    def on_lst_reasons_itemClicked(self, item):
        try: self.box_reason.setEditText(item.text())
        except: ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)

    def on_lst_reasons_itemDoubleClicked(self, item):
        if not self.chk_doubleclick.isChecked(): return
        self.box_reason.setEditText(item.text())
        self.on_btn_ban_clicked()

    def on_chk_alternate_toggled(self, enabled):
        self.disableAlt(enabled)

    def on_btn_ban_clicked(self):
        try:
            ip = self.txt_ip.text if self.grp_ip.isChecked() else ""
            name = self.txt_name.text if self.grp_name.isChecked() else ""
            uid = self.txt_uid.text if self.grp_uid.isChecked() else ""
            reason = self.box_reason.currentText
            if reason[0].isdigit():
                reason = "ยง" + reason
            duration = self.int_duration.value
            if self.moveBeforeBan: ts3lib.requestClientMove(self.schid, self.clid, 26, "")
            if ip:
                check = True
                if len(self.whitelist) < 1: check = confirm("Empty IP Whitelist!", "The IP whitelist is empty! Are you sure you want to ban \"{}\"?\n\nMake sure your whitelist URL\n{}\nis working!".format(ip, self.cfg.get("general", "whitelist")))
                if ip in self.whitelist: ts3lib.printMessageToCurrentTab("{}: [color=red]Not banning whitelisted IP [b]{}".format(self.name, ip))
                elif check: ts3lib.banadd(self.schid, ip, "", "", duration, reason)
            if name: ts3lib.banadd(self.schid, "", name, "", duration, reason)
            if uid: ts3lib.banadd(self.schid, "", "", uid, duration, reason)
            # msgBox("schid: %s\nip: %s\nname: %s\nuid: %s\nduration: %s\nreason: %s"%(self.schid, ip, name, uid, duration, reason))
            self.cfg["last"] = {
                "ip": str(self.grp_ip.isChecked()),
                "name": str(self.grp_name.isChecked()),
                "uid": str(self.grp_uid.isChecked()),
                "reason": reason,
                "duration": str(duration),
                "expanded": str(self.lst_reasons.isVisible()),
                "height": str(self.height),
                "alternate": str(self.chk_alternate.isChecked()),
                "ban on doubleclick": str(self.chk_doubleclick.isChecked()),
            }
            if not self.chk_keep.isChecked():
                self.close()
        except: ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)

    def on_btn_cancel_clicked(self):
        self.cfg.set("last", "expanded", str(self.lst_reasons.isVisible()))
        self.cfg.set("last", "height", str(self.height))
        self.cfg.set("last", "alternate", str(self.chk_alternate.isChecked()))
        self.cfg.set("last", "ban on doubleclick", str(self.chk_doubleclick.isChecked()))
        self.close()

    def on_btn_reasons_clicked(self):
        if self.lst_reasons.isVisible():
            self.disableReasons()
        else: self.disableReasons(True)
Example #2
0
class BanDialog(QDialog):
    moveBeforeBan = False
    clid = 0
    countries = None
    icon_warning = None

    def __init__(self,
                 script,
                 schid,
                 clid,
                 uid,
                 name,
                 ip,
                 mytsid,
                 hwid,
                 servertype,
                 parent=None):
        try:
            super(QDialog, self).__init__(parent)
            setupUi(self, "%s/ban.ui" % script.path)
            try:
                icons = IconPack.current()
                icons.open()
                self.icon_warning = QIcon(icons.icon("WARNING"))
            except:
                pass
            self.setAttribute(Qt.WA_DeleteOnClose)
            self.cfg = script.cfg
            self.ini = script.ini
            self.schid = schid
            self.templates = script.templates
            self.whitelist = script.whitelist
            self.prefix = script.prefix
            self.suffix = script.suffix
            self.name = script.name
            if script.cfg.getboolean("last", "expanded"):
                self.disableReasons(True)
            height = script.cfg.get("last", "height")
            if height: self.resize(self.width, int(height))
            else: self.disableReasons()
            alt = script.cfg.getboolean("last", "alternate")
            if alt: self.chk_alternate.setChecked(True)
            dblclick = script.cfg.getboolean("last", "ban on doubleclick")
            if dblclick: self.chk_doubleclick.setChecked(True)
            for reason in script.templates:
                self.lst_reasons.addItem(reason)
                self.box_reason.addItem(reason)
            self.box_reason.setEditText(script.cfg.get(
                "last", "reason"))  # setItemText(0, )
            """
            ipREX = QRegExp("[\w+\/]{27}=")
            ipREX.setCaseSensitivity(Qt.CaseInsensitive)
            ipREX.setPatternSyntax(QRegExp.RegExp)

            regValidator = QRegExpValidator(ipREX,0)
            self.txt_ip.setValidator(regValidator)
            """
            # self.txt_ip.setInputMask( "000.000.000.000" )

            self.setup(script, schid, clid, uid, name, ip, mytsid, hwid,
                       servertype)
        except:
            ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                              "pyTSon", 0)

    def setup(self, script, schid, clid, uid, name, ip, mytsid, hwid,
              servertype):
        self.setWindowTitle("Ban \"{}\" ({})".format(name, clid))
        self.clid = clid
        if not ip:
            (err, ip) = ts3lib.getConnectionVariable(
                schid, clid,
                ts3defines.ConnectionProperties.CONNECTION_CLIENT_IP)
        url = script.cfg.get("general", "ipapi")
        if url:
            self.nwmc_ip = QNetworkAccessManager()
            self.nwmc_ip.connect("finished(QNetworkReply*)", self.checkIP)
            self.countries = CountryFlags()
            self.countries.open()
        self.disableISP()
        self.grp_ip.setChecked(script.cfg.getboolean("last", "ip"))
        if ip != "None":
            self.txt_ip.setText(ip)
            self.on_txt_ip_textChanged(ip)
        self.grp_name.setChecked(script.cfg.getboolean("last", "name"))
        self.txt_name.setText(name)
        self.on_txt_name_textChanged(name)
        self.grp_uid.setChecked(script.cfg.getboolean("last", "uid"))
        self.txt_uid.setText(uid)
        self.on_txt_uid_textChanged(uid)
        self.grp_mytsid.setChecked(script.cfg.getboolean("last", "mytsid"))
        self.txt_mytsid.setText(mytsid)
        self.on_txt_mytsid_textChanged(mytsid)
        if servertype == ServerInstanceType.TEASPEAK:
            self.grp_hwid.setChecked(script.cfg.getboolean("last", "hwid"))
            self.txt_hwid.setText(hwid)
            self.on_txt_hwid_textChanged(hwid)
        else:
            self.grp_hwid.setVisible(False)
        self.setDuration(script.cfg.getint("last", "duration"))

    def disableReasons(self, enable=False):
        for item in [
                self.lst_reasons, self.line, self.chk_alternate,
                self.chk_doubleclick, self.chk_keep
        ]:
            item.setVisible(enable)
        if enable:
            self.btn_reasons.setText("Reasons <")
            self.setFixedWidth(675)  # self.resize(675, self.height)
        else:
            self.btn_reasons.setText("Reasons >")
            self.setFixedWidth(320)  # self.resize(320, self.height)

    def disableISP(self, enable=False):
        # if not enable and self.txt_loc.isVisible(): return
        # elif enable and not self.txt_loc.isVisible(): return
        for item in [self.lbl_isp, self.txt_isp, self.lbl_flag, self.txt_loc]:
            item.setVisible(enable)

    def disableAlt(self, enable=False):
        self.lst_reasons.setAlternatingRowColors(enable)
        self.lst_reasons.setStyleSheet(
            self.cfg.get("general", "stylesheet") if enable else "")

    def checkIP(self, reply):
        try:
            data = reply.readAll().data().decode('utf-8')
            # if PluginHost.cfg.getboolean("general", "verbose"): print(self.name,"> checkIP() data:",data)
            if PluginHost.cfg.getboolean("general", "verbose"):
                print(self.name, "> Resolved IP ", self.txt_ip.text, ":", data)
            data = loads(data)
            if data["status"] != "success":
                self.disableISP()
                return
            self.txt_isp.setText(data["isp"])
            self.txt_loc.setText("{}, {}, {}".format(data["city"],
                                                     data["regionName"],
                                                     data["country"]))
            code = data["countryCode"]
            self.lbl_flag.setToolTip(code)
            self.lbl_flag.setPixmap(self.countries.flag(code))
            if not self.txt_isp.isVisible(): self.disableISP(True)
        except:
            ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                              "pyTSon", 0)

    def on_txt_ip_textChanged(self, text):
        try:
            if not hasattr(self, "nwmc_ip"):
                self.disableISP()
                return
            if not text:
                self.disableISP()
                return
            if len(text) < 7:
                self.disableISP()
                return
            ip = QHostAddress(text)
            if ip.isNull() or ip.isLoopback() or ip.isMulticast():
                self.disableISP()
                return
            if text.strip() in ["127.0.0.1", "0.0.0.0", "255.255.255"]:
                self.disableISP()
                return
            self.nwmc_ip.get(
                QNetworkRequest(
                    QUrl(self.cfg.get("general", "ipapi").format(ip=text))))
        except:
            ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                              "pyTSon", 0)

    def on_txt_name_textChanged(self, text):
        self.validate(self.txt_name, '^.{3,32}$', text)

    def on_txt_uid_textChanged(self, text):
        self.validate(self.txt_uid, '^[\w+\/]{27}=$',
                      text)  # '^music#[\w]{15}$'

    def on_txt_mytsid_textChanged(self, text):
        self.validate(self.txt_mytsid, '^[\w+\/]{44}$', text)

    def on_txt_hwid_textChanged(self, text):
        self.validate(self.txt_hwid, '^[a-z0-9]{32},[a-z0-9]{32}$', text)

    def validate(self, elem, pattern, text, reason=None):
        try:
            actions = elem.actions()
            if not text:
                elem.setToolTip("")
                if self.icon_warning:
                    if len(actions): elem.removeAction(actions[0])
                else: elem.setStyleSheet("")
            valid = re.match(pattern, text)
            if not valid:
                if reason: elem.setToolTip(reason)
                else:
                    elem.setToolTip("This {name} seems to be invalid!".format(
                        name=elem.parentWidget().title))
                if self.icon_warning:
                    if not len(actions):
                        elem.addAction(self.icon_warning,
                                       QLineEdit.LeadingPosition)
                else:
                    elem.setStyleSheet("background-color:#5C4601")
            else:
                elem.setToolTip("")
                if self.icon_warning:
                    if len(actions): elem.removeAction(actions[0])
                else: elem.setStyleSheet("")
        except:
            ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                              "pyTSon", 0)

    def on_box_reason_currentTextChanged(self, text):
        if not text in self.templates: return
        self.setDuration(self.templates[text])
        self.validate(self.txt_reason, '^[\w+\/]{{,80}}$', text,
                      "This {name} is too long! (max 80 chars)")

    def on_lst_reasons_itemClicked(self, item):
        try:
            self.box_reason.setEditText(item.text())
        except:
            ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                              "pyTSon", 0)

    def on_lst_reasons_itemDoubleClicked(self, item):
        if not self.chk_doubleclick.isChecked(): return
        self.box_reason.setEditText(item.text())
        self.on_btn_ban_clicked()

    def on_chk_alternate_toggled(self, enabled):
        self.disableAlt(enabled)

    def setDuration(self, bantime):
        seconds = int(bantime)
        # delta = timedelta(seconds=bantime)
        # days, seconds = delta.days, delta.seconds
        days = seconds // 86400
        hours = seconds % 86400 // 3600
        minutes = (seconds % 3600) // 60
        seconds = (seconds % 60)
        self.int_duration_s.setValue(seconds)
        self.int_duration_m.setValue(minutes)
        self.int_duration_h.setValue(hours)
        self.int_duration_d.setValue(days)

    """
    def on_grp_hwid_toggled(self, enabled:bool):
        if enabled:
            self.grp_ip.setChecked(True)
            self.grp_uid.setChecked(True)
            self.grp_mytsid.setChecked(True)
            self.grp_name.setEnabled(False)
        else:
            self.grp_name.setEnabled(True)
    """

    def on_btn_regex_clicked(self):
        regex = ""
        name = self.txt_name.text.strip()
        self.txt_name.setText(name)
        name = re.escape(name)
        for char in name:
            if char.isalpha(): regex += "[%s%s]" % (char.upper(), char.lower())
            else: regex += char
        self.txt_name.setText(".*%s.*" % regex)

    def on_btn_ban_clicked(self):
        try:
            ip = self.txt_ip.text if self.grp_ip.isChecked() else ""
            name = self.txt_name.text if self.grp_name.isChecked() else ""
            uid = self.txt_uid.text if self.grp_uid.isChecked() else ""
            mytsid = self.txt_mytsid.text if self.grp_mytsid.isChecked(
            ) else ""
            hwid = self.txt_hwid.text if self.grp_hwid.isVisible(
            ) and self.grp_hwid.isChecked() else ""
            _reason = self.box_reason.currentText
            delta = timedelta(seconds=self.int_duration_s.value,
                              minutes=self.int_duration_m.value,
                              hours=self.int_duration_h.value,
                              days=self.int_duration_d.value)
            # duration = self.templates[_reason]
            err, ownnick = ts3lib.getClientSelfVariable(
                self.schid, ts3defines.ClientProperties.CLIENT_NICKNAME)
            reason = "{}{}{}".format(self.prefix, _reason, self.suffix)
            # delta = timedelta(seconds=duration)
            print(delta)
            reason = reason.replace("%ownnick%",
                                    ownnick).replace("%duration%", str(delta))
            # if reason[0].isdigit(): reason = "" + reason
            duration = int(delta.total_seconds())
            if self.moveBeforeBan:
                ts3lib.requestClientMove(self.schid, self.clid, 26, "")
            # if uid:
            if ip:
                check = True
                if len(self.whitelist) < 1:
                    check = confirm(
                        "Empty IP Whitelist!",
                        "The IP whitelist is empty! Are you sure you want to ban \"{}\"?\n\nMake sure your whitelist URL\n{}\nis working!"
                        .format(ip, self.cfg.get("general", "whitelist")))
                if ip in self.whitelist:
                    ts3lib.printMessageToCurrentTab(
                        "{}: [color=red]Not banning whitelisted IP [b]{}".
                        format(self.name, ip))
                elif check:
                    ts3lib.banadd(self.schid, ip, "", "", duration, reason)
            if name: ts3lib.banadd(self.schid, "", name, "", duration, reason)
            if uid: ts3lib.banadd(self.schid, "", "", uid, duration, reason)
            if mytsid:
                ts3lib.requestSendClientQueryCommand(
                    self.schid,
                    "banadd mytsid={id} banreason={reason} time={duration}".
                    format(id=mytsid,
                           reason=escapeStr(reason),
                           duration=duration))
            if hwid:
                ts3lib.requestSendClientQueryCommand(
                    self.schid,
                    "banadd hwid={id} banreason={reason} time={duration}".
                    format(id=hwid,
                           reason=escapeStr(reason),
                           duration=duration))
            # msgBox("schid: %s\nip: %s\nname: %s\nuid: %s\nduration: %s\nreason: %s"%(self.schid, ip, name, uid, duration, reason))
            self.cfg["last"] = {
                "ip": str(self.grp_ip.isChecked()),
                "name": str(self.grp_name.isChecked()),
                "uid": str(self.grp_uid.isChecked()),
                "mytsid": str(self.grp_mytsid.isChecked()),
                "hwid": str(self.grp_hwid.isChecked()),
                "reason": _reason,
                "duration": str(duration),
                "expanded": str(self.lst_reasons.isVisible()),
                "height": str(self.height),
                "alternate": str(self.chk_alternate.isChecked()),
                "ban on doubleclick": str(self.chk_doubleclick.isChecked()),
            }
            if not self.chk_keep.isChecked():
                self.close()
        except:
            ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                              "pyTSon", 0)

    def on_btn_cancel_clicked(self):
        self.cfg.set("last", "expanded", str(self.lst_reasons.isVisible()))
        self.cfg.set("last", "height", str(self.height))
        self.cfg.set("last", "alternate", str(self.chk_alternate.isChecked()))
        self.cfg.set("last", "ban on doubleclick",
                     str(self.chk_doubleclick.isChecked()))
        self.close()

    def on_btn_reasons_clicked(self):
        if self.lst_reasons.isVisible():
            self.disableReasons()
        else:
            self.disableReasons(True)
Example #3
0
class ServersDialog(QDialog):
    requests = 0
    page = 1
    pages = 1
    cooldown = False
    cooldown_page = False
    cooldown_time = 5000
    cooldown_time_page = 1000
    countries = []
    NAME_MODIFIERS = ["Contains", "Starts with", "Ends with"]

    def buhl(self, s):
        if s.lower() == 'true' or s == 1:
            return True
        elif s.lower() == 'false' or s == 0:
            return False
        else:
            raise ValueError("Cannot convert {} to a bool".format(s))

    def __init__(self, serverBrowser, parent=None):
        self.serverBrowser = serverBrowser
        super(QDialog, self).__init__(parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        setupUi(
            self,
            os.path.join(ts3.getPluginPath(), "pyTSon", "scripts",
                         "serverBrowser", "ui", "servers.ui"))
        self.setWindowTitle("PlanetTeamspeak Server Browser")
        self.flags = CountryFlags()
        self.flags.open()
        self.icons = IconPack.current()
        self.icons.open()
        #ts3.printMessageToCurrentTab("Countries: "+str(self.countries))
        #try:
        #self.serverList.doubleClicked.connect(self.table_doubleclicked)
        #self.serverList.connect("doubleClicked()", self.table_doubleclicked)
        #self.apply.connect("clicked()", self.on_apply_clicked)
        #self.reload.connect("clicked()", self.on_reload_clicked)
        #except:
        #ts3.logMessage(traceback.format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "PyTSon", 0)
        #self.ReasonList.connect("currentItemChanged(QListWidgetItem*, QListWidgetItem*)", self.onReasonListCurrentItemChanged)
        #self.ReasonList.connect("itemChanged(QListWidgetItem*)", self.onReasonListItemChanged)
        # self.serverList.setVisible(False)
        self.serverList.horizontalHeader().setStretchLastSection(True)
        self.serverList.setColumnWidth(0, 350)
        # self.serverList.setColumnWidth(5, 0)
        self.serverList.setColumnHidden(5, True)
        self.serverNameModifier.addItems(self.NAME_MODIFIERS)
        self.serverNameModifier.setEnabled(False)
        #self.pageLabel.mousePressEvent = self.on_pageLabel_clicked
        #self.cfg.set("general", "differentApi", "True" if state == Qt.Checked else "False")
        self.listCountries(True)
        #ReportDialog.ReasonList.clear()
        self.setupFilters()
        # self.serverList.doubleClicked.connect(self.on_serverList_doubleClicked)
        # self.serverList.cellClicked.connect(self.cell_was_clicked)
        #ts3.printMessageToCurrentTab(str(serverBrowser.filters))
        #if serverBrowser.filters.filterServerName != "":
        #self.filterServerName.setText(serverBrowser.filters.filterServerName)
        #item.setFlags(item.flags() &~ Qt.ItemIsEditable)
        # self.countryBox.clear()
        #for item in countries:
        #self.countryBox.addItem(str(item[1]))
        #self.serverList.setStretchLastSection(true)
        self.listServers()

    def setupFilters(self):
        try:
            _filters = self.serverBrowser.config["FILTERS"]
            buhl = self.buhl
            self.hideEmpty.setChecked(buhl(_filters["hideEmpty"]))
            self.hideFull.setChecked(buhl(_filters["hideFull"]))
            self.maxUsers.setChecked(buhl(_filters["maxUsers"]))
            self.maxUsersMin.setValue(int(_filters["maxUsersMin"]))
            self.maxUsersMax.setValue(int(_filters["maxUsersMax"]))
            self.maxSlots.setChecked(buhl(_filters["maxSlots"]))
            self.maxSlotsMin.setValue(int(_filters["maxSlotsMin"]))
            self.maxSlotsMax.setValue(int(_filters["maxSlotsMax"]))
            if _filters["filterPassword"] == "none":
                self.filterPasswordShowWithout.setChecked(True)
                #self.filterPasswordShowWith.setChecked(False)
                #self.filterPasswordShowAll.setChecked(False)
            elif _filters["filterPassword"] == "only":
                #self.filterPasswordShowWithout.setChecked(False)
                self.filterPasswordShowWith.setChecked(True)
                #self.filterPasswordShowAll.setChecked(False)
            else:
                #self.filterPasswordShowWithout.setChecked(False)
                #self.filterPasswordShowWith.setChecked(False)
                self.filterPasswordShowAll.setChecked(True)
            if _filters["filterChannels"] == "none":
                self.filterChannelsCantCreate.setChecked(True)
                #self.filterChannelsCanCreate.setChecked(False)
                #self.filterChannelsShowAll.setChecked(False)
            elif _filters["filterChannels"] == "only":
                #self.filterChannelsCantCreate.setChecked(False)
                self.filterChannelsCanCreate.setChecked(True)
                #self.filterChannelsShowAll.setChecked(False)
            else:
                #self.filterChannelsCantCreate.setChecked(False)
                #self.filterChannelsCanCreate.setChecked(False)
                self.filterChannelsShowAll.setChecked(True)
            self.serverNameModifier.setCurrentText(
                _filters["serverNameModifier"])
            self.filterServerName.setText(_filters["filterServerName"])
            if self.countryBox.findText(
                    _filters["countryBox"].split(' (')[0]) < 0:
                self.countryBox.addItem(_filters["countryBox"])
            self.countryBox.setCurrentIndex(
                self.countryBox.findText(_filters["countryBox"]))
            self.listServers()
        except:
            ts3.logMessage(traceback.format_exc(),
                           ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)

    # def contextMenuEvent(self, event):
    #     try:
    #         self.menu = QMenu(self.serverList)
    #         connectAction = QAction('Connect', self)
    #         #connectAction.triggered.connect(self.connect)
    #         self.menu.addAction(connectAction)
    #         self.menu.popup(QCursor.pos())
    #     except:
    #         ts3.logMessage(traceback.format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)

    def connect(self):
        index = self.serverList.selectedIndexes()[0]
        id_us = int(self.serverList.model().data(index).toString())
        ts3.printMessageToCurrentTab("index : " + str(id_us))

    def setupURL(self):
        # import urllib
        # f = { 'eventName' : 'myEvent', 'eventDescription' : "cool event"}
        # urllib.urlencode(f)
        _filters = self.serverBrowser.config["FILTERS"]
        url = self.serverBrowser.config['GENERAL'][
            'api'] + "serverlist/?page=" + str(self.page) + "&limit=" + str(
                self.serverBrowser.config['GENERAL']['serversperpage'])
        if _filters["filterPassword"] == "none":
            url += "&password=false"
        elif _filters["filterPassword"] == "only":
            url += "&password=true"
        if _filters["filterChannels"] == "none":
            url += "&createchannels=false"
        elif _filters["filterChannels"] == "only":
            url += "&createchannels=true"
        if self.buhl(_filters["maxUsers"]):
            url += "&minusers=" + str(
                _filters["maxUsersMin"]) + "&maxusers=" + str(
                    _filters["maxUsersMax"])
        if self.buhl(_filters["maxSlots"]):
            url += "&minslots=" + str(
                _filters["maxSlotsMin"]) + "&maxslots=" + str(
                    _filters["maxSlotsMax"])
        if _filters["filterServerName"] and _filters["filterServerName"] != "":
            url += "&search=" + urllib.parse.quote_plus(
                _filters["filterServerName"])
        cid = self.getCountryIDbyName(_filters["countryBox"])
        print("cb: \"{0}\"".format(_filters["countryBox"]))
        print("cid: \"{0}\"".format(cid))
        if _filters["countryBox"] != "All" and (cid != '--' or cid != '-'):
            url += "&country=" + cid
        if self.serverBrowser.config["GENERAL"]["debug"] == "True":
            ts3.printMessageToCurrentTab("Requesting: " + url)
        return url

    def getCountryIDbyName(self, name):
        try:
            if name.__contains__(" ("):
                name = name.split(" (")[0]
            return [c for c in self.countries if c[1] == name][0][0]
        except:
            return '-'

    def getCountryNamebyID(self, cid):
        try:
            return [c for c in self.countries if c[0] == cid][0][1]
        except:
            return 'Unknown (' + cid + ')'

    def onCountryListReply(self, reply):
        try:
            _api = self.serverBrowser.config['GENERAL']['api']
            _reply = reply.readAll()
            countries = json.loads(
                _reply.data().decode('utf-8'))["result"]["data"]
            if self.serverBrowser.config["GENERAL"]["debug"] == "True":
                ts3.printMessageToCurrentTab("%s" % countries)
            _reason = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
            self.status.setText("Response from \"{0}\": {1}: {2}".format(
                _api, _reason,
                reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute)))
            palette = QPalette()
            if _reason == 200:
                palette.setColor(QPalette.Foreground, Qt.darkGreen)
                self.countryBox.clear()
            else:
                palette.setColor(QPalette.Foreground, Qt.red)
            self.status.setPalette(palette)
            y = sum(x[2] for x in countries)
            #y = 0
            #for x in countries:
            #   y = y + x[2]
            #if self.serverBrowser.config["GENERAL"]["debug"] == "True":
            #   ts3.printMessageToCurrentTab(str(countries))
            if "-" in [h[0] for h in countries]:
                countries = countries[0:1] + sorted(countries[1:],
                                                    key=lambda x: x[1])
            else:
                countries = sorted(countries, key=lambda x: x[1])
            self.countries = [['ALL', 'All', y]] + countries
            if self.serverBrowser.config['GENERAL']['morerequests'] == "True":
                self.countryBox.addItems(
                    [x[1] + " (" + str(x[2]) + ")" for x in self.countries])
            else:
                self.countryBox.addItems([x[1] for x in self.countries])

            #__countries = __countries.__add__([['ALL', 'All', 0]])
        except:
            ts3.logMessage(traceback.format_exc(),
                           ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)

    def requestCountries(self):
        self.nwmc = QNetworkAccessManager()
        self.nwmc.connect("finished(QNetworkReply*)", self.onCountryListReply)
        self.nwmc.get(
            QNetworkRequest(
                QUrl(self.serverBrowser.config['GENERAL']['api'] +
                     "servercountries")))
        if self.serverBrowser.config["GENERAL"]["debug"] == "True":
            ts3.printMessageToCurrentTab(
                "requestCountries: " +
                self.serverBrowser.config['GENERAL']['api'] +
                "servercountries")

    def listCountries(self, force=False):
        if force or self.serverBrowser.config['GENERAL'][
                'morerequests'] == "True":
            self.requestCountries()

    def serversReply(self, reply):
        try:
            _api = self.serverBrowser.config['GENERAL']['api']
            _reason = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
            _reply = reply.readAll()
            servers = json.loads(_reply.data().decode('utf-8'))
            if self.serverBrowser.config["GENERAL"]["debug"] == "True":
                ts3.printMessageToCurrentTab("servers: %s" % servers)
            self.status.setText("Response from \"{0}\": {1}: {2}".format(
                _api, _reason,
                reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute)))
            palette = QPalette()
            if not _reason == 200:
                palette.setColor(QPalette.Foreground, Qt.red)
            self.status.setPalette(palette)

            self.status.setText(
                "Status: %s" %
                reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute))
            if servers["status"] == "success":
                self.pages = servers["result"]["pagestotal"]
                self.pageLabel.setText(
                    str(servers["result"]["pageactive"]) + " / " +
                    str(servers["result"]["pagestotal"]))
                self.pageLabel.updateGeometry()
                self.info.setText(
                    str(servers["result"]["itemsshown"]) + " / " +
                    str(servers["result"]["itemstotal"]) + " Servers shown.")
                self.serverList.setRowCount(0)
            elif servers["status"] == "error":
                self.info.setText("Requested Page: " + str(self.page))
                self.status.setText(servers["status"].title() + ": " +
                                    servers["result"]["message"] + " (" +
                                    str(servers["result"]["code"]) + ")")
                palette = QPalette()
                palette.setColor(QPalette.Foreground, Qt.red)
                self.status.setPalette(palette)
                return
            else:
                self.info.setText("Requested Page: " + str(self.page))
                palette = QPalette()
                palette.setColor(QPalette.Foreground, Qt.red)
                self.status.setPalette(palette)
                return
            _list = self.serverList
            _filters = self.serverBrowser.config["FILTERS"]
            if servers["result"]["pageactive"] == 1:
                self.previous.setEnabled(False)
            else:
                self.previous.setEnabled(True)
            if servers["result"]["pageactive"] == servers["result"][
                    "pagestotal"]:
                self.next.setEnabled(False)
            else:
                self.next.setEnabled(True)
            for key in servers["result"]["data"]:
                if self.buhl(
                        _filters["hideFull"]) and key["users"] >= key["slots"]:
                    continue
                elif self.buhl(_filters["hideEmpty"]) and key["users"] <= 0:
                    continue
                else:
                    rowPosition = _list.rowCount
                    _list.insertRow(rowPosition)
                    # if key['premium']:
                    #     _list.setItem(rowPosition, 0, QTableWidgetItem("Yes"))
                    # else:
                    #     _list.setItem(rowPosition, 0, QTableWidgetItem("No"))
                    _list.setItem(rowPosition, 0,
                                  QTableWidgetItem(key['name']))
                    _list.setItem(
                        rowPosition, 1,
                        QTableWidgetItem(
                            str(key['users']) + ' / ' + str(key['slots'])))
                    if key['users'] >= key['slots']:
                        palette = QPalette()
                        palette.setColor(QPalette.Foreground, Qt.red)
                        _list.setPalette(palette)
                    item_country = QTableWidgetItem(
                        self.getCountryNamebyID(key['country']))
                    item_country.setIcon(QIcon(self.flags.flag(
                        key['country'])))
                    _list.setItem(rowPosition, 2, item_country)
                    item_createchannels = QTableWidgetItem()
                    if key['createchannels']:
                        item_createchannels.setText("Yes")
                        item_createchannels.setIcon(
                            QIcon(IconPack.icon(self.icons, "channel_create")))
                    else:
                        item_createchannels.setText("No")
                        item_createchannels.setIcon(
                            QIcon(IconPack.icon(self.icons, "channel_delete")))
                    _list.setItem(rowPosition, 3, item_createchannels)
                    item_password = QTableWidgetItem()
                    if key['password']:
                        item_password.setText("Yes")
                        item_password.setIcon(
                            QIcon(IconPack.icon(self.icons,
                                                "channel_private")))
                    else:
                        item_password.setText("No")
                        item_password.setIcon(
                            QIcon(IconPack.icon(self.icons, "channel_green")))
                    _list.setItem(rowPosition, 4, item_password)
                    _list.setItem(rowPosition, 5,
                                  QTableWidgetItem(key["address"]))
                    # first_cell = _list.item(rowPosition, 0)
                    # first_cell.setData(Qt.UserRole, key['address'])
            _color = self.serverBrowser.config["GENERAL"][
                "alternatebackgroundcolor"]
            if _color != "":
                _list.styleSheet = "alternate-background-color: {0};".format(
                    _color)
            else:
                _list.setAlternatingRowColors(False)
        except:
            ts3.logMessage(traceback.format_exc(),
                           ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)

    def requestServers(self, url):
        if self.serverBrowser.config["GENERAL"]["debug"] == "True":
            self.requests += 1
            ts3.printMessageToCurrentTab("Request: " + str(self.requests))
        self.nwm = QNetworkAccessManager()
        self.nwm.connect("finished(QNetworkReply*)", self.serversReply)
        self.nwm.get(QNetworkRequest(QUrl(url)))

    def listServers(self):
        if self.cooldown:
            self.status.setText("You have to wait " +
                                str(self.cooldown_time / 1000) +
                                " second(s) before retrying!")
            palette = QPalette()
            palette.setColor(QPalette.Foreground, Qt.red)
            self.status.setPalette(palette)
            return
        url = self.setupURL()
        self.requestServers(url)

    #def onReasonListItemChanged(self, item):
    #checked = item.checkState() == Qt.Checked
    #name = item.data(Qt.UserRole)

    #if checked and name not in self.host.active:
    #self.host.activate(name)
    #elif not checked and name in self.host.active:
    #self.host.deactivate(name)

    #if self.pluginsList.currentItem() == item:
    #self.settingsButton.setEnabled(checked and name in self.host.active and self.host.active[name].offersConfigure)

    def disable_cooldown(self):
        self.cooldown = False
        self.reload.setEnabled(True)

    def disable_cooldown_page(self):
        self.cooldown_page = False
        if self.page > 1:
            self.previous.setEnabled(True)
            self.first.setEnabled(True)
        if self.page < self.pages:
            self.next.setEnabled(True)
            self.last.setEnabled(True)

    def on_apply_clicked(self):
        try:
            self.serverBrowser.config.set("FILTERS", "hideEmpty",
                                          str(self.hideEmpty.isChecked()))
            self.serverBrowser.config.set("FILTERS", "hideFull",
                                          str(self.hideFull.isChecked()))
            self.serverBrowser.config.set("FILTERS", "maxUsers",
                                          str(self.maxUsers.isChecked()))
            self.serverBrowser.config.set("FILTERS", "maxUsersMin",
                                          str(self.maxUsersMin.value))
            self.serverBrowser.config.set("FILTERS", "maxUsersMax",
                                          str(self.maxUsersMax.value))
            self.serverBrowser.config.set("FILTERS", "maxSlots",
                                          str(self.maxSlots.isChecked()))
            self.serverBrowser.config.set("FILTERS", "maxSlotsMin",
                                          str(self.maxSlotsMin.value))
            self.serverBrowser.config.set("FILTERS", "maxSlotsMax",
                                          str(self.maxSlotsMax.value))
            if self.filterPasswordShowWithout.isChecked():
                self.serverBrowser.config.set("FILTERS", "filterPassword",
                                              "none")
            elif self.filterPasswordShowWith.isChecked():
                self.serverBrowser.config.set("FILTERS", "filterPassword",
                                              "only")
            elif self.filterPasswordShowAll.isChecked():
                self.serverBrowser.config.set("FILTERS", "filterPassword",
                                              "all")
            if self.filterChannelsCantCreate.isChecked():
                self.serverBrowser.config.set("FILTERS", "filterChannels",
                                              "none")
            elif self.filterChannelsCanCreate.isChecked():
                self.serverBrowser.config.set("FILTERS", "filterChannels",
                                              "only")
            elif self.filterChannelsShowAll.isChecked():
                self.serverBrowser.config.set("FILTERS", "filterChannels",
                                              "all")
            self.serverBrowser.config.set("FILTERS", "serverNameModifier",
                                          self.serverNameModifier.currentText)
            self.serverBrowser.config.set("FILTERS", "filterServerName",
                                          self.filterServerName.text)
            self.serverBrowser.config.set(
                "FILTERS", "countryBox",
                self.countryBox.currentText.split(" (")[0])
            with open(self.serverBrowser.ini, 'w') as configfile:
                self.serverBrowser.config.write(configfile)
            if self.buhl(self.serverBrowser.config['GENERAL']['morerequests']):
                self.listCountries()
            self.page = 1
            self.listServers()
            if not self.cooldown:
                self.cooldown = True
                QTimer.singleShot(self.cooldown_time, self.disable_cooldown)
        except:
            ts3.logMessage(traceback.format_exc(),
                           ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)

    def on_navigate(self, page=1, direction=0):
        try:
            if self.cooldown_page:
                self.status.setText("You have to wait " +
                                    str(self.cooldown_time_page / 1000) +
                                    " second(s) before switching pages!")
                palette = QPalette()
                palette.setColor(QPalette.Foreground, Qt.red)
                self.status.setPalette(palette)
                return
            if direction == 2:
                self.page += page
            elif direction == 1:
                self.page -= page
            else:
                self.page = page
            self.listServers()
            if not self.cooldown:
                self.cooldown_page = True
                self.previous.setEnabled(False)
                self.next.setEnabled(False)
                self.first.setEnabled(False)
                self.last.setEnabled(False)
                QTimer.singleShot(self.cooldown_time_page,
                                  self.disable_cooldown_page)
        except:
            ts3.logMessage(traceback.format_exc(),
                           ts3defines.LogLevel.LogLevel_ERROR, "PyTSon", 0)

    def on_reload_clicked(self):
        try:
            self.listServers()
            if not self.cooldown:
                self.cooldown = True
                self.reload.setEnabled(False)
                QTimer.singleShot(self.cooldown_time, self.disable_cooldown)
        except:
            ts3.logMessage(traceback.format_exc(),
                           ts3defines.LogLevel.LogLevel_ERROR, "PyTSon", 0)

    def on_previous_clicked(self):
        try:
            self.on_navigate(1, 1)
        except:
            ts3.logMessage(traceback.format_exc(),
                           ts3defines.LogLevel.LogLevel_ERROR, "PyTSon", 0)

    def on_next_clicked(self):
        try:
            self.on_navigate(1, 2)
        except:
            ts3.logMessage(traceback.format_exc(),
                           ts3defines.LogLevel.LogLevel_ERROR, "PyTSon", 0)

    def on_first_clicked(self):
        try:
            self.on_navigate()
        except:
            ts3.logMessage(traceback.format_exc(),
                           ts3defines.LogLevel.LogLevel_ERROR, "PyTSon", 0)

    def on_last_clicked(self):
        try:
            self.on_navigate(self.pages)
        except:
            ts3.logMessage(traceback.format_exc(),
                           ts3defines.LogLevel.LogLevel_ERROR, "PyTSon", 0)

    def on_pageLabel_clicked(self, event):
        try:
            page = QInputDialog.getInt(self, "Goto Page", "Page:")
            if page > 0:
                if self.cooldown_page:
                    self.status.setText("You have to wait " +
                                        str(self.cooldown_time_page / 1000) +
                                        " second(s) before switching pages!")
                    palette = QPalette()
                    palette.setColor(QPalette.Foreground, Qt.red)
                    self.status.setPalette(palette)
                    return
                self.page = page
                self.listServers()
                if not self.cooldown:
                    self.cooldown_page = True
                    self.previous.setEnabled(False)
                    self.next.setEnabled(False)
                    QTimer.singleShot(self.cooldown_time_page,
                                      self.disable_cooldown_page)
        except:
            ts3.logMessage(traceback.format_exc(),
                           ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)

    def on_serverList_doubleClicked(self):
        try:
            row = self.serverList.selectedItems()[0].row()
            name = self.serverList.item(row, 0).text()
            ip = self.serverList.item(row, 5).text()
            haspw = True if self.serverList.item(row,
                                                 4).text() == "Yes" else False
            if haspw:
                x = QWidget()
                x.setAttribute(Qt.WA_DeleteOnClose)
                password = QInputDialog.getText(x, "Enter Server Password",
                                                "Password:"******"": return
            err, tab = ts3.guiConnect(
                ts3defines.PluginConnectTab.
                PLUGIN_CONNECT_TAB_NEW_IF_CURRENT_CONNECTED, name, ip,
                password if haspw else "", "TeamspeakUser", "", "", "", "", "",
                "", "", "", "")
            # print('item: {0} | row: {1} | item2: {2} |item2_column: {3} | text: {4}'.format(item, row, item2, item2.column(), item2.text()))
            # item.
            # item.setData(Qt.UserRole, 22);
        except:
            print(traceback.format_exc())

    def cell_was_clicked(self, row, column):
        pass
        try:
            print("Row %d and Column %d was clicked" % (row, column))
            item = self.serverList.itemAt(row, column)
            self.ID = item.text()
            print(self.ID)
        except:
            print(traceback.format_exc())