예제 #1
0
    def connect(self):
        logger.debug("tUser: connecting %s" % self.jidFrom)
        self.auth = False
        try:
            self.auth = self.vk.auth(self.token)
            logger.debug("tUser: auth=%s for %s" % (self.auth, self.jidFrom))
        except api.CaptchaNeeded:
            self.rosterSubscribe()
            self.vk.captchaChallenge()
            return True
        except api.TokenError as e:
            if e.message == "User authorization failed: user revoke access for this token.":
                logger.critical("tUser: %s" % e.message)
                self.deleteUser()
            elif e.message == "User authorization failed: invalid access_token.":
                msgSend(Component, self.jidFrom,
                        _(e.message + " Please, register again"), TransportID)
            self.vk.Online = False
        except:
            crashLog("tUser.Connect")
            return False

        if self.auth and self.vk.getToken():
            logger.debug("tUser: updating db for %s because auth done " %
                         self.jidFrom)
            if not self.existsInDB:
                with Database(DatabaseFile, Semaphore) as db:
                    db("insert into users values (?,?,?,?,?)",
                       (self.jidFrom, self.username, self.vk.getToken(),
                        self.lastMsgID, self.rosterSet))
            elif self.password:
                with Database(DatabaseFile, Semaphore) as db:
                    db("update users set token=? where jid=?",
                       (self.vk.getToken(), self.jidFrom))
            try:
                json = self.vk.method("users.get")
                self.UserID = json[0]["uid"]
            except (KeyError, TypeError):
                logger.error("tUser: could not recieve user id. JSON: %s" %
                             str(json))
                self.UserID = 0

            jidToID[self.UserID] = self.jidFrom
            self.friends = self.vk.getFriends()
            self.vk.Online = True
        if not UseLastMessageID:
            self.lastMsgID = 0
        return self.vk.Online
예제 #2
0
 def sendMessages(self):
     messages = self.vk.getMessages(
         200, self.lastMsgID if UseLastMessageID else 0)
     if messages:
         messages = messages[1:]
         messages = sorted(messages, msgSort)
         if messages:
             read = list()
             self.lastMsgID = messages[-1]["mid"]
             for message in messages:
                 read.append(str(message["mid"]))
                 fromjid = vk2xmpp(message["uid"])
                 body = uHTML(message["body"])
                 iter = Handlers["msg01"].__iter__()
                 for func in iter:
                     try:
                         result = func(self, message)
                     except:
                         result = None
                         crashLog("handle.%s" % func.func_name)
                     if result == None:
                         for func in iter:
                             apply(func, (self, message))
                         break
                     else:
                         body += result
                 else:
                     msgSend(Component, self.jidFrom, escapeMsg(body),
                             fromjid, message["date"])
             self.vk.msgMarkAsRead(read)
             if UseLastMessageID:
                 with Database(DatabaseFile, Semaphore) as db:
                     db("update users set lastMsgID=? where jid=?",
                        (self.lastMsgID, self.jidFrom))
예제 #3
0
 def __init__(self, data=(), source=""):
     self.password = None
     if data:
         self.username, self.password = data
     self.friends = {}
     self.auth = None
     self.token = None
     self.lastMsgID = None
     self.rosterSet = None
     self.existsInDB = None
     self.lastStatus = None
     self.last_activity = time.time()
     self.last_udate = time.time()
     self.jidFrom = source
     self.resources = []
     self.chatUsers = {}
     self.vk = VKLogin(self.username, self.password, self.jidFrom)
     logger.debug("initializing tUser for %s" % self.jidFrom)
     with Database(DatabaseFile, Semaphore) as db:
         base = db("select * from users where jid=?", (self.jidFrom, ))
         desc = db.fetchone()
         if desc:
             if not self.token or not self.password:
                 logger.debug("tUser: %s exists in db. Using it." %
                              self.jidFrom)
                 self.existsInDB = True
                 self.jidFrom, self.username, self.token, self.lastMsgID, self.rosterSet = desc
             elif self.password or self.token:
                 logger.debug("tUser: %s exists in db. Will be deleted." %
                              self.jidFrom)
                 threadRun(self.deleteUser)
예제 #4
0
def initDatabase(filename):
    if not os.path.exists(filename):
        with Database(filename) as db:
            db("create table users (jid text, username text, token text, lastMsgID integer, rosterSet bool)"
               )
            db.commit()
    return True
예제 #5
0
def main():
    Counter = [0, 0]
    getPid()
    initDatabase(DatabaseFile)
    globals()["Component"] = xmpp.Component(Host, debug=DEBUG_XMPPPY)
    Print("\n#-# Connecting: ", False)
    if not Component.connect((Server, Port)):
        Print("fail.\n", False)
    else:
        Print("ok.\n", False)
        Print("#-# Auth: ", False)
        if not Component.auth(TransportID, Password):
            Print(
                "fail (%s/%s)!\n" % (Component.lastErr, Component.lastErrCode),
                True)
            disconnectHandler(False)
        else:
            Print("ok.\n", False)
            Component.RegisterHandler("iq", iqHandler)
            Component.RegisterHandler("presence", prsHandler)
            Component.RegisterHandler("message", msgHandler)
            Component.RegisterDisconnectHandler(disconnectHandler)
            Print("#-# Initializing users", False)
            with Database(DatabaseFile) as db:
                users = db("select jid from users").fetchall()
                for user in users:
                    Print(".", False)
                    Sender(Component,
                           xmpp.Presence(user[0], "probe", frm=TransportID))
            Print("\n#-# Finished.")
            if allowBePublic:
                makeMeKnown()
예제 #6
0
 def rosterSubscribe(self, dist={}):
     for id in dist.keys():
         self.sendPresence(self.jidFrom, vk2xmpp(id), "subscribe",
                           dist[id]["name"])
         time.sleep(0.2)
     self.sendPresence(self.jidFrom, TransportID, "subscribe",
                       IDentifier["name"])
     if dist:
         self.rosterSet = True
         with Database(DatabaseFile, Semaphore) as db:
             db("update users set rosterSet=? where jid=?",
                (self.rosterSet, self.jidFrom))
예제 #7
0
 def rosterSubscribe(self, dist=None):
     dist = dist or {}
     for uid, value in dist.iteritems():
         self.sendPresence(self.jidFrom, vk2xmpp(uid), "subscribe",
                           value["name"])
     self.sendPresence(self.jidFrom, TransportID, "subscribe",
                       IDentifier["name"])
     if dist:
         self.rosterSet = True
         with Database(DatabaseFile, Semaphore) as db:
             db("update users set rosterSet=? where jid=?",
                (self.rosterSet, self.jidFrom))
예제 #8
0
 def deleteUser(self, roster=False):
     logger.debug("tUser: deleting user %s from db." % self.jidFrom)
     with Database(DatabaseFile) as db:
         db("delete from users where jid=?", (self.jidFrom, ))
         db.commit()
     self.existsInDB = False
     if roster and self.friends:
         logger.debug("tUser: deleting me from %s roster" % self.jidFrom)
         for id in self.friends.keys():
             jid = vk2xmpp(id)
             self.sendPresence(self.jidFrom, jid, "unsubscribe")
             self.sendPresence(self.jidFrom, jid, "unsubscribed")
         self.vk.Online = False
     if self.jidFrom in Transport:
         del Transport[self.jidFrom]
         try:
             updateTransportsList(self, False)
         except NameError:
             pass
예제 #9
0
파일: gateway.py 프로젝트: opiums9/vk4xmpp
def runDatabaseQuery(query, args=(), set=False, many=True):
    """
	Executes the given sql to the database
	Args:
		query: the sql query to execute
		args: the query argument
		set: whether to commit after the execution
		many: whether to return more than one result
	Returns:
		The query execution result
	"""
    semph = None
    if threading.currentThread() != "MainThread":
        semph = Semaphore
    with Database(DatabaseFile, semph) as db:
        db(query, args)
        if set:
            db.commit()
            result = None
        elif many:
            result = db.fetchall()
        else:
            result = db.fetchone()
    return result
예제 #10
0
def main():
    Counter = [0, 0]
    getPid()
    initDatabase(DatabaseFile)
    globals()["Component"] = xmpp.Component(Host, debug=DEBUG_XMPPPY)
    Print("\n#-# Connecting: ", False)
    if not Component.connect((Server, Port)):
        Print("fail.\n", False)
        crashLog("main.connect")
    else:
        Print("ok.\n", False)
        Print("#-# Auth: ", False)
        if not Component.auth(TransportID, Password):
            Print(
                "fail (%s/%s)!\n" % (Component.lastErr, Component.lastErrCode),
                True)
        else:
            Print("ok.\n", False)
            Print("#-# Initializing users", False)
            with Database(DatabaseFile) as db:
                users = db("select * from users").fetchall()
                for user in users:
                    jid, phone = user[:2]
                    Transport[jid] = tUser((phone, None), jid)
                    try:
                        if Transport[jid].connect():
                            TransportsList.append(Transport[jid])
                            if DefaultStatus == 1:
                                Transport[jid].init(None, False)
                            Print(".", False)
                            Counter[0] += 1
                        else:
                            Print("!", False)
                            Counter[1] += 1
                            crashLog("main.connect", 0, False)
                            msgSend(
                                Component, jid,
                                _("Auth failed! If this error repeated, please register again. This incident will be reported."
                                  ), TransportID)
                    except KeyboardInterrupt:
                        exit()
                    except:
                        crashLog("main.init")
                        continue
            Print("\n#-# Connected %d/%d users." %
                  (Counter[0], len(TransportsList)))
            if Counter[1]:
                Print("#-# Failed to connect %d users." % Counter[1])

            globals()["lengthOfTransportsList"] = int(
                ceil(float(len(TransportsList)) / SLICE_STEP) * SLICE_STEP)
            Component.RegisterHandler("iq", iqHandler)
            Component.RegisterHandler("presence", prsHandler)
            Component.RegisterHandler("message", msgHandler)
            Component.RegisterDisconnectHandler(disconnectHandler)

            for start in xrange(0, lengthOfTransportsList, SLICE_STEP):
                end = start + SLICE_STEP
                threadRun(hyperThread, (start, end), "hyperThread-%d" % start)

            Print("\n#-# Finished.")