def testBasics(self): '''Testing the basics of the interface with a super-simple db''' # Create new, empty database without file-storage db = supersimpledb.MurmeliDb() DbI.setDb(db) # Lists should be empty self.assertEqual(len(DbI.getMessageableProfiles()), 0, "Should be 0 messageables") self.assertEqual(len(DbI.getTrustedProfiles()), 0, "Should be 0 trusted") self.assertFalse(DbI.hasFriends(), "Shouldn't have any friends") # Store some profiles DbI.updateProfile("abc123", {"keyid":"ZYXW987", "status":"self", "name":"That's me"}) DbI.updateProfile("def123", {"keyid":"JKLM987", "status":"trusted", "name":"Jimmy"}) DbI.updateProfile("ghi123", {"keyid":"TUVWX987", "status":"untrusted", "name":"Dave"}) # Get my ids self.assertEqual(DbI.getOwnTorid(), "abc123", "Should find correct tor id") self.assertEqual(DbI.getOwnKeyid(), "ZYXW987", "Should find correct key id") # Get all profiles self.assertEqual(len(DbI.getProfiles()), 3, "Should be three profiles in total") self.assertEqual(len(DbI.getMessageableProfiles()), 2, "Should be two messageables") self.assertEqual(len(DbI.getTrustedProfiles()), 1, "Should be one trusted") self.assertEqual(DbI.getTrustedProfiles()[0]['displayName'], "Jimmy", "Jimmy should be trusted") self.assertTrue(DbI.hasFriends(), "Should have friends") # Update an existing profile DbI.updateProfile("def123", {"displayName":"Slippin' Jimmy"}) self.assertEqual(len(DbI.getTrustedProfiles()), 1, "Should still be one trusted") self.assertEqual(DbI.getTrustedProfiles()[0]['displayName'], "Slippin' Jimmy", "Slippin' Jimmy should be trusted") # Finished DbI.releaseDb()
def servePage(self, view, url, params): self.requirePageResources( ['button-compose.png', 'default.css', 'jquery-3.1.1.js']) DbI.exportAllAvatars(Config.getWebCacheDir()) messageList = None if url == "/send": print("send message of type '%(messageType)s' to id '%(sendTo)s'" % params) if params['messageType'] == "contactresponse": torId = params['sendTo'] if params.get("accept", "0") == "1": ContactMaker.handleAccept(torId) # Make sure this new contact has an empty avatar DbI.exportAllAvatars(Config.getWebCacheDir()) outmsg = message.ContactResponseMessage( message=params['messageBody']) else: ContactMaker.handleDeny(torId) outmsg = message.ContactDenyMessage() # Construct a ContactResponse message object for sending outmsg.recipients = [params['sendTo']] DbI.addToOutbox(outmsg) elif url.startswith("/delete/"): DbI.deleteFromInbox(params.get("msgId", "")) elif url in ["/search", "/search/"]: messageList = DbI.searchInboxMessages(params.get("searchTerm")) # Make dictionary to convert ids to names contactNames = { c['torid']: c['displayName'] for c in DbI.getProfiles() } unknownSender = I18nManager.getText("messages.sender.unknown") unknownRecpt = I18nManager.getText("messages.recpt.unknown") # Get contact requests, responses and mails from inbox conreqs = [] conresps = [] mailTree = MessageTree() if messageList is None: messageList = DbI.getInboxMessages() # TODO: Paging options? for m in messageList: if not m: continue m['msgId'] = str(m.get("_id", "")) if m['messageType'] == "contactrequest": conreqs.append(m) elif m['messageType'] == "contactrefer": senderId = m.get('fromId', None) m['senderName'] = contactNames.get(senderId, unknownSender) conreqs.append(m) elif m['messageType'] == "contactresponse": if not m.get('accepted', False): m['messageBody'] = I18nManager.getText( "messages.contactrequest.refused") m['fromName'] = DbI.getProfile(m['fromId'])["displayName"] elif not m.get('messageBody', False): m['messageBody'] = I18nManager.getText( "messages.contactrequest.accepted") conresps.append(m) else: senderId = m.get('fromId', None) if not senderId and m.get('signatureKeyId', None): senderId = DbI.findUserIdFromKeyId(m['signatureKeyId']) m['senderName'] = contactNames.get(senderId, unknownSender) m['sentTimeStr'] = self.makeLocalTimeString(m['timestamp']) # Split m['recipients'] by commas, and look up each id with contactNames recpts = m.get('recipients', '') if recpts: replyAll = recpts.split(",") m['recipients'] = ", ".join( [contactNames.get(i, unknownRecpt) for i in replyAll]) replyAll.append(senderId) m['replyAll'] = ",".join(replyAll) else: m['recipients'] = unknownRecpt m['replyAll'] = "" mailTree.addMsg(m) mails = mailTree.build() bodytext = self.messagestemplate.getHtml({ "contactrequests": conreqs, "contactresponses": conresps, "mails": mails, "nummessages": len(conreqs) + len(conresps) + len(mails), "webcachedir": Config.getWebCacheDir() }) contents = self.buildPage({ 'pageTitle': I18nManager.getText("messages.title"), 'pageBody': bodytext, 'pageFooter': "<p>Footer</p>" }) view.setHtml(contents)
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', 'status-pending.png' ]) # List of contacts, and show details for the selected one (or self if userid=None) selectedprofile = DbI.getProfile(userid) if not selectedprofile: selectedprofile = DbI.getProfile() userid = selectedprofile['torid'] ownPage = userid == DbI.getOwnTorid() # Build list of contacts userboxes = [] currTime = datetime.datetime.now() for p in DbI.getProfiles(): box = Bean() box.dispName = p['displayName'] box.torid = p['torid'] box.tilestyle = "contacttile" + ("selected" if p['torid'] == userid else "") box.status = p['status'] isonline = Contacts.instance().isOnline(box.torid) lastSeen = Contacts.instance().lastSeen(box.torid) lastSeenTime = str(lastSeen.timetz())[:5] if lastSeen and ( currTime - lastSeen).total_seconds() < 18000 else None if lastSeenTime: box.lastSeen = I18nManager.getText( "contacts.onlinesince" if isonline else "contacts.offlinesince") % lastSeenTime elif isonline: box.lastSeen = I18nManager.getText("contacts.online") else: box.lastSeen = None 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