def __init__(self, appkey, alias, customid, topic, transfer, zigbee_addr): self.__logger = logging.getLogger('zigbee_coordinator.Proxy') self.__logger.debug('init') Messenger.__init__(self, appkey, alias, customid) self.transfer = transfer self.topic = topic self.zigbee_addr = zigbee_addr
class messenger_thread(Thread): def __init__(self, irc_connection): self.messenger = Messenger(irc_connection) Thread.__init__(self) def run(self): self.messenger.run_loop()
def __init__(self, appkey, alias, customid, gpio_num): self.__logger = logging.getLogger('power_plug.PowerPlug') self.__logger.debug('init') Messenger.__init__(self, appkey, alias, customid) self.gpio_num = gpio_num GPIO.setup(self.gpio_num, GPIO.OUT)
def start(self, resource): """Creates Slack Web and RTM clients for the given Resource using the provided API tokens and configuration, then connects websocket and listens for RTM events. Args: resource (dict of Resource JSON): See message payloads: https://beepboophq.com/docs/article/resourcer-api """ logger.info('Starting bot for resource: {}'.format(resource)) if ('resource' in resource and 'SlackBotAccessToken' in resource['resource']): res_access_token = resource['resource']['SlackBotAccessToken'] self.clients = SlackClients(res_access_token) if self.clients.rtm.rtm_connect(): logging.info( u'Connected {} to {} team at https://{}.slack.com'.format( self.clients.rtm.server.username, self.clients.rtm.server.login_data['team']['name'], self.clients.rtm.server.domain ) ) msg_writer = Messenger(self.clients) # Random markov here markov_chain = Markov(3, msg_writer) config_manager.start_config_loader() event_handler = RtmEventHandler( self.clients, msg_writer, markov_chain ) time_event_handler = TimeTriggeredEventManager( self.clients, msg_writer, markov_chain ) os.chmod('./scripts/make_config.sh', 0755) while self.keep_running: for event in self.clients.rtm.rtm_read(): try: event_handler.handle(event) except: err_msg = traceback.format_exc() logging.error('Unexpected error: {}'.format(err_msg)) msg_writer.write_error(err_msg, event['channel']) continue self._auto_ping(time_event_handler) time.sleep(.1) else: logger.error( 'Failed to connect to RTM client with token: {}'.format( self.clients.token ) )
def authenticate_as_client(self, session_socket): # authenticates an external server connected via session_socket iv = self.receive_iv(session_socket) master_encrypter = Encrypter(self.master_key, iv) m = Messenger(session_socket, master_encrypter, self.continueHandler) client_challenge = genStr(CHALLENGE_LENGTH) client_challenge_hash = str(create_key(client_challenge)) hash_len = len(client_challenge_hash) secretA = generateAorB() publicA = pow(g, secretA, p) m.send(client_challenge + str(publicA)) response = m.recv() while not response: response = m.recv() if response[:hash_len] != client_challenge_hash: m.close() raise Exception('client could not authenticate') server_challenge_hash = str(create_key(response[hash_len:hash_len + CHALLENGE_LENGTH])) m.send(server_challenge_hash) public_b = int(response[hash_len + CHALLENGE_LENGTH:]) self.log.info('g^b mod p is {}'.format(public_b)) session_key = create_key(str(pow(public_b, secretA, p))) self.log.info('Session key generated by the client is {}'.format(session_key)) session_encrypter = Encrypter(session_key, iv) session_m = Messenger(session_socket, session_encrypter, self.continueHandler) self._messenger = session_m
def client_thread(conn): current_state = WAITING_TO_START_GAME messenger = Messenger(conn) while current_state is not GAME_OVER: if current_state is WAITING_TO_START_GAME: game = init_game(messenger) current_state = WAITING_FOR_MOVE elif current_state is WAITING_FOR_MOVE: messenger.send( str (game.incorrect + game.correct) ); letter = messenger.read() if game.already_guessed(letter): reply = "You've already guessed %r." % letter else: game.guess_letter(letter) reply = str(game) if game.gameover: current_state = WAITING_TO_PLAY_AGAIN messenger.send(reply) messenger.send(str(game.gameover)) elif current_state is WAITING_TO_PLAY_AGAIN: play_again = messenger.read() if play_again == "play": current_state = WAITING_TO_START_GAME elif play_again == "quit": current_state = GAME_OVER conn.close()
def check_schedule(self, localtime): client = Client() for volume in client.get_volumes(): try: self._check_volume_schedule(localtime, volume) except: error_msg = 'Scheduler failed to check volume schedule. %r' % { 'volume_id': volume.id } logger.exception(error_msg) msg = Messenger(volume) msg.send('%s\n\n%s' % (error_msg, traceback.format_exc()))
def __init__(self, appkey, alias, customid, file, presence, like): self.__logger = logging.getLogger('stat.Stat') self.__logger.debug('init') Messenger.__init__(self, appkey, alias, customid) self.file = file self.data = {} self.data['presence'] = presence self.data['like'] = like if presence != 0 or like != 0: self.write_data() else: self.read_data()
def message_sender(self): self.message_collector() msg = "%d messages waiting to be sent" % len(self.waiting_messages) log.info(msg) print >>sys.stdout, msg sent_list = [] for message in self.waiting_messages: sender = Messenger([message]) sender.check_config("smsleopard") sent_msg = sender.send_sms()[0] sent_list.extend(sent_msg) msg = "%d sent messages" % len(sent_list) log.info(msg) for sent in sent_list: self.db.update_outbox(sent)
def __init__(self, name='alex', nevts=100, evtfreq=100): """ Alex class It is the main driver application It has a list of algorithms that runs in sequence for a given number of events It has a dictionary of services to be set into each algorithm It has a dictionary with run information and event information (clean each event) to be set into in each alorithm """ self.name = name # name of the application self.ievt = 0 # current number of event processed self.nevts = nevts # number of events to run self.evtfreq = evtfreq # frequency to print event number in log self.counters = {} self.algs = [] # list of algorithms to run self.svcs = {} # dictionary with the services # primordial msg service self.msg = Messenger(name='msg') self.addsvc(self.msg) # add msg service # primordial request service (handle errrors, abort/end of job requets) self.req = RequestSvc(name='req',al=self) self.addsvc(self.req) # add request service # event data service self.evt = DataSvc(name='evt') self.addsvc(self.evt) # add event data service self.exports = ['msg','req','evt'] # services to export to algorithms return
def __init__(self, secrets): self.trade_params = secrets["tradeParameters"] self.pause_params = secrets["pauseParameters"] self.Bittrex = Bittrex(secrets) self.Messenger = Messenger(secrets) self.Database = Database()
def start(self, resource): """Creates Slack Web and RTM clients for the given Resource using the provided API tokens and configuration, then connects websocket and listens for RTM events. Args: resource (dict of Resource JSON): See message payloads - https://beepboophq.com/docs/article/resourcer-api """ logger.debug("Python Version: " + sys.version) logging.info('Starting bot for resource: {}'.format(resource)) if 'resource' in resource and 'SlackBotAccessToken' in resource['resource']: res_access_token = resource['resource']['SlackBotAccessToken'] self.clients = SlackClients(res_access_token) if self.clients.rtm.rtm_connect(): logging.info(u'Connected {} to {} team at https://{}.slack.com'.format( self.clients.rtm.server.username, self.clients.rtm.server.login_data['team']['name'], self.clients.rtm.server.domain)) msg_writer = Messenger(self.clients) event_handler = RtmEventHandler(self.clients, msg_writer) while self.keep_running: for event in self.clients.rtm.rtm_read(): try: event_handler.handle(event) except: err_msg = traceback.format_exc() logging.error('Unexpected error: {}'.format(err_msg)) msg_writer.write_error(event['channel'], err_msg) continue self._auto_ping() time.sleep(.1) else: logger.error('Failed to connect to RTM client with token: {}'.format(self.clients.token))
def authenticate_as_server(self, session_socket): # authenticates an external client connected via session_socket iv = self.generate_and_send_iv(session_socket) # the server should generate a random iv master_encrypter = Encrypter(self.master_key, iv) m_messenger = Messenger(session_socket, master_encrypter, self.continueHandler) secret_b = generateAorB() public_b = str(pow(g, secret_b, p)) server_challenge = genStr(CHALLENGE_LENGTH) server_challenge_hash = str(create_key(server_challenge)) response = m_messenger.recv() while not response: response = m_messenger.recv() client_challenge = response[:CHALLENGE_LENGTH] client_challenge_hash = str(create_key(client_challenge)) public_a = response[CHALLENGE_LENGTH:] self.log.info('publicA is {}'.format(public_a)) m_messenger.send(client_challenge_hash + server_challenge + public_b) session_key = create_key(str(pow(int(public_a), secret_b, p))) self.log.info('session key is {}'.format(session_key)) response = m_messenger.recv() while not response: response = m_messenger.recv() if response != server_challenge_hash: self.log.warn('Client could not be authenticated. Session will be terminated!') m_messenger.close() else: print('Server Authentication Successful!!!') session_encrypter = Encrypter(session_key, iv) self._messenger = Messenger(session_socket, session_encrypter, self.continueHandler)
def __init__(self): super().__init__() self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.protocol("WM_DELETE_WINDOW", lambda: destroy_all(self.connection, self)) self.title("Chat Client") self.length_struct = struct.Struct("!I") self.messenger = Messenger(self.connection, self.length_struct) self.username = "" self.password = "" self.connect = ConnectScreen(self, self.connect_to_server) self.login = LoginScreen(self, self.check_data) self.chat = ChatScreen(self, self.handle_out_going) self.connect.pack() self.connect.pack_children()
def _new_tube_cb(self, identifier, initiator, type, service, params, state): _logger.debug('New tube: ID=%d initator=%d type=%d service=%s ' 'params=%r state=%d' %(identifier, initiator, type, service, params, state)) if (type == telepathy.TUBE_TYPE_DBUS and service == SERVICE): if state == telepathy.TUBE_STATE_LOCAL_PENDING: self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].AcceptDBusTube( identifier) self.tube_conn = TubeConnection(self.conn, self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES], identifier, group_iface = self.text_chan[ telepathy.CHANNEL_INTERFACE_GROUP]) _logger.debug('Tube created') self.messenger = Messenger(self.tube_conn, self.initiating, self.model)
def __init__(self): super(Registry, self).__init__() # Set up YAML parser for optional config file self.config_path = path("cosmid.yaml") self.config = ConfigReader(self.config_path) # Extract stuff from config self.email = self.config.find("email") # Path to resource storage directory self.directory = path(self.config.find("directory", default="resources")) # Load history file consisting of already downloaded resources self.history_path = path(self.directory + "/.cosmid.yaml") self.history = HistoryReader(self.history_path) # Set up a :class:`cosmid.messenger.Messenger` self.messenger = Messenger("cosmid")
def receive_message(): messenger = Messenger() if request.method == 'GET': token_sent = request.args.get("hub.verify_token") return messenger.verify_fb_token(token_sent) else: output = request.get_json() for event in output['entry']: messaging = event['messaging'] for message in messaging: db_tools = DbLibrary() musixmatch = MusixMatch() if message.get('message'): recipient_id = message['sender']['id'] timestamp = message.get('timestamp') messageText = message['message'].get('text') db_tools.storeMessage(recipient_id, messageText, timestamp) if messageText: if db_tools.isFirstTime(recipient_id): firstTimeVisitor(db_tools, messenger, recipient_id, timestamp) else: current_state = db_tools.getConversationState( recipient_id) # Search Song if (current_state == const.findSong): askHowToFind(db_tools, messenger, recipient_id) elif (current_state == const.byAuthor): title, author, track_id = musixmatch.getSongWithAuthor( messageText) foundSong(db_tools, messenger, musixmatch, recipient_id, title, author, track_id, timestamp) messenger.send_option_message( recipient_id, text.addFavorites, [text.yes, text.no]) db_tools.updateConversationState( recipient_id, const.addFavorite) elif (current_state == const.byTitle): title, author, track_id = musixmatch.getSongWithTitle( messageText) foundSong(db_tools, messenger, musixmatch, recipient_id, title, author, track_id, timestamp) messenger.send_option_message( recipient_id, text.addFavorites, [text.yes, text.no]) db_tools.updateConversationState( recipient_id, const.addFavorite) elif (current_state == const.byLyric): title, author, track_id = musixmatch.getSongWithLyrics( messageText) foundSong(db_tools, messenger, musixmatch, recipient_id, title, author, track_id, timestamp) messenger.send_option_message( recipient_id, text.addFavorites, [text.yes, text.no]) db_tools.updateConversationState( recipient_id, const.addFavorite) # My Songs elif (current_state == const.showMySongs): showSongs(db_tools, messenger, recipient_id) # Reports elif (current_state == const.displayReport): askWhichReport(db_tools, messenger, recipient_id) #Other else: returningVisitor(messenger, recipient_id) if message['message'].get('attachments'): messenger.send_message(recipient_id, text.onlyTextMessage) elif message.get('postback'): recipient_id = message['sender']['id'] timestamp = message.get('timestamp') option = message['postback'].get('title') db_tools.storeMessage(recipient_id, option, timestamp) updateState(db_tools, recipient_id, option) current_state = db_tools.getConversationState(recipient_id) # Search Songs if (current_state == const.findSong): askHowToFind(db_tools, messenger, recipient_id) elif (current_state == const.byAuthor): messenger.send_message(recipient_id, text.inputWords) elif (current_state == const.byTitle): messenger.send_message(recipient_id, text.inputWords) elif (current_state == const.byLyric): messenger.send_message(recipient_id, text.inputWords) elif (current_state == const.yes): db_tools.updateFavoriteSong(recipient_id) messenger.send_message(recipient_id, "Listo") db_tools.updateConversationState( recipient_id, const.greeting) elif (current_state == const.no): messenger.send_message(recipient_id, "Para la proxima sera :)") db_tools.updateConversationState( recipient_id, const.greeting) # My Songs elif (current_state == const.showMySongs): showSongs(db_tools, messenger, recipient_id) # Reports elif (current_state == const.displayReport): askWhichReport(db_tools, messenger, recipient_id) elif (current_state == const.personsReport): getNumberOfUsers(db_tools, messenger, recipient_id) elif (current_state == const.chatsReport): getChatsPerDay(db_tools, messenger, recipient_id) elif (current_state == const.songReport): getTopSongs(db_tools, messenger, recipient_id) db_tools.close() return "MessageProcessed"
def __init__(self, appkey, alias, customid, topic, transfer): self.__logger = logging.getLogger('serial_gateway.Proxy') self.__logger.debug('init') Messenger.__init__(self, appkey, alias, customid) self.transfer = transfer self.topic = topic
GAME_OVER = 5 def make_socket(): try: c = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, msg: print "Client: Failed to create socket. Error code: " + str(msg[0]) \ + ", Error message: " + msg[1] sys.exit() return c if __name__ == "__main__": sock = make_socket() sock.connect((HOST,PORT)) messenger = Messenger(sock) current_state = WAITING_FOR_WELCOME while current_state is not GAME_OVER: if current_state is WAITING_FOR_WELCOME: print messenger.read() current_state = WAITING_FOR_BOARD elif current_state is WAITING_FOR_BOARD: print messenger.read() current_state = WAITING_FOR_GAME_STATUS elif current_state is WAITING_FOR_GAME_STATUS: msg = messenger.read() if msg == "True": current_state = WAITING_TO_PLAY_AGAIN elif msg == "False": current_state = WAITING_FOR_USER_INPUT
#!/usr/bin/python from messenger import Messenger from os import getpid messenger = Messenger('http://paxos.leedscodedojo.org.uk/live/a/gp-' + str(getpid()).zfill(5)) def sendMessage(msg): print "Sending: " + str(msg) messenger.postMessage(msg) name = "brian" lastAcceptedTimePeriod = 0 lastAcceptedValue = None sentAccepted = False lastPromisedTimePeriod = 0 while True: currMessage = messenger.getNextMessage() print "Received: " + str(currMessage) timePeriod = currMessage['timePeriod'] if currMessage['type'] == 'prepare': msg = {'type':'promised', 'timePeriod':timePeriod, 'by':name} if not sentAccepted: if timePeriod > lastPromisedTimePeriod: lastPromisedTimePeriod = timePeriod
class Manager: """ The middle-man of interaction between messenger and the SMS service. """ def __init__(self): self.config = self.__load_config_file() self.messenger = Messenger(self.config) self.sms_service = SMSService() def send_initial_greeting(self): """ Sends the initial SMS to new* patients at a pre-defined client time. *New patients are those that have recently been added to the clients database, which the service does not know. Note: this is REQUIRED otherwise 'respond' & other services do not function as database errors are thrown (understandably). """ from datetime import datetime current_time = str(datetime.now().time())[0:5] # Send the message to new patients at the defined time. if current_time == self.config['initialQuestion']['time']: for number in self.__new_patients(): message = self.messenger.initial_message() self.sms_service.send(number, message) self.__create_new_patient(number) self.__save_message(number, message, 'sent') def respond(self, patient_response): """ Respond to new SMS when it is received via a POST request. Args: patient_message (dict): Contains the number, and message sent to the service by a patient. Returns: response (XML): twilio formatted response. """ number = patient_response['number'] patient_message = patient_response['message'] # Generate a reflective summary based on the patient's response. summary = self.messenger.summary(patient_message) # TODO: Fix this with the system set time (i.e. UTC) midnight = int(datetime.today().strftime("%s")) - 24*60*60 # The number of questions sent since last night. _questions = db.session.query(models.Message).filter( models.Message.mobile == number, models.Message.status == 'sent', models.Message.timestamp >= midnight).all() all_sent = [item.message for item in _questions] # The number of OEQ sent since last night. num_oeq = len([i for i in self.config['questions'] if i in all_sent]) print 'Number OEQ sent since last night was: %s' % str(num_oeq) response = None # Do not send a response if initial daily conversation not started. if num_oeq >= 1: print 'The last sms sent was: %s' % all_sent[-1] if all_sent[-1] in self.config['questions']: print 'Last message sent was an OEQ. Sending a RS to patient.' response = summary else: print 'Inside the else..' if (num_oeq >= int(self.config['limit'])): # True: OEQ >= LIMIT print 'Inside the else... in the if...' if self.config['endQuestion'] not in all_sent: print 'Sending the conversation closer as limit met.' response = self.config['endQuestion'] else: print 'Message received was response to a RS. Sending OEQ.' response = self.__select_question(number) if response: self.__save_message(number, patient_message, 'received') self.__save_message(number, response, 'sent') print 'The response (%s) has been saved to the database.' % response return self.sms_service.reply(response) else: print 'No response was created.' return '' # Prevents a 500 error code returned to POST. def send_initial_question_to_all(self): """ Sends a question to all patients at a pre-defined day and time. """ known_patients = [item.mobile for item in db.session.query(models.Patient.mobile).all()] from datetime import datetime print "Checking to see if open-ended question should be sent." isDay = datetime.now().strftime("%A") in self.config["daysToSend"] isTime = str(datetime.now().time())[0:5] == self.config["sendTime"] if isDay and isTime: for number in known_patients: message = self.__select_question(number) print "OEQ (%s) to patient (%s)." % (message, number) self.__save_message(number, message, 'sent') self.sms_service.send(number, message) def __select_question(self, number): """ Select a client-defined open-ended question that has not been previously selected at random. If all have been sent then select one at random. Args: number (str): The mobile number of the patient. Returns: str: An open-ended question to ask the patient. """ questions = self.config['questions'] sent_questions = [item.message for item in db.session.query( models.Message).filter(models.Message.mobile == number).all()] unsent_questions = list(set(questions).difference(sent_questions)) # TODO: Select most important question based on client's situation import random if unsent_questions: print "Sending a message that HAS NOT been previously sent." message = random.choice(unsent_questions) else: print "Sending a message that HAS been previously sent." message = random.choice(questions) return message def __load_config_file(self): """ Stores the contents of the client-defined config file to a json object. Returns: json: A json object of the user-defined config file. """ import json from flask import current_app config_file = current_app.config['PROJECT_ROOT'] + '/sris/config/' + \ current_app.config['CLIENT_NAME'] + '.json' with open(config_file) as json_settings: return json.load(json_settings) def __new_patients(self): """ Checks to see if any new patients have been added to the client DB. Returns: list: Mobile numbers the client knows & the service does not. """ # ALL numbers obtained from the client. client_numbers = db.session.query(models.Patient.mobile).all() # The numbers the service has to date. service_numbers = db.session.query(models.User.mobile).all() # The numbers the client has, but the service does not. numbers = set(client_numbers).difference(service_numbers) print 'There was %s new patients' % str(len(numbers)) # Convert SQLAlchemy KeyedTuple to ordinary list. return [item.mobile for item in numbers] def __create_new_patient(self, number): """ Adds the patient to the service database. Args: number (str): The mobile number of the patient. """ db.session.add(models.User(mobile=number)) db.session.commit() def __save_message(self, number, message, status): """ Save the SMS message (sent or received) to the service database. Args: number (str): The mobile number of the patient. message (str): The SMS message content. status (str): The status of the message, e.g. 'sent' or 'received'. """ db.session.add(models.Message(mobile=number, message=message, status=status)) db.session.commit()
def sendMessage(self, arg): send = Messenger(arg) print send.check_config() send.send_sms()
settings_content = get_json_from_file(settings_file_directory, settings_template) if settings_content == settings_template: print( "Please complete the `settings.json` file in your `database` directory" ) exit() return settings_content if __name__ == "__main__": secrets = get_secrets() settings = get_settings() Messenger = Messenger(secrets, settings) Trader = Trader(secrets, settings) Trader.initialise() while True: try: Trader.analyse_pauses() Trader.analyse_buys() Trader.analyse_sells() time.sleep(10) except SSLError as exception: Messenger.print_error("SSL") logger.exception(exception) time.sleep(10)
'If specified, a dedicated master will be used. If one server specifies this flag, all must' ) args = p.parse_args() if args.master: class ReplicatedValue(DedicatedMasterStrategyMixin, ExponentialBackoffResolutionStrategyMixin, SimpleSynchronizationStrategyMixin, BaseReplicatedValue): ''' Mixes the dedicated master, resolution, and synchronization strategies into the base class ''' else: class ReplicatedValue(ExponentialBackoffResolutionStrategyMixin, SimpleSynchronizationStrategyMixin, BaseReplicatedValue): ''' Mixes just the resolution and synchronization strategies into the base class ''' state_file = config.state_files[args.uid] r = ReplicatedValue(args.uid, config.peers.keys(), state_file) m = Messenger(args.uid, config.peers, config.clients, r) reactor.run()
class Alex(): def __init__(self, name='alex', nevts=100, evtfreq=100): """ Alex class It is the main driver application It has a list of algorithms that runs in sequence for a given number of events It has a dictionary of services to be set into each algorithm It has a dictionary with run information and event information (clean each event) to be set into in each alorithm """ self.name = name # name of the application self.ievt = 0 # current number of event processed self.nevts = nevts # number of events to run self.evtfreq = evtfreq # frequency to print event number in log self.counters = {} self.algs = [] # list of algorithms to run self.svcs = {} # dictionary with the services # primordial msg service self.msg = Messenger(name='msg') self.addsvc(self.msg) # add msg service # primordial request service (handle errrors, abort/end of job requets) self.req = RequestSvc(name='req',al=self) self.addsvc(self.req) # add request service # event data service self.evt = DataSvc(name='evt') self.addsvc(self.evt) # add event data service self.exports = ['msg','req','evt'] # services to export to algorithms return def _declare(self,obj): """ add services and stores to the object """ if (not hasattr(obj,'imports')): return nsvcs = obj.imports if (not isinstance(nsvcs,list)): self.msg.error(self.name,' no list of importing svc ',nsvcs) return if (isinstance(obj,ISvc)): if (not 'msg' in nsvcs): nsvcs.append('msg') elif (isinstance(obj,IAlg)): for svc in self.exports: if (not svc in nsvcs): nsvcs.append(svc) #self.msg.info(self.name,' importing services to ', obj.name) for nsvc in nsvcs: if (not self.svcs.has_key(nsvc)): self.msg.error(self.name,' no service ',nsvc,' to import ') else: svc = self.svcs[nsvc] if (svc.name != obj.name): setattr(obj,svc.name,svc) return def addsvc(self,svc): """ add a service by its name. Each service hass access to the msg svc and run store """ self.msg.cinfo(self.name,' adding service ',svc.name) self.svcs[svc.name] = svc setattr(self,svc.name,svc) self._declare(svc) return def addalg(self,alg): """ add an algorithm to the list of algorithms to run. Services are set into the algorithm. It has access to the run store and event store. """ self.msg.cinfo(self.name,' algorithm to run ',alg.name) self.algs.append(alg) self._declare(alg) # decorate the objects underneath if (hasattr(alg,'algs')): map(self._declare,alg.algs) return def initialize(self): """ initilize the services and the algorithms """ self.msg.cinfo(' initilize ') svcs = self.svcs.values() map(self._declare, svcs) oks1 = map(lambda svc: svc.initialize(), svcs) if (len(self.algs) == 0): self.msg.warning(self.name,' No algorithms to run') return True for alg in self.algs: self.counters[alg.name] = 0 oks2 = map(lambda alg: alg.initialize(), self.algs) return (isok(oks1) and isok(oks2)) def execute(self): """ do the execute method over the list of algorithms """ if (self.ievt%self.evtfreq==0): self.msg.cinfo(' event ', self.ievt) self.evt.clear() if (len(self.algs)==0): self.ievt += 1; return True oks = map(lambda alg: alg.execute(), self.algs) def count(alg,ok): if (ok): self.counters[alg.name]+=1 map(count,self.algs,oks) self.ievt+=1 return isok(oks) def finalize(self): """ finalize the list of algorithms and the sercices """ self.msg.cinfo(' finalize ') self.msg.cinfo(' events ',self.ievt) def infocounter(alg): self.msg.info(' counter algorithm ',alg.name, self.counters[alg.name]) if (len(self.algs)>0): map(infocounter,self.algs) oks1 = map(lambda alg: alg.finalize(), self.algs) svcs = self.svcs.values() oks2 = map(lambda svc: svc.finalize(), svcs) self.msg.cinfo(' end!') exit() def loop(self,nevts): """ do execute in a loop with range nevts """ self.msg.cinfo(' loop events ',nevts) for i in range(nevts): self.execute() return def run(self): """ run alex: initialize, loop nevents (do execute to each one) and finalize """ self.msg.cinfo(' run ') self.initialize() self.loop(self.nevts) self.finalize() return
import asyncio from messenger import Messenger m = Messenger() async def hello(): await m.connect() while True: data = await m.read() print(f'data : {data}') m.write(input()) asyncio.run(hello())
from flask import Flask, request, json import requests from messenger import Messenger import meraki from pprint import pprint app = Flask(__name__) port = 5005 msg = Messenger() @app.route('/', methods=['GET', 'POST']) def index(): """Receive a notification from Webex Teams and handle it""" if request.method == 'GET': return f'Request received on local port {port}' elif request.method == 'POST': if 'application/json' in request.headers.get('Content-Type'): # Notification payload, received from Webex Teams webhook data = request.get_json() # Loop prevention, ignore messages which were posted by bot itself. # The bot_id attribute is collected from the Webex Teams API # at object instatiation. if msg.bot_id == data.get('data').get('personId'): return 'Message from self ignored' else: # Print the notification payload, received from the webhook print(json.dumps(data,indent=4)) # Collect the roomId from the notification,
#!/usr/bin/python from messenger import Messenger from os import getpid messenger = Messenger('http://127.0.0.1:24192/l/dt-py-' + str(getpid()).zfill(5)) received = [] while True: currMessage = messenger.getNextMessage() for prevMessage in received: if currMessage['timePeriod'] == prevMessage[ 'timePeriod'] and currMessage['by'] != prevMessage['by']: print "Value '" + currMessage['value'] + "' learned" break received.append(currMessage)
class App(tkinter.Tk): def __init__(self): super().__init__() self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.protocol("WM_DELETE_WINDOW", lambda: destroy_all(self.connection, self)) self.title("Chat Client") self.length_struct = struct.Struct("!I") self.messenger = Messenger(self.connection, self.length_struct) self.username = "" self.password = "" self.connect = ConnectScreen(self, self.connect_to_server) self.login = LoginScreen(self, self.check_data) self.chat = ChatScreen(self, self.handle_out_going) self.connect.pack() self.connect.pack_children() def connect_to_server(self): """ Callback for self.connect. Retrieves the user submitted address and port. Attempts to make connection. If any errors are caught the connect_message widget will be updated with information about the error. """ host_address = self.connect.ip_entry.get() host_port = self.connect.port_entry.get() try: host_port = int(host_port) self.connection.connect((host_address, host_port)) self.connect.pack_forget() self.login.pack() self.login.pack_children() except ValueError: self.connect.connect_message.config( text="Invalid Entry For Port\nMust Be an Integer", fg="red") except ConnectionRefusedError: self.connect.connect_message.config( text="Server Refused Connection", fg="red") except socket.gaierror: self.connect.connect_message.config(text="Invalid Address", fg="red") def check_data(self, message_type): """ Communicates with chat server to verify login information. If the login or sign up attempt fails a message is displayed on the login screen. :param message_type: tells the server whether it is a login attempt or signup request """ self.username = self.login.name_entry.get() self.password = self.login.pass_entry.get() # restrict user names to alpha numeric values if not self.username.isalnum(): self.login.display_message.config( text="Username can only be numbers and letters", fg="red") return # format message to be sent message = "{}`{}`{}".format(message_type, self.username, self.password) reply = "" # try communicating with server try: self.messenger.send(message) reply = self.messenger.recv() except ConnectionResetError or ValueError: self.login.display_message.config( text="Connection with server lost...restarting", fg="red") self.login.pack_forget() self.connection.detach() self.connect.pack() # check for all possible server responses if reply == "OK": self.login.pack_forget() self.title(self.username) self.chat.pack() self.chat.pack_children() self.connection.settimeout( .10) # prevents blocking calls of handle_incoming() self.handle_incoming() elif reply == "UNAVAILABLE": self.login.display_message.config(text="Username Unavailable", fg="red") elif reply == "BAD": self.login.display_message.config(text="Incorrect user Info", fg="red") elif reply == "USER ACTIVE": self.login.display_message.config( text="Username is currently already logged in", fg="red") else: self.login.display_message.config( text="Unexpected Server Response") def handle_out_going(self, event=None): """ reads from the chat_entry and sends it to the server. :param event: is used as a place holder for the event information sent by self.chat_entry.bind(<RETURN>) it is not used. """ text = self.chat.chat_entry.get() if text: # prevent empty messages from being sent try: message = "{}: {}".format( self.username, text) # This should be handled by server self.messenger.send(message) self.chat.chat_entry.delete(0, "end") except ConnectionResetError: self.chat.pack_forget() self.login.pack() self.login.display_message.config( text="Connection with server lost") def handle_incoming(self): """ called every 500 milliseconds from within the tkinter mainloop. Will check for incoming socket data, but will pass if socket timeout limit is reached. """ try: message = self.messenger.recv() self.chat.add_message(message) except socket.timeout: pass except ConnectionResetError or struct.error: self.chat.pack_forget() self.login.pack() self.login.display_message.config( text="Connection with server lost") return finally: self.after(500, self.handle_incoming)
class Trader(object): """ Used for handling all trade functionality """ def __init__(self, secrets, settings): self.trade_params = settings["tradeParameters"] self.pause_params = settings["pauseParameters"] self.Bittrex = Bittrex(secrets) self.Messenger = Messenger(secrets, settings) self.Database = Database() def initialise(self): """ Fetch the initial coin pairs to track and to print the header line """ try: if len(self.Database.app_data["coinPairs"]) < 1: self.Database.store_coin_pairs(self.get_markets("BTC")) self.Messenger.print_header( len(self.Database.app_data["coinPairs"])) except ConnectionError as exception: self.Messenger.print_error("connection", [], True) logger.exception(exception) exit() def analyse_pauses(self): """ Check all the paused buy and sell pairs and reactivate the necessary ones """ if self.Database.check_resume(self.pause_params["buy"]["pauseTime"], "buy"): self.Database.store_coin_pairs(self.get_markets("BTC")) self.Messenger.print_resume_pause( len(self.Database.app_data["coinPairs"]), "buy") if "sell" in self.pause_params and self.Database.check_resume( self.pause_params["sell"]["pauseTime"], "sell"): self.Messenger.print_resume_pause( self.Database.app_data["pausedTrackedCoinPairs"], "sell") self.Database.resume_sells() def analyse_buys(self): """ Analyse all the un-paused coin pairs for buy signals and apply buys """ trade_len = len(self.Database.trades["trackedCoinPairs"]) pause_trade_len = len(self.Database.app_data["pausedTrackedCoinPairs"]) if (trade_len < 1 or pause_trade_len == trade_len ) and trade_len < self.trade_params["buy"]["maxOpenTrades"]: for coin_pair in self.Database.app_data["coinPairs"]: self.buy_strategy(coin_pair) def analyse_sells(self): """ Analyse all the un-paused tracked coin pairs for sell signals and apply sells """ for coin_pair in self.Database.trades["trackedCoinPairs"]: if coin_pair not in self.Database.app_data[ "pausedTrackedCoinPairs"]: self.sell_strategy(coin_pair) def buy_strategy(self, coin_pair): """ Applies the buy checks on the coin pair and handles the results appropriately :param coin_pair: Coin pair market to check (ex: BTC-ETH, BTC-FCT) :type coin_pair: str """ if (len(self.Database.trades["trackedCoinPairs"]) >= self.trade_params["buy"]["maxOpenTrades"] or coin_pair in self.Database.trades["trackedCoinPairs"]): return rsi = self.calculate_RSI(coin_pair=coin_pair, period=14, unit=self.trade_params["tickerInterval"]) day_volume = self.get_current_24hr_volume(coin_pair) current_buy_price = self.get_current_price(coin_pair, "ask") if rsi is None: return if self.check_buy_parameters(rsi, day_volume, current_buy_price): buy_stats = {"rsi": rsi, "24HrVolume": day_volume} self.buy(coin_pair, self.trade_params["buy"]["btcAmount"], current_buy_price, buy_stats) elif "buy" in self.pause_params and rsi >= self.pause_params["buy"][ "rsiThreshold"] > 0: self.Messenger.print_pause(coin_pair, [rsi, day_volume], self.pause_params["buy"]["pauseTime"], "buy") self.Database.pause_buy(coin_pair) else: self.Messenger.print_no_buy(coin_pair, rsi, day_volume, current_buy_price) def sell_strategy(self, coin_pair): """ Applies the sell checks on the coin pair and handles the results appropriately :param coin_pair: Coin pair market to check (ex: BTC-ETH, BTC-FCT) :type coin_pair: str """ if (coin_pair in self.Database.app_data["pausedTrackedCoinPairs"] or coin_pair not in self.Database.trades["trackedCoinPairs"]): return rsi = self.calculate_RSI(coin_pair=coin_pair, period=14, unit=self.trade_params["tickerInterval"]) current_sell_price = self.get_current_price(coin_pair, "bid") profit_margin = self.Database.get_profit_margin( coin_pair, current_sell_price) if rsi is None: return if self.check_sell_parameters(rsi, profit_margin): sell_stats = {"rsi": rsi, "profitMargin": profit_margin} self.sell(coin_pair, current_sell_price, sell_stats) elif "sell" in self.pause_params and profit_margin <= self.pause_params[ "sell"]["profitMarginThreshold"] < 0: self.Messenger.print_pause(coin_pair, [profit_margin, rsi], self.pause_params["sell"]["pauseTime"], "sell") self.Database.pause_sell(coin_pair) else: self.Messenger.print_no_sell(coin_pair, rsi, profit_margin, current_sell_price) def check_buy_parameters(self, rsi, day_volume, current_buy_price): """ Used to check if the buy conditions have been met :param rsi: The coin pair's current RSI :type rsi: float :param day_volume: The coin pair's current 24 hour volume :type day_volume: float :param current_buy_price: The coin pair's current price :type current_buy_price: float :return: Boolean indicating if the buy conditions have been met :rtype : bool """ rsi_check = rsi <= self.trade_params["buy"]["rsiThreshold"] day_volume_check = day_volume >= self.trade_params["buy"][ "24HourVolumeThreshold"] current_buy_price_check = current_buy_price >= self.trade_params[ "buy"]["minimumUnitPrice"] return rsi_check and day_volume_check and current_buy_price_check def check_sell_parameters(self, rsi, profit_margin): """ Used to check if the sell conditions have been met :param rsi: The coin pair's current RSI :type rsi: float :param profit_margin: The coin pair's current profit margin :type profit_margin: float :return: Boolean indicating if the sell conditions have been met :rtype : bool """ rsi_check = rsi >= self.trade_params["sell"]["rsiThreshold"] lower_profit_check = profit_margin >= self.trade_params["sell"][ "minProfitMarginThreshold"] upper_profit_check = profit_margin >= self.trade_params["sell"][ "profitMarginThreshold"] loss_check = ("lossMarginThreshold" in self.trade_params["sell"] and 0 > self.trade_params["sell"]["lossMarginThreshold"] >= profit_margin) return (rsi_check and lower_profit_check) or upper_profit_check or ( rsi_check and loss_check) def buy(self, coin_pair, btc_quantity, price, stats, trade_time_limit=2): """ Used to place a buy order to Bittrex. Wait until the order is completed. If the order is not filled within trade_time_limit minutes cancel it. :param coin_pair: String literal for the market (ex: BTC-LTC) :type coin_pair: str :param btc_quantity: The amount of BTC to buy with :type btc_quantity: float :param price: The price at which to buy :type price: float :param stats: The buy stats object :type stats: dict :param trade_time_limit: The time in minutes to wait fot the order before cancelling it :type trade_time_limit: float """ buy_quantity = round(btc_quantity / price, 8) buy_data = self.Bittrex.buy_limit(coin_pair, buy_quantity, price) if not buy_data["success"]: error_str = self.Messenger.print_error( "buy", [coin_pair, buy_data["message"]]) logger.error(error_str) return self.Database.store_initial_buy(coin_pair, buy_data["result"]["uuid"]) buy_order_data = self.get_order(buy_data["result"]["uuid"], trade_time_limit * 60) self.Database.store_buy(buy_order_data["result"], stats) self.Messenger.print_buy(coin_pair, price, stats["rsi"], stats["24HrVolume"]) self.Messenger.send_buy_slack(coin_pair, stats["rsi"], stats["24HrVolume"]) self.Messenger.send_buy_gmail(buy_order_data["result"], stats) self.Messenger.play_sw_imperial_march() def sell(self, coin_pair, price, stats, trade_time_limit=2): """ Used to place a sell order to Bittrex. Wait until the order is completed. If the order is not filled within trade_time_limit minutes cancel it. :param coin_pair: String literal for the market (ex: BTC-LTC) :type coin_pair: str :param price: The price at which to buy :type price: float :param stats: The buy stats object :type stats: dict :param trade_time_limit: The time in minutes to wait fot the order before cancelling it :type trade_time_limit: float """ trade = self.Database.get_open_trade(coin_pair) sell_data = self.Bittrex.sell_limit(coin_pair, trade["quantity"], price) if not sell_data["success"]: error_str = self.Messenger.print_error( "sell", [coin_pair, sell_data["message"]]) logger.error(error_str) return sell_order_data = self.get_order(sell_data["result"]["uuid"], trade_time_limit * 60) # TODO: Handle partial/incomplete sales. self.Database.store_sell(sell_order_data["result"], stats) self.Messenger.print_sell(coin_pair, price, stats["rsi"], stats["profitMargin"]) self.Messenger.send_sell_slack(coin_pair, stats["rsi"], stats["profitMargin"]) self.Messenger.send_sell_gmail(sell_order_data["result"], stats) self.Messenger.play_sw_theme() def get_markets(self, main_market_filter=None): """ Gets all the Bittrex markets and filters them based on the main market filter :param main_market_filter: Main market to filter on (ex: BTC, ETH, USDT) :type main_market_filter: str :return: All Bittrex markets (with filter applied, if any) :rtype : list """ markets = self.Bittrex.get_markets() if not markets["success"]: error_str = self.Messenger.print_error("market", [], True) logger.error(error_str) exit() markets = markets["result"] if main_market_filter is not None: market_check = main_market_filter + "-" markets = py_.filter_( markets, lambda market: market_check in market["MarketName"]) markets = py_.map_(markets, lambda market: market["MarketName"]) return markets def get_current_price(self, coin_pair, price_type): """ Gets current market price for a coin pair :param coin_pair: Coin pair market to check (ex: BTC-ETH, BTC-FCT) :type coin_pair: str :param price_type: The type of price to get (one of: 'ask', 'bid') :type price_type: str :return: Coin pair's current market price :rtype : float """ coin_summary = self.Bittrex.get_market_summary(coin_pair) if not coin_summary["success"]: error_str = self.Messenger.print_error("coinMarket", [coin_pair]) logger.error(error_str) return None if price_type == "ask": return coin_summary["result"][0]["Ask"] if price_type == "bid": return coin_summary["result"][0]["Bid"] return coin_summary["result"][0]["Last"] def get_current_24hr_volume(self, coin_pair): """ Gets current 24 hour market volume for a coin pair :param coin_pair: Coin pair market to check (ex: BTC-ETH, BTC-FCT) :type coin_pair: str :return: Coin pair's current 24 hour market volume :rtype : float """ coin_summary = self.Bittrex.get_market_summary(coin_pair) if not coin_summary["success"]: error_str = self.Messenger.print_error("coinMarket", [coin_pair]) logger.error(error_str) return None return coin_summary["result"][0]["BaseVolume"] def get_closing_prices(self, coin_pair, period, unit): """ Returns closing prices within a specified time frame for a coin pair :param coin_pair: String literal for the market (ex: BTC-LTC) :type coin_pair: str :param period: Number of periods to query :type period: int :param unit: Ticker interval (one of: 'oneMin', 'fiveMin', 'thirtyMin', 'hour', 'week', 'day', and 'month') :type unit: str :return: Array of closing prices :rtype : list """ historical_data = self.Bittrex.get_historical_data( coin_pair, period, unit) closing_prices = [] for i in historical_data: closing_prices.append(i["C"]) return closing_prices def get_order(self, order_uuid, trade_time_limit): """ Used to get an order from Bittrex by it's UUID. First wait until the order is completed before retrieving it. If the order is not completed within trade_time_limit seconds, cancel it. :param order_uuid: The order's UUID :type order_uuid: str :param trade_time_limit: The time in seconds to wait fot the order before cancelling it :type trade_time_limit: float :return: Order object :rtype : dict """ start_time = time.time() order_data = self.Bittrex.get_order(order_uuid) while time.time() - start_time <= trade_time_limit and order_data[ "result"]["IsOpen"]: time.sleep(10) order_data = self.Bittrex.get_order(order_uuid) if order_data["result"]["IsOpen"]: error_str = self.Messenger.print_error("order", [ order_uuid, trade_time_limit, order_data["result"]["Exchange"] ]) logger.error(error_str) if order_data["result"]["Type"] == "LIMIT_BUY": self.Bittrex.cancel(order_uuid) return order_data def calculate_RSI(self, coin_pair, period, unit): """ Calculates the Relative Strength Index for a coin_pair If the returned value is above 75, it's overbought (SELL IT!) If the returned value is below 25, it's oversold (BUY IT!) :param coin_pair: String literal for the market (ex: BTC-LTC) :type coin_pair: str :param period: Number of periods to query :type period: int :param unit: Ticker interval (one of: 'oneMin', 'fiveMin', 'thirtyMin', 'hour', 'week', 'day', and 'month') :type unit: str :return: RSI :rtype : float """ closing_prices = self.get_closing_prices(coin_pair, period * 3, unit) count = 0 change = [] # Calculating price changes for i in closing_prices: if count != 0: change.append(i - closing_prices[count - 1]) count += 1 if count == 15: break # Calculating gains and losses advances = [] declines = [] for i in change: if i > 0: advances.append(i) if i < 0: declines.append(abs(i)) average_gain = (sum(advances) / 14) average_loss = (sum(declines) / 14) new_avg_gain = average_gain new_avg_loss = average_loss for _ in closing_prices: if 14 < count < len(closing_prices): close = closing_prices[count] new_change = close - closing_prices[count - 1] add_loss = 0 add_gain = 0 if new_change > 0: add_gain = new_change if new_change < 0: add_loss = abs(new_change) new_avg_gain = (new_avg_gain * 13 + add_gain) / 14 new_avg_loss = (new_avg_loss * 13 + add_loss) / 14 count += 1 if new_avg_loss == 0: return None rs = new_avg_gain / new_avg_loss new_rs = 100 - 100 / (1 + rs) return new_rs
class TestBroker(unittest.TestCase): def setUp(self): r = rconfig.Read() self.messenger = Messenger(topic_name) self.redis = redis.StrictRedis(host=r.host, port=r.port, db=r.db, password=r.password) def test_send(self): oldLen = self.redis.llen(input_channel_key(topic_name)) self.messenger.send("To test messenger send a msg.") len = self.redis.llen(input_channel_key(topic_name)) - oldLen self.assertEquals(1, len) self.redis.lpop(input_channel_key(topic_name)) def test_request(self): flag = [True] exception = [None] rst = [None] exit_event = threading.Event() def on_resolve(data): rst[0] = data exit_event.set() def on_reject(ex): print ex flag[0] = False exception[0] = ex exit_event.set() self.messenger.request("To test messenger request a msg.", 5).then(on_resolve, on_reject) pck = self.messenger.broker.get_input_channel( "request_test_input_reader").read(1) pck.respond("OK!") pck.ack() exit_event.wait(5) self.assertEquals("OK!", rst[0].Payload) def test_register_handler(self): messenger = Messenger("TestBot") messenger.register_handler(EchoHandler()) msg_client = Messenger("TestBot") flag = [True] exception = [None] rst = [None] exit_event = threading.Event() def on_resolve(data): rst[0] = data exit_event.set() def on_reject(ex): print ex flag[0] = False exception[0] = ex exit_event.set() try: msg_client.request("To test handler response", 5).then(on_resolve, on_reject) exit_event.wait(5) self.assertEquals("OK!", rst[0].Payload) finally: messenger.stop_monitor()
class App(tkinter.Tk): def __init__(self): super().__init__() self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.protocol("WM_DELETE_WINDOW", lambda: destroy_all(self.connection, self)) self.title("Chat Client") self.length_struct = struct.Struct("!I") self.messenger = Messenger(self.connection, self.length_struct) self.username = "" self.password = "" self.connect = ConnectScreen(self, self.connect_to_server) self.login = LoginScreen(self, self.check_data) self.chat = ChatScreen(self, self.handle_out_going) self.connect.pack() self.connect.pack_children() def connect_to_server(self): """ Callback for self.connect. Retrieves the user submitted address and port. Attempts to make connection. If any errors are caught the connect_message widget will be updated with information about the error. """ host_address = self.connect.ip_entry.get() host_port = self.connect.port_entry.get() try: host_port = int(host_port) self.connection.connect((host_address, host_port)) self.connect.pack_forget() self.login.pack() self.login.pack_children() except ValueError: self.connect.connect_message.config(text="Invalid Entry For Port\nMust Be an Integer", fg="red") except ConnectionRefusedError: self.connect.connect_message.config(text="Server Refused Connection", fg="red") except socket.gaierror: self.connect.connect_message.config(text="Invalid Address", fg="red") def check_data(self, message_type): """ Communicates with chat server to verify login information. If the login or sign up attempt fails a message is displayed on the login screen. :param message_type: tells the server whether it is a login attempt or signup request """ self.username = self.login.name_entry.get() self.password = self.login.pass_entry.get() # restrict user names to alpha numeric values if not self.username.isalnum(): self.login.display_message.config(text="Username can only be numbers and letters", fg="red") return # format message to be sent message = "{}`{}`{}".format(message_type, self.username, self.password) reply = "" # try communicating with server try: self.messenger.send(message) reply = self.messenger.recv() except ConnectionResetError or ValueError: self.login.display_message.config(text="Connection with server lost...restarting", fg="red") self.login.pack_forget() self.connection.detach() self.connect.pack() # check for all possible server responses if reply == "OK": self.login.pack_forget() self.title(self.username) self.chat.pack() self.chat.pack_children() self.connection.settimeout(.10) # prevents blocking calls of handle_incoming() self.handle_incoming() elif reply == "UNAVAILABLE": self.login.display_message.config(text="Username Unavailable", fg="red") elif reply == "BAD": self.login.display_message.config(text="Incorrect user Info", fg="red") elif reply == "USER ACTIVE": self.login.display_message.config(text="Username is currently already logged in", fg="red") else: self.login.display_message.config(text="Unexpected Server Response") def handle_out_going(self, event=None): """ reads from the chat_entry and sends it to the server. :param event: is used as a place holder for the event information sent by self.chat_entry.bind(<RETURN>) it is not used. """ text = self.chat.chat_entry.get() if text: # prevent empty messages from being sent try: message = "{}: {}".format(self.username, text) # This should be handled by server self.messenger.send(message) self.chat.chat_entry.delete(0, "end") except ConnectionResetError: self.chat.pack_forget() self.login.pack() self.login.display_message.config(text="Connection with server lost") def handle_incoming(self): """ called every 500 milliseconds from within the tkinter mainloop. Will check for incoming socket data, but will pass if socket timeout limit is reached. """ try: message = self.messenger.recv() self.chat.add_message(message) except socket.timeout: pass except ConnectionResetError or struct.error: self.chat.pack_forget() self.login.pack() self.login.display_message.config(text="Connection with server lost") return finally: self.after(500, self.handle_incoming)
#!/usr/bin/python from messenger import Messenger from os import getpid from sys import argv freeValue = argv[1] messenger = Messenger('http://127.0.0.1:24192/p/dt-py-' + str(getpid()).zfill(5)) received = [] latestProposedTimePeriod = 0 while True: currMessage = messenger.getNextMessage() if currMessage['timePeriod'] <= latestProposedTimePeriod: continue for prevMessage in received: if currMessage['timePeriod'] != prevMessage['timePeriod']: continue if currMessage['by'] == prevMessage['by']: continue proposedValue = freeValue currLATP = currMessage.get('lastAcceptedTimePeriod', -1) prevLATP = prevMessage.get('lastAcceptedTimePeriod', -1) if currLATP > 0: proposedValue = currMessage['lastAcceptedValue'] if prevLATP > 0 and prevLATP > currLATP: proposedValue = currMessage['lastAcceptedValue'] messenger.postMessage({'type':'proposed','timePeriod':currMessage['timePeriod'], 'value':proposedValue}) break
import warnings from messenger import Messenger from colorama import init from colorama import Fore, Back, Style init(autoreset=True) login_info = open(sys.argv[1]).read().splitlines() username = login_info[0] password = login_info[1] with warnings.catch_warnings(): warnings.simplefilter("ignore") # Log in print "Logging in..." m = Messenger(username=username, password=password) print "Logged in!" while True: # Get friend to talk to friend = raw_input("Who do you want to talk to? ") # Get message to send message = raw_input("What do you want to tell " + friend + "?") m.send(friend, message) # my id: 1326450295 # my id: 1664490365
import requests from flask import Flask, request, Response from viberbot import Api from viberbot.api.bot_configuration import BotConfiguration from viberbot.api.messages import VideoMessage from viberbot.api.messages.text_message import TextMessage from viberbot.api.messages.keyboard_message import KeyboardMessage from viberbot.api.viber_requests import ViberConversationStartedRequest from viberbot.api.viber_requests import ViberFailedRequest from viberbot.api.viber_requests import ViberMessageRequest from viberbot.api.viber_requests import ViberSubscribedRequest from viberbot.api.viber_requests import ViberUnsubscribedRequest from messenger import Messenger messenger = Messenger() app = Flask(__name__) bot_configuration = BotConfiguration( name='Reckoner', avatar='http://viber.com/avatar.jpg', auth_token='47ae7c0b0d27d1ef-2fe58f2b05086cfb-8a87db5e8dd49f97') viber = Api(bot_configuration) @app.route('/viber_bot', methods=['POST']) def incoming(): log("received request. post data: {0}".format(request.get_data())) # every viber message is signed, you can verify the signature using this method if not viber.verify_signature(
def __init__(self): self.config = self.__load_config_file() self.messenger = Messenger(self.config) self.sms_service = SMSService()
class Registry(object): """ Hub of-sorts to talk with different `Cosmid` related files and resources. Can be seen as the API endpoint for `Cosmid`. """ def __init__(self): super(Registry, self).__init__() # Set up YAML parser for optional config file self.config_path = path("cosmid.yaml") self.config = ConfigReader(self.config_path) # Extract stuff from config self.email = self.config.find("email") # Path to resource storage directory self.directory = path(self.config.find("directory", default="resources")) # Load history file consisting of already downloaded resources self.history_path = path(self.directory + "/.cosmid.yaml") self.history = HistoryReader(self.history_path) # Set up a :class:`cosmid.messenger.Messenger` self.messenger = Messenger("cosmid") def get(self, resource_id, type_="class"): """ <public> Returns an instance of the specified resource class. Dodges an ``ImportError`` when failing to import a resource and returns ``None`` instead. .. code-block:: python >>> resource = registry.get("ccds") >>> resource.latest() 'Hs104' :param str resource_id: The resource key (name of module) :returns: A class instance of the resource """ try: if type_ == "class": return load_class("cosmid.resources.{}.Resource".format(resource_id))() elif type_ == "module": return importlib.import_module("cosmid.resources." + resource_id) else: raise ValueError("Argument must be either 'class' or 'module'.") except ImportError: return None def grab(self, resource_id, target, collapse=False): """ <public> Returns all that's nessesary to download a specific resource. The method will try to correct both ``resource_id`` and the ``target`` release tag. :param str resource_id: What resource to download :param str target: What release of the resource to download """ # Either import resource class or print warning and move on. # Test matching the resource ID options = [item[0] for item in self.ls()] resource_id = self.matchOne(resource_id, options) if resource_id is None: message = "Couldn't match resource ID: '{}'".format(resource_id) self.messenger.send("warning", message) return None, None, None, None # Get the resource resource = self.get(resource_id) # Now let's figure out the version # No specified version will match to the latest resource release if target == "latest": version = resource.latest() else: options = resource.versions() version = self.matchOne(target, options) if version is None: message = ("Couldn't match version '{id}#{v}'; {vers}" .format(v=target, id=resource.id, vers=", ".join(options))) self.messenger.send("warning", message) return None, None, None, None # Get the goahead! (that we haven't already downloaded it) if self.goahead(resource, version): # Finally we can determine the paths to download and save the files dl_paths = resource.paths(version) if collapse: # The user can select to store all downloaded files in the same # directory resource_dir = "" else: # Or by default separate different resources into subdirectories resource_dir = "/" + resource.id save_paths = [("{dir}{mid}/{file}" .format(dir=self.directory, mid=resource_dir, file=name)) for name in resource.names] # Add the resource to the history file as downloaded self.history.add(resource_id, { "version": version, "target": target, "names": resource.names, "sources": dl_paths }) return resource, dl_paths, save_paths, version else: # The resource was already downloaded return None, None, None, None def ls(self): """ <public> Returns a list of resource IDs and docstrings for all the included resource modules. *Reference*: http://stackoverflow.com/questions/1707709/list-all-the-modules-that-are-part-of-a-python-package .. code-block:: python >>> registry.ls() [('ccds', 'A curated database of generic element'), ...] :returns: A list of tuples: ``(resource_id, docstring)`` :rtype: list """ # Store everything here items = [] prefix = resources.__name__ + "." # Fetch all the resource modules modules = pkgutil.iter_modules(resources.__path__, prefix) # Loop over all resource modules for importer, modpath, ispkg in modules: # Strip path modname = modpath.split(".")[-1] # Load the `Resource` class for the module module = self.get(modname, type_="module") # Save name and docstring items.append((modname, module.__doc__)) return items def search(self, query, limit=5): """ <public> Fuzzy matches a query string against each of the resource IDs and returns a limited number of results in order of match score. .. code-block:: python >>> registry.search("asmebly", limit=2) [('ensembl_assembly', 68), ('ncbi_assembly', 68)] :param str query: A string to match against the resource IDs :param int limit: (optional) A maximum number of results to return :returns: A list of tuples: ``(resource_id, score)` :rtype: list """ # List all the available resources resources = self.ls() # Focus on resource IDs resource_ids = [resource[0] for resource in resources] # Fuzzy match against the resource IDs and return in order of best match return process.extract(query, resource_ids, limit=limit) def matchOne(self, target, options, threshold=60): """ <public> Fuzzy matches e.g. a target version tag against a list of options. Returns the most likely match if the match score is sufficient. .. code-block:: python >>> resource = registry.get("ccds") >>> registry.matchOne(104, resource.versions()) 'Hs104' >>> registry.matchOne("ensembl", registry.ls()) 'ensembl_assembly' :param object target: Any Python object to match with :param list options: A list of possible options to match against :param int threshold: A lower threshold for accepting a best match :returns: The object with the best match (unless score is below threshold) :rtype: Python object """ # Match against the options and extract the top match only result, score = process.extractOne(target, map(str, options)) # Arbitrary lower limit for returning a *mathcing* result if score >= threshold: return result else: return None def goahead(self, resource, version): """ Determines whether it's any idea in going ahead with a download. """ # Get any currently downloaded resources current = self.history.find(resource.id, default={}) # Make sure we haven't already downloaded the resource if current.get("version") == version: message = "'{}' already downloaded and up-to-date.".format(resource.id) self.messenger.send("update", message) return False return True
def recvPrepare(self, req, body): block = pickle.loads(body['block']) sch_challenge = body['ch'] sch_response = self.cosi.response(sch_challenge) msg = self.msg_mgr.create_ack_msg(sch_response) Messenger.get().send(msg, req['addr'])
def __init__(self, python_version): self.python_version = python_version self.set_chrome_path() self.set_actions() self.messenger = Messenger(self.python_version) self.is_running = False
def thread_client(conn, addr, db_conn, active_clients): """ Checks and verifies password/username, and handles adding new users to the database. Main client loop Accepts messages from client socket then broadcasts message to all clients. If the connection is broken the loop will break, database will be updated(active state). :param conn: socket objected connected with remote client :param addr: tuple of the remote clients address and port :param db_conn: connection to the sqlite3 database containing user-info """ length_struct = struct.Struct("!I") local_messenger = Messenger(conn, length_struct) lock = _thread.allocate_lock() verified = False # used to control looping while not verified: # handle client login/signup credentials try: """ first message received will be a login or sign up attempt message_type will be "LOGIN" or "SIGNUP" """ message = local_messenger.recv() message_type, username, password = message.split("`", 2) except ValueError or ConnectionResetError: print("bad connection at {}".format(addr)) break # retrieve user info from database. username_check() returns two boolean values lock.acquire() username_exists, correct_password = username_check(db_conn, username, password) lock.release() # add new users to database if message_type == "SIGNUP": if username_exists: # username already taken local_messenger.send("UNAVAILABLE") else: # acquire lock and add user to database and active_clients lock.acquire() new_user(db_conn, username, password) active_clients[username] = conn lock.release() local_messenger.send("OK") verified = True # login existing users elif message_type == "LOGIN": if username_exists and correct_password: if username not in active_clients: # username is not already signed in # acquire lock and add username to active_clients lock.acquire() active_clients[username] = conn lock.release() local_messenger.send("OK") verified = True else: local_messenger.send("USER_ACTIVE") # user is already active else: local_messenger.send("BAD") # wrong password or username while verified: """ client will only be verified when an existing username and password have been submitted, or a new username and password has been created. verified loop will handle all incoming messages, errors, socket closures """ try: message = local_messenger.recv() except socket.error or struct.error: print("bad connection at {}".format(addr)) break if message: lock.acquire() local_messenger.broadcast(active_clients, message) lock.release() else: # empty string signaling connection closed lock.acquire() del active_clients[username] lock.release() conn.close() break # clean up after client disconnects or the connection is broken if username in active_clients: lock.acquire() del active_clients[username] lock.release() conn.close() print("{} DISCONNECTED".format(addr))
class Daemon: """ Application entry point. Initializes the application. :param python_version str: the current major python version """ def __init__(self, python_version): self.python_version = python_version self.set_chrome_path() self.set_actions() self.messenger = Messenger(self.python_version) self.is_running = False def set_actions(self): """Defines the different messages from the addon that will be handled.""" self.actions = {} self.actions[ACTIONS['VERSION']] = self.send_version self.actions[ACTIONS['COLORS']] = self.send_colorscheme self.actions[ACTIONS['CSS_ENABLE']] = self.send_enable_css_response self.actions[ACTIONS['CSS_DISABLE']] = self.send_disable_css_response def set_chrome_path(self): """Tries to set the path to the chrome directory.""" self.chrome_path = custom_css.get_firefox_chrome_path() def check_chrome_path(self, action): """ Checks if the path to the 'chrome' directory was found and sends a message if it was not. :return: if chrome_path is set :rType: bool """ if not self.chrome_path: self.messenger.send_message( Message(action, 'Could not find path to chrome folder', success=False)) return False else: return True def check_target(self, message): """ Checks if the message received specifies a target, or the message is invalid. :param message object: the decoded message :return: if message has key 'target' with a valid value :rType: bool """ if 'target' in message and len(message['target']) > 0: return message['target'] logging.error('%s: target was not specified' % message['action']) self.send_invalid_action() return False def send_version(self, message): """Sends the current daemon version to the addon.""" self.messenger.send_message(Message(ACTIONS['VERSION'], DAEMON_VERSION)) def send_colorscheme(self, message): """Sends the current colorscheme to the addon.""" (success, data) = fetcher.get_colorscheme(PYWAL_COLORS_PATH, BG_LIGHT_MODIFIER) self.messenger.send_message( Message(ACTIONS['COLORS'], data, success=success)) def send_invalid_action(self): """Sends an action to the addon indicating that the action sent was invalid""" self.messenger.send_message( Message(ACTIONS['INVALID_ACTION'], {}, success=False)) def send_output(self, message): """ Sends an output message to the addon that will be displayed in the 'Debugging output' area. :param message str: the message to send to the addon """ self.messenger.send_message(Message(ACTIONS['OUTPUT'], message)) def send_enable_css_response(self, message): """ Tries to enable a custom CSS file and sends the result to the addon. :param target string: the name of the CSS file to enable/disable """ action = ACTIONS['CSS_ENABLE'] target = self.check_target(message) if target is not False: if self.check_chrome_path(action): (success, message) = custom_css.enable_custom_css( self.chrome_path, target) self.messenger.send_message( Message(action, message, success=success)) def send_disable_css_response(self, message): """ Tries to disable a custom CSS file and sends the result to the addon. :param target string: the name of the CSS file to enable/disable """ action = ACTIONS['CSS_DISABLE'] target = self.check_target(message) if target is not False: if self.check_chrome_path(action): (success, message) = custom_css.disable_custom_css( self.chrome_path, target) self.messenger.send_message( Message(action, message, success=success)) def handle_message(self, message): """ Handles the incoming messages and does the appropriate action. :param message object: the decoded message """ try: action = message['action'] if action in self.actions: self.actions[action](message) else: logging.debug('%s: no such action' % action) self.send_invalid_action() except KeyError: logging.error('action was not defined') self.send_invalid_action() def socket_thread_worker(self): """The socket server thread worker.""" while True: message = self.socket_server.get_message() if message == 'update': logging.debug('Update triggered from external script') self.send_colorscheme() def start_socket_server(self): """Starts the socket server and creates the socket thread.""" success = self.socket_server.start() if success == True: if self.python_version == 3: # We use daemon=True so that the thread will exit when the daemon exits. # https://docs.python.org/2/library/threading.html#threading.Thread.daemon self.socket_thread = Thread(target=self.socket_thread_worker, daemon=True) else: self.socket_thread = Thread(target=self.socket_thread_worker) self.socket_thread.start() def start(self): """Starts the daemon and listens for incoming messages.""" self.is_running = True try: while True: message = self.messenger.get_message() logging.debug('Received message from addon: %s' % message) self.handle_message(message) except KeyboardInterrupt: return def close(self): """Application cleanup.""" self.socket_server.close() self.is_running = False logging.debug('Cleanup')
class WebActivity(activity.Activity): def __init__(self, handle): activity.Activity.__init__(self, handle) _logger.debug('Starting the web activity') session = WebKit.get_default_session() session.set_property('accept-language-auto', True) # By default, cookies are not stored persistently, we have to # add a cookie jar so that they get saved to disk. We use one # with a SQlite database: cookie_jar = SoupGNOME.CookieJarSqlite(filename=_cookies_db_path, read_only=False) session.add_feature(cookie_jar) _seed_xs_cookie(cookie_jar) # FIXME # downloadmanager.remove_old_parts() self._force_close = False self._tabbed_view = TabbedView() self._tabbed_view.connect('focus-url-entry', self._on_focus_url_entry) self._tray = HTray() self.set_tray(self._tray, Gtk.PositionType.BOTTOM) self._tray.show() self._primary_toolbar = PrimaryToolbar(self._tabbed_view, self) self._edit_toolbar = EditToolbar(self) self._view_toolbar = ViewToolbar(self) self._primary_toolbar.connect('add-link', self._link_add_button_cb) self._primary_toolbar.connect('go-home', self._go_home_button_cb) self._edit_toolbar_button = ToolbarButton(page=self._edit_toolbar, icon_name='toolbar-edit') self._primary_toolbar.toolbar.insert(self._edit_toolbar_button, 1) view_toolbar_button = ToolbarButton(page=self._view_toolbar, icon_name='toolbar-view') self._primary_toolbar.toolbar.insert(view_toolbar_button, 2) self._primary_toolbar.show_all() self.set_toolbar_box(self._primary_toolbar) self.set_canvas(self._tabbed_view) self._tabbed_view.show() self.model = Model() self.model.connect('add_link', self._add_link_model_cb) self.connect('key-press-event', self._key_press_cb) if handle.uri: self._tabbed_view.current_browser.load_uri(handle.uri) elif not self._jobject.file_path: # TODO: we need this hack until we extend the activity API for # opening URIs and default docs. self._tabbed_view.load_homepage() self.messenger = None self.connect('shared', self._shared_cb) # Get the Presence Service self.pservice = presenceservice.get_instance() try: name, path = self.pservice.get_preferred_connection() self.tp_conn_name = name self.tp_conn_path = path self.conn = telepathy.client.Connection(name, path) except TypeError: _logger.debug('Offline') self.initiating = None if self.get_shared_activity() is not None: _logger.debug('shared: %s', self.get_shared()) # We are joining the activity _logger.debug('Joined activity') self.connect('joined', self._joined_cb) if self.get_shared(): # We've already joined self._joined_cb() else: _logger.debug('Created activity') def _on_focus_url_entry(self, gobject): self._primary_toolbar.entry.grab_focus() def _shared_cb(self, activity_): _logger.debug('My activity was shared') self.initiating = True self._setup() _logger.debug('This is my activity: making a tube...') self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].OfferDBusTube( SERVICE, {}) def _setup(self): if self.get_shared_activity() is None: _logger.debug('Failed to share or join activity') return bus_name, conn_path, channel_paths = \ self.get_shared_activity().get_channels() # Work out what our room is called and whether we have Tubes already room = None tubes_chan = None text_chan = None for channel_path in channel_paths: channel = telepathy.client.Channel(bus_name, channel_path) htype, handle = channel.GetHandle() if htype == telepathy.HANDLE_TYPE_ROOM: _logger.debug('Found our room: it has handle#%d "%s"', handle, self.conn.InspectHandles(htype, [handle])[0]) room = handle ctype = channel.GetChannelType() if ctype == telepathy.CHANNEL_TYPE_TUBES: _logger.debug('Found our Tubes channel at %s', channel_path) tubes_chan = channel elif ctype == telepathy.CHANNEL_TYPE_TEXT: _logger.debug('Found our Text channel at %s', channel_path) text_chan = channel if room is None: _logger.debug("Presence service didn't create a room") return if text_chan is None: _logger.debug("Presence service didn't create a text channel") return # Make sure we have a Tubes channel - PS doesn't yet provide one if tubes_chan is None: _logger.debug("Didn't find our Tubes channel, requesting one...") tubes_chan = self.conn.request_channel( telepathy.CHANNEL_TYPE_TUBES, telepathy.HANDLE_TYPE_ROOM, room, True) self.tubes_chan = tubes_chan self.text_chan = text_chan tubes_chan[telepathy.CHANNEL_TYPE_TUBES].connect_to_signal( \ 'NewTube', self._new_tube_cb) def _list_tubes_reply_cb(self, tubes): for tube_info in tubes: self._new_tube_cb(*tube_info) def _list_tubes_error_cb(self, e): _logger.debug('ListTubes() failed: %s', e) def _joined_cb(self, activity_): if not self.get_shared_activity(): return _logger.debug('Joined an existing shared activity') self.initiating = False self._setup() _logger.debug('This is not my activity: waiting for a tube...') self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].ListTubes( reply_handler=self._list_tubes_reply_cb, error_handler=self._list_tubes_error_cb) def _new_tube_cb(self, identifier, initiator, type, service, params, state): _logger.debug( 'New tube: ID=%d initator=%d type=%d service=%s ' 'params=%r state=%d', identifier, initiator, type, service, params, state) if (type == telepathy.TUBE_TYPE_DBUS and service == SERVICE): if state == telepathy.TUBE_STATE_LOCAL_PENDING: self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].AcceptDBusTube( identifier) self.tube_conn = TubeConnection( self.conn, self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES], identifier, group_iface=self.text_chan[telepathy.CHANNEL_INTERFACE_GROUP]) _logger.debug('Tube created') self.messenger = Messenger(self.tube_conn, self.initiating, self.model) def _get_data_from_file_path(self, file_path): fd = open(file_path, 'r') try: data = fd.read() finally: fd.close() return data def read_file(self, file_path): if self.metadata['mime_type'] == 'text/plain': data = self._get_data_from_file_path(file_path) self.model.deserialize(data) for link in self.model.data['shared_links']: _logger.debug('read: url=%s title=%s d=%s' % (link['url'], link['title'], link['color'])) self._add_link_totray(link['url'], base64.b64decode(link['thumb']), link['color'], link['title'], link['owner'], -1, link['hash']) logging.debug('########## reading %s', data) self._tabbed_view.set_history(self.model.data['history']) for number, tab in enumerate(self.model.data['currents']): tab_page = self._tabbed_view.get_nth_page(number) tab_page.browser.set_history_index(tab['history_index']) self._tabbed_view.set_current_page(self.model.data['current_tab']) elif self.metadata['mime_type'] == 'text/uri-list': data = self._get_data_from_file_path(file_path) uris = mime.split_uri_list(data) if len(uris) == 1: self._tabbed_view.props.current_browser.load_uri(uris[0]) else: _logger.error('Open uri-list: Does not support' 'list of multiple uris by now.') else: file_uri = 'file://' + file_path self._tabbed_view.props.current_browser.load_uri(file_uri) def write_file(self, file_path): if not self.metadata['mime_type']: self.metadata['mime_type'] = 'text/plain' if self.metadata['mime_type'] == 'text/plain': browser = self._tabbed_view.current_browser if not self._jobject.metadata['title_set_by_user'] == '1': if browser.props.title is None: self.metadata['title'] = _('Untitled') else: self.metadata['title'] = browser.props.title self.model.data['history'] = self._tabbed_view.get_history() current_tab = self._tabbed_view.get_current_page() self.model.data['current_tab'] = current_tab self.model.data['currents'] = [] for n in range(0, self._tabbed_view.get_n_pages()): tab_page = self._tabbed_view.get_nth_page(n) n_browser = tab_page.browser if n_browser != None: uri = n_browser.get_uri() history_index = n_browser.get_history_index() info = { 'title': n_browser.props.title, 'url': uri, 'history_index': history_index } self.model.data['currents'].append(info) f = open(file_path, 'w') try: logging.debug('########## writing %s', self.model.serialize()) f.write(self.model.serialize()) finally: f.close() def _link_add_button_cb(self, button): self._add_link() def _go_home_button_cb(self, button): self._tabbed_view.load_homepage() def _key_press_cb(self, widget, event): key_name = Gdk.keyval_name(event.keyval) browser = self._tabbed_view.props.current_browser if event.get_state() & Gdk.ModifierType.CONTROL_MASK: if key_name == 'd': self._add_link() elif key_name == 'f': _logger.debug('keyboard: Find') self._edit_toolbar_button.set_expanded(True) self._edit_toolbar.search_entry.grab_focus() elif key_name == 'l': _logger.debug('keyboard: Focus url entry') self._primary_toolbar.entry.grab_focus() elif key_name == 'minus': _logger.debug('keyboard: Zoom out') browser.zoom_out() elif key_name in ['plus', 'equal']: _logger.debug('keyboard: Zoom in') browser.zoom_in() elif key_name == 'Left': _logger.debug('keyboard: Go back') browser.go_back() elif key_name == 'Right': _logger.debug('keyboard: Go forward') browser.go_forward() elif key_name == 'r': _logger.debug('keyboard: Reload') browser.reload() elif Gdk.keyval_name(event.keyval) == "t": self._tabbed_view.add_tab() else: return False return True elif key_name in ('KP_Up', 'KP_Down', 'KP_Left', 'KP_Right'): scrolled_window = browser.get_parent() if key_name in ('KP_Up', 'KP_Down'): adjustment = scrolled_window.get_vadjustment() elif key_name in ('KP_Left', 'KP_Right'): adjustment = scrolled_window.get_hadjustment() value = adjustment.get_value() step = adjustment.get_step_increment() if key_name in ('KP_Up', 'KP_Left'): adjustment.set_value(value - step) elif key_name in ('KP_Down', 'KP_Right'): adjustment.set_value(value + step) return True return False def _add_link(self): ''' take screenshot and add link info to the model ''' browser = self._tabbed_view.props.current_browser ui_uri = browser.get_uri() for link in self.model.data['shared_links']: if link['hash'] == sha1(ui_uri).hexdigest(): _logger.debug('_add_link: link exist already a=%s b=%s', link['hash'], sha1(ui_uri).hexdigest()) return buf = self._get_screenshot() timestamp = time.time() self.model.add_link(ui_uri, browser.props.title, buf, profile.get_nick_name(), profile.get_color().to_string(), timestamp) if self.messenger is not None: self.messenger._add_link(ui_uri, browser.props.title, profile.get_color().to_string(), profile.get_nick_name(), base64.b64encode(buf), timestamp) def _add_link_model_cb(self, model, index): ''' receive index of new link from the model ''' link = self.model.data['shared_links'][index] self._add_link_totray(link['url'], base64.b64decode(link['thumb']), link['color'], link['title'], link['owner'], index, link['hash']) def _add_link_totray(self, url, buf, color, title, owner, index, hash): ''' add a link to the tray ''' item = LinkButton(buf, color, title, owner, hash) item.connect('clicked', self._link_clicked_cb, url) item.connect('remove_link', self._link_removed_cb) # use index to add to the tray self._tray.add_item(item, index) item.show() if self._tray.props.visible is False: self._tray.show() self._view_toolbar.traybutton.props.sensitive = True def _link_removed_cb(self, button, hash): ''' remove a link from tray and delete it in the model ''' self.model.remove_link(hash) self._tray.remove_item(button) if len(self._tray.get_children()) == 0: self._view_toolbar.traybutton.props.sensitive = False def _link_clicked_cb(self, button, url): ''' an item of the link tray has been clicked ''' self._tabbed_view.props.current_browser.load_uri(url) def _get_screenshot(self): browser = self._tabbed_view.props.current_browser window = browser.get_window() width, height = window.get_width(), window.get_height() thumb_width, thumb_height = style.zoom(100), style.zoom(80) thumb_surface = Gdk.Window.create_similar_surface( window, cairo.CONTENT_COLOR, thumb_width, thumb_height) cairo_context = cairo.Context(thumb_surface) thumb_scale_w = thumb_width * 1.0 / width thumb_scale_h = thumb_height * 1.0 / height cairo_context.scale(thumb_scale_w, thumb_scale_h) Gdk.cairo_set_source_window(cairo_context, window, 0, 0) cairo_context.paint() thumb_str = StringIO.StringIO() thumb_surface.write_to_png(thumb_str) return thumb_str.getvalue() def can_close(self): if self._force_close: return True elif downloadmanager.can_quit(): return True else: alert = Alert() alert.props.title = ngettext('Download in progress', 'Downloads in progress', downloadmanager.num_downloads()) message = ngettext('Stopping now will erase your download', 'Stopping now will erase your downloads', downloadmanager.num_downloads()) alert.props.msg = message cancel_icon = Icon(icon_name='dialog-cancel') cancel_label = ngettext('Continue download', 'Continue downloads', downloadmanager.num_downloads()) alert.add_button(Gtk.ResponseType.CANCEL, cancel_label, cancel_icon) stop_icon = Icon(icon_name='dialog-ok') alert.add_button(Gtk.ResponseType.OK, _('Stop'), stop_icon) stop_icon.show() self.add_alert(alert) alert.connect('response', self.__inprogress_response_cb) alert.show() self.present() return False def __inprogress_response_cb(self, alert, response_id): self.remove_alert(alert) if response_id is Gtk.ResponseType.CANCEL: logging.debug('Keep on') elif response_id == Gtk.ResponseType.OK: logging.debug('Stop downloads and quit') self._force_close = True downloadmanager.remove_all_downloads() self.close() def get_document_path(self, async_cb, async_err_cb): browser = self._tabbed_view.props.current_browser browser.get_source(async_cb, async_err_cb) def get_canvas(self): return self._tabbed_view
#!/usr/bin/python from messenger import Messenger from os import getpid messenger = Messenger('http://leedscodedojo.tessanddave.com/paxos-test/a/xx-' + str(getpid()).zfill(5)) while True: currMessage = messenger.getNextMessage() print "Received: " + str(currMessage) ''' process currMessage as described, possibly sending back some other messages, e.g.: messenger.postMessage({'type':'messageType','timePeriod':timePeriod}) '''
def publish(self, msg): Messenger.publish(self, msg, self.topic, 1)
class Controller: def __init__(self): self.siteID = sys.argv[1] with open('knownhosts.json') as hosts_file: self.hosts = json.load(hosts_file)['hosts'] #self.hostToID = dict() count = 0 for key in sorted(self.hosts.keys()): #self.hostToID[key] = count self.hosts[key]['id'] = count count += 1 self.messenger = Messenger(self.hosts[self.siteID], self.hosts) #self.airport = planes.Planes() self.store = StableStorage() if len(sys.argv) >= 3: handle_test_file() else: #wu = imp.Wuubern(len(hosts), hostToID[siteID]) wu, self.airport = self.store.initialize( len(self.hosts), self.hosts[self.siteID]['id']) self.messenger.add_listener(wu) self.messenger.add_listener(self.store) self.messenger.add_listener(self.airport) self.handle_user_input(wu) #def handle_user_input(wu, messenger, hosts, hostToID, siteID, airport, stable_storage): def handle_user_input(self, wu): ''' Main loop for handling user input. ''' command = input().split(" ") counter = 0 while command[0] != 'quit': if command[0] == "reserve" and len(command) == 3: counter += 1 spotsLeft = self.airport.checkPlanes(command[2], command[1]) if not spotsLeft: print("Cannot schedule reservation for " + command[1] + ".") else: plns = command[2].split(',') plns = [int(x) for x in plns] self.airport.addUser(command[1], self.hosts[self.siteID]['id'], len(self.hosts.keys()), plns) ev = event.Event("Reservation", counter, self.hosts[self.siteID]['id']) ev.resInfo(command[1], "pending", command[2]) wu.insert(ev) print("Reservation submitted for " + command[1] + ".") elif command[0] == "cancel": counter += 1 for e in wu.dct: if (e.resUser == command[1]): if e.resStatus == "confirmed": plns = e.resPlaneList.split(',') plns = [int(x) for x in plns] for pln in plns: self.airport.removeSpot(pln, e.resUser) wu.delete(e) break print("Reservation for", command[1], "cancelled.") elif command[0] == "view": for ev in sorted(wu.dct, key=lambda event: event.resUser): print(ev.resUser, ev.resPlaneList, ev.resStatus) elif command[0] == "log": for ev in sorted(wu.log, key=lambda event: event.timeStamp): if (ev.type == "insert"): print(ev.type, ev.inserted.resUser, ev.inserted.resPlaneList) elif (ev.type == "delete"): print(ev.type, ev.deleted.resUser) elif command[0] == "send": np, myMC = wu.send(self.hosts[command[1]]['id']) if (len(command) > 2): m = Message(np, myMC, self.siteID, command[2]) else: m = Message(np, myMC, self.siteID) host = command[1] self.messenger.send((self.hosts[host]['ip_address'], self.hosts[host]['udp_end_port']), pickle.dumps(m)) elif command[0] == "sendall": np1 = set() for key, host in self.hosts.items(): if key != self.siteID: np, myMC = wu.send(host['id']) np1 = np1.union(np) m = Message(np1, myMC, self.siteID) for key, host in self.hosts.items(): self.messenger.send( (host['ip_address'], host['udp_end_port']), pickle.dumps(m)) elif command[0] == "clock": for i in range(len(wu.myMC)): for j in range(len(wu.myMC[i]) - 1): print(wu.myMC[i][j], end=" ") print(wu.myMC[i][-1]) else: print("invalid command") # Write to stable storage self.store.store() # Wait for next command command = input().split(" ") print("exiting...") os._exit(0)
#!/usr/bin/python from messenger import Messenger from os import getpid from sys import argv acceptorName = argv[1] messenger = Messenger('http://127.0.0.1:24192/a/dt-py-' + str(getpid()).zfill(5) + '-' + acceptorName) promisedToAcceptNoEarlierThan = 0 lastAccepted = -1 while True: currMessage = messenger.getNextMessage() if currMessage['timePeriod'] <= lastAccepted: continue response = {'by':acceptorName, 'timePeriod':currMessage['timePeriod']} if currMessage['type'] == 'prepare': if currMessage['timePeriod'] > promisedToAcceptNoEarlierThan: promisedToAcceptNoEarlierThan = currMessage['timePeriod'] response['type'] = 'promised' if lastAccepted >= 0: response['lastAcceptedTimePeriod'] = lastAccepted response['lastAcceptedValue'] = lastAcceptedValue else: response['haveAccepted'] = False elif currMessage['type'] == 'proposed': if currMessage['timePeriod'] < promisedToAcceptNoEarlierThan: continue
class WebActivity(activity.Activity): def __init__(self, handle): activity.Activity.__init__(self, handle) _logger.debug('Starting the web activity') session = WebKit.get_default_session() session.set_property('accept-language-auto', True) session.set_property('ssl-use-system-ca-file', True) session.set_property('ssl-strict', False) # By default, cookies are not stored persistently, we have to # add a cookie jar so that they get saved to disk. We use one # with a SQlite database: cookie_jar = SoupGNOME.CookieJarSqlite(filename=_cookies_db_path, read_only=False) session.add_feature(cookie_jar) _seed_xs_cookie(cookie_jar) # FIXME # downloadmanager.remove_old_parts() self._force_close = False self._tabbed_view = TabbedView() self._tabbed_view.connect('focus-url-entry', self._on_focus_url_entry) self._tabbed_view.connect('switch-page', self.__switch_page_cb) self._tray = HTray() self.set_tray(self._tray, Gtk.PositionType.BOTTOM) self._primary_toolbar = PrimaryToolbar(self._tabbed_view, self) self._edit_toolbar = EditToolbar(self) self._view_toolbar = ViewToolbar(self) self._primary_toolbar.connect('add-link', self._link_add_button_cb) self._primary_toolbar.connect('go-home', self._go_home_button_cb) self._primary_toolbar.connect('go-library', self._go_library_button_cb) self._primary_toolbar.connect('set-home', self._set_home_button_cb) self._primary_toolbar.connect('reset-home', self._reset_home_button_cb) self._edit_toolbar_button = ToolbarButton( page=self._edit_toolbar, icon_name='toolbar-edit') self._primary_toolbar.toolbar.insert( self._edit_toolbar_button, 1) view_toolbar_button = ToolbarButton( page=self._view_toolbar, icon_name='toolbar-view') self._primary_toolbar.toolbar.insert( view_toolbar_button, 2) self._primary_toolbar.show_all() self.set_toolbar_box(self._primary_toolbar) self.set_canvas(self._tabbed_view) self._tabbed_view.show() self.model = Model() self.model.connect('add_link', self._add_link_model_cb) self.connect('key-press-event', self._key_press_cb) if handle.uri: self._tabbed_view.current_browser.load_uri(handle.uri) elif not self._jobject.file_path: # TODO: we need this hack until we extend the activity API for # opening URIs and default docs. self._tabbed_view.load_homepage() self.messenger = None self.connect('shared', self._shared_cb) # Get the Presence Service self.pservice = presenceservice.get_instance() try: name, path = self.pservice.get_preferred_connection() self.tp_conn_name = name self.tp_conn_path = path self.conn = telepathy.client.Connection(name, path) except TypeError: _logger.debug('Offline') self.initiating = None if self.get_shared_activity() is not None: _logger.debug('shared: %s', self.get_shared()) # We are joining the activity _logger.debug('Joined activity') self.connect('joined', self._joined_cb) if self.get_shared(): # We've already joined self._joined_cb() else: _logger.debug('Created activity') # README: this is a workaround to remove old temp file # http://bugs.sugarlabs.org/ticket/3973 self._cleanup_temp_files() def _cleanup_temp_files(self): """Removes temporary files generated by Download Manager that were cancelled by the user or failed for any reason. There is a bug in GLib that makes this to happen: https://bugzilla.gnome.org/show_bug.cgi?id=629301 """ try: uptime_proc = open('/proc/uptime', 'r').read() uptime = int(float(uptime_proc.split()[0])) except EnvironmentError: logging.warning('/proc/uptime could not be read') uptime = None temp_path = os.path.join(self.get_activity_root(), 'instance') now = int(time.time()) cutoff = now - 24 * 60 * 60 # yesterday if uptime is not None: boot_time = now - uptime cutoff = max(cutoff, boot_time) for f in os.listdir(temp_path): if f.startswith('.goutputstream-'): fpath = os.path.join(temp_path, f) mtime = int(os.path.getmtime(fpath)) if mtime < cutoff: logging.warning('Removing old temporary file: %s', fpath) try: os.remove(fpath) except EnvironmentError: logging.error('Temporary file could not be ' 'removed: %s', fpath) def _on_focus_url_entry(self, gobject): self._primary_toolbar.entry.grab_focus() def _shared_cb(self, activity_): _logger.debug('My activity was shared') self.initiating = True self._setup() _logger.debug('This is my activity: making a tube...') self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].OfferDBusTube(SERVICE, {}) def _setup(self): if self.get_shared_activity() is None: _logger.debug('Failed to share or join activity') return bus_name, conn_path, channel_paths = \ self.get_shared_activity().get_channels() # Work out what our room is called and whether we have Tubes already room = None tubes_chan = None text_chan = None for channel_path in channel_paths: channel = telepathy.client.Channel(bus_name, channel_path) htype, handle = channel.GetHandle() if htype == telepathy.HANDLE_TYPE_ROOM: _logger.debug('Found our room: it has handle#%d "%s"', handle, self.conn.InspectHandles(htype, [handle])[0]) room = handle ctype = channel.GetChannelType() if ctype == telepathy.CHANNEL_TYPE_TUBES: _logger.debug('Found our Tubes channel at %s', channel_path) tubes_chan = channel elif ctype == telepathy.CHANNEL_TYPE_TEXT: _logger.debug('Found our Text channel at %s', channel_path) text_chan = channel if room is None: _logger.debug("Presence service didn't create a room") return if text_chan is None: _logger.debug("Presence service didn't create a text channel") return # Make sure we have a Tubes channel - PS doesn't yet provide one if tubes_chan is None: _logger.debug("Didn't find our Tubes channel, requesting one...") tubes_chan = self.conn.request_channel( telepathy.CHANNEL_TYPE_TUBES, telepathy.HANDLE_TYPE_ROOM, room, True) self.tubes_chan = tubes_chan self.text_chan = text_chan tubes_chan[telepathy.CHANNEL_TYPE_TUBES].connect_to_signal( 'NewTube', self._new_tube_cb) def _list_tubes_reply_cb(self, tubes): for tube_info in tubes: self._new_tube_cb(*tube_info) def _list_tubes_error_cb(self, e): _logger.debug('ListTubes() failed: %s', e) def _joined_cb(self, activity_): if not self.get_shared_activity(): return _logger.debug('Joined an existing shared activity') self.initiating = False self._setup() _logger.debug('This is not my activity: waiting for a tube...') self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].ListTubes( reply_handler=self._list_tubes_reply_cb, error_handler=self._list_tubes_error_cb) def _new_tube_cb(self, identifier, initiator, type, service, params, state): _logger.debug('New tube: ID=%d initator=%d type=%d service=%s ' 'params=%r state=%d', identifier, initiator, type, service, params, state) if (type == telepathy.TUBE_TYPE_DBUS and service == SERVICE): if state == telepathy.TUBE_STATE_LOCAL_PENDING: self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].AcceptDBusTube( identifier) self.tube_conn = TubeConnection( self.conn, self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES], identifier, group_iface=self.text_chan[ telepathy.CHANNEL_INTERFACE_GROUP]) _logger.debug('Tube created') self.messenger = Messenger(self.tube_conn, self.initiating, self.model) def _get_data_from_file_path(self, file_path): fd = open(file_path, 'r') try: data = fd.read() finally: fd.close() return data def read_file(self, file_path): if self.metadata['mime_type'] == 'text/plain': data = self._get_data_from_file_path(file_path) self.model.deserialize(data) for link in self.model.data['shared_links']: _logger.debug('read: url=%s title=%s d=%s' % (link['url'], link['title'], link['color'])) self._add_link_totray(link['url'], base64.b64decode(link['thumb']), link['color'], link['title'], link['owner'], -1, link['hash'], link.get('notes')) logging.debug('########## reading %s', data) self._tabbed_view.set_history(self.model.data['history']) for number, tab in enumerate(self.model.data['currents']): tab_page = self._tabbed_view.get_nth_page(number) tab_page.browser.set_history_index(tab['history_index']) zoom_level = tab.get('zoom_level') if zoom_level is not None: tab_page.browser.set_zoom_level(zoom_level) tab_page.browser.grab_focus() self._tabbed_view.set_current_page(self.model.data['current_tab']) elif self.metadata['mime_type'] == 'text/uri-list': data = self._get_data_from_file_path(file_path) uris = mime.split_uri_list(data) if len(uris) == 1: self._tabbed_view.props.current_browser.load_uri(uris[0]) else: _logger.error('Open uri-list: Does not support' 'list of multiple uris by now.') else: file_uri = 'file://' + file_path self._tabbed_view.props.current_browser.load_uri(file_uri) self._tabbed_view.props.current_browser.grab_focus() def write_file(self, file_path): if not self.metadata['mime_type']: self.metadata['mime_type'] = 'text/plain' if self.metadata['mime_type'] == 'text/plain': browser = self._tabbed_view.current_browser if not self._jobject.metadata['title_set_by_user'] == '1': if browser.props.title is None: self.metadata['title'] = _('Untitled') else: self.metadata['title'] = browser.props.title self.model.data['history'] = self._tabbed_view.get_history() current_tab = self._tabbed_view.get_current_page() self.model.data['current_tab'] = current_tab self.model.data['currents'] = [] for n in range(0, self._tabbed_view.get_n_pages()): tab_page = self._tabbed_view.get_nth_page(n) n_browser = tab_page.browser if n_browser is not None: uri = n_browser.get_uri() history_index = n_browser.get_history_index() info = {'title': n_browser.props.title, 'url': uri, 'history_index': history_index, 'zoom_level': n_browser.get_zoom_level()} self.model.data['currents'].append(info) f = open(file_path, 'w') try: logging.debug('########## writing %s', self.model.serialize()) f.write(self.model.serialize()) finally: f.close() def _link_add_button_cb(self, button): self._add_link() def _go_home_button_cb(self, button): self._tabbed_view.load_homepage() def _go_library_button_cb(self, button): self._tabbed_view.load_homepage(ignore_gconf=True) def _set_home_button_cb(self, button): self._tabbed_view.set_homepage() self._alert(_('The initial page was configured')) def _reset_home_button_cb(self, button): self._tabbed_view.reset_homepage() self._alert(_('The default initial page was configured')) def _alert(self, title, text=None): alert = NotifyAlert(timeout=5) alert.props.title = title alert.props.msg = text self.add_alert(alert) alert.connect('response', self._alert_cancel_cb) alert.show() def _alert_cancel_cb(self, alert, response_id): self.remove_alert(alert) def _key_press_cb(self, widget, event): key_name = Gdk.keyval_name(event.keyval) browser = self._tabbed_view.props.current_browser if event.get_state() & Gdk.ModifierType.CONTROL_MASK: if key_name == 'd': self._add_link() elif key_name == 'f': _logger.debug('keyboard: Find') self._edit_toolbar_button.set_expanded(True) self._edit_toolbar.search_entry.grab_focus() elif key_name == 'l': _logger.debug('keyboard: Focus url entry') self._primary_toolbar.entry.grab_focus() elif key_name == 'minus': _logger.debug('keyboard: Zoom out') browser.zoom_out() elif key_name in ['plus', 'equal']: _logger.debug('keyboard: Zoom in') browser.zoom_in() elif key_name == '0': _logger.debug('keyboard: Actual size') browser.set_zoom_level(ZOOM_ORIGINAL) elif key_name == 'Left': _logger.debug('keyboard: Go back') browser.go_back() elif key_name == 'Right': _logger.debug('keyboard: Go forward') browser.go_forward() elif key_name == 'r': _logger.debug('keyboard: Reload') browser.reload() elif Gdk.keyval_name(event.keyval) == "t": self._tabbed_view.add_tab() elif key_name == 'w': _logger.debug('keyboard: close tab') self._tabbed_view.close_tab() elif key_name == "Tab": _logger.debug('keyboard: next tab') current_index = self._tabbed_view.get_current_page() if current_index == self._tabbed_view.get_n_pages() - 1: self._tabbed_view.set_current_page(0) else: self._tabbed_view.set_current_page(current_index + 1) elif event.get_state() & Gdk.ModifierType.SHIFT_MASK: if key_name == "ISO_Left_Tab": _logger.debug('keyboard: previous tab') current_index = self._tabbed_view.get_current_page() last_index = self._tabbed_view.get_n_pages() if current_index == 0: self._tabbed_view.set_current_page(last_index - 1) else: self._tabbed_view.set_current_page(current_index - 1) else: return False return True elif key_name in ('KP_Up', 'KP_Down', 'KP_Left', 'KP_Right'): scrolled_window = browser.get_parent() if key_name in ('KP_Up', 'KP_Down'): adjustment = scrolled_window.get_vadjustment() elif key_name in ('KP_Left', 'KP_Right'): adjustment = scrolled_window.get_hadjustment() value = adjustment.get_value() step = adjustment.get_step_increment() if key_name in ('KP_Up', 'KP_Left'): adjustment.set_value(value - step) elif key_name in ('KP_Down', 'KP_Right'): adjustment.set_value(value + step) return True elif key_name == 'Escape': status = browser.get_load_status() loading = WebKit.LoadStatus.PROVISIONAL <= status \ < WebKit.LoadStatus.FINISHED if loading: _logger.debug('keyboard: Stop loading') browser.stop_loading() return False def _add_link(self): ''' take screenshot and add link info to the model ''' browser = self._tabbed_view.props.current_browser ui_uri = browser.get_uri() for link in self.model.data['shared_links']: if link['hash'] == sha1(ui_uri).hexdigest(): _logger.debug('_add_link: link exist already a=%s b=%s', link['hash'], sha1(ui_uri).hexdigest()) return buf = self._get_screenshot() timestamp = time.time() self.model.add_link(ui_uri, browser.props.title, buf, profile.get_nick_name(), profile.get_color().to_string(), timestamp) if self.messenger is not None: self.messenger._add_link(ui_uri, browser.props.title, profile.get_color().to_string(), profile.get_nick_name(), base64.b64encode(buf), timestamp) def _add_link_model_cb(self, model, index): ''' receive index of new link from the model ''' link = self.model.data['shared_links'][index] self._add_link_totray(link['url'], base64.b64decode(link['thumb']), link['color'], link['title'], link['owner'], index, link['hash'], link.get('notes')) def _add_link_totray(self, url, buf, color, title, owner, index, hash, notes=None): ''' add a link to the tray ''' item = LinkButton(buf, color, title, owner, hash, notes) item.connect('clicked', self._link_clicked_cb, url) item.connect('remove_link', self._link_removed_cb) item.notes_changed_signal.connect(self.__link_notes_changed) # use index to add to the tray self._tray.add_item(item, index) item.show() self._view_toolbar.traybutton.props.sensitive = True self._view_toolbar.traybutton.props.active = True self._view_toolbar.update_traybutton_tooltip() def _link_removed_cb(self, button, hash): ''' remove a link from tray and delete it in the model ''' self.model.remove_link(hash) self._tray.remove_item(button) if len(self._tray.get_children()) == 0: self._view_toolbar.traybutton.props.sensitive = False self._view_toolbar.traybutton.props.active = False self._view_toolbar.update_traybutton_tooltip() def __link_notes_changed(self, button, hash, notes): self.model.change_link_notes(hash, notes) def _link_clicked_cb(self, button, url): ''' an item of the link tray has been clicked ''' self._tabbed_view.props.current_browser.load_uri(url) def _get_screenshot(self): browser = self._tabbed_view.props.current_browser window = browser.get_window() width, height = window.get_width(), window.get_height() thumb_width, thumb_height = style.zoom(100), style.zoom(80) thumb_surface = Gdk.Window.create_similar_surface( window, cairo.CONTENT_COLOR, thumb_width, thumb_height) cairo_context = cairo.Context(thumb_surface) thumb_scale_w = thumb_width * 1.0 / width thumb_scale_h = thumb_height * 1.0 / height cairo_context.scale(thumb_scale_w, thumb_scale_h) Gdk.cairo_set_source_window(cairo_context, window, 0, 0) cairo_context.paint() thumb_str = StringIO.StringIO() thumb_surface.write_to_png(thumb_str) return thumb_str.getvalue() def can_close(self): if self._force_close: return True elif downloadmanager.can_quit(): return True else: alert = Alert() alert.props.title = ngettext('Download in progress', 'Downloads in progress', downloadmanager.num_downloads()) message = ngettext('Stopping now will erase your download', 'Stopping now will erase your downloads', downloadmanager.num_downloads()) alert.props.msg = message cancel_icon = Icon(icon_name='dialog-cancel') cancel_label = ngettext('Continue download', 'Continue downloads', downloadmanager.num_downloads()) alert.add_button(Gtk.ResponseType.CANCEL, cancel_label, cancel_icon) stop_icon = Icon(icon_name='dialog-ok') alert.add_button(Gtk.ResponseType.OK, _('Stop'), stop_icon) stop_icon.show() self.add_alert(alert) alert.connect('response', self.__inprogress_response_cb) alert.show() self.present() return False def __inprogress_response_cb(self, alert, response_id): self.remove_alert(alert) if response_id is Gtk.ResponseType.CANCEL: logging.debug('Keep on') elif response_id == Gtk.ResponseType.OK: logging.debug('Stop downloads and quit') self._force_close = True downloadmanager.remove_all_downloads() self.close() def __switch_page_cb(self, tabbed_view, page, page_num): browser = page._browser status = browser.get_load_status() if status in (WebKit.LoadStatus.COMMITTED, WebKit.LoadStatus.FIRST_VISUALLY_NON_EMPTY_LAYOUT): self.get_window().set_cursor(Gdk.Cursor(Gdk.CursorType.WATCH)) elif status in (WebKit.LoadStatus.PROVISIONAL, WebKit.LoadStatus.FAILED, WebKit.LoadStatus.FINISHED): self.get_window().set_cursor(Gdk.Cursor(Gdk.CursorType.LEFT_PTR)) def get_document_path(self, async_cb, async_err_cb): browser = self._tabbed_view.props.current_browser browser.get_source(async_cb, async_err_cb) def get_canvas(self): return self._tabbed_view
def share_instance(self, connection, is_initiator): self.chat.messenger = Messenger(connection, is_initiator, self.chat)
def __init__(self, topic, alias, cmd): self.__logger = logging.getLogger('get_status.Status') self.__logger.info('init') Messenger.__init__(self, APPKEY, 'status', 'status') self.topic = topic self.alias = alias self.cmd = cmd