def POST(self): # Initialize the SMART client (will raise excepton if the credentails are bad) smart_client = get_smart_client() # Load the message parameters me = SMTP_USER + "@" + SMTP_HOST # we always use the primary SMART Direct address you = web.input().recipient_email subject = web.input().subject message = web.input().message # Create the body of the message (plain-text and HTML version). text = message html = markdown(text) # Generate the PDF attachment content pdf_buffer = generate_pdf(html) # Initialize the attachment and general settings for the mailer attachments = [{"file_buffer": generate_pdf(html), "name": "patient.pdf", "mime": "application/pdf"}] settings = {"host": SMTP_HOST, "user": SMTP_USER, "password": SMTP_PASS} # Send the SMART Direct message send_message(me, you, subject, text, html, attachments, settings) # Clean up the string buffer pdf_buffer.close() # If needed, add the recipient to the app's preferences if web.input().recipient_add == "true": add_recipient(smart_client, you) # Respond with success message return json.dumps({"result": "ok"})
def POST(self): # Initialize the SMART client (will raise excepton if the credentails are bad) smart_client = get_smart_client() # Load the message parameters me = SMTP_USER + "@" + SMTP_HOST # we always use the primary SMART Direct address you = web.input().recipient_email subject = web.input().subject message = web.input().message # Create the body of the message (plain-text and HTML version). text = message html = markdown(text) # Generate the PDF attachment content pdf_buffer = generate_pdf (html) # Initialize the attachment and general settings for the mailer attachments = [{'file_buffer': generate_pdf(html), 'name': "patient.pdf", 'mime': "application/pdf"}] settings = {'host': SMTP_HOST, 'user': SMTP_USER, 'password': SMTP_PASS} # Send the SMART Direct message send_message (me, you, subject, text, html, attachments, settings) # Clean up the string buffer pdf_buffer.close() # If needed, add the recipient to the app's preferences if web.input().recipient_add == "true": add_recipient (smart_client, you) # Respond with success message return json.dumps({'result': 'ok'})
def POST(self): # First, try setting up a dummy SMART client to test the credentials # for securty reasons (will raise excepton if the credentails are bad) get_smart_client() # Load the message parameters me = SMTP_USER + "@" + SMTP_HOST # we always use the primary SMART Direct address you = web.input().recipient_email subject = web.input().subject message = web.input().message # Create the body of the message (plain-text and HTML version). text = message html = markdown(text) # Generate the PDF attachment content pdf_buffer = generate_pdf (html) # Initialize the attachment and general settings for the mailer attachments = [{'file_buffer': generate_pdf(html), 'name': "patient.pdf", 'mime': "application/pdf"}] settings = {'host': SMTP_HOST, 'user': SMTP_USER, 'password': SMTP_PASS} # Send the SMART Direct message send_message (me, you, subject, text, html, attachments, settings) # Clean up the string buffer pdf_buffer.close() # Respond with success message return json.dumps({'result': 'ok'})
def check_mail (): '''Processes all the new messages in the SMART Direct mailbox''' # Log into the mailbox M = poplib.POP3_SSL(SMTP_HOST) M.user(SMTP_USER) M.pass_(SMTP_PASS) # Obtain the count of the new messages numMessages = len(M.list()[1]) # Iterate over the new messages for i in range(numMessages): # Load the message into an e-mail object msg = M.retr(i+1) str = string.join(msg[1], "\n") mail = email.message_from_string(str) # Print some useful information print "From:", mail["From"] print "Subject:", mail["Subject"] print "Date:", mail["Date"] # Delete any Direct auto-response message if mail["Subject"].lower().startswith("processed:"): M.dele(i+1) print "Auto-response confirmation message... deleted" # Process any SMART Direct Apps message elif mail["Subject"].startswith(SMART_DIRECT_PREFIX): # The message is expected to be multipart assert mail.is_multipart(), "Non-multipart SMART Direct message detected" # Process the various message parts for part in mail.walk(): # Get the content type and disposition of the part c_type = part.get_content_type() c_disp = part.get('Content-Disposition') # Process an attachment part if c_disp != None: print "attachment: ", part.get_filename() # Process a patient RDF payload if part.get_filename() == "patient.xml": # Generate a new PID and write the attachment in a new # file named "p123456.xml" where 123456 is the new PID # (consider using the python tempfile library here # once the import script requirement to have the patientID # in the filename is relaxed) patientID = generate_pid() datafile = "p" + patientID + ".xml" patientRDF_str = part.get_payload(decode=True) fp = open(APP_PATH + "/temp/" + datafile, 'wb') fp.write(patientRDF_str) fp.close() # Manifest data should be loaded into a string elif part.get_filename() == "manifest.json": manifest = part.get_payload(decode=True) # Load any inline HTML or plain-text part into local variables elif c_type == 'text/plain' and c_disp == None: mytext = part.get_payload(decode=True) elif c_type == 'text/html' and c_disp == None: myhtml = part.get_payload(decode=True) # Skip everything else else: continue # Would be nice to improve the import script so that it could take # an arbitrary file and get the patientID as a separate parameter. # Then we won't need to encode the patientID in the filename. os.system(APP_PATH + "/import-patient " + APP_PATH + "/temp/" + datafile) pin = generate_pin() url = get_access_url (patientID, pin) sender,recipient = get_sender_recipient(manifest) mytext,myhtml = get_updated_messages(myhtml, url, manifest, pin) # Generate the subject of the final message from the original subject # by stripping out the prefix subject = mail["Subject"].replace(SMART_DIRECT_PREFIX, "") # Set the sender address to the primary Direct account sender = SMTP_USER + "@" + SMTP_HOST # Initialize a string buffer object with the patient RDF rdfbuffer = StringIO() rdfbuffer.write(patientRDF_str) # Set up the attachments and general settings for the mailer attachments = [{'file_buffer': rdfbuffer, 'name': 'patient.xml', 'mime': "text/xml"}] settings = {'host': SMTP_HOST, 'user': SMTP_USER, 'password': SMTP_PASS} # Send out the final direct message send_message (sender, recipient, subject, mytext, myhtml, attachments, settings) # Delete the processed direct message M.dele(i+1) # Clean up the string buffer rdfbuffer.close() print "Direct message sent to", recipient else: # We've got a boogie here! print "Message format not recognized... skipping" print "=" * 40 # Log out from the mail server M.quit()
def check_mail(): '''Processes all the new messages in the SMART Direct mailbox''' # Log into the mailbox M = poplib.POP3_SSL(SMTP_HOST) M.user(SMTP_USER) M.pass_(SMTP_PASS) # Obtain the count of the new messages numMessages = len(M.list()[1]) # Iterate over the new messages for i in range(numMessages): # Load the message into an e-mail object msg = M.retr(i + 1) str = string.join(msg[1], "\n") mail = email.message_from_string(str) # Print some useful information print "From:", mail["From"] print "Subject:", mail["Subject"] print "Date:", mail["Date"] # Delete any Direct auto-response message if mail["Subject"].lower().startswith("processed:"): M.dele(i + 1) print "Auto-response confirmation message... deleted" # Process any SMART Direct Apps message elif mail["Subject"].startswith(SMART_DIRECT_PREFIX): # The message is expected to be multipart assert mail.is_multipart( ), "Non-multipart SMART Direct message detected" # Process the various message parts for part in mail.walk(): # Get the content type and disposition of the part c_type = part.get_content_type() c_disp = part.get('Content-Disposition') # Process an attachment part if c_disp != None: print "attachment: ", part.get_filename() # Process a patient RDF payload if part.get_filename() == "patient.xml": # Generate a new PID and write the attachment in a new # file named "p123456.xml" where 123456 is the new PID # (consider using the python tempfile library here # once the import script requirement to have the patientID # in the filename is relaxed) patientID = generate_pid() datafile = "p" + patientID + ".xml" patientRDF_str = part.get_payload(decode=True) fp = open(APP_PATH + "/temp/" + datafile, 'wb') fp.write(patientRDF_str) fp.close() # Manifest data should be loaded into a string elif part.get_filename() == "manifest.json": manifest = part.get_payload(decode=True) # Load any inline HTML or plain-text part into local variables elif c_type == 'text/plain' and c_disp == None: mytext = part.get_payload(decode=True) elif c_type == 'text/html' and c_disp == None: myhtml = part.get_payload(decode=True) # Skip everything else else: continue # Would be nice to improve the import script so that it could take # an arbitrary file and get the patientID as a separate parameter. # Then we won't need to encode the patientID in the filename. os.system(APP_PATH + "/import-patient " + APP_PATH + "/temp/" + datafile) pin = generate_pin() url = get_access_url(patientID, pin) sender, recipient = get_sender_recipient(manifest) mytext, myhtml = get_updated_messages(myhtml, url, manifest, pin) # Generate the subject of the final message from the original subject # by stripping out the prefix subject = mail["Subject"].replace(SMART_DIRECT_PREFIX, "") # Set the sender address to the primary Direct account sender = SMTP_USER + "@" + SMTP_HOST # Initialize a string buffer object with the patient RDF rdfbuffer = StringIO() rdfbuffer.write(patientRDF_str) # Set up the attachments and general settings for the mailer attachments = [{ 'file_buffer': rdfbuffer, 'name': 'patient.xml', 'mime': "text/xml" }] settings = { 'host': SMTP_HOST, 'user': SMTP_USER, 'password': SMTP_PASS } # Send out the final direct message send_message(sender, recipient, subject, mytext, myhtml, attachments, settings) # Delete the processed direct message M.dele(i + 1) # Clean up the string buffer rdfbuffer.close() print "Direct message sent to", recipient else: # We've got a boogie here! print "Message format not recognized... skipping" print "=" * 40 # Log out from the mail server M.quit()
def POST(self): # Initialize the SMART client (will raise excepton if the credentails are bad) smart_client = get_smart_client() # Load the message parameters sender = web.input().sender_email recipient = web.input().recipient_email subject = SMART_DIRECT_PREFIX + web.input().subject message = web.input().message apps = string.split(web.input().apps, ",") apis = [] # Generate the end-point direct addresses for the first message hop me = SMTP_USER_ALT + "@" + SMTP_HOST_ALT you = SMTP_USER + "@" + SMTP_HOST # Load and parse the apps manifests JSON myapps = json.loads(get_apps().GET()) # Initialize the outbound manifest data object manifest = {"from": sender, "to": recipient, "apps": []} # Populate the manifest object with a subset of the manifest data # for the selected apps. Also build a list of the APIs needed by the # selected aps. for a in myapps: if (a['id'] in apps): if 'requires' in a.keys(): myapis = a['requires'].keys() for i in myapis: if (i not in apis and 'GET' in a['requires'][i]['methods']): apis.append(i) del (a['requires']) manifest["apps"].append({ 'id': a['id'], 'version': a['version'] }) # Load the manifest in a string buffer (in JSON format) manifesttxt = json.dumps(manifest, sort_keys=True, indent=4) manifestbuffer = StringIO() manifestbuffer.write(manifesttxt) # Build the patient RDF graph with the demographics rdfres = smart_client.get_demographics().graph # Augment the RDF graph with the needed data models (except demographics) for a in apis: call = get_call(a) if call != "get_demographics": method_to_call = getattr(smart_client, get_call(a)) rdfres += method_to_call().graph # Anonymize the RDF graph for export rdfres = anonymize_smart_rdf(rdfres) # Serialize the RDF graph in a string buffer rdftext = rdfres.serialize() rdfbuffer = StringIO() rdfbuffer.write(rdftext) # Initialize the attachments descriptor object attachments = [{ 'file_buffer': rdfbuffer, 'name': "patient.xml", 'mime': "text/xml" }, { 'file_buffer': manifestbuffer, 'name': "manifest.json", 'mime': "text/xml" }] # Initialize the mailer settings settings = { 'host': SMTP_HOST_ALT, 'user': SMTP_USER_ALT, 'password': SMTP_PASS_ALT } # Send the SMART Direct message send_message(me, you, subject, message, message, attachments, settings) # Clean up the string buffers manifestbuffer.close() rdfbuffer.close() # If needed, add the recipient to the app's preferences if web.input().recipient_add == "true": add_recipient(smart_client, recipient) # Respond with success message return json.dumps({'result': 'ok'})
def POST(self): # Initialize the SMART client (will raise excepton if the credentails are bad) smart_client = get_smart_client() # Load the message parameters sender = web.input().sender_email recipient = web.input().recipient_email subject = SMART_DIRECT_PREFIX + web.input().subject message = web.input().message apps = string.split(web.input().apps, ",") apis = [] # Generate the end-point direct addresses for the first message hop me = SMTP_USER_ALT + "@" + SMTP_HOST_ALT you = SMTP_USER + "@" + SMTP_HOST # Load and parse the apps manifests JSON myapps = json.loads(get_apps().GET()) # Initialize the outbound manifest data object manifest = {"from": sender, "to": recipient, "apps": []} # Populate the manifest object with a subset of the manifest data # for the selected apps. Also build a list of the APIs needed by the # selected aps. for a in myapps: if a["id"] in apps: if "requires" in a.keys(): myapis = a["requires"].keys() for i in myapis: if i not in apis and "GET" in a["requires"][i]["methods"]: apis.append(i) del (a["requires"]) manifest["apps"].append({"id": a["id"], "version": a["version"]}) # Load the manifest in a string buffer (in JSON format) manifesttxt = json.dumps(manifest, sort_keys=True, indent=4) manifestbuffer = StringIO() manifestbuffer.write(manifesttxt) # Build the patient RDF graph with the demographics rdfres = smart_client.records_X_demographics_GET().graph # Augment the RDF graph with the needed data models (except demographics) for a in apis: call = get_call(a) if call != "records_X_demographics_GET": method_to_call = getattr(smart_client, get_call(a)) rdfres += method_to_call().graph # Anonymize the RDF graph for export rdfres = anonymize_smart_rdf(rdfres) # Serialize the RDF graph in a string buffer rdftext = rdfres.serialize() rdfbuffer = StringIO() rdfbuffer.write(rdftext) # Initialize the attachments descriptor object attachments = [ {"file_buffer": rdfbuffer, "name": "patient.xml", "mime": "text/xml"}, {"file_buffer": manifestbuffer, "name": "manifest.json", "mime": "text/xml"}, ] # Initialize the mailer settings settings = {"host": SMTP_HOST_ALT, "user": SMTP_USER_ALT, "password": SMTP_PASS_ALT} # Send the SMART Direct message send_message(me, you, subject, message, message, attachments, settings) # Clean up the string buffers manifestbuffer.close() rdfbuffer.close() # If needed, add the recipient to the app's preferences if web.input().recipient_add == "true": add_recipient(smart_client, recipient) # Respond with success message return json.dumps({"result": "ok"})
def POST(self): # First, try setting up a dummy SMART client to test the credentials # for securty reasons (will raise excepton if the credentails are bad) get_smart_client() # Initialize the SMART client smart_client = get_smart_client() # Load the message parameters sender = web.input().sender_email recipient = web.input().recipient_email subject = SMART_DIRECT_PREFIX + web.input().subject message = web.input().message apps = string.split (web.input().apps, ",") apis = [] # Generate the end-point direct addresses for the first message hop me = SMTP_USER_ALT + "@" + SMTP_HOST_ALT you = SMTP_USER + "@" + SMTP_HOST # Load the app manifests JSON FILE = open(APP_PATH + '/data/apps.json', 'r') APPS_JSON = FILE.read() FILE.close() # Parse the apps manifests JSON myapps = json.loads(APPS_JSON) # Initialize the outbound manifest data object manifest= {"from": sender, "to": recipient, "apps": []} # Populate the manifest object with a subset of the manifest data # for the selected apps. Also build a list of the APIs needed by the # selected aps. for a in myapps: if (a['id'] in apps): myapis = a['apis'] for i in myapis: if (i not in apis): apis.append(i) del(a['apis']) del(a['name']) del(a['icon']) manifest["apps"].append(a) # Load the manifest in a string buffer (in JSON format) manifesttxt = json.dumps(manifest) manifestbuffer = StringIO() manifestbuffer.write(manifesttxt) # Build the patient RDF graph rdfres = smart_client.records_X_demographics_GET() if ("problems" in apis): rdfres += smart_client.records_X_problems_GET() if ("medications" in apis): rdfres += smart_client.records_X_medications_GET() if ("vital_signs" in apis): rdfres += smart_client.records_X_vital_signs_GET() # Anonymize the RDF graph for export rdfres = anonymize_smart_rdf (rdfres) # Serialize the RDF graph in a string buffer rdftext = rdfres.serialize() rdfbuffer = StringIO() rdfbuffer.write(rdftext) # Initialize the attachments descriptor object attachments = [ {'file_buffer': rdfbuffer, 'name': "patient.xml", 'mime': "text/xml"}, {'file_buffer': manifestbuffer, 'name': "manifest.json", 'mime': "text/xml"} ] # Initialize the mailer settings settings = {'host': SMTP_HOST_ALT, 'user': SMTP_USER_ALT, 'password': SMTP_PASS_ALT} # Send the SMART Direct message send_message (me, you, subject, message, message, attachments, settings) # Clean up the string buffers manifestbuffer.close() rdfbuffer.close() # Respond with success message return json.dumps({'result': 'ok'})
def POST(self): # First, try setting up a dummy SMART client to test the credentials # for securty reasons (will raise excepton if the credentails are bad) get_smart_client() # Initialize the SMART client smart_client = get_smart_client() # Load the message parameters sender = web.input().sender_email recipient = web.input().recipient_email subject = SMART_DIRECT_PREFIX + web.input().subject message = web.input().message apps = string.split(web.input().apps, ",") apis = [] # Generate the end-point direct addresses for the first message hop me = SMTP_USER_ALT + "@" + SMTP_HOST_ALT you = SMTP_USER + "@" + SMTP_HOST # Load the app manifests JSON FILE = open(APP_PATH + '/data/apps.json', 'r') APPS_JSON = FILE.read() FILE.close() # Parse the apps manifests JSON myapps = json.loads(APPS_JSON) # Initialize the outbound manifest data object manifest = {"from": sender, "to": recipient, "apps": []} # Populate the manifest object with a subset of the manifest data # for the selected apps. Also build a list of the APIs needed by the # selected aps. for a in myapps: if (a['id'] in apps): myapis = a['apis'] for i in myapis: if (i not in apis): apis.append(i) del (a['apis']) del (a['name']) del (a['icon']) manifest["apps"].append(a) # Load the manifest in a string buffer (in JSON format) manifesttxt = json.dumps(manifest) manifestbuffer = StringIO() manifestbuffer.write(manifesttxt) # Build the patient RDF graph rdfres = smart_client.records_X_demographics_GET() if ("problems" in apis): rdfres += smart_client.records_X_problems_GET() if ("medications" in apis): rdfres += smart_client.records_X_medications_GET() if ("vital_signs" in apis): rdfres += smart_client.records_X_vital_signs_GET() # Anonymize the RDF graph for export rdfres = anonymize_smart_rdf(rdfres) # Serialize the RDF graph in a string buffer rdftext = rdfres.serialize() rdfbuffer = StringIO() rdfbuffer.write(rdftext) # Initialize the attachments descriptor object attachments = [{ 'file_buffer': rdfbuffer, 'name': "patient.xml", 'mime': "text/xml" }, { 'file_buffer': manifestbuffer, 'name': "manifest.json", 'mime': "text/xml" }] # Initialize the mailer settings settings = { 'host': SMTP_HOST_ALT, 'user': SMTP_USER_ALT, 'password': SMTP_PASS_ALT } # Send the SMART Direct message send_message(me, you, subject, message, message, attachments, settings) # Clean up the string buffers manifestbuffer.close() rdfbuffer.close() # Respond with success message return json.dumps({'result': 'ok'})