def on_message(self, message): 'Accepting message from javasctipt client' #print 'message received: %s' % message message = json.loads(message) if message['action'] == 'ping': self.write_message('pong'); if message['action'] == 'connect': timers['%s_%s' % (message["tpa"],message["user_id"])] = int(time.time()) #self.replace_timer(message["tpa"],message["user_id"], int(time.time())) #print 'set time %s' % time.time() url = get_url_by_name('set_connected',{'user_id':message["user_id"], 'app_name': message["tpa"], 'source': message['source']}) try: requests.get(url) except: print '!!ERROR!! can not make a request to %s' % url chanel = '%s_%s' % (message["tpa"], message["user_id"]) clients.append(int(message["user_id"])) self._listen(chanel) self.current_user_id = message["user_id"] self.tpa_name = message["tpa"] self.source = message['source'] self.write_message(json.dumps({'action': 'connected', 'status': 0, 'user_id': self.current_user_id, 'message': 'you have been connected to %s' % chanel })) #self.set_user_online() #mes = {'action': 'update_users_online'} #self.broadcast(mes) #mes = {'action': 'set_me_online', 'uid': self.current_user_id} #self.broadcast(mes) #print 'set me online!!!!!!!!!!!!' #except Exception, e: # print e # self.write_message(json.dumps({'status': 1, 'message': str(e)})) handle(message,self)
def job(): global accounts,last_message_notify,BASEPATH,ONLINECACHE # Job #1 List new messages sh = shelve.open(os.path.join(BASEPATH,"configs","orichalcum.db"),writeback=True) now = time.time() if sh.has_key('accounts') == False: sh['accounts'] = {} for key in accounts: if now - accounts[key]['lastls'] > 30: accounts[key]['lastls'] = now # VISIT THE SITE codes = check_messages_list(accounts[key]['host'],accounts[key]['user'],accounts[key]['secret'],accounts[key]['bits']) if codes != False: print "Listing: %d new message(s) found." % len(codes) for code in codes: # Save required code. if sh['accounts'].has_key(key) == False: sh['accounts'][key] = {'codes':[],'messages':[]} sh['accounts'][key]['codes'].append(code) else: print codes # Job #2: Pull messages for key in accounts: if now - accounts[key]['lastpull'] > 30: accounts[key]['lastpull'] = now pulled = [] if sh['accounts'].has_key(key) == False: sh['accounts'][key] = {'codes':[]} for pullcode in sh['accounts'][key]['codes']: print "Pulling message ID = %s ..." % pullcode pm = pull_message(accounts[key]['host'],accounts[key]['user'],accounts[key]['secret'],pullcode,accounts[key]['bits']) if pm != False: print "(Message retrived successfully.)" # postoffice support processor.handle(pm,key,accounts[key]['user']) # key is account name(not username). else: print "(Error in retriving message.)" pulled.append(pullcode) for todel in pulled: if todel in sh['accounts'][key]['codes']: sh['accounts'][key]['codes'].remove(todel) notify_timed = now - last_message_notify if notify_timed > 60: processor.notify() last_message_notify = now sh.close() # Job #3: Refresh Online Cache try: required = [] olcache = shelve.open(ONLINECACHE) for server in olcache: for user in olcache[server]: if olcache[server][user]['wantupdate']: required.append({'server':server,'user':user}) olcache.close() for each in required: each['result'] = query_onlinestate(each['server'],each['user'],20) olcache = shelve.open(ONLINECACHE,writeback=True) for each in required: olcache[each['server']][each['user']] = {'lastcheck':each['result'],'lastupdate':time.time(),'wantupdate':False} olcache.close() except Exception,e: print "Error refreshing online cache: %s" % e
def run(self): logger.info("Starting up XMPP clients...") for each in self.clients: each[0].start() logger.info("All XMPP Clients fired.") logger.info("Feed watchdog.") self.feedDog() # begin looping while not self.sig_terminate.isSet(): logger.debug("Enter a daemon running loop.") # Job now. now = time.time() # Job #1: Check if clients got messages for us. newmessages = [] for each in self.clients: if each[0].isAlive(): newmessages += each[0].getMessage() if newmessages: logger.info("New message(s) retrived from clients. Will parse them.") for msg in newmessages: # print msg processor.handle(msg["message"], utils.stripJID(str(msg["jid"]))) newmessages = [] # Job #2: Check if there is anything to send. missions = utils.stack_get("outgoing") if missions: logger.info("New mission(s) accepted. Distributing them to clients.") for mission in missions: for each in self.clients: if not each[0].isAlive(): continue each[1].append(mission) logger.info("Will try sending messages(if any).") for each in self.clients: if not each[1]: continue if not each[0].isAlive(): logger.debug("[%s] is not alive. Will omit its job." % each[0].jid) continue if not each[0].connect_status == 2: logger.debug( "[%s] is not connected(Status: %s). Will omit its job." % (each[0].jid, each[0].connect_status) ) continue if each[0].xmpp.client_roster or True: # XXX This hack enables forcing each account to send. mission = each[1].pop(0) possible_jids = entity.getJIDsByNickname(mission["receiver"]) if possible_jids == False: continue for jid in possible_jids: if utils.stripJID(jid) == utils.stripJID(each[0].jid): continue if jid in each[0].xmpp.client_roster.keys() or True: # The same with XXX logger.debug("Set [%s] a new mission." % each[0].jid) each[0].setMessage(jid, mission["message"]) # Do WatchDog self.watchDog() # Now All Job Done time.sleep(0.1) logger.info("Exit the program.") for each in self.clients: each[0].terminate() each[0].join(10) if each[0].isAlive(): try: each[0].abort() except: pass