def getConversation(form, inbox, peer): splitTime = timeutil.getTime() - config.configuration['thread-split-age']; try: conv = Conversation.get(Conversation.inbox == inbox and Conversation.peer == peer and Conversation.last_update > splitTime) except Conversation.DoesNotExist: logger.info("Creating new conversation for %s -> %s", inbox.phone_number, peer.phone_number) conv = Conversation.create( user = inbox.user, inbox = inbox, last_update = timeutil.getTime(), peer = peer) return conv
def getConversation(form, inbox, peer): splitTime = timeutil.getTime() - config.configuration['thread-split-age'] try: conv = Conversation.get(Conversation.inbox == inbox and Conversation.peer == peer and Conversation.last_update > splitTime) except Conversation.DoesNotExist: logger.info("Creating new conversation for %s -> %s", inbox.phone_number, peer.phone_number) conv = Conversation.create(user=inbox.user, inbox=inbox, last_update=timeutil.getTime(), peer=peer) return conv
def lastitem(): try: latest = user.threads.order_by( Conversation.last_update.desc()).get().last_update except Conversation.DoesNotExist: latest = timeutil.getTime() return timeutil.toStamp(latest)
def getConversation(form, inbox, peer): splitTime = timeutil.getTime() - config.configuration['thread-split-age'] logger.info('getConversation %s %s', inbox.phone_number, peer.phone_number) try: conv = Conversation.get(Conversation.inbox == inbox, Conversation.peer == peer, Conversation.last_update > splitTime) logger.info("%s: got existing conversation for %s->%s %d->%d", peer.phone_number, conv.inbox.phone_number, conv.peer.phone_number, peer.id, conv.peer.id) except Conversation.DoesNotExist: logger.info("Creating new conversation for %s -> %s", inbox.phone_number, peer.phone_number) conv = Conversation.create(user=inbox.user, inbox=inbox, last_update=timeutil.getTime(), peer=peer) return conv
def getConversation(form, inbox, peer): splitTime = timeutil.getTime() - config.configuration['thread-split-age']; logger.info('getConversation %s %s', inbox.phone_number, peer.phone_number) try: conv = Conversation.get(Conversation.inbox == inbox, Conversation.peer == peer, Conversation.last_update > splitTime) logger.info("%s: got existing conversation for %s->%s %d->%d", peer.phone_number, conv.inbox.phone_number, conv.peer.phone_number, peer.id, conv.peer.id) except Conversation.DoesNotExist: logger.info("Creating new conversation for %s -> %s", inbox.phone_number, peer.phone_number) conv = Conversation.create( user = inbox.user, inbox = inbox, last_update = timeutil.getTime(), peer = peer) return conv
def lastitem(): try: latest = user.threads.order_by(Conversation.last_update.desc()).get().last_update except Conversation.DoesNotExist: latest = timeutil.getTime() return timeutil.toStamp(latest)
def user(doLogin=True): """Gets the currently logged in user, or presents a login form and exits if there is none. """ global _user if _user: return _user cookie = Cookie.SimpleCookie() cookie_string = os.environ.get('HTTP_COOKIE') if cookie_string: cookie.load(cookie_string) # check for an existing valid session, and return the user if so # TODO also clean up stale cookies at some point session_cookie = cookie.get('session', None) if session_cookie: try: sess = WebSession.get(WebSession.session_id == session_cookie.value) sess.last_seen = timeutil.getTime() sess.last_ip = ipAddr sess.save() _user = sess.user return _user except WebSession.DoesNotExist: logger.info('Got invalid session id "%s" for request %s', session_cookie.value, os.getenv('REQUEST_URI')) login_error_string = None if _form.getfirst('username') and _form.getfirst('password'): user = User.get(username=_form.getfirst('username')) if bcrypt.hashpw(_form.getfirst('password'), user.password) == user.password: # Login succeeded sess = WebSession.create(session_id=uuid.uuid4().hex, user=user, last_ip=ipAddr, last_seen = timeutil.getTime()) cookie['session'] = sess.session_id cookie['session']['expires'] = 86400*14 print cookie print '''\ Content-type: text/html Location: %s Redirecting...''' % request_url() # this is a good time to clean up old sessions WebSession.delete().where(WebSession.last_seen < timeutil.getTime() - timedelta(weeks=2)).execute() sys.exit() else: # Login failed; set an error string to that effect login_error_string = "Username/password did not match our records" if (doLogin == False): print """Status: 401 unauthorized\nContent-type: text/plain\n\nYou gotta be logged in for this to work""" sys.exit() print """Content-type: text/html <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="style.css"> <title>Login required</title> </head><body class="loginForm"> <div id="login">""" if login_error_string: print '<div class="error">%s</div>' % login_error_string else: print '<div class="explain">You must log in to continue.</div>' print '<form method="POST" action="%s"><ul>' % os.environ.get('REQUEST_URI') print '<li><label for="username">Username:</label>' print '<input type="text" name="username" value="%s"></li>' % (_form.getfirst('username') or '') print """<li><label for="password">Password:</label> <input type="password" name="password"></li> </ul><input type="submit" value="Log in"></form> </div></body></html>""" sys.exit()
with model.transaction(): body = form.getfirst('Body') try: message = client.messages.create( body=body, from_=form.getfirst('From'), to=form.getfirst('To'), status_callback=config.configuration['root-url'] + '/sms.py/outgoing') except twilio.TwilioRestException as e: print "Status: 400 Bad Request\nContent-type: text/html\n\n%s" % str(e) sys.exit() now = timeutil.getTime() try: # It's possible that the callback fired before we got here... event = Event.get(Event.sid == message.sid) event.message_body = body event.last_update = now event.save() conversation = event.conversation conversation.last_update = now conversation.save() except Event.DoesNotExist: # ... but not likely peer = control.getPeer(form, user, whoValue=message.to) conversation = control.getConversation(form, inbox, peer) event = Event.create(sid=message.sid, inbound=False,
def getEvent(form, sidField, inbound, type): if inbound: whoField = 'From' inboxField = 'To' else: whoField = 'To' inboxField = 'From' logger.info('getEvent sid=%s inbound=%s who=%s inbox=%s', form.getfirst(sidField), inbound, form.getfirst(whoField), form.getfirst(inboxField)) whoValue = form.getfirst(whoField) try: event = Event.get(Event.sid == form.getfirst(sidField)) except Event.DoesNotExist: user = getUser(form) inbox = getInbox(form, user, inboxField) peer = getPeer(form, user, whoValue=whoValue) logger.info(' peer=%s %s', peer.phone_number, peer.display_name) now = timeutil.getTime() conversation = getConversation(form, inbox, peer) logger.info('getEvent conversation.peer=%s %s', conversation.peer.phone_number, conversation.peer.display_name) event = Event.create(sid=form.getfirst(sidField), inbound=inbound, inbox=inbox, conversation=conversation, time=now, last_update=now, type=type) conversation.last_update = now conversation.unread = True conversation.save() peer.last_event = now peer.save() # there are several fields that could rightfully become 'status' and we want to guarantee precedence save = False for field in ['CallStatus', 'DialCallStatus', 'MessageStatus']: if applyAttribs(event, form, {field: 'status'}): save = True if applyAttribs(event, form, { 'DialCallDuration': 'call_duration', 'Body': 'message_body', }): save = True if save: event.save() # Attach any voicemail if form.getfirst('RecordingSid'): try: attach = Attachment.get( Attachment.sid == form.getfirst('RecordingSid')) except Attachment.DoesNotExist: attach = Attachment.create(sid=form.getfirst('RecordingSid'), url='%s.mp3' % form.getfirst('RecordingUrl'), mime_type='audio/mpeg', event=event) save = False if form.getfirst('RecordingDuration'): attach.duration = int(form.getfirst('RecordingDuration')) save = True if applyAttribs(attach, form, {'TranscriptionText': 'transcription'}): save = True if save: attach.save() return event
def user(doLogin=True): """Gets the currently logged in user, or presents a login form and exits if there is none. """ global _user if _user: return _user cookie = Cookie.SimpleCookie() cookie_string = os.environ.get('HTTP_COOKIE') if cookie_string: cookie.load(cookie_string) # check for an existing valid session, and return the user if so # TODO also clean up stale cookies at some point session_cookie = cookie.get('session', None) if session_cookie: try: sess = WebSession.get( WebSession.session_id == session_cookie.value) sess.last_seen = timeutil.getTime() sess.last_ip = ipAddr sess.save() _user = sess.user return _user except WebSession.DoesNotExist: logger.info('Got invalid session id "%s" for request %s', session_cookie.value, os.getenv('REQUEST_URI')) login_error_string = None if _form.getfirst('username') and _form.getfirst('password'): user = User.get(username=_form.getfirst('username')) if bcrypt.hashpw(_form.getfirst('password'), user.password) == user.password: # Login succeeded sess = WebSession.create(session_id=uuid.uuid4().hex, user=user, last_ip=ipAddr, last_seen=timeutil.getTime()) cookie['session'] = sess.session_id cookie['session']['expires'] = 86400 * 14 print cookie print '''\ Content-type: text/html Location: %s Redirecting...''' % request_url() # this is a good time to clean up old sessions WebSession.delete().where( WebSession.last_seen < timeutil.getTime() - timedelta(weeks=2)).execute() sys.exit() else: # Login failed; set an error string to that effect login_error_string = "Username/password did not match our records" if (doLogin == False): print """Status: 401 unauthorized\nContent-type: text/plain\n\nYou gotta be logged in for this to work""" sys.exit() print """Content-type: text/html <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="style.css"> <title>Login required</title> </head><body class="loginForm"> <div id="login">""" if login_error_string: print '<div class="error">%s</div>' % login_error_string else: print '<div class="explain">You must log in to continue.</div>' print '<form method="POST" action="%s"><ul>' % os.environ.get( 'REQUEST_URI') print '<li><label for="username">Username:</label>' print '<input type="text" name="username" value="%s"></li>' % ( _form.getfirst('username') or '') print """<li><label for="password">Password:</label> <input type="password" name="password"></li> </ul><input type="submit" value="Log in"></form> </div></body></html>""" sys.exit()
with model.transaction(): body = form.getfirst('Body') try: message = client.messages.create( body=body, from_=form.getfirst('From'), to=form.getfirst('To'), status_callback=config.configuration['root-url'] + '/sms.py/outgoing' ) except twilio.TwilioRestException as e: print "Status: 400 Bad Request\nContent-type: text/html\n\n%s" % str(e) sys.exit() now = timeutil.getTime() try: # It's possible that the callback fired before we got here... event = Event.get(Event.sid == message.sid) event.message_body = body event.last_update = now event.save() conversation = event.conversation conversation.last_update = now conversation.save() except Event.DoesNotExist: # ... but not likely peer = control.getPeer(form, user, whoValue=message.to) conversation = control.getConversation(form, inbox, peer) event = Event.create( sid=message.sid,
def getEvent(form, sidField, inbound, type): if inbound: whoField = 'From' inboxField = 'To' else: whoField = 'To' inboxField = 'From' logger.info('getEvent sid=%s inbound=%s who=%s inbox=%s', form.getfirst(sidField), inbound, form.getfirst(whoField), form.getfirst(inboxField)) whoValue=form.getfirst(whoField) try: event = Event.get(Event.sid == form.getfirst(sidField)) except Event.DoesNotExist: user = getUser(form) inbox = getInbox(form, user, inboxField) peer = getPeer(form, user, whoValue=whoValue) logger.info(' peer=%s %s', peer.phone_number, peer.display_name) now = timeutil.getTime() conversation = getConversation(form, inbox, peer) logger.info('getEvent conversation.peer=%s %s', conversation.peer.phone_number, conversation.peer.display_name) event = Event.create( sid=form.getfirst(sidField), inbound=inbound, inbox=inbox, conversation=conversation, time=now, last_update=now, type=type ) conversation.last_update = now conversation.unread = True conversation.save() peer.last_event = now peer.save() # there are several fields that could rightfully become 'status' and we want to guarantee precedence save = False for field in ['CallStatus', 'DialCallStatus', 'MessageStatus']: if applyAttribs(event, form, { field : 'status' }): save = True if applyAttribs(event, form, { 'DialCallDuration': 'call_duration', 'Body': 'message_body', }): save = True if save: event.save() # Attach any voicemail if form.getfirst('RecordingSid'): try: attach = Attachment.get(Attachment.sid==form.getfirst('RecordingSid')) except Attachment.DoesNotExist: attach = Attachment.create(sid=form.getfirst('RecordingSid'), url='%s.mp3' % form.getfirst('RecordingUrl'), mime_type = 'audio/mpeg', event=event) save = False if form.getfirst('RecordingDuration'): attach.duration = int(form.getfirst('RecordingDuration')) save = True if applyAttribs(attach, form, { 'TranscriptionText' : 'transcription' }): save = True if save: attach.save() return event