def initiateGame(self, addrList, contactList): print addrList threads = [] game = Game(len(addrList)) contacts = Contacts() for con in contactList: contacts.add(con) contacts.notifyAll(Code.START) contacts.notifyAll(Code.INFO, ["You wait until the fateful night of the " + "party, dressing up in your finest attire. " + "At the house you're greeted by a elderly " + 'butler. "Which guest are you again?" ' + "he asks."]) contacts.notifyAll(Code.CHAR_PROMPT, game.availableSuspects()) for i in range(len(contacts)): threads.append(threading.Thread(target= ClientHandler.start, args=(i, game, contacts))) threads[-1].start() for thread in threads: thread.join() self.s.shutdown(socket.SHUT_RDWR) self.s.close()
def sendMessage(self, message, whoto): # Check status of recipient in profile profile = DbI.getProfile(whoto) status = profile['status'] if profile else "deleted" if status in ['deleted', 'blocked']: return self.RC_MESSAGE_IGNORED print("Trying to send message to '%s'" % whoto) if whoto is not None and len(whoto) == 16: try: s = socks.socksocket() s.setproxy(socks.PROXY_TYPE_SOCKS4, "localhost", 11109) s.connect((whoto + ".onion", 11009)) numsent = s.send(message) s.close() if numsent != len(message): print("Oops - num bytes sent:", numsent, "but message has length:", len(message)) # For really long messages, maybe need to chunk into 4k blocks or something? else: Contacts.instance().comeOnline(whoto) return self.RC_MESSAGE_SENT except Exception as e: print("Woah, that threw something:", e) print("Bailed from the send attempt, returning failure") return self.RC_MESSAGE_FAILED # it didn't work
def dealWithMessage(message): '''Examine the received message and decide what to do with it''' print("Hmm, the MessageShuffler has been given some kind of message") # We must be online if we've received a message Contacts.comeOnline(MessageShuffler.getOwnTorId()) if message.senderMustBeTrusted: sender = DbClient.getProfile(message.senderId, False) if not sender or sender['status'] != "trusted": return # throw message away if not message.isComplete(): print("A message of type", message.encryptionType, "was received but it's not complete - throwing away") return # throw message away # if it's not encrypted, it's for us -> save in inbox if message.encryptionType == Message.ENCTYPE_NONE: MessageShuffler.dealWithUnencryptedMessage(message) elif message.encryptionType == Message.ENCTYPE_SYMM: # if it's symmetric, forget it for now pass elif message.encryptionType == Message.ENCTYPE_ASYM: MessageShuffler.dealWithAsymmetricMessage(message) else: print("Hä? What kind of encryption type is that? ", message.encryptionType) # Log receipt of message (do we want to know about relays at all?) if message.encryptionType in [Message.ENCTYPE_NONE, Message.ENCTYPE_ASYM]: logMessage = "Message of type: %s received from %s" % (message.getMessageTypeKey(), message.senderId) MessageShuffler.getTannoy().shout(logMessage)
def text_find_contact_by_number(self): """test to check if we can find a contact by phone number and display information""" self.new_contact.save_contact() test_contact = Contacts('Test', 'User', '071234786', '*****@*****.**') test_contact.save_contact() found_contact = Contacts.find_by_number('0711223344') self.assertEqual(found_contact.email, test_contact.email)
def test_delete_contact(self): """test_delete_contact to test if we can remove a contact from our contact list""" self.new_contact.save_contact() test_contact = Contacts('Test', 'User', '071234786', '*****@*****.**') test_contact.save_contact() self.new_contact.delete_contact() self.assertEqual(len(Contacts.contact_list), 1)
def test_contact_exists(self): """test to check if we can return Boolean "if we cannot find the contact""" self.new_contact.save_contact() test_contact = Contacts('Test', 'User', '071234786', '*****@*****.**') test_contact.save_contact() contact_exists = Contacts.contact_exists('0711223344') self.assertTrue(contact_exists)
def flushOutboxInSeparateThread(self): '''This can take quite a while to do the flush''' if self._flushing: return print("Outgoing postman is flushing the outbox...") self._flushing = True # Look in the outbox for messages messagesFound = 0 messagesSent = 0 failedRecpts = set() for m in DbClient.getOutboxMessages(): messagesFound += 1 # Get recipient, timestamp, relays, message message = m['message'] sendTimestamp = m.get('timestamp', None) # not used yet # TODO: if the timestamp is too old, then either just delete the message (if it's not to be queued) or move to inbox # Some messages have a single recipient (and maybe relays), others only have a recipientList recipient = m.get('recipient', None) if recipient: sendSuccess = self.RC_MESSAGE_FAILED if recipient in failedRecpts else self.sendMessage(message, recipient) if sendSuccess == self.RC_MESSAGE_IGNORED: print("Dealt with message so I should delete it from the db:", m["_id"]) DbClient.deleteMessageFromOutbox(m["_id"]) elif sendSuccess == self.RC_MESSAGE_SENT: print("Sent message so I should delete it from the db:", m["_id"]) DbClient.deleteMessageFromOutbox(m["_id"]) messagesSent += 1 testMsg = "Message sent, type was %s and recipient was %s" % (m.get("msgType", "unknown"), recipient) # TODO: Pass these values with the signal as an object, not a string self.emit(QtCore.SIGNAL("messageSent"), testMsg) elif not m.get('queue', False): print("I failed to send a message but it shouldn't be queued, deleting it") DbClient.deleteMessageFromOutbox(m["_id"]) failedRecpts.add(recipient) else: print("I failed to send but I'll keep the message and try again later") failedRecpts.add(recipient) else: # There isn't a direct recipient, so let's hope there's a recipient list recipientList = m.get('recipientList', None) if recipientList: print("I've got a message to relay to: ", recipientList) failedRecipientsForThisMessage = set() # TODO: Try to send to each in the list # TODO: Does the parent even need to know when a send has worked? if messagesSent > 0: self.parent.postmanKnock() # only once if messagesFound > 0: print("For %d found messages, I managed to send %d copies" % (messagesFound, messagesSent)) # We tried to send a message to these recipients but failed - set them to be offline for r in failedRecpts: Contacts.goneOffline(r) self._flushing = False
def __init__(self, scope, resources, calibration): #initialise pygame self.compass = Compass(calibration) #get a compass object self.scope = scope #Use a pyscope object so we can run the program from the console self.resources = resources #get the resources class instance self.contactsArray = Contacts() #get a contacts class instance self.text = None self.smallnumber_text = None self.dots = None self.display_scale = None self.closest_text = "" self.smallnumber = ""
def update_contact_info(self): """ Updates contact information in the database. """ contact_info, task_info = self.get_contact_task_information( self.spreadsheetId) self.contacts = Contacts(contact_info) for month in self.months: month.update_contacts(self.contacts)
def __init__(self, slug, api_key): super(NationBuilder, self).__init__() self.people = People(slug, api_key) self.tags = NBTags(slug, api_key) self.lists = Lists(slug, api_key) self.contacts = Contacts(slug, api_key)
def __init__(self, options=None): defaults = { 'contacts_file': os.path.join(DATA_DIR, 'contacts.json'), } if not options: options = defaults # Auth self.credentials = self.authenticate() self.http = self.credentials.authorize(httplib2.Http()) self._messages = None self._drafts = None self._people = None # Try to instantiate services (requires internet connection) try: self.service = discovery.build('gmail', 'v1', http=self.http) self.users = self.service.users() except Exception as e: print('Google API je nedostupan:', e) self.ok = False # Prepare contacts self.contacts = Contacts(options.get('contacts_file'), self.people)
def dealWithMessage(message): '''Examine the received message and decide what to do with it''' print("Hmm, the MessageShuffler has been given some kind of message") # We must be online if we've received a message Contacts.instance().comeOnline(DbI.getOwnTorid()) if message.senderMustBeTrusted: sender = DbI.getProfile(message.senderId) if not sender or sender['status'] != "trusted": return # throw message away if not message.isComplete(): print("A message of type", message.encryptionType, "was received but it's not complete - throwing away") return # throw message away # if it's not encrypted, it's for us -> save in inbox if message.encryptionType == Message.ENCTYPE_NONE: MessageShuffler.dealWithUnencryptedMessage(message) elif message.encryptionType == Message.ENCTYPE_SYMM: # if it's symmetric, forget it for now pass elif message.encryptionType == Message.ENCTYPE_ASYM: MessageShuffler.dealWithAsymmetricMessage(message) elif message.encryptionType == Message.ENCTYPE_RELAY: # Get received bytes of message, and add to Outbox, send to everybody EXCEPT the sender bytesToSend = message.createOutput(None) if bytesToSend: # add to outbox, but don't send it back to message.senderId DbI.addRelayMessageToOutbox(bytesToSend, message.senderId) else: print("Hä? What kind of encryption type is that? ", message.encryptionType) # Log receipt of message (do we want to know about relays at all?) if message.encryptionType in [ Message.ENCTYPE_NONE, Message.ENCTYPE_ASYM ]: logMessage = "Message of type: %s received from %s" % ( message.getMessageTypeKey(), message.senderId) MessageShuffler.getTannoy().shout(logMessage)
def generateListPage(self, doEdit=False, userid=None, extraParams=None): self.requirePageResources(['avatar-none.jpg', 'status-self.png', 'status-requested.png', 'status-untrusted.png', 'status-trusted.png']) # List of contacts, and show details for the selected one (or self if userid=None) selectedprofile = DbClient.getProfile(userid) if selectedprofile is None: selectedprofile = DbClient.getProfile() userid = selectedprofile['torid'] ownPage = userid == DbClient.getOwnTorId() # Build list of contacts userboxes = [] for p in DbClient.getContactList(): box = Bean() box.dispName = p['displayName'] box.torid = p['torid'] box.tilestyle = "contacttile" + ("selected" if p['torid'] == userid else "") box.status = p['status'] box.isonline = Contacts.isOnline(box.torid) userboxes.append(box) # expand templates using current details lefttext = self.listtemplate.getHtml({'webcachedir' : Config.getWebCacheDir(), 'contacts' : userboxes}) pageProps = {"webcachedir" : Config.getWebCacheDir(), 'person':selectedprofile} # Add extra parameters if necessary if extraParams: pageProps.update(extraParams) # See which contacts we have in common with this person (sharedContactIds, possIdsForThem, possIdsForMe, nameMap) = ContactMaker.getSharedAndPossibleContacts(userid) sharedContacts = self._makeIdAndNameBeanList(sharedContactIds, nameMap) pageProps.update({"sharedcontacts" : sharedContacts}) possibleContacts = self._makeIdAndNameBeanList(possIdsForThem, nameMap) pageProps.update({"possiblecontactsforthem" : possibleContacts}) possibleContacts = self._makeIdAndNameBeanList(possIdsForMe, nameMap) pageProps.update({"possiblecontactsforme" : possibleContacts}) # Which template to use depends on whether we're just showing or also editing if doEdit: # Use two different details templates, one for self and one for others detailstemplate = self.editowndetailstemplate if ownPage else self.editdetailstemplate righttext = detailstemplate.getHtml(pageProps) else: detailstemplate = self.detailstemplate # just show righttext = detailstemplate.getHtml(pageProps) contents = self.buildTwoColumnPage({'pageTitle' : I18nManager.getText("contacts.title"), 'leftColumn' : lefttext, 'rightColumn' : righttext, 'pageFooter' : "<p>Footer</p>"}) return contents
def __init__(self): self.history = History(db_name=DATABASE) self.contacts = Contacts(db_name=DATABASE) self.builder = gtk.Builder() self.builder.add_from_file("ui.glade") window = self.builder.get_object("window") self.message = self.builder.get_object("text") ### # Menu --> Connect self.builder.get_object("history").connect("activate", self.history_browsing) self.builder.get_object("contact").connect("activate", self.contact_browsing) ### window.show_all() window.connect("destroy", gtk.main_quit) ### cancel = self.builder.get_object("cancel") cancel.connect("clicked", gtk.main_quit) self.builder.get_object("exit").connect("activate", gtk.main_quit) ### ok = self.builder.get_object("ok") ok.connect("clicked", self.ok_clicked) ### self.check_box = self.builder.get_object("history_check") ### self.number = self.builder.get_object("number") self.number.connect("changed", self.on_number_changed) # Počítání znaků self.charcounter = self.builder.get_object("charcounter") self.message.get_buffer().connect("changed", self.on_message_changed) # Doplňování self.completion = gtk.EntryCompletion() self.store = gtk.TreeStore(str, str) self.completion.set_model(self.store) # Model creating self.completion.set_text_column(0) name_cell = gtk.CellRendererText() self.completion.pack_start(name_cell) self.completion.add_attribute(name_cell, 'text', 1) self.number.set_completion(self.completion) # About dialog self.about_dialog = self.builder.get_object("aboutdialog") self.builder.get_object("about").connect("activate", self.on_about_activate) # Progress dialog self.progress_dialog = self.builder.get_object("progressdialog") self.progress_ok = self.builder.get_object("progressok") self.progress_ok.connect("clicked", self.on_progressok_clicked) self.progress_bar = self.builder.get_object("progressbar") #gtkmainloop gtk.main()
def sendMessage(self, message, whoto): # Check status of recipient in profile profile = DbClient.getProfile(whoto, False) status = profile['status'] if profile else "deleted" if status in ['deleted', 'blocked']: return self.RC_MESSAGE_IGNORED print("Trying to send message to '%s'" % whoto) if whoto is not None and len(whoto) == 16: try: s = socks.socksocket() s.setproxy(socks.PROXY_TYPE_SOCKS4, "localhost", 11109) s.connect((whoto + ".onion", 11009)) numsent = s.send(message) s.close() if numsent != len(message): print("Oops - num bytes sent:", numsent, "but message has length:", len(message)) # For really long messages, maybe need to chunk into 4k blocks or something? else: Contacts.comeOnline(whoto) return self.RC_MESSAGE_SENT except Exception as e: print("Woah, that threw something:", e) print("Bailed from the send attempt, returning failure") return self.RC_MESSAGE_FAILED # it didn't work
def __init__(self, app=None, token=None, refresh_token=None, tokens=None): if tokens: token = tokens["access_token"] refresh_token = tokens["refresh_token"] self.app = app self.token = token self.refresh_token = refresh_token self.session = self.app.oauth.get_session(token=self.token) self.session.headers.update({'Content-Type': 'application/json'}) self.timeline = Timeline(self) self.contacts = Contacts(self)
def testEmptyList(self): '''Check that an empty list is handled properly''' contacts = Contacts() self.assertFalse(contacts.isOnline("abcdef")) self.assertIsNone(contacts.lastSeen("abcdef"), "last seen time should be None") self.assertIsNone(contacts.lastSeen(None), "last seen time should be None") self.assertIsNone(contacts.lastSeen(""), "last seen time should be None")
def load(self, command=False): if command: return "Load" with open("data.json", "r") as file: data = json.load(file) contact_data = data["owner"]["contacts"] contacts = Contacts(contact_data["adress"], contact_data["mobile"], contact_data["nif"], contact_data["email"]) self.owner = Owner(data["owner"]["name"], contacts) self.product_manager.from_dict(data["products"]) self.warehouse_manager.from_dict(data["warehouses"]) self.order_manager.from_dict(data["orders"]) self.client_manager.from_dict(data["clients"]) self.product_group_manager.from_dict(data["product_groups"])
def __init__(self): self.product_manager = ProductManager() self.warehouse_manager = WarehouseManager() self.order_manager = OrderManager() self.client_manager = ClientManager() self.product_group_manager = ProductGroupManager() self.owner = Owner( "Yo Corp.", Contacts("Tomar", 123456789, 987654321, "*****@*****.**")) prods_list = self.product_manager.get_all().keys() self.product_group_manager.from_dict([{ "id": 0, "name": "ALL PRODUCTS", "products": prods_list }, { "id": 1, "name": "OLD PRODUCTS", "products": [] }]) self.load()
def __init__(self, editors, names, tasks, spreadsheetId, month_file=None, new_page=False): super(GSheetsRequest, self).__init__() self.editors = editors self.service = None self.spreadsheetId = spreadsheetId self.write_body = {} self.request_body = {} self.service = self.start() if new_page: self.new_page() self.full_send(request_only=True) contact_info, task_info = self.get_contact_task_information( self.spreadsheetId) self.contacts = Contacts(contact_info) self.tasks = TaskManager(task_info) self.current_sheet_name, self.current_sheet_id, self.totals_sheet_id = self.get_sheet_name_and_id( self.spreadsheetId) self.months = [ Month(self.contacts, self.tasks, self.current_sheet_id, self.spreadsheetId, self.current_sheet_name, self.editors) if month_file is None else Month.load(month_file) ] self.recent_month = self.months[0] self.sheet_name_date_start = None self.sheet_name_date_end = None self.save()
class TestContacts(unittest.TestCase): def setUp(self): self.home_book = Contacts() self.work_book = Contacts() def test_create_and_search(self): self.home_book.add('Tom', { 'lives_in': 'USA', 'email': '*****@*****.**' }) self.home_book.add('Bob', { 'lives_in': 'USA', 'email': '*****@*****.**' }) self.work_book.add('Mike', { 'lives_in': 'Marks', 'email': '*****@*****.**' }) results = self.home_book.contacts_by_lives_in('USA') self.assertTrue('Tom' in results) self.assertTrue('Bob' in results) self.assertEqual(len(results), 2)
else: mlog_file = sys.stderr mlog_observer = FilteringLogObserver(textFileLogObserver(mlog_file), predicates=[info_predicate]) globalLogPublisher.addObserver(mlog_observer) # logger.info('resetting log output file') return reset_log_file() logger = Logger() globalLogBeginner.beginLoggingTo([]) contacts = Contacts(config_top) # noinspection PyUnusedLocal def receive_signal(signal_number, frame): logger.info('Received signal: {signal_number}', signal_number=signal_number) if ('True' == config.get('Testing')) and (signal.SIGUSR1 == signal_number): # testing is set logger.info('Testing is set') # noinspection PyBroadException,PyPep8 try: contacts.reset() except: logger.failure('error resetting, exiting') reactor.stop()
#!/usr/bin/python import yaml config = yaml.safe_load(open("config.yml")) from contacts import Contacts, Contact c = Contacts() # syntax: list_contacts.py import sys for contact in c.get_contacts(): print("Name: " + contact.name) print("Number: " + contact.number) print
class MailService: MAILSET_PATH = os.path.join(os.environ['HOME'], 'mailsets', 'mediumtagged') def __init__(self): self.mailset = MailSet() self.tagsset = TagsSet() self.contacts = Contacts() def reset(self): self.mailset = MailSet() self.tagsset = TagsSet() self.contacts = Contacts() def _read_file(self, filename): with open(filename, 'r') as fd: return fd.read() def _create_message_from_file(self, filename): data = self._read_file(filename) return self.create_message_from_string(data, filename) def create_message_from_string(self, data, filename=None): if data.startswith('From '): msg = mailbox.mboxMessage(data) from_addr = re.sub(r"^From ", "", msg.get_unixfrom()) msg.from_addr = from_addr msg.set_from(from_addr) else: msg = mailbox.Message(data) msg.from_addr = msg.get('From') return msg def _create_message_from_string(self, data): return mailbox.Message(data) def load_mailset(self): mbox_filenames = [ filename for filename in os.listdir (self.MAILSET_PATH) if filename.startswith('mbox')] messages = (self._create_message_from_file(os.path.join(self.MAILSET_PATH, mbox)) for mbox in mbox_filenames) self.index_messages(messages) def index_messages(self, messages): for message in messages: self.mailset.add(message) self.tagsset.add(message) self.contacts.add(message) def mails(self, query, page, window_size): mails = self.mailset.values() mails = [mail for mail in mails if query.test(mail)] return sorted(mails, key=lambda mail: mail.date, reverse=True) def mail(self, mail_id): return self.mailset.get(mail_id) def search_contacts(self, query): return self.contacts.search(query) def mark_as_read(self, mail_id): self.mailset.mark_as_read(mail_id) self.tagsset.mark_as_read(self.mail(mail_id).tags) def delete_mail(self, mail_id): purged = self.mailset.delete(mail_id) if not purged: self.tagsset.increment_tag_total_count('trash') def update_tags_for(self, mail_id, new_tags): mail = self.mail(mail_id) new_tags_set = set(new_tags) old_tags_set = set(mail.tags) increment_set = new_tags_set - old_tags_set decrement_set = old_tags_set - new_tags_set map(lambda x: self.tagsset.increment_tag_total_count(x), increment_set) map(lambda x: self.tagsset.decrement_tag_total_count(x), decrement_set) mail.tags = new_tags def send(self, mail): mail = Mail.from_json(mail) self.mailset.update(mail) self.tagsset.increment_tag_total_count('sent') self.tagsset.decrement_tag_total_count('drafts') return mail.ident def save_draft(self, mail): mail = self.mailset.add_draft(Mail.from_json(mail)) return mail.ident def update_draft(self, mail): mail = Mail.from_json(mail) self.mailset.update(mail) return mail.ident def draft_reply_for(self, mail_id): return self.mailset.find(draft_reply_for=mail_id)
#!/usr/bin/python import yaml config = yaml.safe_load(open("config.yml")) from contacts import Contacts, Contact c = Contacts() # syntax: add_contact.py <name> <number> import sys if len(sys.argv) < 2: print("usage: add_contact.py <name> <number>") sys.exit() script_name = sys.argv.pop(0) name = sys.argv.pop(0) number = sys.argv.pop(0) if len(number) < 11: print("number must be in the format 12062551028 or +12062551028") sys.exit() if number[0] != "+": number = "+" + number contact = c.find_contact_by_name(name) if contact: print("already have a contact named " + name) sys.exit() else: new_contact = Contact(name, number)
def create_contact(fname, lname, phone, email): """Function to create a new contact """ new_contact = Contacts(fname, lname, phone, email) return new_contact
def setUp(self): self.home_book = Contacts() self.work_book = Contacts()
def dealWithAsymmetricMessage(message): '''Decide what to do with the given asymmetric message''' if message.senderId == DbI.getOwnTorid(): print("*** Shouldn't receive a message from myself!") return # Sort message according to type if message.messageType == Message.TYPE_CONTACT_RESPONSE: print("Received a contact accept from", message.senderId, "name", message.senderName) if MessageShuffler._isProfileStatusOk( message.senderId, ['pending', 'requested', 'untrusted']): print(message.senderName, "'s public key is", message.senderKey) ContactMaker.handleReceiveAccept(message.senderId, message.senderName, message.senderKey) # Store new message in inbox rowToStore = { "messageType": "contactresponse", "fromId": message.senderId, "fromName": message.senderName, "messageBody": message.introMessage, "accepted": True, "messageRead": False, "messageReplied": False, "timestamp": message.timestamp, "recipients": DbI.getOwnTorid() } DbI.addToInbox(rowToStore) elif MessageShuffler._isProfileStatusOk(message.senderId, [None, 'blocked']): print( "Received a contact response but I didn't send them a request!" ) print("Encrypted contents are:", message.encryptedContents) rowToStore = { "messageType": "contactresponse", "fromId": message.senderId, "fromName": message.senderName, "messageBody": message.introMessage, "accepted": True, "timestamp": message.timestamp, "encryptedMsg": message.encryptedContents } DbI.addMessageToPendingContacts(rowToStore) elif message.messageType == Message.TYPE_STATUS_NOTIFY: if message.online: print("One of our contacts has just come online- ", message.senderId, "and hash is", message.profileHash) prof = DbI.getProfile(message.senderId) if prof: storedHash = prof.get("profileHash", "empty") if message.profileHash != storedHash: reply = InfoRequestMessage( infoType=InfoRequestMessage.INFO_PROFILE) reply.recipients = [message.senderId] DbI.addToOutbox(reply) if message.ping: print("Now sending back a pong, too") reply = StatusNotifyMessage(online=True, ping=False, profileHash=None) reply.recipients = [message.senderId] DbI.addToOutbox(reply) else: print("It's already a pong so I won't reply") Contacts.instance().comeOnline(message.senderId) else: print("One of our contacts is going offline -", message.senderId) Contacts.instance().goneOffline(message.senderId) elif message.messageType == Message.TYPE_INFO_REQUEST: print("I've received an info request message for type", message.infoType) if MessageShuffler._isProfileStatusOk(message.senderId, ['trusted']): reply = InfoResponseMessage(message.messageType) reply.recipients = [message.senderId] DbI.addToOutbox(reply) elif message.messageType == Message.TYPE_INFO_RESPONSE: if message.profile and MessageShuffler._isProfileStatusOk( message.senderId, ['trusted', 'untrusted']): if message.profileHash: message.profile['profileHash'] = message.profileHash DbI.updateProfile(message.senderId, message.profile, Config.getWebCacheDir()) elif message.messageType == Message.TYPE_FRIEND_REFERRAL: print("I've received a friend referral message from:", message.senderId, "for:", message.friendName) if MessageShuffler._isProfileStatusOk(message.senderId, ['trusted']): # Store new referral message in inbox rowToStore = { "messageType": "contactrefer", "fromId": message.senderId, "friendId": message.friendId, "friendName": message.friendName, "messageBody": message.message, "publicKey": message.publicKey, "timestamp": message.timestamp, "messageRead": False, "messageReplied": False } DbI.addToInbox(rowToStore) elif message.messageType == Message.TYPE_FRIENDREFER_REQUEST: print("I've received a friend referral request from:", message.senderId, "who wants me to refer:", message.friendId) if MessageShuffler._isProfileStatusOk(message.senderId, ['trusted']): # Store message in the inbox rowToStore = { "messageType": "referrequest", "fromId": message.senderId, "friendId": message.friendId, "friendName": message.friendName, "messageBody": message.message, "publicKey": message.publicKey, "timestamp": message.timestamp, "messageRead": False, "messageReplied": False } DbI.addToInbox(rowToStore) elif message.messageType == Message.TYPE_ASYM_MESSAGE: print( "It's a general kind of message, this should go in the Inbox, right?" ) if MessageShuffler._isProfileStatusOk(message.senderId, ['trusted', 'untrusted']): rowToStore = { "messageType": "normal", "fromId": message.senderId, "messageBody": message.messageBody, "timestamp": message.timestamp, "messageRead": False, "messageReplied": False, "recipients": message.sendTo, "parentHash": message.replyToHash } DbI.addToInbox(rowToStore) Contacts.instance().comeOnline(message.senderId) else: # It's another asymmetric message type print("Hä? What kind of asymmetric message type is that? ", message.messageType)
class TrackerGraphics: smallNumber = "" def __init__(self, scope, resources, calibration): #initialise pygame self.compass = Compass(calibration) #get a compass object self.scope = scope #Use a pyscope object so we can run the program from the console self.resources = resources #get the resources class instance self.contactsArray = Contacts() #get a contacts class instance self.text = None self.smallnumber_text = None self.dots = None self.display_scale = None self.closest_text = "" self.smallnumber = "" def update(self, wave_size, addcontact, calibration): self.compass.updatexy(calibration) if addcontact: self.contactsArray.addContact(self.compass.smbusAvailable) #Read the current direction of the tracker from the digital compass bearing = self.compass.getCompassBearing() #rotate the contacts in relation to the grid self.contactsArray.updateContactsInWorld(bearing) #Set the screen background backdrop = self.rot_center(self.resources.compass, bearing) background_colour = (0, 0, 0) self.scope.pySurface.fill(background_colour) self.scope.pySurface.blit(backdrop, (0, 22)) #render our contacts if (len(self.contactsArray.ContactArray)) > 0: for x in self.contactsArray.ContactArray: trackerScale = self.contactsArray.trackerScale opacityIndex = x.getOpacityIndex(wave_size, trackerScale) self.scope.pySurface.blit( self.resources.contactBack[opacityIndex], (x.worldX - 25, x.worldY - 25)) for x in self.contactsArray.ContactArray: trackerScale = self.contactsArray.trackerScale opacityIndex = x.getOpacityIndex(wave_size, trackerScale) self.scope.pySurface.blit( self.resources.contactFore[opacityIndex], (x.worldX - 25, x.worldY - 25)) #render the wave pulse with current wave size self.scope.pySurface.blit(self.resources.waves[wave_size], (0, 0)) #Convert the range to the closest blip to text. If no blip present display dashes if self.contactsArray.getClosestContactDistance() == 999: self.closest_text = "" self.smallnumber = "" else: if wave_size == 0: self.closest_text = str( self.contactsArray.getClosestContactDistance()) self.smallnumber = str(random.randint(10, 99)) range_prefix = "" if len(self.closest_text) == 1: range_prefix = '0' if len(self.closest_text) == 2: range_prefix = '' #Render the display self.text = self.resources.font.render(str(bearing), 1, (215, 0, 0)) self.text = self.resources.font.render( range_prefix + self.closest_text, 1, (215, 0, 0)) self.smallnumber_text = self.resources.smallfont.render( self.smallnumber, 1, (215, 0, 0)) self.dots = self.resources.smallfont.render("-", 1, (215, 0, 0)) self.display_scale = self.resources.displayScaleFont.render( 'm', 1, (215, 0, 0)) #render the info panel to screen self.scope.pySurface.blit(self.resources.info, (0, 182)) self.scope.pySurface.blit(self.text, (129, 182)) self.scope.pySurface.blit(self.smallnumber_text, (170, 182)) self.scope.pySurface.blit(self.dots, (162, 182)) self.scope.pySurface.blit(self.display_scale, (178, 195)) self.scope.screen.blit(self.scope.pySurface, (0, 0)) #update the display and show our images pygame.display.update() if wave_size == 15: self.contactsArray.moveContacts() return self.contactsArray #Define the image rotation function def rot_center(self, image, angle): orig_rect = image.get_rect() rot_image = pygame.transform.rotate(image, angle * -1) rot_rect = orig_rect.copy() rot_rect.center = rot_image.get_rect().center rot_image = rot_image.subsurface(rot_rect).copy() return rot_image
def reset(self): self.mailset = MailSet() self.tagsset = TagsSet() self.contacts = Contacts()
def main(): c = Connections() users = c.get_all_data() contacts = Contacts(users).contacts for contact in contacts: print(contact)
def from_dict (self, client_list): for client in client_list: contacts = Contacts(client["contacts"]["adress"], client["contacts"]["mobile"], client["contacts"]["nif"], client["contacts"]["email"]) self.clients[client["id"]] = Client(client["name"], contacts)
def contacts(self): phone_contacts = Contacts( ) # phone_contacts is the object of the class
def main(): myContacts = Contacts() print "My " + str(myContacts) myContacts.addContact("Mickey") myContacts.addContact("Fred") myContacts.addContact("Edward") myContacts.addContact("Harry") print "My " + str(myContacts) yourContacts = Contacts() yourContacts.addContact("Pat") print "Your " + str(yourContacts) print "My " + str(myContacts)
def getjson(request, datatype): req = request.REQUEST start = req.get('start', None) end = req.get('end', None) daysofweek = req.get('daysofweek', '') reply = req.get('reply', None) lat = bool(req.get('lat', False)) email = req.get('email', None) granularity = req.get('granularity', None) if start: start = parse(start) if end: end = parse(end) if daysofweek: daysofweek = daysofweek.split(",") if reply is not None: reply = bool(reply) curruser = Userdbs.objects.get(username=request.user) print request.user print curruser.dbname conn = sqlite3.connect(curruser.dbname, detect_types=sqlite3.PARSE_DECLTYPES) # db call to get data if datatype == 'topsenders': req = request.REQUEST start = req.get('start', None) end = req.get ('end', None) top = 10 data = topsenders.get_top_senders(top, start, end, conn) elif datatype == "getrate": req = request.REQUEST start = req.get('start', None) end = req.get('end', None) emailAddy = curruser.username replyAddy = req.get('replyAddy', None) mode = req.get('mode', None) data = responseRateByTime.get_response_rate(mode, start, end, emailAddy, replyAddy, conn) elif datatype == "byhour": ebh = RepliesByHour() queries = [] print "EMAIL", email queries.append(('y', ebh.get_sql(lat=lat, reply=reply, start=start, end=end, daysofweek=daysofweek, email=email))) ld = LineData() data = ld.get_data(queries, conn) elif datatype == "contacts": contacts = Contacts() data = contacts.get_data(conn) elif datatype == "getlatency": bd = ByDay() queries = [] queries.append(('y', bd.get_sql(lat=lat, reply=reply, start=start, end=end, granularity=granularity, email=email))) ld = BDLineData() data = ld.get_data(queries, conn, 0, granularity=granularity, start=start, end=end) elif datatype == "getcount": bd = ByDayNorm() queries = [] queries.append(('y', bd.get_sql(lat=lat, reply=reply, start=start, end=end, granularity=granularity, email=email))) ld = BDLineData() data = ld.get_data(queries, conn, 1, granularity=granularity, start=start, end=end) else: return HttpResponse('json call not recognized') # return data as json return HttpResponse(json.dumps(data), mimetype="application/json")
def dealWithAsymmetricMessage(message): '''Decide what to do with the given asymmetric message''' if message.senderId == MessageShuffler.getOwnTorId(): print("*** Shouldn't receive a message from myself!") return # Sort message according to type if message.messageType == Message.TYPE_CONTACT_RESPONSE: print("Received a contact accept from", message.senderId, "name", message.senderName) if MessageShuffler._isProfileStatusOk(message.senderId, ['pending', 'requested', 'untrusted']): print(message.senderName, "'s public key is", message.senderKey) ContactMaker.handleReceiveAccept(message.senderId, message.senderName, message.senderKey) # Call DbClient to store new message in inbox rowToStore = {"messageType":"contactresponse", "fromId":message.senderId, "fromName":message.senderName, "messageBody":message.introMessage, "accepted":True, "messageRead":False, "messageReplied":False, "timestamp":message.timestamp, "recipients":MessageShuffler.getOwnTorId()} DbClient.addMessageToInbox(rowToStore) elif MessageShuffler._isProfileStatusOk(message.senderId, [None, 'blocked']): print("Received a contact response but I didn't send them a request!") print("Encrypted contents are:", message.encryptedContents) rowToStore = {"messageType":"contactresponse", "fromId":message.senderId, "fromName":message.senderName, "messageBody":message.introMessage, "accepted":True, "timestamp":message.timestamp, "encryptedMsg":message.encryptedContents} DbClient.addMessageToPendingContacts(rowToStore) elif message.messageType == Message.TYPE_STATUS_NOTIFY: if message.online: print("One of our contacts has just come online- ", message.senderId, "and hash is", message.profileHash) prof = DbClient.getProfile(userid=message.senderId, extend=False) if prof: storedHash = prof.get("profileHash", "empty") if message.profileHash != storedHash: reply = InfoRequestMessage(infoType=InfoRequestMessage.INFO_PROFILE) reply.recipients = [message.senderId] DbClient.addMessageToOutbox(reply) if message.ping: print("Now sending back a pong, too") reply = StatusNotifyMessage(online=True, ping=False, profileHash=None) reply.recipients = [message.senderId] DbClient.addMessageToOutbox(reply) else: print("It's already a pong so I won't reply") Contacts.comeOnline(message.senderId) else: print("One of our contacts is going offline -", message.senderId) Contacts.goneOffline(message.senderId) elif message.messageType == Message.TYPE_INFO_REQUEST: print("I've received an info request message for type", message.infoType) if MessageShuffler._isProfileStatusOk(message.senderId, ['trusted']): reply = InfoResponseMessage(message.messageType) reply.recipients = [message.senderId] DbClient.addMessageToOutbox(reply) elif message.messageType == Message.TYPE_INFO_RESPONSE: if message.profile and MessageShuffler._isProfileStatusOk(message.senderId, ['trusted', 'untrusted']): if message.profileHash: message.profile['profileHash'] = message.profileHash DbClient.updateContact(message.senderId, message.profile) elif message.messageType == Message.TYPE_ASYM_MESSAGE: print("It's a general kind of message, this should go in the Inbox, right?") if MessageShuffler._isProfileStatusOk(message.senderId, ['trusted', 'untrusted']): Contacts.comeOnline(message.senderId) else: # It's another asymmetric message type print("Hä? What kind of asymmetric message type is that? ", message.messageType)
def getjson(request, datatype): req = request.REQUEST start = req.get('start', None) end = req.get('end', None) daysofweek = req.get('daysofweek', '') reply = req.get('reply', None) lat = bool(req.get('lat', False)) email = req.get('email', None) granularity = req.get('granularity', None) if start: start = parse(start) if end: end = parse(end) if daysofweek: daysofweek = daysofweek.split(",") if reply is not None: reply = bool(reply) curruser = User.objects.get(username=request.user) #ATTENTION: going to need to change the host once we deploy live #conn_string = "host=localhost dbname=liamg user=liamg password=liamg" #connect to db to get the data #conn = psycopg2.connect(conn_string) conn = connection #DEPRECATED: for the sqlite prototype database #conn = sqlite3.connect(curruser.dbname, detect_types=sqlite3.PARSE_DECLTYPES) #get the curruser id so that you can pass it to the functions below curridsql = "select id from accounts where user_id = %s" c = conn.cursor() c.execute(curridsql, (request.user.pk,)) currid = c.fetchone()[0] #get the top people who respond to the user if datatype == 'topsenders': req = request.REQUEST start = req.get('start', None) end = req.get ('end', None) top = 10 email = curruser.username data = topsenders.get_top_senders(top, start, end, email, conn) #get the sent top ten people who the user contacts elif datatype == "topsent": req = request.REQUEST start = req.get('start', None) end = req.get('end', None) top = 10 email = curruser.username data = topsent.get_top_sent(top, start, end, email, conn) #get the rate for a specifc user (filtered) and for the general population elif datatype == "getrate": req = request.REQUEST start = req.get('start', None) end = req.get('end', None) emailAddy = curruser.username replyAddy = req.get('email', None) mode = req.get('mode', None) data = responseRateByTime.get_response_rate(mode, start, end, emailAddy, replyAddy, conn) #use this to get the count in the first graph and maybe the second graph? elif datatype == "byhour": ebh = RepliesByHour() queries = [] queries.append(('y', ebh.get_sql(lat=lat, reply=reply, start=start, end=end, daysofweek=daysofweek, email=email, currid = currid))) ld = LineData() data = ld.get_data(queries, conn) #not sure what this does yet? elif datatype == "contacts": contacts = Contacts() data = contacts.get_data(conn) #get the second graph that shows the response time elif datatype == "getlatency": bd = ByDay() queries = [] queries.append(('y', bd.get_sql(lat=lat, reply=reply, start=start, end=end, granularity=granularity, email=email))) ld = BDLineData() chartdata, maxval = ld.get_data(queries, conn, 0, granularity=granularity, start=start, end=end) data = [chartdata, maxval] #use this to get the small graph next to the top ten elif datatype == "getcount": bd = ByDayNorm() queries = [] #get the queries for the line charts in the top ten queries.append(('y', bd.get_sql(lat=lat, reply=reply, start=start, end=end, granularity=granularity, email=email, currid=currid))) ld = BDLineData() chartdata, maxval = ld.get_data(queries, conn, 1, granularity=granularity, start=start, end=end) data = [chartdata, maxval] else: return HttpResponse('json call not recognized') # return data as json return HttpResponse(json.dumps(data), mimetype="application/json")
def __init__(self): self.mailset = MailSet() self.tagsset = TagsSet() self.contacts = Contacts()
pfile = "/Users/jmht/Documents/AMPLE/data/coiled-coils/ar_results.pkl" pfile = "/Users/jmht/Documents/AMPLE/data/coiled-coils/test.pkl" f = open(pfile) resultsDict = cPickle.load(f) f.close() # cPickle.dump( obj, f) #print resultsDict #print len( resultsDict ) # all = [] # for result in resultsDict: # if result.goodContacts > 40: # all.append( result ) # # pfile = "/Users/jmht/Documents/AMPLE/data/coiled-coils/test.pkl" # f = open( pfile, 'w' ) # cPickle.dump( all, f ) # f.close() for result in [resultsDict[0]]: c = Contacts() c.best = result.contactData dssp_file = os.path.join(dataDir, result.pdbCode + ".dssp") dsspP = dssp.DsspParser(dssp_file) print c.helixFromContacts(dsspP)
# unknown locale, use en is better than fail LANG = None if LANG is None: LANG = 'en' else: LANG = LANG[:2] # en, fr, el etc.. gmail_domains = ['gmail.com', 'googlemail.com'] transport_type = {} # list the type of transport last_message_time = {} # list of time of the latest incomming message # {acct1: {jid1: time1, jid2: time2}, } encrypted_chats = {} # list of encrypted chats {acct1: [jid1, jid2], ..} contacts = Contacts() gc_connected = { } # tell if we are connected to the room or not {acct: {room_jid: True}} gc_passwords = { } # list of the pass required to enter a room {room_jid: password} automatic_rooms = { } # list of rooms that must be automaticaly configured and for which we have a list of invities {account: {room_jid: {'invities': []}}} groups = {} # list of groups newly_added = {} # list of contacts that has just signed in to_be_removed = {} # list of contacts that has just signed out events = Events() nicks = {} # list of our nick names in each account # should we block 'contact signed in' notifications for this account?
import yaml config = yaml.safe_load(open("config.yml")) twilio_account_sid = config["twilio"]["account_sid"] twilio_auth_token = config["twilio"]["auth_token"] twilio_from_number = config["twilio"]["from_number"] from twilio.rest import TwilioRestClient twilio_client = TwilioRestClient(twilio_account_sid, twilio_auth_token) from contacts import Contacts, Contact c = Contacts() # syntax: text.py <contact> <message> import sys script_name = sys.argv.pop(0) name = sys.argv.pop(0) msg = " ".join([str(x) for x in sys.argv]) contact = c.find_contact_by_name(name) if contact and msg: print("from " + str(twilio_from_number)) message = twilio_client.messages.create(body=msg, from_=twilio_from_number, to=contact.number) print("message is " + message.sid) else:
import pytz config = yaml.safe_load(open("config.yml")) my_timezone = timezone(config["global"]["timezone"]) utc = pytz.utc dt_format = config["global"]["dt_format"] twilio_account_sid = config["twilio"]["account_sid"] twilio_auth_token = config["twilio"]["auth_token"] from twilio.rest import TwilioRestClient twilio_client = TwilioRestClient(twilio_account_sid, twilio_auth_token) from contacts import Contacts, Contact c = Contacts() # syntax: print_texts_with.py <contact> import sys script_name = sys.argv.pop(0) name = sys.argv.pop(0) contact = c.find_contact_by_name(name) def name_or_number(number): contact = c.find_contact_by_number(number) if contact: return contact.name else: return number
def __init__ (self, name, contacts=Contacts()): self.name = name self.contacts = contacts
def flushOutboxInSeparateThread(self): '''This can take quite a while to do the flush''' if self._flushing: return print("Outgoing postman is flushing the outbox...") self._flushing = True # Look in the outbox for messages messagesFound = 0 messagesSent = 0 failedRecpts = set() for m in DbI.getOutboxMessages(): if not m: continue # message already deleted messagesFound += 1 # Get recipient, timestamp, relays, message message = imageutils.stringToBytes(m['message']) sendTimestamp = m.get('timestamp', None) # not used yet # TODO: if the timestamp is too old, then either just delete the message (if it's not to be queued) or move to inbox # Some messages have a single recipient (and maybe relays), others only have a recipientList recipient = m.get('recipient', None) if recipient: sendSuccess = self.RC_MESSAGE_FAILED if recipient in failedRecpts else self.sendMessage( message, recipient) if sendSuccess == self.RC_MESSAGE_IGNORED: print( "Dealt with message so I should delete it from the db:", m["_id"]) DbI.deleteFromOutbox(m["_id"]) elif sendSuccess == self.RC_MESSAGE_SENT: print("Sent message so I should delete it from the db:", m["_id"]) DbI.deleteFromOutbox(m["_id"]) messagesSent += 1 testMsg = "Message sent, type was %s and recipient was %s" % ( m.get("msgType", "unknown"), recipient) # TODO: Pass these values with the signal as an object, not a string self.messageSentSignal.emit(testMsg) elif not m.get('queue', False): print( "I failed to send a message but it shouldn't be queued, deleting it" ) DbI.deleteFromOutbox(m["_id"]) failedRecpts.add(recipient) else: print( "I failed to send but I'll keep the message and try again later" ) failedRecpts.add(recipient) # Message couldn't be sent directly, but maybe there are some relays we can use relays = m.get('relays', None) sentSomething = False if relays: # TODO: Check current timestamp and compare with sendTimestamp (types?) failedrelays = set() signedRelayMessage = m.get('relayMessage', None) if not signedRelayMessage: # Take the message bytes and make a RelayingMessage out of them to get the signed output signedRelayMessage = RelayingMessage( message).createOutput(None) # TODO: Store signedRelayMessage back in m # Loop over each relay in the list and try to send to each one for relay in relays: # Should we try to send if this relay is not online? On the other hand it doesn't hurt. if relay not in failedRecpts and self.sendMessage( signedRelayMessage, relay) == self.RC_MESSAGE_SENT: print("Sent message to relay '%s'" % relay) sentSomething = True messagesSent += 1 else: # Send failed, so add this relay to the list of failed ones failedrelays.add(relay) if sentSomething: DbI.updateOutboxMessage( m["_id"], {"relays": list(failedrelays)}) else: # There isn't a direct recipient, so let's hope there's a recipient list recipientList = m.get('recipientList', None) if recipientList: print("I've got a message to relay to: ", recipientList) failedRecipientsForThisMessage = set() # Try to send to each in the list for rRecipient in recipientList: if rRecipient in failedRecpts or self.sendMessage( message, rRecipient) == self.RC_MESSAGE_FAILED: # Couldn't send to this recipient failedRecipientsForThisMessage.add(rRecipient) if failedRecipientsForThisMessage: # Update m with the recipientList = failedRecipientsForThisMessage DbI.updateOutboxMessage(m["_id"], { "recipientList": list(failedRecipientsForThisMessage) }) print("I failed to send a relay to:", failedRecipientsForThisMessage) else: print( "I managed to relay everything, now deleting relay message" ) DbI.deleteFromOutbox(m["_id"]) # TODO: Wait inbetween sending to avoid overloading the network # TODO: Does the parent even need to know when a send has worked? if messagesSent > 0: self.parent.postmanKnock() # only once if messagesFound > 0: print("For %d found messages, I managed to send %d copies" % (messagesFound, messagesSent)) # We tried to send a message to these recipients but failed - set them to be offline for r in failedRecpts: Contacts.instance().goneOffline(r) self._flushing = False
#!/usr/bin/python import yaml config = yaml.safe_load(open("config.yml")) from contacts import Contacts, Contact c = Contacts() import sys if len(sys.argv) < 2: print("usage: delete_contact.py <name>") sys.exit() script_name = sys.argv.pop(0) name = sys.argv.pop(0) contact = c.find_contact_by_name(name) if contact: c.delete_contact(contact) else: print("no contact named " + name) sys.exit()
class sms_sender: def __init__(self): self.history = History(db_name=DATABASE) self.contacts = Contacts(db_name=DATABASE) self.builder = gtk.Builder() self.builder.add_from_file("ui.glade") window = self.builder.get_object("window") self.message = self.builder.get_object("text") ### # Menu --> Connect self.builder.get_object("history").connect("activate", self.history_browsing) self.builder.get_object("contact").connect("activate", self.contact_browsing) ### window.show_all() window.connect("destroy", gtk.main_quit) ### cancel = self.builder.get_object("cancel") cancel.connect("clicked", gtk.main_quit) self.builder.get_object("exit").connect("activate", gtk.main_quit) ### ok = self.builder.get_object("ok") ok.connect("clicked", self.ok_clicked) ### self.check_box = self.builder.get_object("history_check") ### self.number = self.builder.get_object("number") self.number.connect("changed", self.on_number_changed) # Počítání znaků self.charcounter = self.builder.get_object("charcounter") self.message.get_buffer().connect("changed", self.on_message_changed) # Doplňování self.completion = gtk.EntryCompletion() self.store = gtk.TreeStore(str, str) self.completion.set_model(self.store) # Model creating self.completion.set_text_column(0) name_cell = gtk.CellRendererText() self.completion.pack_start(name_cell) self.completion.add_attribute(name_cell, 'text', 1) self.number.set_completion(self.completion) # About dialog self.about_dialog = self.builder.get_object("aboutdialog") self.builder.get_object("about").connect("activate", self.on_about_activate) # Progress dialog self.progress_dialog = self.builder.get_object("progressdialog") self.progress_ok = self.builder.get_object("progressok") self.progress_ok.connect("clicked", self.on_progressok_clicked) self.progress_bar = self.builder.get_object("progressbar") #gtkmainloop gtk.main() def send(self, target, what): test = 0 ##Commend next row for production use test = 1 if test == 1: return True print "Odesílám %s do %d" % (what, target) self.progress_dialog.hide() self.progress_dialog.show() self.progress_ok.set_sensitive(False) self.progress_bar.set_fraction(0.33) self.progress_bar.set_text("Kontaktuji web") timestamp = int(time.time()) data = { 'timestamp' : timestamp, 'action' : 'send', 'sendingProfile1' : 11, 'sendingProfile2' : 20, 'sendingProfile3' : 32, 'textsms' : what, 'cislo-prijemce' : target } data = urllib.urlencode(data) print('http://www.poslatsms.cz/', data) try: req = urllib2.Request('http://www.poslatsms.cz/', data) self.progress_bar.set_fraction(0.66) self.progress_bar.set_text("Odesílám data") response = urllib2.urlopen(req) the_page = str(response.read()) except urllib2.error as e: print "error", e self.progress_bar.hide() print the_page if 'SMS zprávy přijaty k odeslání!' in the_page: self.progress_bar.set_text("Hotovo") self.progress_ok.set_sensitive(True) self.progress_bar.set_fraction(1.00) return True return False def on_message_changed(self, model): text = self.message.get_buffer().get_text(self.message.get_buffer().get_start_iter(), self.message.get_buffer().get_end_iter()) chars = len(text) colour = "darkgreen" if chars > 625: self.message.get_buffer().set_text(text[:625]) self.alert(self.message, "Překročena maximální délka zprávy!") text = self.message.get_buffer().get_text(self.message.get_buffer().get_start_iter(), self.message.get_buffer().get_end_iter()) chars = len(text) colour = "red" label = "Napsáno %d/125" % (chars % 125) if chars > 125: label += "Počet zpráv %d/5" % (((chars - 1) / 125) + 1) preformat = '<span foreground="%s">' % colour postformat= '</span>' label = preformat + label + postformat self.charcounter.set_markup(label) def on_number_changed(self, model): cislo = True try: text = int(self.number.get_text()) except ValueError: cislo = False self.store.clear() self.update_model(self.store, cislo) def update_model(self, model, number): #GET FROM CONTACTS try: for i in self.contacts.list_all(): if number: model.append(None, [i[0], i[1]]) else: model.append(None, [i[1], i[0]]) except TypeError: print "No contacts stored" #GET FROM HISTORY try: for i in self.history.disctinct_contacts(): model.append(None, [i[0], ""]) except TypeError: print "History doesnt contain \"non-contact\" numbers" return model def info(self, msg): dialog = gtk.MessageDialog(None, 0, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, msg) choice = dialog.run() if choice != None: dialog.hide() def alert(self, what, msg): #call alert from "what" with message "msg" dialog = gtk.MessageDialog(None, 0, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, msg) choice = dialog.run() if choice != None: dialog.hide() if what: what.grab_focus() def on_about_activate(self, widget): self.about_dialog.run() self.about_dialog.hide() def history_browsing(self, widget): self.history_window = History_UI(parent=self) self.history_window.builder.get_object("history_dialog").show() if self.history_window.result: self.number.set_text(str(self.history_window.result[0])) self.message.get_buffer().set_text(self.history_window.result[1]) def contact_browsing(self, widget): self.contact_window = Contacts_UI(parent=self) def ok_clicked(self, widget): if isInteger(self.number.get_text()): cislo = int(self.number.get_text()) if (len(self.number.get_text()) != 9): self.alert(self.nubmer, "Číslo příjemce není 9 místné číslo") return 1 else: cislo = self.contacts.get_num(self.number.get_text()) if cislo == None: self.alert(self.number, "Uvedený kontakt nebyl nalezen") return 1 text = self.message.get_buffer().get_text(self.message.get_buffer().get_start_iter(), self.message.get_buffer().get_end_iter()) if (text == ""): self.alert(self.message, "Nelze odeslat prázdnou zprávu!") return 1 while text <> "": if not(self.send(cislo, text[:125])): self.alert(None, "Chyba při odesílání! Změna enginu poskytovatele?") text = text[125:] else: # ukládání do historie if (self.check_box.get_active()): self.history.add(cislo, text[:125]) text = text[125:] self.message.get_buffer().set_text("") self.number.set_text("") def on_progressok_clicked(self,widget): self.progress_dialog.hide()