def test_bad_password(self): self.request.post('/login/', {'username': self.provider.username, 'password': '******'}) sender = authenticate(username=self.provider.username, password='******') msg = Message(sender=sender, sender_site=None, subject="pandas") recipient = User.objects.get(id=self.provider2.id) msg.urgent = False msg.message_type = 'NM' msg.save() body = "i am indeed a talking panda. how are you?" msg_body = msg.save_body(body) MessageRecipient(message=msg, user=recipient).save() self.request.logout() test = CalledTest() models.sendSMS_Twilio_newMessage = test msg.send(self.request, msg_body, []) self.assertTrue(test.was_called) response = self.request.post('/login/', {'username': self.provider2.username, 'password': '******'}) clean_msg_body = MessageBody.objects.get(message=msg) self.request.user = recipient store_user_key(self.request, response, 'wrongpassword') self.request.COOKIES = {'ss': response.cookies['ss'].value} self.assertRaises(KeyInvalidException, clean_msg_body.decrypt, self.request) self.request.logout()
def test_bad_password(self): self.request.post('/login/', { 'username': self.provider.username, 'password': '******' }) sender = authenticate(username=self.provider.username, password='******') msg = Message(sender=sender, sender_site=None, subject="pandas") recipient = User.objects.get(id=self.provider2.id) msg.urgent = False msg.message_type = 'NM' msg.save() body = "i am indeed a talking panda. how are you?" msg_body = msg.save_body(body) MessageRecipient(message=msg, user=recipient).save() self.request.logout() test = CalledTest() models.sendSMS_Twilio_newMessage = test msg.send(self.request, msg_body, []) self.assertTrue(test.was_called) response = self.request.post('/login/', { 'username': self.provider2.username, 'password': '******' }) clean_msg_body = MessageBody.objects.get(message=msg) self.request.user = recipient store_user_key(self.request, response, 'wrongpassword') self.request.COOKIES = {'ss': response.cookies['ss'].value} self.assertRaises(KeyInvalidException, clean_msg_body.decrypt, self.request) self.request.logout()
def test_system_message(self): self.request.post('/login/', { 'username': self.provider.username, 'password': '******' }) provider = authenticate(username=self.provider.username, password='******') msg = Message(sender=None, sender_site=None, subject="I'm in space!", message_type='ANS') msg.save() recipient = User.objects.get(id=self.provider2.id) MessageRecipient(user=recipient, message=msg).save() body = 'SPACE!' msg_body = msg.save_body(body) path = ''.join([settings.MEDIA_ROOT, 'audio/fetch_error.wav']) wav_data = open(path, "r").read() attachment = encrypt_object(MessageAttachment, { 'message': msg, 'size': len(wav_data), 'encrypted': True, }) self.request.user = provider attachment.encrypt_url(self.request, ''.join(['file://', attachment.uuid])) attachment.encrypt_filename(self.request, "i'm in space") attachment.encrypt_file(self.request, [wav_data]) attachment.suffix = 'wav' attachment.content_type = 'audio/wav' attachment.save() test = CalledTest() models.sendSMS_Twilio_newMessage = test msg.send(self.request, msg_body, [attachment]) self.assertTrue(test.was_called) self.request.logout() response = self.request.post('/login/', { 'username': self.provider2.username, 'password': '******' }) recipient = authenticate(username=self.provider2.username, password='******') self.request.user = recipient self.request.COOKIES = {'ss': response.cookies['ss'].value} clean_attachment = MessageAttachment.objects.get(pk=attachment.pk) clean_attachment.get_file(self.request, response) self.assertEqual(response.content, wav_data) self.assertTrue(clean_attachment.decrypt_url(self.request)) self.assertRaises(Exception, clean_attachment.delete, self.request) self.request.logout()
def updateRefer(request, form, refer_id): refer = MessageRefer.objects.get(uuid=refer_id) if refer.status != 'NO': return False refer.status = form.cleaned_data["status"] refer.refuse_reason = form.cleaned_data["refuse_reason"] refer.save() message = Message.objects.filter(id=refer.message_id).extra(select= {'title':'SELECT title FROM MHLUsers_mhluser \ WHERE MHLUsers_mhluser.user_ptr_id = Messaging_message.sender_id'}) sender = message[0].sender recipient_name=get_fullname_bystr(sender.last_name,sender.first_name,message[0].title) get_object_or_404(MessageBody, message=message) recipient_email_list = [] recipient_list = [] recipient_email_list.append(sender.email) duser_ids = list(Physician.objects.all().values_list("user__user__pk", flat=True)) recipients= message[0].recipients.all().extra(select={'title':'SELECT title FROM MHLUsers_mhluser \ WHERE MHLUsers_mhluser.user_ptr_id = Messaging_message_recipients.user_id'}) for recipient in recipients: recipient_list.append(get_fullname_bystr(str(recipient.last_name),str(recipient.first_name),recipient.title)) emailContext = dict() emailContext['refuse_reason'] = '' emailContext['sender_name'] = ', '.join(recipient_list) emailContext['recipient_name'] = recipient_name emailContext['patient_name'] = ' '.join([refer.first_name, refer.middle_name, refer.last_name]) emailContext['operator_name'] = ' '.join([request.user.first_name, request.user.last_name]) emailContext['status'] = dict(REFER_STATUS)[refer.status].lower() if refer.status == "RE": if refer.refuse_reason: emailContext['refuse_reason'] = _(u'\nDeclined Reason: %s') % refer.refuse_reason else: emailContext['refuse_reason'] = _(u'\nDeclined Reason: N/A') msgBody = render_to_string('DoctorCom/Messaging/ReferStaUpdEmail.html', emailContext) msg_subject = _('DoctorCom: Refer [%s]') % dict(REFER_STATUS)[refer.status] msg = Message(sender=None, sender_site=None, subject=msg_subject, message_type='NM') msg.save() MessageRecipient(user=sender, message=msg).save() msg_body = msg.save_body(msgBody) msg.send(request, msg_body) email_msgBody = msgBody + _("\n Best, \n DoctorCom") send_mail(msg_subject, email_msgBody, settings.SERVER_EMAIL, recipient_email_list, fail_silently=False) return True
def send_refer_forward(refer, request, data, mgrs=None, forward_to_manager=True): pdf_data = refer.decrypt_file(request) from MHLogin.DoctorCom.Messaging.views import getFormatToAndCc recipients, ccs = getFormatToAndCc(data['user_to_recipients'], data['user_cc_recipients']) if pdf_data and ((mgrs and forward_to_manager) or recipients): msg = Message(sender=request.user, subject=u'Refer Forwarding', thread_uuid=uuid.uuid4().hex) msg.save() refer_msg_body = _("%s has forwarded you a referral, please see details in " "attachment.\n\nBest,\nDoctorCom\n") % \ ' '.join([request.user.first_name, request.user.last_name]) msg_body = msg.save_body(refer_msg_body) user_ids_sent = [] if mgrs and forward_to_manager: for recipient in mgrs: user_ids_sent.append(int(recipient.user.user.id)) for recipient in recipients: user_ids_sent.append(recipient) user_ids_sent = list(set(user_ids_sent)) if not user_ids_sent: return for recipient in user_ids_sent: MessageRecipient(message=msg, user_id=recipient).save() attachment = encrypt_object( MessageAttachment, { 'message': msg, 'size': len(pdf_data), 'encrypted': True, }, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) refer_forwarding_name = _('Refer Forwarding') + '.pdf' attachment.encrypt_url(request, ''.join(['file://', attachment.uuid])) attachment.encrypt_filename(request, refer_forwarding_name) attachment.encrypt_file(request, [pdf_data]) attachment.suffix = 'pdf' (attachment.content_type, attachment.encoding) = \ mimetypes.guess_type(refer_forwarding_name) attachment.save() msg.send(request, msg_body, [attachment])
def send_refer_forward(refer, request, data, mgrs=None, forward_to_manager=True): pdf_data = refer.decrypt_file(request) from MHLogin.DoctorCom.Messaging.views import getFormatToAndCc recipients, ccs = getFormatToAndCc(data['user_to_recipients'], data['user_cc_recipients']) if pdf_data and ((mgrs and forward_to_manager) or recipients): msg = Message( sender=request.user, subject=u'Refer Forwarding', thread_uuid=uuid.uuid4().hex ) msg.save() refer_msg_body = _("%s has forwarded you a referral, please see details in " "attachment.\n\nBest,\nDoctorCom\n") % \ ' '.join([request.user.first_name, request.user.last_name]) msg_body = msg.save_body(refer_msg_body) user_ids_sent = [] if mgrs and forward_to_manager: for recipient in mgrs: user_ids_sent.append(int(recipient.user.user.id)) for recipient in recipients: user_ids_sent.append(recipient) user_ids_sent = list(set(user_ids_sent)) if not user_ids_sent: return for recipient in user_ids_sent: MessageRecipient(message=msg, user_id=recipient).save() attachment = encrypt_object( MessageAttachment, { 'message': msg, 'size': len(pdf_data), 'encrypted': True, }, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) refer_forwarding_name = _('Refer Forwarding') + '.pdf' attachment.encrypt_url(request, ''.join(['file://', attachment.uuid])) attachment.encrypt_filename(request, refer_forwarding_name) attachment.encrypt_file(request, [pdf_data]) attachment.suffix = 'pdf' (attachment.content_type, attachment.encoding) = \ mimetypes.guess_type(refer_forwarding_name) attachment.save() msg.send(request, msg_body, [attachment])
def test_normal_message(self): self.request.post('/login/', { 'username': self.provider.username, 'password': '******' }) sender = authenticate(username=self.provider.username, password='******') msg = Message(sender=sender, sender_site=None, subject="pandas") recipient = User.objects.get(id=self.provider2.id) msg.urgent = False msg.message_type = 'NM' self.assertRaises(Exception, msg.save_body, '') msg.save() body = "i am indeed a talking panda. how are you?" msg_body = msg.save_body(body) MessageRecipient(message=msg, user=recipient).save() test = CalledTest() models.sendSMS_Twilio_newMessage = test msg.send(self.request, msg_body, []) self.assertTrue(test.was_called) self.assertTrue( Message.objects.filter(sender=sender, subject="pandas").exists()) self.assertTrue( MessageRecipient.objects.filter(message=msg, user=recipient).exists()) msg_body.delete() clean_msg_body = MessageBody.objects.get(pk=msg_body.pk) self.request.logout() self.assertEqual(msg_body.decrypt(self.request), body) response = self.request.post('/login/', { 'username': self.provider2.username, 'password': '******' }) self.request.user = authenticate(username=self.provider2.username, password='******') self.request.COOKIES = {'ss': response.cookies['ss'].value} try: self.assertEqual(clean_msg_body.decrypt(self.request), body) except KeyInvalidException: raise self.failureException("message body decryption failed") self.assertRaises(Exception, msg.save) self.assertRaises(Exception, msg.delete, self.request) self.assertRaises(Exception, msg.send, self.request, msg_body, []) self.request.logout()
def test_system_message(self): self.request.post('/login/', {'username': self.provider.username, 'password': '******'}) provider = authenticate(username=self.provider.username, password='******') msg = Message(sender=None, sender_site=None, subject="I'm in space!", message_type='ANS') msg.save() recipient = User.objects.get(id=self.provider2.id) MessageRecipient(user=recipient, message=msg).save() body = 'SPACE!' msg_body = msg.save_body(body) path = ''.join([settings.MEDIA_ROOT, 'audio/fetch_error.wav']) wav_data = open(path, "r").read() attachment = encrypt_object( MessageAttachment, { 'message': msg, 'size': len(wav_data), 'encrypted': True, }) self.request.user = provider attachment.encrypt_url(self.request, ''.join(['file://', attachment.uuid])) attachment.encrypt_filename(self.request, "i'm in space") attachment.encrypt_file(self.request, [wav_data]) attachment.suffix = 'wav' attachment.content_type = 'audio/wav' attachment.save() test = CalledTest() models.sendSMS_Twilio_newMessage = test msg.send(self.request, msg_body, [attachment]) self.assertTrue(test.was_called) self.request.logout() response = self.request.post('/login/', {'username': self.provider2.username, 'password': '******'}) recipient = authenticate(username=self.provider2.username, password='******') self.request.user = recipient self.request.COOKIES = {'ss': response.cookies['ss'].value} clean_attachment = MessageAttachment.objects.get(pk=attachment.pk) clean_attachment.get_file(self.request, response) self.assertEqual(response.content, wav_data) self.assertTrue(clean_attachment.decrypt_url(self.request)) self.assertRaises(Exception, clean_attachment.delete, self.request) self.request.logout()
def message_managers(request, practice, subject, body, **kwargs): """ Creates and sends an email to all practice managers with the given subject and body, from the optional argument sender. Note that the body will always be rendered with kwargs as the render context. Additionally, the following context variables are defined: - manager: The MHLUser of the manager being emailed. - managers: The list of MHLUsers of all managers :param practice: A PracticeLocation object or pk. :param subject: The subject the email should be sent with. :param body: The body of the email. This should be a string containing optional template markup. See the docstring for details of the render context. :returns: None :raises: All exceptions from django.core.mail are passed. """ template = Template(body) context = Context(kwargs) officemanagers = Office_Manager.objects.filter( practice=practice).values_list('user', flat=True) officestaff = OfficeStaff.objects.filter( pk__in=officemanagers).values_list('user', flat=True) managers = list(User.objects.filter(pk__in=officestaff)) #raise Exception(repr(managers)) context['managers'] = managers #emails = [] # Used to store the emails #for manager in managers: # send_mail() msg = Message( sender=None, sender_site=None, subject=subject, ) msg.save() msg_body = msg.save_body(template.render(context)) for mgr in managers: MessageRecipient(message=msg, user=mgr).save() #msg.recipients.add(*managers), msg.send(request, msg_body)
def message_managers(request, practice, subject, body, **kwargs): """ Creates and sends an email to all practice managers with the given subject and body, from the optional argument sender. Note that the body will always be rendered with kwargs as the render context. Additionally, the following context variables are defined: - manager: The MHLUser of the manager being emailed. - managers: The list of MHLUsers of all managers :param practice: A PracticeLocation object or pk. :param subject: The subject the email should be sent with. :param body: The body of the email. This should be a string containing optional template markup. See the docstring for details of the render context. :returns: None :raises: All exceptions from django.core.mail are passed. """ template = Template(body) context = Context(kwargs) officemanagers = Office_Manager.objects.filter(practice=practice).values_list('user', flat=True) officestaff = OfficeStaff.objects.filter(pk__in=officemanagers).values_list('user', flat=True) managers = list(User.objects.filter(pk__in=officestaff)) #raise Exception(repr(managers)) context['managers'] = managers #emails = [] # Used to store the emails #for manager in managers: # send_mail() msg = Message( sender=None, sender_site=None, subject=subject, ) msg.save() msg_body = msg.save_body(template.render(context)) for mgr in managers: MessageRecipient(message=msg, user=mgr).save() #msg.recipients.add(*managers), msg.send(request, msg_body)
def test_self_message(self): self.request.post('/login/', {'username': self.provider.username, 'password': '******'}) sender = authenticate(username=self.provider.username, password='******') msg = Message(sender=sender, sender_site=None, subject="this was a triumph") recipient = sender msg.urgent = False msg.message_type = 'NM' msg.save() body = "i'm making a note here: huge success" msg_body = msg.save_body(body) MessageRecipient(message=msg, user=recipient).save() self.request.user = recipient test = CalledTest() models.sendSMS_Twilio_newMessage = test msg.send(self.request, msg_body, []) self.assertTrue(test.was_called) self.request.logout()
def handle_charge(invoice, charge, owner, **kwargs): # Notify the user via docotor com messaging, its account owner who gets message msg = Message(sender=None, sender_site=None, subject=_("Your Autopayment Processed")) recipient = MHLUser.objects.get(id=owner.id) msg.urgent = False msg.message_type = 'NM' msg.save() formatted_body = _("The payment in amount of $%s was charged to your credit card on file.") \ % (charge.amount) attachments = [] msg_body = msg.save_body(formatted_body) MessageRecipient(message=msg, user=recipient).save() # Send the message request = _FauxRequest() msg.send(request, msg_body, attachments)
def message_super_managers(request, practice, subject, body, **kwargs): """ Creates and sends a message t to all practice SUPER managers, if ANY exist with the given subject and body, from the optional argument sender. - manager: The MHLUser of the manager being emailed. - managers: The list of MHLUsers of all managers :param practice: A PracticeLocation object or pk. :param subject: The subject the email should be sent with. :param body: The body of the email. This should be a string containing optional template markup. See the docstring for details of the render context. :returns: None :raises: All exceptions from django.core.mail are passed. """ template = Template(body) context = Context(kwargs) officemanagers = Office_Manager.objects.filter(practice=practice, manager_role=2).\ values_list('user', flat=True) officestaff = OfficeStaff.objects.filter(pk__in=officemanagers).\ values_list('user', flat=True) managers = list(User.objects.filter(pk__in=officestaff)) context['managers'] = managers if (len(managers) > 0): msg = Message( sender=None, sender_site=None, subject=subject, ) msg.save() msg_body = msg.save_body(template.render(context)) for mgr in managers: MessageRecipient(message=msg, user=mgr).save() msg.send(request, msg_body)
def message_super_managers(request, practice, subject, body, **kwargs): """ Creates and sends a message t to all practice SUPER managers, if ANY exist with the given subject and body, from the optional argument sender. - manager: The MHLUser of the manager being emailed. - managers: The list of MHLUsers of all managers :param practice: A PracticeLocation object or pk. :param subject: The subject the email should be sent with. :param body: The body of the email. This should be a string containing optional template markup. See the docstring for details of the render context. :returns: None :raises: All exceptions from django.core.mail are passed. """ template = Template(body) context = Context(kwargs) officemanagers = Office_Manager.objects.filter(practice=practice, manager_role=2).\ values_list('user', flat=True) officestaff = OfficeStaff.objects.filter(pk__in=officemanagers).\ values_list('user', flat=True) managers = list(User.objects.filter(pk__in=officestaff)) context['managers'] = managers if (len(managers) > 0): msg = Message( sender=None, sender_site=None, subject=subject, ) msg.save() msg_body = msg.save_body(template.render(context)) for mgr in managers: MessageRecipient(message=msg, user=mgr).save() msg.send(request, msg_body)
def test_normal_message(self): self.request.post('/login/', {'username': self.provider.username, 'password': '******'}) sender = authenticate(username=self.provider.username, password='******') msg = Message(sender=sender, sender_site=None, subject="pandas") recipient = User.objects.get(id=self.provider2.id) msg.urgent = False msg.message_type = 'NM' self.assertRaises(Exception, msg.save_body, '') msg.save() body = "i am indeed a talking panda. how are you?" msg_body = msg.save_body(body) MessageRecipient(message=msg, user=recipient).save() test = CalledTest() models.sendSMS_Twilio_newMessage = test msg.send(self.request, msg_body, []) self.assertTrue(test.was_called) self.assertTrue(Message.objects.filter(sender=sender, subject="pandas").exists()) self.assertTrue(MessageRecipient.objects.filter(message=msg, user=recipient).exists()) msg_body.delete() clean_msg_body = MessageBody.objects.get(pk=msg_body.pk) self.request.logout() self.assertEqual(msg_body.decrypt(self.request), body) response = self.request.post('/login/', {'username': self.provider2.username, 'password': '******'}) self.request.user = authenticate(username=self.provider2.username, password='******') self.request.COOKIES = {'ss': response.cookies['ss'].value} try: self.assertEqual(clean_msg_body.decrypt(self.request), body) except KeyInvalidException: raise self.failureException("message body decryption failed") self.assertRaises(Exception, msg.save) self.assertRaises(Exception, msg.delete, self.request) self.assertRaises(Exception, msg.send, self.request, msg_body, []) self.request.logout()
def test_self_message(self): self.request.post('/login/', { 'username': self.provider.username, 'password': '******' }) sender = authenticate(username=self.provider.username, password='******') msg = Message(sender=sender, sender_site=None, subject="this was a triumph") recipient = sender msg.urgent = False msg.message_type = 'NM' msg.save() body = "i'm making a note here: huge success" msg_body = msg.save_body(body) MessageRecipient(message=msg, user=recipient).save() self.request.user = recipient test = CalledTest() models.sendSMS_Twilio_newMessage = test msg.send(self.request, msg_body, []) self.assertTrue(test.was_called) self.request.logout()
def _convertVoicemails(output=sys.stderr): from models import VMMessage from django.db.models import Model vms = VMMessage.objects.all() for vm in vms: try: oldconfig = VMBox_Config.objects.get(owner_id=vm.owner_id) config = VMBox_Config.objects.get(owner_id=vm.owner_id) #url = vm.recording msg = Message(sender=None, sender_site=None, subject="Voice mail") msg.urgent = False msg.message_type = 'VM' msg.callback_number = vm.callbacknumber msg.read_flag = vm.read_flag msg.delete_flag = vm.deleted msg.save() MessageRecipient(message=msg, user=vm.owner).save() request = _FauxRequest() request.session['ivr_makeRecording_recording'] = vm.recording request.session[ 'ivr_makeRecording_callbacknumber'] = vm.callbacknumber attachment = save_voice_attachment(request, msg) msg_body = msg.save_body("Message from %s." % msg.callback_number) config.notification_page = False config.notification_sms = False config.save() msg.send(request, msg_body, [attachment]) msg.send_timestamp = time.mktime(vm.timestamp.timetuple()) Model.save(msg) oldconfig.save() except Exception as e: err_msg = "Warning no VMBoxConfig found for: %s, Exception: %s\n" \ % (repr(vm.owner), str(e)) output.write(err_msg) logger.warning(err_msg)
def message_edit_multi(request, message_id=None): context = get_context(request) context['MAX_UPLOAD_SIZE'] = settings.MAX_UPLOAD_SIZE context['ioerror'] = '' if(request.method == 'GET'): user_recipients = request.GET['user_recipients'] else: user_recipients = request.POST['user_recipients'] if not user_recipients: return HttpResponseRedirect('/') recipient_ids = [] for item in user_recipients.split(','): recipient_ids.append(int(item)) form_initial_data = {'recipients': None, 'user_recipients': user_recipients} context['user_recipient_name'] = '; '.join([' '.join([user.first_name, user.last_name]) for user in MHLUser.objects.filter(pk__in=recipient_ids)]) context['recipientsform'] = MessageOptionsForm(initial={'user_recipients': user_recipients}) if (request.method == 'POST'): form = MessageForm(request.POST, request.FILES) if (form.is_valid()): logger.debug('Form is valid') rec_count = len(recipient_ids) for recipient in recipient_ids: # Build the message and body rec_count -= 1 msg = Message( sender=request.user, sender_site=None, subject=form.cleaned_data['subject'], ) msg.save() MessageRecipient(message=msg, user_id=recipient).save() msg_body = msg.save_body(form.cleaned_data['body']) attachments = save_attachments(request, context, msg, form, rec_count == 0) msg.send(request, msg_body, attachments) return HttpResponseRedirect('/') else: logger.debug('Form is invalid') file_saved_names = request.POST.getlist('file_saved_name') file_display_names = request.POST.getlist('file_display_name') file_charsets = request.POST.getlist('file_charset') file_sizes = request.POST.getlist('file_size') file_len = len(file_saved_names) file_list = [ { 'file_saved_name':file_saved_names[i], 'file_display_name':file_display_names[i], 'file_charset':file_charsets[i], 'file_size':file_sizes[i], } for i in range(file_len) ] context['file_list'] = file_list context['form'] = form if (not message_id and request.method == 'GET'): # clean temp files FileHelper.cleanTempFile() context['form'] = MessageForm(initial=form_initial_data) elif(message_id): # Grab the message in question msg = Message.objects.get(uuid=message_id) # Check to ensure that the user has rights to mess with this message if (request.user != msg.owner): errlib.err403() return render_to_response('DoctorCom/Messaging/MessageMultiEditForm.html', context)
def save_refer(request, data, recipient_provider, context, file_list=None): sender = None if ('Provider' in request.session['MHL_Users']): sender = request.session['MHL_Users']['Provider'] elif ('OfficeStaff' in request.session['MHL_Users']): sender = request.session['MHL_Users']['OfficeStaff'] if sender is None: return err403(request) form = MessageReferForm(data) if form.is_valid(): try: cur_prac = sender.current_practice user_recipients = data['user_recipients'] context['user_recipients'] = user_recipients sel_practice = int(data['selected_practice']) mhluser = request.session['MHL_Users']['MHLUser'] msg = Message(sender=request.user, subject=_('Refer')) msg.save() msg_body = msg.save_body(data['reason_of_refer']) forward_to_manager = True mgrs = list( Office_Manager.active_objects.filter( practice__pk=sel_practice)) if REFER_FORWARD_CHOICES_ONLY_MANAGER == recipient_provider.user.refer_forward \ and len(mgrs) > 0: forward_to_manager = False for recipient in mgrs: MessageRecipient(message=msg, user_id=recipient.user.user.id).save() else: MessageRecipient(message=msg, user_id=user_recipients).save() refer = form.save(commit=False) form.cleaned_data.update({ 'message': msg, 'status': 'NO', 'alternative_phone_number': '' }) refer = encrypt_object( MessageRefer, form.cleaned_data, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) if file_list is None: file_list = get_file_list(request) attachments = generateAttachement(request, context, msg, file_list) msg.send(request, msg_body, attachment_objs=attachments, refer_objs=[refer]) refer.refer_pdf = refer.uuid if cur_prac: refer.practice = cur_prac refer.save() data['today'] = datetime.date.today() context['refer_form'] = data try: rec = MHLUser.objects.get(pk=data['user_recipients']) context['user_recipient_name'] = get_fullname(rec) except: pass if cur_prac: context['current_practice_photo'] = ImageHelper.get_image_by_type(\ cur_prac.practice_photo, size="Middle", type='Practice') context['current_practice'] = cur_prac else: context['current_practice_photo'] = "" context['current_practice'] = "" context['referring_physician_name'] = get_fullname(mhluser) context['physician_phone_number'] = '' if mhluser and mhluser.mobile_phone: context['physician_phone_number'] = mhluser.mobile_phone generate_pdf(refer, request, context) send_refer_forward(refer, request, data, mgrs=mgrs, forward_to_manager=forward_to_manager) request.session[REFER_CACHE_SESSION_KEY] = None request.session[PREVENT_REPEAT_COMMIT_TOKEN] = None except KeyInvalidException: context["err_message"] = _( "Sorry. Security Key Error. Please contact " "system administrator.") return render_to_response('DoctorCom/Messaging/refer_success.html', context)
def admin_message_edit(request, userID): """ Handles message composition, editing, and drafts. :param request: The HTTP request :type request: django.core.handlers.wsgi.WSGIRequest :param userID: user's ID :type userID: int :returns: django.http.HttpResponse -- The webpage """ context = get_context(request) recipients = [] form_initial_data = {'recipient': userID} if (request.method == 'POST'): form = AdminMessageForm(request.POST, request.FILES) if (form.is_valid()): recipients = [form.cleaned_data['recipient']] for recipient in recipients: try: recipient = MHLUser.objects.get(pk=recipient) except MHLUser.DoesNotExist: raise InvalidRecipientException() if (not recipient.is_active): raise InvalidRecipientException() # Build the message and body msg = Message( subject=form.cleaned_data['subject'], message_type=form.cleaned_data['message_type'], callback_number=form.cleaned_data.get('callback_number', ''), ) msg.save() msg_body = msg.save_body(form.cleaned_data['body']) for recipient in recipients: MessageRecipient(message=msg, user_id=recipient).save() # Build the attachments attachments = [] if ('file' in request.FILES): upload = request.FILES['file'] attachment = encrypt_object( MessageAttachment, { 'message': msg, 'size': upload.size, 'encrypted': True, }, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) attachment.encrypt_url(request, ''.join(['file://', attachment.uuid])) attachment.encrypt_filename(request, upload.name) attachment.encrypt_file(request, upload.chunks()) suffix = suffix_re.search(upload.name) if (suffix): attachment.suffix = suffix.group(1)[:255] (attachment.content_type, attachment.encoding) = mimetypes.guess_type(upload.name) attachment.charset = upload.charset attachment.save() attachments.append(attachment) if (form.cleaned_data['url']): request.POST['CallSid'] = '' request.session[ 'ivr_makeRecording_recording'] = form.cleaned_data['url'] request.session['ivr_makeRecording_callbacknumber'] = \ form.cleaned_data['callback_number'] attachment = save_voice_attachment(request, msg) attachments.append(attachment) # Send the message msg.send(request, msg_body, attachments) return HttpResponseRedirect('/') else: context['recipient'] = MHLUser.objects.get(pk=userID) context['form'] = form else: context['recipient'] = MHLUser.objects.get(pk=userID) context['form'] = AdminMessageForm(initial=form_initial_data) return render_to_response('admin_message.html', context)
def save_message(request, subject, recipients, cc=None, message_type='VM', urgent=False): #now that we live about 1.5ms away from twilio instead of 100ms, #we sometimes end up requesting recordings before twilio has put them up. #so we sleep for 100ms as a workaround time.sleep(.1) cc = cc or [] msg = Message(sender=None, sender_site=None, subject=subject) msg.urgent = urgent msg.message_type = message_type msg.callback_number = request.session['ivr_makeRecording_callbacknumber'] msg.save() attachments = [] all_recipients = recipients[:] for recipient in all_recipients: MessageRecipient(message=msg, user=recipient).save() if isinstance(cc, collections.Iterable): for recipient in cc: MessageCC(message=msg, user=recipient).save() if ('ivr_makeRecording_recording' in request.session): #make a file out of twilio recording attachment = save_voice_attachment(request, msg) if (attachment): attachments.append(attachment) #'For ANS ONLY! ivr_caller_id_area_code' present means the call back number contained no area code, #and we saved twillio's caller id are code if (message_type == 'ANS' and 'ivr_caller_id_area_code' in request.session): caller_id_area_code = " Area Code From Caller Id :%s." % \ request.session['ivr_caller_id_area_code'] else: caller_id_area_code = "" if ('ivr_only_callbacknumber' in request.session and request.session['ivr_only_callbacknumber']): if ('ivr_no_pound' in request.session and request.session['ivr_no_pound'] == True): formatted_body = _( "Caller hung up from CONFIRMED %s before leaving message. " "No attachment." ) % request.session['ivr_makeRecording_callbacknumber'] msg.vmstatus = 'C' else: formatted_body = _( "Caller hung up from unconfirmed %s before leaving message. " "No attachment." ) % request.session['ivr_makeRecording_callbacknumber'] msg.vmstatus = 'U' else: msg.vmstatus = 'R' if (attachments): formatted_body = "Message from %s.%s" % ( request.session['ivr_makeRecording_callbacknumber'], caller_id_area_code) else: # There was a recording, but Twilio must have errored when we # tried to get it. formatted_body = _("Message from %(callbacknumber)s. Unfortunately, an error occurred " "downloading the recording from our telephone company. We will " "automatically retry the download and you will receive a new " "message once the recording is successfully retrieved. This call " "will be referenced using the following ID: %(CallSid)s.\nWe " "apologize for any inconvenience.\nDoctorCom Staff") % \ {'callbacknumber': request.session['ivr_makeRecording_callbacknumber'], 'CallSid': request.REQUEST['CallSid']} url = request.session['ivr_makeRecording_recording'] log = AnsSvcDLFailure( practice_id=request.session.get('practice_id', 0), error_message_uuid=msg.uuid, recording_url=url, callback_number=request. session['ivr_makeRecording_callbacknumber'], failure_type='DL', ) log.init_from_post_data(request.REQUEST) log.save() msg_body = msg.save_body(formatted_body) event = callEvent(callSID=request.POST['CallSid'], event='V_NMG') target = callEventTarget(event=event, target=msg) # Send the message msg.send(request, msg_body, attachments)
def handle_errors(invoice, charge, owner, **kwargs): if not charge: # The user does not have a CC# number attached and charge never went through # logging.error(" %s does not have credit card entered", owner) # Notify the user via docotor com messaging, its account owner who gets message msg = Message( sender=None, sender_site=None, subject="Action required: Please set up Doctor Com Billing") recipient = MHLUser.objects.get(id=owner.id) msg.urgent = False msg.message_type = 'NM' msg.save() formatted_body = "The last charge for your last invoice in the amount of $%s was " \ "rejected due to the missing billing information of file. Please update your " \ "billing information. Contact [email protected], if you have any additional " \ "questions." % (invoice.accounttransaction.amount) attachments = [] msg_body = msg.save_body(formatted_body) MessageRecipient(message=msg, user=recipient).save() # Send the message request = _FauxRequest() msg.send(request, msg_body, attachments) # email support email_body = "Account number %s failed autopayment due to account owner not " \ "having a payment instrument on file." % (invoice.accounttransaction.account.id) email_msg = EmailMessage("Problem with payment", email_body, settings.DEFAULT_FROM_EMAIL, settings.SUPPORT_RECIPIENTS) email_msg.send() else: # logging.error(" %s error charging with message. %s", (owner, charge.message)) # Notify the user via docotor com messaging, its account owner who gets message msg = Message(sender=None, sender_site=None, subject="Action required: " "Your last auto payment was rejected") recipient = MHLUser.objects.get(id=owner.id) msg.urgent = False msg.message_type = 'NM' msg.save() formatted_body = _( "The last charge for your last invoice in the amount of " "$%(amount)s was rejected with the following error: %(message)s Please update " "your billing information. Contact [email protected] if you have any additional " "questions.") % { 'amount': charge.amount, 'message': charge.message } attachments = [] msg_body = msg.save_body(formatted_body) MessageRecipient(message=msg, user=recipient).save() # Send the message request = _FauxRequest() msg.send(request, msg_body, attachments) # email support email_body = "Account number %(account_id)s failed autopayment due to the " \ "following error %(message)s" % {'account_id': invoice.accounttransaction.account.id, 'message': charge.message} email_msg = EmailMessage("Problem with payment", email_body, settings.DEFAULT_FROM_EMAIL, settings.SUPPORT_RECIPIENTS) email_msg.send()
def removePractice(request): if (request.method == 'POST'): form = PractIdAssociationForm(request.POST) else: form = PractIdAssociationForm(request.GET) if (not form.is_valid()): return HttpResponse(json.dumps(['err', 'A server error has occurred.']), mimetype='application/json') pract_id = form.cleaned_data['pract_id'] current_date = datetime.datetime.now() two_weeks_date = current_date + datetime.timedelta(days=15) user = request.user provider = request.session['MHL_Users']['Provider'] practice = PracticeLocation.objects.get(pk=pract_id) #remove from call group for this practice #if schedule exists in next two weeks massage managers, so they can cover gaps if practice.call_group: call_group = practice.call_group events_set = EventEntry.objects.filter(callGroup=call_group, oncallPerson=user, eventStatus=1, endDate__range=(current_date, two_weeks_date)) else: call_group = practice.call_groups.all() events_set = EventEntry.objects.filter(callGroup__in=call_group, oncallPerson=user, eventStatus=1, endDate__range=(current_date, two_weeks_date)) if (events_set.count() > 0): subject = _('DoctorCom: Gaps in On Call Schedule') body = """Dear Manager, %(user)s has left %(practice_name)s. %(user)s was removed from the on-call schedule, creating gaps in coverage. Please update your on-call schedule to fill these gaps. Best, DoctorCom Staff""" % {'user': provider.user, 'practice_name': practice.practice_name} #get a list of all office managers for this practice OfficeManagers = get_all_practice_managers(practice.id) #this will be message for office managers, next key makes sms not being sent out #with message-becasue office managers do not have to carry cell phones, dahsboard only request.session['answering_service'] = _('yes') #create message object msg = Message(sender=None, sender_site=None, subject=subject) msg.save() msg_body = msg.save_body(body) #create list of recepients - all office manager of the practice in question for OfficeStaff in OfficeManagers: MessageRecipient(message=msg, user=OfficeStaff.user).save() msg.send(request, msg_body) #send email as well to all managers mail_managers(practice, subject, body) #remove from schedule - mark as deleted if practice.call_group: CallGroupMember.objects.filter(call_group=call_group, member=user).delete() EventEntry.objects.filter(callGroup=call_group, oncallPerson=user, endDate__gte=current_date).update(eventStatus=0, lastupdate=current_date) else: CallGroupMember.objects.filter(call_group__in=call_group, member=user).delete() EventEntry.objects.filter(callGroup__in=call_group, oncallPerson=user, endDate__gte=current_date).update(eventStatus=0, lastupdate=current_date) #remove from provider if (provider.current_practice == practice): provider.current_practice = None provider.save() provider.practices.remove(practice) # send notification to related users thread.start_new_thread(notify_user_tab_changed, (provider.user.id,)) return HttpResponse(json.dumps(['err', 'No errors.']), mimetype='application/json')
def removePractice(request): if (request.method == 'POST'): form = PractIdAssociationForm(request.POST) else: form = PractIdAssociationForm(request.GET) if (not form.is_valid()): return HttpResponse(json.dumps(['err', 'A server error has occurred.']), mimetype='application/json') pract_id = form.cleaned_data['pract_id'] current_date = datetime.datetime.now() two_weeks_date = current_date + datetime.timedelta(days=15) user = request.user provider = request.session['MHL_Users']['Provider'] practice = PracticeLocation.objects.get(pk=pract_id) #remove from call group for this practice #if schedule exists in next two weeks massage managers, so they can cover gaps if practice.call_group: call_group = practice.call_group events_set = EventEntry.objects.filter(callGroup=call_group, oncallPerson=user, eventStatus=1, endDate__range=(current_date, two_weeks_date)) else: call_group = practice.call_groups.all() events_set = EventEntry.objects.filter(callGroup__in=call_group, oncallPerson=user, eventStatus=1, endDate__range=(current_date, two_weeks_date)) if (events_set.count() > 0): subject = _('DoctorCom: Gaps in On Call Schedule') body = """Dear Manager, %(user)s has left %(practice_name)s. %(user)s was removed from the on-call schedule, creating gaps in coverage. Please update your on-call schedule to fill these gaps. Best, DoctorCom Staff""" % { 'user': provider.user, 'practice_name': practice.practice_name } #get a list of all office managers for this practice OfficeManagers = get_all_practice_managers(practice.id) #this will be message for office managers, next key makes sms not being sent out #with message-becasue office managers do not have to carry cell phones, dahsboard only request.session['answering_service'] = _('yes') #create message object msg = Message(sender=None, sender_site=None, subject=subject) msg.save() msg_body = msg.save_body(body) #create list of recepients - all office manager of the practice in question for OfficeStaff in OfficeManagers: MessageRecipient(message=msg, user=OfficeStaff.user).save() msg.send(request, msg_body) #send email as well to all managers mail_managers(practice, subject, body) #remove from schedule - mark as deleted if practice.call_group: CallGroupMember.objects.filter(call_group=call_group, member=user).delete() EventEntry.objects.filter(callGroup=call_group, oncallPerson=user, endDate__gte=current_date).update( eventStatus=0, lastupdate=current_date) else: CallGroupMember.objects.filter(call_group__in=call_group, member=user).delete() EventEntry.objects.filter(callGroup__in=call_group, oncallPerson=user, endDate__gte=current_date).update( eventStatus=0, lastupdate=current_date) #remove from provider if (provider.current_practice == practice): provider.current_practice = None provider.save() provider.practices.remove(practice) # send notification to related users thread.start_new_thread(notify_user_tab_changed, (provider.user.id, )) return HttpResponse(json.dumps(['err', 'No errors.']), mimetype='application/json')
def removeProviderPractice(request): if (request.method == 'POST'): form = AssociationProviderIdForm(request.POST) else: form = AssociationProviderIdForm(request.GET) if (not form.is_valid()): return HttpResponse(json.dumps({'err': _('The data is error. Please ' 'refresh page again.')}), mimetype='application/json') prov_id = form.cleaned_data['prov_id'] #get managers' practice, and practices call group office_staff = request.session['MHL_Users']['OfficeStaff'] practice = office_staff.current_practice call_group = practice.call_group current_date = datetime.datetime.now() two_weeks_date = current_date + datetime.timedelta(days=15) #get provider to be removed provider = Provider.objects.get(user=prov_id) user = provider.user #if schedule exists in next two weeks massage managers, so they can cover gaps events_set = EventEntry.objects.filter(callGroup=call_group, oncallPerson=user, eventStatus=1, endDate__gt=current_date) #raise Exception('return set is', events_set, practice, user) if (events_set.count() > 0): subject = 'DoctorCom: Gaps in On Call Schedule' body = _("""Dear Manager, %(first_name)s %(last_name)s has removed %(user)s from %(practice_name)s. %(user)s was removed from the on-call schedule, creating gaps in coverage. Please update your on-call schedule to fill these gaps. Best, DoctorCom Staff""") \ % { 'first_name': request.user.first_name, 'last_name': request.user.last_name, 'user': provider.user, 'practice_name': practice.practice_name } #work around message_managers fails to message: #message_managers(request, practice, subject, # body, # practice_name=practice.practice_name, # manager_name=request.user.first_name, # manager_name_last=request.user.last_name, # provider_name=provider.user # ) #get a list of all office managers for this practice OfficeManagers = get_all_practice_managers(practice.id) #this will be message for office managers, next key makes sms not being sent out with #message-becasue office managers do not have to carry cell phones, dahsboard only request.session['answering_service'] = 'yes' #create message object msg = Message(sender=None, sender_site=None, subject=subject) msg.save() msg_body = msg.save_body(body) #create list of recepients - all office manager of the practice in question for OfficeStaff in OfficeManagers: MessageRecipient(message=msg, user=OfficeStaff.user).save() msg.send(request, msg_body) #send email as well to all managers mail_managers(practice, subject, body) today = datetime.date.today() #remove from schedule - mark as deleted EventEntry.objects.filter(callGroup=call_group, oncallPerson=user, startDate__gte=today).update(eventStatus=0, lastupdate=current_date) EventEntry.objects.filter(callGroup=call_group, oncallPerson=user, endDate__gte=today, startDate__lt=today).update(endDate=today, lastupdate=current_date) CallGroupMember.objects.filter(call_group=call_group, member=user).delete() #remove from provider if (provider.current_practice == practice): provider.current_practice = None provider.save() provider.practices.remove(practice) return HttpResponse(json.dumps('ok'), mimetype='application/json')
def createNewMessage(request, sender, sender_role_user, recipients, body, ccs=None, subject=None, uploads=None, file_data_list=None, temporary_files_data=None, exist_attchments=None, exist_refer=None, refer_data=None, thread_uuid=None, ss=None): """ createNewMessage :param request: request :param sender: message's sender as auth_user :param sender_role_user: message's sender as Provider/Office Staff/Broker :param recipients: user_id for message's recipients (integer or integer list) :param body: message's content body :param ccs: user_id for message's ccs (integer or integer list) :param subject: messages subject :param uploads: uploads is from request.FILES :param file_data_list: files information to be stored in message (file information dictionary list). The element in the file_data_list likes [{'name':'','file_chunks':'','size':,'suffix':'','charset':},...] :param temporary_files_data: (reserved) temporary files information, structure like Example:: { 'file_saved_name': file saved name list, 'file_display_name': file display name list, 'file_charset': file charset list, 'file_size': file size list, } :param exist_attchments: attachment information, structure like Example:: { 'message_id': message_id(used for validating the attachment), 'attachment_ids': attachment_id list } :param exist_refer: used for forwarding refer pdf Example:: { 'message_id': message_id(used for validating the refer), 'refer_id': refer_id } :param refer_data: refer information dictionary :param thread_uuid: is used for threading :param ss: sender's private key api_secret and ss are used for :returns: Message :raises: Http404, KeyInvalidException """ # compose message and message body sender_site = None if sender_role_user and hasattr(sender_role_user, 'current_site'): sender_site = sender_role_user.current_site thread_uuid = thread_uuid if thread_uuid else uuid.uuid4().hex msg = Message( sender=sender, sender_site=sender_site, subject=subject, thread_uuid=thread_uuid, ) msg.save() body = msg.save_body(body) # compose recipients and ccs if not isinstance(recipients, list): recipients = [recipients] if not isinstance(ccs, list): ccs = [ccs] recipients, ccs = getDistinctToAndCc(recipients, ccs) if recipients: for recipient in recipients: MessageRecipient(message=msg, user_id=recipient).save() if ccs: for cc in ccs: MessageCC(message=msg, user_id=cc).save() # compose upload attachment data attachments = saveAttachmentsUsingRequestFiles(request, msg, uploads) # compose attachment using data like [{'name':'','file_chunks':'','size':,'suffix':'','charset':},...] if file_data_list: for file_data in file_data_list: attachment = saveSingleAttachment(request, msg, file_data) attachments.append(attachment) # TODO: compose exist file it's in temporary directory #attachments.extend(saveAttachmentsUsingTemporaryFiles(request, msg, temporary_files_data)) # compose exist file using exist attachment attachments.extend( saveAttachmentsUsingExistAttachments(request, msg, exist_attchments, ss)) # compose exist refer pdf attachments.extend( saveAttachmentsForForwardReferPdf(request, msg, exist_refer, ss)) # compose refer data refers = createNewRefer(msg, request, sender, sender_role_user, refer_data=refer_data) msg.send(request, body, attachment_objs=attachments, refer_objs=refers) createReferFowarding(refers, request, sender, sender_role_user, refer_data=refer_data, ss=ss) return msg
def save_refer(request, data, recipient_provider, context, file_list=None): sender = None if ('Provider' in request.session['MHL_Users']): sender = request.session['MHL_Users']['Provider'] elif ('OfficeStaff' in request.session['MHL_Users']): sender = request.session['MHL_Users']['OfficeStaff'] if sender is None: return err403(request) form = MessageReferForm(data) if form.is_valid(): try: cur_prac = sender.current_practice user_recipients = data['user_recipients'] context['user_recipients'] = user_recipients sel_practice = int(data['selected_practice']) mhluser = request.session['MHL_Users']['MHLUser'] msg = Message(sender=request.user, subject=_('Refer')) msg.save() msg_body = msg.save_body(data['reason_of_refer']) forward_to_manager = True mgrs = list(Office_Manager.active_objects.filter(practice__pk=sel_practice)) if REFER_FORWARD_CHOICES_ONLY_MANAGER == recipient_provider.user.refer_forward \ and len(mgrs) > 0: forward_to_manager = False for recipient in mgrs: MessageRecipient(message=msg, user_id=recipient.user.user.id).save() else: MessageRecipient(message=msg, user_id=user_recipients).save() refer = form.save(commit=False) form.cleaned_data.update({ 'message': msg, 'status': 'NO', 'alternative_phone_number': '' }) refer = encrypt_object( MessageRefer, form.cleaned_data, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) if file_list is None: file_list = get_file_list(request) attachments = generateAttachement(request, context, msg, file_list) msg.send(request, msg_body, attachment_objs=attachments, refer_objs=[refer]) refer.refer_pdf = refer.uuid if cur_prac: refer.practice = cur_prac refer.save() data['today'] = datetime.date.today() context['refer_form'] = data try: rec = MHLUser.objects.get(pk=data['user_recipients']) context['user_recipient_name'] = get_fullname(rec) except: pass if cur_prac: context['current_practice_photo'] = ImageHelper.get_image_by_type(\ cur_prac.practice_photo, size="Middle", type='Practice') context['current_practice'] = cur_prac else: context['current_practice_photo'] = "" context['current_practice'] = "" context['referring_physician_name'] = get_fullname(mhluser) context['physician_phone_number'] = '' if mhluser and mhluser.mobile_phone: context['physician_phone_number'] = mhluser.mobile_phone generate_pdf(refer, request, context) send_refer_forward(refer, request, data, mgrs=mgrs, forward_to_manager=forward_to_manager) request.session[REFER_CACHE_SESSION_KEY] = None request.session[PREVENT_REPEAT_COMMIT_TOKEN] = None except KeyInvalidException: context["err_message"] = _("Sorry. Security Key Error. Please contact " "system administrator.") return render_to_response('DoctorCom/Messaging/refer_success.html', context)
def message_edit_multi(request, message_id=None): context = get_context(request) context['MAX_UPLOAD_SIZE'] = settings.MAX_UPLOAD_SIZE context['ioerror'] = '' if (request.method == 'GET'): user_recipients = request.GET['user_recipients'] else: user_recipients = request.POST['user_recipients'] if not user_recipients: return HttpResponseRedirect('/') recipient_ids = [] for item in user_recipients.split(','): recipient_ids.append(int(item)) form_initial_data = { 'recipients': None, 'user_recipients': user_recipients } context['user_recipient_name'] = '; '.join([ ' '.join([user.first_name, user.last_name]) for user in MHLUser.objects.filter(pk__in=recipient_ids) ]) context['recipientsform'] = MessageOptionsForm( initial={'user_recipients': user_recipients}) if (request.method == 'POST'): form = MessageForm(request.POST, request.FILES) if (form.is_valid()): logger.debug('Form is valid') rec_count = len(recipient_ids) for recipient in recipient_ids: # Build the message and body rec_count -= 1 msg = Message( sender=request.user, sender_site=None, subject=form.cleaned_data['subject'], ) msg.save() MessageRecipient(message=msg, user_id=recipient).save() msg_body = msg.save_body(form.cleaned_data['body']) attachments = save_attachments(request, context, msg, form, rec_count == 0) msg.send(request, msg_body, attachments) return HttpResponseRedirect('/') else: logger.debug('Form is invalid') file_saved_names = request.POST.getlist('file_saved_name') file_display_names = request.POST.getlist('file_display_name') file_charsets = request.POST.getlist('file_charset') file_sizes = request.POST.getlist('file_size') file_len = len(file_saved_names) file_list = [{ 'file_saved_name': file_saved_names[i], 'file_display_name': file_display_names[i], 'file_charset': file_charsets[i], 'file_size': file_sizes[i], } for i in range(file_len)] context['file_list'] = file_list context['form'] = form if (not message_id and request.method == 'GET'): # clean temp files FileHelper.cleanTempFile() context['form'] = MessageForm(initial=form_initial_data) elif (message_id): # Grab the message in question msg = Message.objects.get(uuid=message_id) # Check to ensure that the user has rights to mess with this message if (request.user != msg.owner): errlib.err403() return render_to_response('DoctorCom/Messaging/MessageMultiEditForm.html', context)
def createNewMessage(request, sender, sender_role_user, recipients, body, ccs=None, subject=None, uploads=None, file_data_list=None, temporary_files_data=None, exist_attchments=None, exist_refer=None, refer_data=None, thread_uuid=None, ss=None): """ createNewMessage :param request: request :param sender: message's sender as auth_user :param sender_role_user: message's sender as Provider/Office Staff/Broker :param recipients: user_id for message's recipients (integer or integer list) :param body: message's content body :param ccs: user_id for message's ccs (integer or integer list) :param subject: messages subject :param uploads: uploads is from request.FILES :param file_data_list: files information to be stored in message (file information dictionary list). The element in the file_data_list likes [{'name':'','file_chunks':'','size':,'suffix':'','charset':},...] :param temporary_files_data: (reserved) temporary files information, structure like Example:: { 'file_saved_name': file saved name list, 'file_display_name': file display name list, 'file_charset': file charset list, 'file_size': file size list, } :param exist_attchments: attachment information, structure like Example:: { 'message_id': message_id(used for validating the attachment), 'attachment_ids': attachment_id list } :param exist_refer: used for forwarding refer pdf Example:: { 'message_id': message_id(used for validating the refer), 'refer_id': refer_id } :param refer_data: refer information dictionary :param thread_uuid: is used for threading :param ss: sender's private key api_secret and ss are used for :returns: Message :raises: Http404, KeyInvalidException """ # compose message and message body sender_site = None if sender_role_user and hasattr(sender_role_user, 'current_site'): sender_site = sender_role_user.current_site thread_uuid = thread_uuid if thread_uuid else uuid.uuid4().hex msg = Message( sender=sender, sender_site=sender_site, subject=subject, thread_uuid=thread_uuid, ) msg.save() body = msg.save_body(body) # compose recipients and ccs if not isinstance(recipients, list): recipients = [recipients] if not isinstance(ccs, list): ccs = [ccs] recipients, ccs = getDistinctToAndCc(recipients, ccs) if recipients: for recipient in recipients: MessageRecipient(message=msg, user_id=recipient).save() if ccs: for cc in ccs: MessageCC(message=msg, user_id=cc).save() # compose upload attachment data attachments = saveAttachmentsUsingRequestFiles(request, msg, uploads) # compose attachment using data like [{'name':'','file_chunks':'','size':,'suffix':'','charset':},...] if file_data_list: for file_data in file_data_list: attachment = saveSingleAttachment(request, msg, file_data) attachments.append(attachment) # TODO: compose exist file it's in temporary directory #attachments.extend(saveAttachmentsUsingTemporaryFiles(request, msg, temporary_files_data)) # compose exist file using exist attachment attachments.extend(saveAttachmentsUsingExistAttachments(request, msg, exist_attchments, ss)) # compose exist refer pdf attachments.extend(saveAttachmentsForForwardReferPdf(request, msg, exist_refer, ss)) # compose refer data refers = createNewRefer(msg, request, sender, sender_role_user, refer_data=refer_data) msg.send(request, body, attachment_objs=attachments, refer_objs=refers) createReferFowarding(refers, request, sender, sender_role_user, refer_data=refer_data, ss=ss) return msg
def resolve_download_failure(failure_record): url = failure_record.recording_url request = _FauxRequest() request.REQUEST = {"CallSid": failure_record.call_sid} request.session['ivr_makeRecording_recording'] = url request.session.session_key = '' wav_data, metadata = _download_recording(request) metadata = json.dumps(metadata) if (not wav_data): log = AnsSvcDLFailureActivityLog(call_sid=failure_record.call_sid, action='FAI') log.save() return False log = AnsSvcDLFailureActivityLog(call_sid=failure_record.call_sid, action='SUC') log.save() managers = get_all_practice_managers(failure_record.practice_id) msg = Message(sender=None, sender_site=None, subject='Answering Service - Recording Retrieved') msg.save() if (managers): # Assign all practice managers as recipients of this message. for staffer in managers: MessageRecipient(message=msg, user=staffer.user).save() else: #if this was a voicemail on a provider number error_msg = Message.objects.get(uuid=failure_record.error_message_uuid) recipients = error_msg.recipients.all() for user in recipients: MessageRecipient(message=msg, user=user).save() body = _('We were able to successfully retrieve a recording we had trouble ' 'downloading earlier today (callback number %(callbacknumber)s with ' 'ID %(call_sid)s). Please see the attached recording.\nAgain, we apologize ' 'for any inconvenience and thank you for your patience.\nDoctorCom Staff') % \ {'callbacknumber': failure_record.callback_number, 'call_sid': failure_record.call_sid} body = msg.save_body(body) attachment = encrypt_object( MessageAttachment, { 'message': msg, 'size': len(wav_data), 'encrypted': True, 'metadata': metadata }) attachment.encrypt_url(None, ''.join(['file://', attachment.uuid])) attachment.encrypt_filename( None, ''.join(['call_from_', failure_record.callback_number, '.mp3'])) attachment.encrypt_file(None, [wav_data]) if (not USE_MP3): attachment.suffix = 'wav' attachment.content_type = 'audio/wav' else: attachment.suffix = 'mp3' attachment.content_type = 'audio/mp3' attachment.save() attachments = [attachment] request.session['answering_service'] = 'yes' # Send the message msg.send(request, body, attachments) failure_record.mark_resolved(msg) return True
def message_edit(request, message_id=None): """ Handles message composition, editing, and drafts. :param request: The HTTP request :type request: django.core.handlers.wsgi.WSGIRequest :param message_id: Message id :type message_id: int :returns: django.http.HttpResponse -- the result in an HttpResonse object :raises: InvalidRecipientException, Http404 """ context = get_context(request) context['show_subscribe'] = False context['ioerror'] = '' recipients = [] form_initial_data = {'recipients': None} current_site = None if ('Provider' in request.session['MHL_Users']): current_site = request.session['MHL_Users']['Provider'].current_site if ('OfficeStaff' in request.session['MHL_Users']): current_practice = request.session['MHL_Users'][ 'OfficeStaff'].current_practice requestDataDict = request.GET if (request.method == 'POST'): requestDataDict = request.POST recipientsform = MessageOptionsForm(requestDataDict) if (recipientsform.is_valid()): data = recipientsform.cleaned_data if ('user_recipients' in recipientsform.cleaned_data and recipientsform.cleaned_data['user_recipients']): form_initial_data['user_recipient'] = recipientsform.cleaned_data[ 'user_recipients'] if (type(form_initial_data['user_recipient']) is list): form_initial_data['user_recipient'] = form_initial_data[ 'user_recipient'][0] context['user_recipient'] = MHLUser.objects.get( pk=form_initial_data['user_recipient']) user_recipients = MHLUser.objects.filter( pk__in=recipientsform.cleaned_data['user_recipients']) user_recipientst = [] for user_recipient in user_recipients: user_recipientst = [{ 'id': user_recipient.id, 'fullname': get_fullname(user_recipient) }] context['user_recipients'] = user_recipientst user_cc_recipients = MHLUser.objects.filter( pk__in=recipientsform.cleaned_data['user_cc_recipients']) user_cc_recipientst = [] for user_cc_recipient in user_cc_recipients: user_cc_recipientst = [{ 'id': user_cc_recipient.id, 'fullname': get_fullname(user_cc_recipient) }] context['user_cc_recipients'] = user_cc_recipientst if 'msg_prefix' in data and data['msg_prefix']: user_recipients = MHLUser.objects.filter( pk__in=recipientsform.cleaned_data['user_recipients']) user_cc_recipients = MHLUser.objects.filter( pk__in=recipientsform.cleaned_data['user_cc_recipients']) elif ('practice_recipients' in recipientsform.cleaned_data and recipientsform.cleaned_data['practice_recipients']): form_initial_data[ 'practice_recipient'] = recipientsform.cleaned_data[ 'practice_recipients'] if (type(form_initial_data['practice_recipient']) is list): form_initial_data['practice_recipient'] = form_initial_data[ 'practice_recipient'][0] context['practice_recipient'] = PracticeLocation.objects.get( pk=form_initial_data['practice_recipient']) if 'msg_id' in data and data[ 'msg_id'] and 'msg_prefix' in data and data['msg_prefix']: origin_msg = Message.objects.get(uuid=data['msg_id']) if data['msg_prefix'] == "RE": form_initial_data['subject'] = get_format_subject( origin_msg.subject, data['msg_prefix']) elif data['msg_prefix'] == "FW": origin_attachment = MessageAttachment.objects.filter( message=origin_msg) file_list = [] for att in origin_attachment: f = att.get_content_file(request) file_name = FileHelper.generateTempFile( f, utils.get_user_key(request)) file_list.append({ 'file_saved_name': file_name, 'file_display_name': att.decrypt_filename(request), 'file_charset': att.charset, 'file_size': att.size, }) refer = MessageRefer.objects.filter(message=origin_msg) if refer: f = refer[0].decrypt_file(request) file_name = FileHelper.generateTempFile( f, utils.get_user_key(request)) file_list.append({ 'file_saved_name': file_name, 'file_display_name': 'refer.pdf', 'file_charset': '', 'file_size': len(f) }) context['file_list'] = file_list form_initial_data['subject'] = get_format_subject( origin_msg.subject, data['msg_prefix']) msg_body = MessageBody.objects.filter(message=origin_msg)[0] form_initial_data['body'] = get_text_from_messge( request, origin_msg, msg_body, context['current_practice']) data['msg_id'] = '' # else: # raise Http404 data['user_recipients'] = ','.join( str(x) for x in data['user_recipients'] if x) data['practice_recipients'] = ','.join( str(x) for x in data['practice_recipients'] if x) context['recipientsform'] = MessageOptionsForm( initial=recipientsform.cleaned_data) if (request.method == 'POST'): form = MessageForm(request.POST, request.FILES) if (form.is_valid()): logger.debug('Form is valid') manager_list = [] if (form.cleaned_data['practice_recipient']): managers = Office_Manager.active_objects.filter( practice=form.cleaned_data['practice_recipient']) manager_list.extend(m.user.user.pk for m in managers) recipients, ccs = getFormatToAndCc( form.cleaned_data['user_recipients'], form.cleaned_data['user_cc_recipients'], manager_list=manager_list) # Build the message and body thread_uuid = recipientsform.cleaned_data['thread_uuid'] if \ recipientsform.cleaned_data['thread_uuid'] else uuid.uuid4().hex msg = Message( sender=request.user, sender_site=current_site, subject=form.cleaned_data['subject'], thread_uuid=thread_uuid, ) msg.save() msg_body = msg.save_body(form.cleaned_data['body']) for recipient in recipients: MessageRecipient(message=msg, user_id=recipient).save() for cc in ccs: MessageCC(message=msg, user_id=cc).save() len_attachments = len(request.POST.getlist('file_saved_name')) if can_send_msg_with_attachments(request.user, recipients, ccs, len_attachments) \ or 'Broker' in request.session['MHL_Users']: # Build the attachments attachments = save_attachments(request, context, msg, form) msg.send(request, msg_body, attachments) return HttpResponseRedirect('/') else: context['show_subscribe'] = True transaction.rollback() logger.debug('Form is invalid') file_saved_names = request.POST.getlist('file_saved_name') file_display_names = request.POST.getlist('file_display_name') file_charsets = request.POST.getlist('file_charset') file_sizes = request.POST.getlist('file_size') file_len = len(file_saved_names) file_list = [{ 'file_saved_name': file_saved_names[i], 'file_display_name': file_display_names[i], 'file_charset': file_charsets[i], 'file_size': file_sizes[i], } for i in range(file_len)] context['file_list'] = file_list context['form'] = form if (not message_id and request.method == 'GET'): # clean temp files FileHelper.cleanTempFile() context['form'] = MessageForm(initial=form_initial_data) elif (message_id): # Grab the message in question msg = Message.objects.get(uuid=message_id) # Check to ensure that the user has rights to mess with this message if (request.user != msg.owner): errlib.err403(err_msg='') context['MAX_UPLOAD_SIZE'] = settings.MAX_UPLOAD_SIZE return render_to_response('DoctorCom/Messaging/MessageEditForm.html', context)
def admin_message_edit(request, userID): """ Handles message composition, editing, and drafts. :param request: The HTTP request :type request: django.core.handlers.wsgi.WSGIRequest :param userID: user's ID :type userID: int :returns: django.http.HttpResponse -- The webpage """ context = get_context(request) recipients = [] form_initial_data = {'recipient': userID} if (request.method == 'POST'): form = AdminMessageForm(request.POST, request.FILES) if (form.is_valid()): recipients = [form.cleaned_data['recipient']] for recipient in recipients: try: recipient = MHLUser.objects.get(pk=recipient) except MHLUser.DoesNotExist: raise InvalidRecipientException() if (not recipient.is_active): raise InvalidRecipientException() # Build the message and body msg = Message( subject=form.cleaned_data['subject'], message_type=form.cleaned_data['message_type'], callback_number=form.cleaned_data.get('callback_number', ''), ) msg.save() msg_body = msg.save_body(form.cleaned_data['body']) for recipient in recipients: MessageRecipient(message=msg, user_id=recipient).save() # Build the attachments attachments = [] if ('file' in request.FILES): upload = request.FILES['file'] attachment = encrypt_object( MessageAttachment, { 'message': msg, 'size': upload.size, 'encrypted': True, }, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) attachment.encrypt_url(request, ''.join(['file://', attachment.uuid])) attachment.encrypt_filename(request, upload.name) attachment.encrypt_file(request, upload.chunks()) suffix = suffix_re.search(upload.name) if (suffix): attachment.suffix = suffix.group(1)[:255] (attachment.content_type, attachment.encoding) = mimetypes.guess_type(upload.name) attachment.charset = upload.charset attachment.save() attachments.append(attachment) if(form.cleaned_data['url']): request.POST['CallSid'] = '' request.session['ivr_makeRecording_recording'] = form.cleaned_data['url'] request.session['ivr_makeRecording_callbacknumber'] = \ form.cleaned_data['callback_number'] attachment = save_voice_attachment(request, msg) attachments.append(attachment) # Send the message msg.send(request, msg_body, attachments) return HttpResponseRedirect('/') else: context['recipient'] = MHLUser.objects.get(pk=userID) context['form'] = form else: context['recipient'] = MHLUser.objects.get(pk=userID) context['form'] = AdminMessageForm(initial=form_initial_data) return render_to_response('admin_message.html', context)
def updateRefer(request, form, refer_id): refer = MessageRefer.objects.get(uuid=refer_id) if refer.status != 'NO': return False refer.status = form.cleaned_data["status"] refer.refuse_reason = form.cleaned_data["refuse_reason"] refer.save() message = Message.objects.filter(id=refer.message_id).extra( select={ 'title': 'SELECT title FROM MHLUsers_mhluser \ WHERE MHLUsers_mhluser.user_ptr_id = Messaging_message.sender_id' }) sender = message[0].sender recipient_name = get_fullname_bystr(sender.last_name, sender.first_name, message[0].title) get_object_or_404(MessageBody, message=message) recipient_email_list = [] recipient_list = [] recipient_email_list.append(sender.email) duser_ids = list(Physician.objects.all().values_list("user__user__pk", flat=True)) recipients = message[0].recipients.all().extra( select={ 'title': 'SELECT title FROM MHLUsers_mhluser \ WHERE MHLUsers_mhluser.user_ptr_id = Messaging_message_recipients.user_id' }) for recipient in recipients: recipient_list.append( get_fullname_bystr(str(recipient.last_name), str(recipient.first_name), recipient.title)) emailContext = dict() emailContext['refuse_reason'] = '' emailContext['sender_name'] = ', '.join(recipient_list) emailContext['recipient_name'] = recipient_name emailContext['patient_name'] = ' '.join( [refer.first_name, refer.middle_name, refer.last_name]) emailContext['operator_name'] = ' '.join( [request.user.first_name, request.user.last_name]) emailContext['status'] = dict(REFER_STATUS)[refer.status].lower() if refer.status == "RE": if refer.refuse_reason: emailContext['refuse_reason'] = _( u'\nDeclined Reason: %s') % refer.refuse_reason else: emailContext['refuse_reason'] = _(u'\nDeclined Reason: N/A') msgBody = render_to_string('DoctorCom/Messaging/ReferStaUpdEmail.html', emailContext) msg_subject = _('DoctorCom: Refer [%s]') % dict(REFER_STATUS)[refer.status] msg = Message(sender=None, sender_site=None, subject=msg_subject, message_type='NM') msg.save() MessageRecipient(user=sender, message=msg).save() msg_body = msg.save_body(msgBody) msg.send(request, msg_body) email_msgBody = msgBody + _("\n Best, \n DoctorCom") send_mail(msg_subject, email_msgBody, settings.SERVER_EMAIL, recipient_email_list, fail_silently=False) return True
def message_edit(request, message_id=None): """ Handles message composition, editing, and drafts. :param request: The HTTP request :type request: django.core.handlers.wsgi.WSGIRequest :param message_id: Message id :type message_id: int :returns: django.http.HttpResponse -- the result in an HttpResonse object :raises: InvalidRecipientException, Http404 """ context = get_context(request) context['show_subscribe'] = False context['ioerror'] = '' recipients = [] form_initial_data = {'recipients': None} current_site = None if ('Provider' in request.session['MHL_Users']): current_site = request.session['MHL_Users']['Provider'].current_site if ('OfficeStaff' in request.session['MHL_Users']): current_practice = request.session['MHL_Users']['OfficeStaff'].current_practice requestDataDict = request.GET if(request.method == 'POST'): requestDataDict = request.POST recipientsform = MessageOptionsForm(requestDataDict) if (recipientsform.is_valid()): data = recipientsform.cleaned_data if ('user_recipients' in recipientsform.cleaned_data and recipientsform.cleaned_data['user_recipients']): form_initial_data['user_recipient'] = recipientsform.cleaned_data['user_recipients'] if (type(form_initial_data['user_recipient']) is list): form_initial_data['user_recipient'] = form_initial_data['user_recipient'][0] context['user_recipient'] = MHLUser.objects.get(pk=form_initial_data['user_recipient']) user_recipients = MHLUser.objects.filter( pk__in=recipientsform.cleaned_data['user_recipients']) user_recipientst=[] for user_recipient in user_recipients: user_recipientst=[{ 'id':user_recipient.id, 'fullname':get_fullname(user_recipient) }] context['user_recipients']=user_recipientst user_cc_recipients = MHLUser.objects.filter( pk__in=recipientsform.cleaned_data['user_cc_recipients']) user_cc_recipientst=[] for user_cc_recipient in user_cc_recipients: user_cc_recipientst=[{ 'id':user_cc_recipient.id, 'fullname':get_fullname(user_cc_recipient) }] context['user_cc_recipients']=user_cc_recipientst if 'msg_prefix' in data and data['msg_prefix']: user_recipients = MHLUser.objects.filter( pk__in=recipientsform.cleaned_data['user_recipients']) user_cc_recipients = MHLUser.objects.filter( pk__in=recipientsform.cleaned_data['user_cc_recipients']) elif ('practice_recipients' in recipientsform.cleaned_data and recipientsform.cleaned_data['practice_recipients']): form_initial_data['practice_recipient'] = recipientsform.cleaned_data['practice_recipients'] if (type(form_initial_data['practice_recipient']) is list): form_initial_data['practice_recipient'] = form_initial_data['practice_recipient'][0] context['practice_recipient'] = PracticeLocation.objects.get( pk=form_initial_data['practice_recipient']) if 'msg_id' in data and data['msg_id'] and 'msg_prefix' in data and data['msg_prefix']: origin_msg = Message.objects.get(uuid=data['msg_id']) if data['msg_prefix'] == "RE": form_initial_data['subject'] = get_format_subject( origin_msg.subject, data['msg_prefix']) elif data['msg_prefix'] == "FW": origin_attachment = MessageAttachment.objects.filter(message=origin_msg) file_list = [] for att in origin_attachment: f = att.get_content_file(request) file_name = FileHelper.generateTempFile(f, utils.get_user_key(request)) file_list.append( { 'file_saved_name': file_name, 'file_display_name': att.decrypt_filename(request), 'file_charset': att.charset, 'file_size': att.size, }) refer = MessageRefer.objects.filter(message=origin_msg) if refer: f = refer[0].decrypt_file(request) file_name = FileHelper.generateTempFile(f, utils.get_user_key(request)) file_list.append( { 'file_saved_name': file_name, 'file_display_name': 'refer.pdf', 'file_charset': '', 'file_size': len(f) }) context['file_list'] = file_list form_initial_data['subject'] = get_format_subject( origin_msg.subject, data['msg_prefix']) msg_body = MessageBody.objects.filter(message=origin_msg)[0] form_initial_data['body'] = get_text_from_messge(request, origin_msg, msg_body, context['current_practice']) data['msg_id'] = '' # else: # raise Http404 data['user_recipients'] = ','.join(str(x) for x in data['user_recipients'] if x) data['practice_recipients'] = ','.join(str(x) for x in data['practice_recipients'] if x) context['recipientsform'] = MessageOptionsForm(initial=recipientsform.cleaned_data) if (request.method == 'POST'): form = MessageForm(request.POST, request.FILES) if (form.is_valid()): logger.debug('Form is valid') manager_list = [] if(form.cleaned_data['practice_recipient']): managers = Office_Manager.active_objects.filter( practice=form.cleaned_data['practice_recipient']) manager_list.extend(m.user.user.pk for m in managers) recipients, ccs = getFormatToAndCc(form.cleaned_data['user_recipients'], form.cleaned_data['user_cc_recipients'], manager_list=manager_list) # Build the message and body thread_uuid = recipientsform.cleaned_data['thread_uuid'] if \ recipientsform.cleaned_data['thread_uuid'] else uuid.uuid4().hex msg = Message( sender=request.user, sender_site=current_site, subject=form.cleaned_data['subject'], thread_uuid=thread_uuid, ) msg.save() msg_body = msg.save_body(form.cleaned_data['body']) for recipient in recipients: MessageRecipient(message=msg, user_id=recipient).save() for cc in ccs: MessageCC(message=msg, user_id=cc).save() len_attachments = len(request.POST.getlist('file_saved_name')) if can_send_msg_with_attachments(request.user, recipients, ccs, len_attachments) \ or 'Broker' in request.session['MHL_Users']: # Build the attachments attachments = save_attachments(request, context, msg, form) msg.send(request, msg_body, attachments) return HttpResponseRedirect('/') else: context['show_subscribe'] = True transaction.rollback() logger.debug('Form is invalid') file_saved_names = request.POST.getlist('file_saved_name') file_display_names = request.POST.getlist('file_display_name') file_charsets = request.POST.getlist('file_charset') file_sizes = request.POST.getlist('file_size') file_len = len(file_saved_names) file_list = [ { 'file_saved_name':file_saved_names[i], 'file_display_name':file_display_names[i], 'file_charset':file_charsets[i], 'file_size':file_sizes[i], } for i in range(file_len) ] context['file_list'] = file_list context['form'] = form if (not message_id and request.method == 'GET'): # clean temp files FileHelper.cleanTempFile() context['form'] = MessageForm(initial=form_initial_data) elif(message_id): # Grab the message in question msg = Message.objects.get(uuid=message_id) # Check to ensure that the user has rights to mess with this message if (request.user != msg.owner): errlib.err403(err_msg='') context['MAX_UPLOAD_SIZE'] = settings.MAX_UPLOAD_SIZE return render_to_response('DoctorCom/Messaging/MessageEditForm.html', context)