Beispiel #1
0
 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())
Beispiel #2
0
 def __init__(self, purgeContacts, filter, txt, date, parent=None):
     try:
         super(QDialog, self).__init__(parent)
         setupUi(self, path.join(purgeContacts.scriptpath, "preview.ui"))
         self.setAttribute(Qt.WA_DeleteOnClose)
         db = ts3client.Config()
         q = db.query("SELECT * FROM contacts")
         while q.next():
             contact = q.value("value").split('\n')
             """
             if line.startswith('Friend='):
                 status = int(line[-1])
                 if status == ContactStatus.FRIEND: buddies += 1
                 elif status == ContactStatus.BLOCKED: blocked += 1
                 elif status == ContactStatus.NEUTRAL: neutral += 1
                 else: unknown += 1
             elif line.lower().startswith('nickname=w/'):
                 female += 1
             elif line.lower().startswith('nickname=m/'):
                 male += 1
             """
         del db
         # self.setWindowTitle(self.windowTitle().format()) # TODO
     except:
         ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                           "pyTSon", 0)
Beispiel #3
0
def getContacts():
    """
    :return:
    """
    db = ts3client.Config()
    ret = []
    q = db.query("SELECT * FROM contacts")
    while q.next():
        try:
            cur = {"Key": int(q.value("key")), "Timestamp": q.value("timestamp")}
            val = q.value("value")
            for l in val.split('\n'):
                try:
                    l = l.split('=', 1)
                    if len(l) != 2: continue
                    if l[0] in ["Nickname","PhoneticNickname","LastSeenServerName"]: cur[l[0]] = l[1].encode('ascii', 'ignore')
                    elif l[0] in ["LastSeenServerAddress","IDS","VolumeModifier", "LastSeen"]: cur[l[0]] = l[1]
                    elif l[0] in ["Friend","NickShowType"]: cur[l[0]] = int(l[1])
                    elif l[0] in ["Automute","IgnorePublicMessages","IgnorePrivateMessages","IgnorePokes","IgnoreAvatar","IgnoreAwayMessage","HaveVolumeModifier","WhisperAllow"]:
                        if l[1] == "false": cur[l[0]] = False
                        elif l[1] == "true": cur[l[0]] = True
                    if l[0] == "LastSeen" and l[1]: cur["LastSeenEpoch"] = int(time.mktime(time.strptime(l[1], '%Y-%m-%dT%H:%M:%S')))
                except: continue
            ret.append(cur)
        except: continue
    del db
    return ret
Beispiel #4
0
def loadBadges():
    """
    Loads Badges from ts3settings.db
    :return: int(timestamp), str(ret), dict(badges)
    """
    db = ts3client.Config()
    q = db.query("SELECT * FROM Badges")  #  WHERE key = BadgesListData
    timestamp = 0
    ret = {}
    badges = b''
    while q.next():
        key = q.value("key")
        if key == "BadgesListTimestamp":
            timestamp = q.value("value")
        elif key == "BadgesListData":
            badges = q.value("value")
            next = 12
            guid_len = 0
            guid = ""
            name_len = 0
            name = ""
            url_len = 0
            url = ""
            filename = ""
            desc_len = 0
            desc = ""
            try:
                for i in range(0, badges.size()):
                    if i == next:  #guid_len
                        guid_len = int(badges.at(i))
                        guid = str(badges.mid(i + 1, guid_len))
                    elif i == (next + 1 + guid_len + 1):
                        name_len = int(badges.at(i))
                        name = str(badges.mid(i + 1, name_len))
                    elif i == (next + 1 + guid_len + 1 + name_len + 2):
                        url_len = int(badges.at(i))
                        url = str(badges.mid(i + 1, url_len))
                        filename = url.rsplit('/', 1)[1]
                    elif i == (next + 1 + guid_len + 1 + name_len + 2 +
                               url_len + 2):
                        desc_len = int(badges.at(i))
                        desc = str(badges.mid(i + 1, desc_len))
                        ret[guid] = {
                            "name": name,
                            "url": url,
                            "filename": filename,
                            "description": desc
                        }
                        next = (next + guid_len + 2 + name_len + 2 + url_len +
                                2 + desc_len + 13)
                delimiter = badges.mid(0, 12)
            except:
                from traceback import format_exc
                ts3lib.logMessage(format_exc(),
                                  ts3defines.LogLevel.LogLevel_ERROR, "pyTSon",
                                  0)
    del db
    return timestamp, ret, badges
Beispiel #5
0
 def infoData(self, schid, id, atype):
     if self.count < 3:
         self.count += 1
         return None
     clist = list()
     if atype == ts3defines.PluginItemType.PLUGIN_SERVER:
         (err, clist) = ts3lib.getClientList(schid)
     elif atype == ts3defines.PluginItemType.PLUGIN_CHANNEL:
         return None
         (err, clist) = ts3lib.getChannelClientList(schid, id)
     else:
         return None
     sum = 0
     buddies = 0
     blocked = 0
     neutral = 0
     unknown = 0
     uidlist = []
     for clid in clist:
         (err, uid) = ts3lib.getClientVariable(
             schid, clid,
             ts3defines.ClientProperties.CLIENT_UNIQUE_IDENTIFIER)
         uidlist.append(uid)
     db = ts3client.Config()
     q = db.query("SELECT * FROM contacts")
     while q.next():
         sum += 1
         val = q.value("value").split('\n')
         uid = ""
         for line in val:
             if line.startswith('IDS='):
                 uid = line.split('IDS=')[1]
         if not uid in uidlist: continue
         for line in val:
             if line.startswith('Friend='):
                 status = int(line[-1])
                 if status == ContactStatus.FRIEND: buddies += 1
                 elif status == ContactStatus.BLOCKED: blocked += 1
                 elif status == ContactStatus.NEUTRAL: neutral += 1
                 else: unknown += 1
     del db
     _return = list()
     _sum = buddies + blocked + neutral + unknown
     _return.append("Online: {} / {} ({}%)".format(_sum, sum,
                                                   percentage(_sum, sum)))
     _return.append("[color=green]Buddies[/color]: {} ({}%)".format(
         buddies, percentage(buddies, _sum)))
     _return.append("[color=red]Blocked[/color]: {} ({}%)".format(
         blocked, percentage(blocked, _sum)))
     _return.append("Neutral: {} ({}%)".format(neutral,
                                               percentage(neutral, _sum)))
     if unknown > 0:
         _return.append("[color=orange]Unknown[/color]: {} ({}%)".format(
             unknown, percentage(unknown, _sum)))
     return _return
Beispiel #6
0
def getContactStatus(uid):
    db = ts3client.Config()
    q = db.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])
    del db
    return ret
Beispiel #7
0
def getAddons():
    db = ts3client.Config()
    q = db.query("SELECT * FROM addons")
    ret = {}
    while q.next():
        try:
            key = q.value("key")
            ret[key] = {"timestamp": q.value("timestamp")}
            val = q.value("value")
            for l in val.split('\n'):
                l = l.split('=', 1)
                ret[key][l[0]] = l[1]
        except: from traceback import format_exc;ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0);continue
    return ret
Beispiel #8
0
def loadBadges():
    """
    Loads Badges from ts3settings.db
    :return: int(timestamp), str(ret), dict(badges)
    """
    db = ts3client.Config()
    q = db.query("SELECT * FROM Badges")  #  WHERE key = BadgesListData
    timestamp = 0
    ret = {}
    badges = QByteArray()
    while q.next():
        key = q.value("key")
        if key == "BadgesListTimestamp":
            timestamp = q.value("value")
        elif key == "BadgesListData":
            ret, badges = parseBadgesBlob(q.value("value"))
    del db
    return timestamp, ret, badges
Beispiel #9
0
 def setMeta(self, schid, ownID=None):
     try:
         if not self.cfg.getboolean('general', 'enabled'): return
         if ownID is None: (error, ownID) = ts3.getClientID(schid)
         (error, oldmeta) = ts3.getClientVariableAsString(schid, ownID, ts3defines.ClientProperties.CLIENT_META_DATA)
         # e = xml.etree.ElementTree.parse('<addons><pytson></pytson></addons>').getroot()
         if oldmeta and '<{}>'.format(self.tag) in oldmeta:
             oldmeta = re.sub(r"<{0}>.*</{0}>".format(self.tag), "", oldmeta)
         newmeta = xml.Element('addons')
         db = ts3client.Config()
         q = db.query("SELECT value FROM addons")
         while(q.next()):
             val = q.value("value")
             addon = xml.SubElement(newmeta, "a")
             for l in val.split('\n'):
                 try:
                     if l.startswith('name='):
                         name = l.split('=', 1)[1].strip()
                         addon.text = name
                     elif l.startswith('version='):
                         version = l.split('=', 1)[1].strip()
                         addon.set("v", version)
                     elif l.startswith('author='):
                         author = l.split('=', 1)[1].strip()
                         addon.set("a", author)
                     elif l.startswith('type='):
                         type = l.split('=', 1)[1].strip()
                         addon.set("t", type)
                 except:from traceback import format_exc;ts3.logMessage("Error reading addon from Database:\n%s"%(name,format_exc()), ts3defines.LogLevel.LogLevel_ERROR, "{c}.{f}".format(c=self.__class__,f=__name__), schid);continue
         del db
         try: pytson = [element for element in newmeta.iter() if element.text == 'pyTSon'][0]
         except: pass
         if self.cfg.getboolean("general", "activeonly"): plugins = pluginhost.PluginHost.active.items()
         else: plugins = pluginhost.PluginHost.plugins.items()
         for name, plugin in plugins:
             try:
                 script = xml.SubElement(pytson, "s",{'v': plugin.version, 'a': plugin.author})
                 script.text = name
             except:from traceback import format_exc;ts3.logMessage("Error parsing script %s:\n%s"%(name,format_exc()), ts3defines.LogLevel.LogLevel_ERROR, "{c}.{f}".format(c=self.__class__,f=__name__), schid);continue
         newmeta = "{old}{new}".format(old=oldmeta,new=xml.tostring(newmeta).decode("utf-8"))
         # if PluginHost.cfg.getboolean("general", "verbose"): ts3.printMessageToCurrentTab(newmeta)
         error = ts3.setClientSelfVariableAsString(schid, ts3defines.ClientProperties.CLIENT_META_DATA, newmeta)
         if not error == ts3defines.ERROR_ok: ts3.printMessageToCurrentTab("Error: Unable to set own meta data to \"%s\"."%newmeta);return False
     except: from traceback import format_exc;ts3.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "{c}.{f}".format(c=self.__class__,f=__name__), schid)
Beispiel #10
0
    def setupTranslator(cls):
        lang = cls.cfg.get("general", "language")
        if lang == "inherited":
            ccfg = ts3client.Config()
            q = ccfg.query("SELECT * FROM application WHERE key='Language'")

            if q.next():
                lang = q.value("value")
            else:
                lang = "en_US"
                logprint(cls._tr("Error querying language from client config"),
                         ts3defines.LogLevel.LogLevel_ERROR,
                         "pyTSon.PluginHost.setupTranslator")
            del ccfg

        if cls.translator:
            if not QCoreApplication.removeTranslator(cls.translator):
                logprint(cls._tr("Error removing translator"),
                         ts3defines.LogLevel.LogLevel_ERROR,
                         "pyTSon.PluginHost.setupTranslator")
            cls.translator = None

        p = pytson.getPluginPath("ressources", "i18n", "pyTSon-%s.qm" % lang)

        if os.path.isfile(p):
            cls.verboseLog(
                cls._tr("Using translator from {file}").format(file=p),
                "pyTSon.PluginHost.setupTranslator")

            cls.translator = QTranslator()
            if not cls.translator.load(p):
                logprint("Error loading translator from %s" % p,
                         ts3defines.LogLevel.LogLevel_ERROR,
                         "pyTSon.PluginHost.setupTranslator")
                cls.translator = None
                return

            if not QCoreApplication.installTranslator(cls.translator):
                logprint("Error installing translator from %s" % p,
                         ts3defines.LogLevel.LogLevel_ERROR,
                         "pyTSon.PluginHost.setupTranslator")
                cls.translator = None
Beispiel #11
0
 def contactStats(self):
     buddies = 0
     blocked = 0
     neutral = 0
     unknown = 0
     female = 0
     male = 0
     db = ts3client.Config()
     q = db.query("SELECT * FROM contacts")
     while q.next():
         for line in q.value("value").split('\n'):
             if line.startswith('Friend='):
                 status = int(line[-1])
                 if status == ContactStatus.FRIEND: buddies += 1
                 elif status == ContactStatus.BLOCKED: blocked += 1
                 elif status == ContactStatus.NEUTRAL: neutral += 1
                 else: unknown += 1
             elif line.lower().startswith('nickname=w/'):
                 female += 1
             elif line.lower().startswith('nickname=m/'):
                 male += 1
     del db
     sum = buddies + blocked + neutral + unknown
     msg = ["Contacts: [b]{}[/b]".format(sum)]
     msg.append("[color=green]Buddies[/color]: [b]{}[/b] ({}%)".format(
         buddies, percentage(buddies, sum)))
     msg.append("[color=red]Blocked[/color]: [b]{}[/b] ({}%)".format(
         blocked, percentage(blocked, sum)))
     msg.append("Neutral: [b]{}[/b] ({}%)".format(
         neutral, percentage(neutral, sum)))  # [color=white][/color]
     if unknown > 0:
         msg.append("Unknown: [color=orange]{}[/color] ({}%)".format(
             unknown, percentage(unknown, sum)))
     if female > 0:
         msg.append("[color=purple]Female[/color]: {} ({}%)".format(
             female, percentage(female, sum)))
     if male > 0:
         msg.append("[color=lightblue]Male[/color]: {} ({}%)".format(
             male, percentage(male, sum)))
     return " | ".join(msg)
 def __init__(self):
     self.settings = ts3client.Config()
Beispiel #13
0
    def __init__(self,
                 schid,
                 cid,
                 password='',
                 path='/',
                 parent=None,
                 *,
                 staticpath=False,
                 readonly=False,
                 downloaddir=None,
                 iconpack=None):
        """
        Instantiates a new object.
        @param schid: the id of the serverconnection handler
        @type schid: int
        @param cid: the id of the channel
        @type cid: int
        @param password: password to the channel, defaults to an empty string
        @type password: str
        @param path: path to display, defaults to the root path
        @type path: str
        @param parent: parent of the dialog; optional keyword arg;
        defaults to None
        @type parent: QWidget
        @param staticpath: if set to True, the initial path can't be
        changed by the user; optional keyword arg; defaults to False
        @type staticpath: bool
        @param readonly: if set to True, the user can't download, upload
        or delete files, or create new directories; optional keyword arg;
        defaults to False
        @type readonly: bool
        @param downloaddir: directory to download files to; optional keyword
        arg; defaults to None; if set to None, the TS3 client's download
        directory is used
        @type downloaddir: str
        @param iconpack: iconpack to load icons from; optional keyword arg;
        defaults to None; if set to None, the current iconpack is used
        @type iconpack: ts3client.IconPack
        """
        super(QDialog, self).__init__(parent)
        self.setAttribute(Qt.WA_DeleteOnClose)

        iconpackopened = False
        if not iconpack:
            try:
                iconpack = ts3client.IconPack.current()
                iconpack.open()
                iconpackopened = True
            except Exception as e:
                self.delete()
                raise e

        try:
            setupUi(self,
                    pytson.getPluginPath("ressources", "filebrowser.ui"),
                    iconpack=iconpack)

            self.statusbar = SmartStatusBar(self)
            self.layout().addWidget(self.statusbar)
            self.statusbar.hide()
        except Exception as e:
            self.delete()
            raise e

        err, cname = ts3lib.getChannelVariableAsString(
            schid, cid, ChannelProperties.CHANNEL_NAME)

        if err == ERROR_ok:
            self.setWindowTitle(
                self._tr("File Browser - {cname}").format(cname=cname))
        else:
            self.setWindowTitle(self._tr("File Browser"))

        self.schid = schid
        self.cid = cid
        self.password = password
        self.path = None

        self.staticpath = staticpath
        self.readonly = readonly

        self.createretcode = None
        self.delretcode = None

        if not self.readonly and not downloaddir:
            cfg = ts3client.Config()
            q = cfg.query("SELECT value FROM filetransfer "
                          "WHERE key='DownloadDir'")
            del cfg

            if q.next():
                self.downloaddir = q.value("value")
            else:
                self.delete()
                raise Exception("Error getting DownloadDir from config")
        else:
            self.downloaddir = downloaddir

        if not self.readonly:
            menu = self.menu = QMenu(self)

            self.openAction = menu.addAction(QIcon(iconpack.icon("FILE_UP")),
                                             self._tr("Open"))
            self.openAction.connect("triggered()",
                                    self.on_openAction_triggered)

            self.downAction = menu.addAction(QIcon(iconpack.icon("DOWN")),
                                             self._tr("Download"))
            self.downAction.connect("triggered()", self.downloadFiles)
            self.renameAction = menu.addAction(QIcon(iconpack.icon("EDIT")),
                                               self._tr("Rename"))
            self.renameAction.connect("triggered()",
                                      self.on_renameAction_triggered)
            self.copyAction = menu.addAction(QIcon(iconpack.icon("COPY")),
                                             self._tr("Copy URL"))
            self.copyAction.connect("triggered()",
                                    self.on_copyAction_triggered)
            self.delAction = menu.addAction(QIcon(iconpack.icon("DELETE")),
                                            self._tr("Delete"))
            self.delAction.connect("triggered()", self.deleteFiles)

            self.upAction = menu.addAction(QIcon(iconpack.icon("UP")),
                                           self._tr("Upload files"))
            self.upAction.connect("triggered()", self.uploadFiles)
            self.createAction = menu.addAction(QIcon.fromTheme("folder"),
                                               self._tr("Create Folder"))
            self.createAction.connect("triggered()", self.createFolder)
            self.refreshAction = menu.addAction(
                QIcon(iconpack.icon("FILE_REFRESH")), self._tr("Refresh"))
            self.refreshAction.connect("triggered()", self.refresh)

            self.allactions = [
                self.openAction, self.downAction, self.renameAction,
                self.copyAction, self.delAction, self.upAction,
                self.createAction, self.refreshAction
            ]

        self.collector = FileCollector(schid, cid, password, self.downloaddir)
        self.collector.collectionFinished.connect(self._startDownload)
        self.collector.collectionError.connect(self.showError)

        self.fileDoubleClicked = Signal()
        self.contextMenuRequested = Signal()

        self.transdlg = None

        self.listmodel = FileListModel(schid,
                                       cid,
                                       password,
                                       self,
                                       readonly=readonly)
        self.listmodel.pathChanged.connect(self.onPathChanged)
        self.listmodel.error.connect(self.showError)

        self.proxy = QSortFilterProxyModel(self)
        self.proxy.setSortRole(Qt.UserRole)
        self.proxy.setSortCaseSensitivity(Qt.CaseInsensitive)
        self.proxy.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.proxy.setSourceModel(self.listmodel)

        self.listmodel.path = path

        self._adjustUi()

        if iconpackopened:
            iconpack.close()

        PluginHost.registerCallbackProxy(self)