def getMembers(request, practice_id, callgroup_id): callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id) if (not canAccessMultiCallGroup(request.user, long(callgroup_id), practice_id)): return err403(request) #sort by first name 180 Chen Hu members = list( CallGroupMember.objects.filter( call_group__id=callgroup_id).values_list( 'member__pk', 'member__user__first_name', 'member__user__last_name', 'member__user__title').order_by('member__user__last_name')) members = [(m[0], m[1], m[2], 'drop', get_fullname_bystr(m[1], m[2], m[3])) for m in members] pendings = list( CallGroupMemberPending.objects.filter( call_group__id=callgroup_id, accept_status=0).values_list( 'to_user__pk', 'to_user__user__first_name', 'to_user__user__last_name', 'to_user__user__title').order_by('to_user__user__last_name')) pendings = [(p[0], p[1], p[2], 'disabled', get_fullname_bystr(p[1], p[2], p[3])) for p in pendings] members.extend(pendings) return HttpResponse(content=json.dumps(members), mimetype='application/json')
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 sender_name_safe(message, title=None): if (message.sender): return get_fullname_bystr(message.sender.last_name, message.sender.first_name, title=title) else: return _('System Message')
def render_action_histories(mahs, user=None, time_zone=None): return [{ 'content': _("[%(user_name)s] %(type)s this message at") %\ {'user_name': get_fullname_bystr(mah.user.last_name, mah.user.first_name,mah.title), 'type': mah.get_type_display().lower()}, 'timestamp': formatTimeSetting(user, mah.timestamp, time_zone)\ if time_zone is not None and user else mah.timestamp }for mah in mahs]
def getMembers(request, callgroup_id): if (not canAccessCallGroup(request.user, long(callgroup_id))): return err403(request) #sort by first name 180 Chen Hu members = CallGroupMember.objects.filter(call_group__id=callgroup_id).values_list('member__pk', 'member__user__first_name','member__user__last_name','member__user__title').order_by('member__user__last_name') members = [(m[0],m[1],m[2],get_fullname_bystr(m[1],m[2],m[3])) for m in members] return HttpResponse(content=json.dumps(list(members)), mimetype='application/json')
def render_action_histories(mahs, user=None, time_zone=None): return [{ 'content': _("[%(user_name)s] %(type)s this message at") %\ {'user_name': get_fullname_bystr(mah.user.last_name, mah.user.first_name,mah.title), 'type': mah.get_type_display().lower()}, 'timestamp': formatTimeSetting(user, mah.timestamp, time_zone)\ if time_zone is not None and user else mah.timestamp }for mah in mahs]
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_view(request, message_id, type): """Process message view request: :param request: The HTTP message view request :type request: django.core.handlers.wsgi.WSGIRequest :param message_id: The message id :type message_id: int :returns: django.http.HttpResponse -- the JSON result in an HttpResonse object :raises: None """ resolved = request.GET['resolved'] thread_uuid = Message.objects.get(uuid=message_id).thread_uuid msgs = MessageBodyUserStatus.objects.filter(user=request.user, delete_flag=False, msg_body__message__thread_uuid=thread_uuid).order_by( '-msg_body__message__send_timestamp').\ select_related('msg_body', 'msg_body__message', 'msg_body__message__sender')\ .extra(select={'sender_title':"SELECT MHLUsers_mhluser.title \ FROM MHLUsers_mhluser INNER JOIN Messaging_message ON \ MHLUsers_mhluser.user_ptr_id = Messaging_message.sender_id \ INNER JOIN Messaging_messagebody ON \ Messaging_message.id = Messaging_messagebody.message_id \ WHERE Messaging_messagebody.id = Messaging_messagebodyuserstatus.msg_body_id" }) if (resolved == ''): pass elif str(resolved).lower() in ("true"): msgs = msgs.filter(msg_body__message__in=[ m.msg_body.message for m in msgs if m.msg_body.message.resolved_by != None ]) else: msgs = msgs.filter(msg_body__message__in=[ m.msg_body.message for m in msgs if m.msg_body.message.resolved_by == None ]) msgs.select_related( 'msg_body', 'msg_body__message', 'msg_body__message__sender', ) msgs = list(msgs) context = get_context(request) user = request.session['MHL_Users']['MHLUser'] local_tz = getCurrentTimeZoneForUser( user, current_practice=context['current_practice']) is_received = type == 'received' current_user = getCurrentUserInfo(request) current_user_mobile = getCurrentUserMobile(current_user) call_enable = bool(current_user_mobile) and settings.CALL_ENABLE msgs_list = [] audio_list = [] for status_obj in msgs: try: read_flag = status_obj.read_flag body = decrypt_object(request, status_obj.msg_body) # TODO, this function need to refactor, when get threading message list, # don't need to decrypt every message body in the threading message. # When refactors, use following line while reading message body. # body = read_message(request, status_obj.msg_body) if not read_flag: status_obj.read_flag = read_flag status_obj.save() except KeyInvalidException: mail_admins( _('Message Body Decryption Error'), ''.join([('An error occurred decryption data for user '), request.user.username, (' on server '), settings.SERVER_ADDRESS, '.\n', ('Message ID: '), message_id])) callbacks = CallbackLog.objects.filter(message=status_obj.msg_body.message).\ order_by('time').values('time') callbacks = [{ 'timestamp': _get_system_time_as_tz(c['time'], local_tz).strftime('%m/%d/%y %H:%M'), 'caller_name': 'Joe Bloggs', 'caller_id': 123, } for c in callbacks] msg_cc_maps = MessageCC.objects.filter(message=status_obj.msg_body.message).\ select_related('user').extra(select={'title':'SELECT title FROM MHLUsers_mhluser \ WHERE MHLUsers_mhluser.user_ptr_id = Messaging_message_ccs.user_id' })\ .only('user__first_name', 'user__last_name', 'message') ccs = '; '.join([get_fullname_bystr(msg_cc_map.user.last_name,\ msg_cc_map.user.first_name,msg_cc_map.title)\ for msg_cc_map in msg_cc_maps]) msg_to_maps = MessageRecipient.objects.filter(message=status_obj.msg_body.message).\ select_related('user').extra(select={'title':'SELECT title FROM MHLUsers_mhluser \ WHERE MHLUsers_mhluser.user_ptr_id = Messaging_message_recipients.user_id' })\ .only('user__first_name', 'user__last_name', 'message') recipients = '; '.join([get_fullname_bystr(msg_to_map.user.last_name,\ msg_to_map.user.first_name,msg_to_map.title)\ for msg_to_map in msg_to_maps]) to_recipient_ids = [] msg_sender = status_obj.msg_body.message.sender msg_sender_id = None if msg_sender: msg_sender_id = msg_sender.id to_recipient_ids.append(str(msg_sender_id)) for rec in msg_to_maps: if rec.user.id != request.user.id: to_recipient_ids.append(str(rec.user.id)) cc_recipient_ids = [] for cc in msg_cc_maps: cc_recipient_ids.append(str(cc.user.id)) is_read = status_obj.read_flag user_id = request.user.id read_recipients = [ r.id for r in status_obj.msg_body.message.recipients.all() ] read_ccs = [c.id for c in status_obj.msg_body.message.ccs.all()] if not is_read: if is_received: if user_id not in read_recipients + read_ccs: is_read = True else: if msg_sender_id != request.user.id: is_read = True is_sender = request.user.id == msg_sender_id if is_received and (request.user.id == msg_sender_id and user_id in read_recipients + read_ccs): is_sender = False result = { 'id': status_obj.msg_body.message.uuid, 'sender': sender_name_safe(status_obj.msg_body.message, title=status_obj.sender_title), 'sender_id': msg_sender_id, 'thread_uuid': status_obj.msg_body.message.thread_uuid, 'timestamp': formatTimeSetting(user, status_obj.msg_body.message.send_timestamp, local_tz), 'subject': conditional_escape(status_obj.msg_body.message.subject), 'body': replace_number(status_obj.msg_body.clear_data, call_enable), 'answering_service': status_obj.msg_body.message.message_type == 'ANS', 'callback_number': replace_number(status_obj.msg_body.message.callback_number, call_enable), 'callbacks': callbacks, 'urgent': status_obj.msg_body.message.urgent, 'ccs': ccs, 'recipients': recipients, 'to_recipient_ids': ','.join(to_recipient_ids), 'cc_recipient_ids': ','.join(cc_recipient_ids), 'is_sender': is_sender, 'is_resolved': status_obj.msg_body.message.resolved_by != None, 'read': 'true' if is_read else '' } attachments = MessageAttachment.objects.filter( message=status_obj.msg_body.message) result["attachments"] = [] for att in attachments: attach_dict = { 'id': att.uuid, 'suffix': att.suffix, 'size': att.size, 'metadata': att.metadata, 'filename': att.decrypt_filename(request), 'msgId': status_obj.msg_body.message.uuid } result["attachments"].append(attach_dict) if att.suffix and att.suffix.lower() in ['mp3', 'wav']: audio_list.append(attach_dict) result["refer"] = _get_refer_from_mbus(status_obj, call_enable=call_enable) result["action_history"] = get_message_action_history( status_obj.msg_body.message.id, user, time_zone=local_tz) msgs_list.append(result) context['msgs'] = msgs_list context['audio_list'] = audio_list context['type'] = type return HttpResponse( render_to_string('DoctorCom/Messaging/MessageBody.html', context))
def get_message_details(request): if (request.method != 'POST'): return err_GE002() form = GetMsgDetailsForm(request.POST) if (not form.is_valid()): return err_GE031(form) message_uuids = form.cleaned_data['message_uuids'] msgss = list(MessageBodyUserStatus.objects.filter(user=request.user, delete_flag=False, msg_body__message__uuid__in=message_uuids) .extra(select={'sender_title':"SELECT MHLUsers_mhluser.title \ FROM MHLUsers_mhluser INNER JOIN Messaging_message ON \ MHLUsers_mhluser.user_ptr_id = Messaging_message.sender_id \ INNER JOIN Messaging_messagebody ON \ Messaging_message.id = Messaging_messagebody.message_id \ WHERE Messaging_messagebody.id = Messaging_messagebodyuserstatus.msg_body_id"}) .order_by('-msg_body__message__send_timestamp') .select_related('msg_body', 'msg_body__message', 'msg_body__message__sender')) if (len(msgss) == 0): raise Http404 # Get/set up data for KMS. request.session['key'] = request.device_assn.secret ss = form.cleaned_data['secret'] recipients = MessageRecipient.objects.filter(message__uuid__in=message_uuids) \ .select_related('user', 'message')\ .only('user__first_name', 'user__last_name', 'message__uuid') recp_dict = convert_query_set_to_dict_with_uuid(recipients) ccs = MessageCC.objects.filter(message__uuid__in=message_uuids)\ .select_related('user', 'message')\ .only('user__first_name', 'user__last_name', 'message__uuid') cc_dict = convert_query_set_to_dict_with_uuid(ccs) attachments = MessageAttachment.objects.filter(message__uuid__in=message_uuids)\ .select_related('message') attach_dict = convert_query_set_to_dict_with_uuid(attachments) mahs = MessageActionHistory.objects.filter(message__uuid__in=message_uuids)\ .select_related('user', 'message')\ .extra(select={'title':'SELECT title FROM MHLUsers_mhluser \ WHERE MHLUsers_mhluser.user_ptr_id = Messaging_messageactionhistory.user_id'}) mah_dict = convert_query_set_to_dict_with_uuid(mahs) refers = MessageRefer.objects.filter(message__uuid__in=message_uuids)\ .select_related('message') refer_dict = convert_query_set_to_dict_with_uuid(refers) user = request.user local_tz = getCurrentTimeZoneForUser(user) current_user = request.role_user current_user_mobile = current_user.user.mobile_phone ret_msgs = [] for status_obj in msgss: try: read_message(request, status_obj.msg_body, ss=ss) except KeyInvalidException: return err_GE021() msg = status_obj.msg_body.message msg_uuid = msg.uuid recipients = [] if msg_uuid in recp_dict: recipients = [{ 'name': get_fullname_bystr(msg.sender.last_name, msg.sender.first_name,status_obj.sender_title), 'id': u.user.id, } for u in recp_dict[msg_uuid]] ccs = [] if msg_uuid in cc_dict: ccs = [{ 'name': get_fullname_bystr(u.user.last_name, u.user.first_name, u.title), 'id': u.user.id, } for u in cc_dict[msg_uuid]] attachments = [] if msg_uuid in attach_dict: attachments = [ { 'id': att.uuid, 'filename': get_attachment_filename(request, att, ss), 'filesize': att.size, 'suffix':att.suffix, } for att in attach_dict[msg_uuid]] refer = None if msg_uuid in refer_dict: refer = _get_refer_from_mbus(status_obj, logo_size="Large", refers=refer_dict[msg_uuid]) action_history = [] if msg_uuid in mah_dict: action_history = render_action_histories(mah_dict[msg_uuid], user=user, time_zone=local_tz) ret_msgs.append({ 'body': status_obj.msg_body.clear_data, 'timestamp': formatTimeSetting(user, msg.send_timestamp, local_tz, True), 'send_timestamp': msg.send_timestamp, 'sender': { 'name': get_fullname_bystr(msg.sender.last_name, msg.sender.first_name,status_obj.sender_title)\ if msg.sender else "System Message", 'id': msg.sender.id if msg.sender else 0, }, 'recipients': recipients, 'ccs': ccs, 'attachments': attachments, 'message_type': msg.message_type if msg.message_type else 'NM', 'callback_number': msg.callback_number, 'callback_available': settings.CALL_ENABLE and bool(msg.callback_number) and bool(current_user_mobile), 'urgent': bool(msg.urgent), 'resolution_flag': bool(msg._resolved_by_id), 'refer': refer, 'thread_uuid': msg.thread_uuid, 'action_history': action_history, 'action_history_count': len(action_history) }) response = { 'data': ret_msgs, 'warnings': {}, } return HttpResponse(content=json.dumps(response), mimetype='application/json')
def get_message(request, message_id): if (request.method != 'POST'): return err_GE002() form = MsgGetForm(request.POST) if (not form.is_valid()): return err_GE031(form) msgs = list(MessageBodyUserStatus.objects.filter(user=request.user, delete_flag=False, msg_body__message__uuid=message_id) .extra(select={'sender_title':"SELECT MHLUsers_mhluser.title \ FROM MHLUsers_mhluser INNER JOIN Messaging_message ON \ MHLUsers_mhluser.user_ptr_id = Messaging_message.sender_id \ INNER JOIN Messaging_messagebody ON \ Messaging_message.id = Messaging_messagebody.message_id \ WHERE Messaging_messagebody.id = Messaging_messagebodyuserstatus.msg_body_id"}). order_by('-msg_body__message__send_timestamp').select_related( 'msg_body', 'msg_body__message', 'msg_body__message__sender'))\ # Integrity check. if (len(msgs) > 1): # shouldn't be possible! mail_admins('Duplicate message ID', ' '.join(['server: ', settings.SERVER_ADDRESS, '\n', 'The message id with uuid', message_id, 'has returned with', 'more than one Message!\nAt: ', str(inspect.getfile(inspect.currentframe())), ':', str(inspect.currentframe().f_back.f_lineno) ])) if (len(msgs) == 0): raise Http404 status_obj = msgs[0] # Get/set up data for KMS. request.session['key'] = request.device_assn.secret ss = form.cleaned_data['secret'] current_user = request.role_user current_user_mobile = current_user.user.mobile_phone try: read_message(request, status_obj.msg_body, ss=ss) except KeyInvalidException: return err_GE021() msg = status_obj.msg_body.message recipients = MessageRecipient.objects.filter(message__uuid=message_id).\ select_related('user').extra(select={'title':'SELECT title FROM MHLUsers_mhluser \ WHERE MHLUsers_mhluser.user_ptr_id = Messaging_message_recipients.user_id'}).\ only('user__first_name', 'user__last_name') attachments = MessageAttachment.objects.filter(message=msg) ccs = MessageCC.objects.filter(message__uuid=message_id).select_related('user').\ extra(select={'title':'SELECT title FROM MHLUsers_mhluser \ WHERE MHLUsers_mhluser.user_ptr_id = Messaging_message_ccs.user_id'}).\ only('user__first_name', 'user__last_name', 'message') use_time_setting = False if 'use_time_setting' in request.POST and request.POST['use_time_setting'] == 'true': use_time_setting = True user = request.user local_tz = getCurrentTimeZoneForUser(user) action_history = get_message_action_history(status_obj.msg_body.message.id) response = { 'data': { 'body': status_obj.msg_body.clear_data, 'timestamp': formatTimeSetting(user, msg.send_timestamp, local_tz, use_time_setting), 'send_timestamp': msg.send_timestamp, 'sender': { 'name': get_fullname_bystr(msg.sender.last_name,msg.sender.first_name,status_obj.sender_title)\ if msg.sender else "System Message", 'id': msg.sender.id if msg.sender else 0, }, 'recipients': [{ 'name': get_fullname_bystr(u.user.last_name,u.user.first_name,u.title), 'id': u.user.id, } for u in recipients], 'ccs': [{ 'name': get_fullname_bystr(u.user.last_name,u.user.first_name,u.title), 'id': u.user.id, } for u in ccs], 'attachments': [ { 'id': att.uuid, 'filename': get_attachment_filename(request, att, ss), 'filesize': att.size, 'suffix':att.suffix, } for att in attachments], 'message_type': msg.message_type if msg.message_type else 'NM', 'callback_number': msg.callback_number, 'callback_available': settings.CALL_ENABLE and bool(msg.callback_number) and bool(current_user_mobile), 'urgent': bool(msg.urgent), 'resolution_flag': bool(msg._resolved_by_id), 'refer': _get_refer_from_mbus(status_obj, logo_size="Large"), 'thread_uuid': msg.thread_uuid, 'action_history': action_history, 'action_history_count': len(action_history) }, 'warnings': {}, } return HttpResponse(content=json.dumps(response), mimetype='application/json')
def get_msgs_for_threading(user, from_ts=None, to_ts=None, count=20, resolved=None, read=None, ccs=True, exclude_id=None, is_threading=True, thread_uuid=None, is_received_msg=True, offset=0): if count is None: count = 20 if offset is None: offset = 0 mbus = get_threading_mbus(user, None, thread_uuid, is_received_msg) mbu_list_all = mbus.values_list('msg_body__message__thread_uuid', flat=True) total_msg_count = len(set(mbu_list_all)) msg_unread_list = mbus.filter(read_flag=False).values_list( 'msg_body__message__id', flat=True) unread_msg_count = len(set(msg_unread_list)) msg_list = [] msg = Message.objects.filter().order_by('-send_timestamp', '-id').select_related( 'sender', 'recipients', 'ccs') exclude_msg_thread_uuid = [] if from_ts: if from_ts.__class__.__name__ == 'datetime': from_ts = from_ts.astimezone(UTC) exclude_msg_thread_uuid += list( msg.exclude(send_timestamp__gte=from_ts).values_list('thread_uuid', flat=True)) if to_ts: if to_ts.__class__.__name__ == 'datetime': to_ts = to_ts.astimezone(UTC) exclude_msg_thread_uuid += list( msg.exclude(send_timestamp__lte=to_ts).values_list('thread_uuid', flat=True)) if exclude_id: exclude_msg_thread_uuid += list( msg.filter(uuid=exclude_id).values_list('thread_uuid', flat=True)) msg = msg.exclude(thread_uuid__in=exclude_msg_thread_uuid) if is_received_msg: msg = msg.filter(Q(recipients=user) | Q(ccs=user)) else: msg = msg.filter(sender=user) msg_id_list = list(msg.values_list('id', flat=True)) mbus = MessageBodyUserStatus.objects.filter(user=user, delete_flag=False)\ .order_by('-msg_body__message__send_timestamp', '-msg_body__message__id')\ .select_related('msg_body', 'msg_body__message', 'msg_body__message__sender')\ .extra(select={'sender_title':"SELECT MHLUsers_mhluser.title \ FROM MHLUsers_mhluser INNER JOIN Messaging_message ON \ MHLUsers_mhluser.user_ptr_id = Messaging_message.sender_id \ INNER JOIN Messaging_messagebody ON \ Messaging_message.id = Messaging_messagebody.message_id \ WHERE Messaging_messagebody.id = Messaging_messagebodyuserstatus.msg_body_id" }) mbu_threading_uuid = [m.thread_uuid for m in msg] mbus = mbus.filter(msg_body__message__thread_uuid__in=mbu_threading_uuid) if resolved is None: pass else: msgs_resolved_uuid = Message.objects.filter(_resolved_by=None, thread_uuid__in=mbu_threading_uuid)\ .values_list('thread_uuid', flat=True) if resolved: mbus = mbus.exclude( msg_body__message__thread_uuid__in=list(msgs_resolved_uuid)) else: mbus = mbus.filter( msg_body__message__thread_uuid__in=list(msgs_resolved_uuid)) if read is None: pass else: mbus_unread = MessageBodyUserStatus.objects.filter(user=user,\ delete_flag=False, read_flag=False)\ .select_related('msg_body__message')\ .values_list('msg_body__message__thread_uuid', flat=True) if read: mbus = mbus.exclude( msg_body__message__thread_uuid__in=list(mbus_unread)) else: mbus = mbus.filter( msg_body__message__thread_uuid__in=list(mbus_unread)) mbu_dict = {} for mbu in mbus: if mbu.msg_body.message.thread_uuid not in mbu_dict: mbu_dict[mbu.msg_body.message.thread_uuid] = [mbu] else: mbu_dict[mbu.msg_body.message.thread_uuid].append(mbu) mbu_list = sorted(mbu_dict.values(), key=lambda item: item[0].msg_body.message.send_timestamp, reverse=True) query_count = len(mbu_list) ml = set() for v in mbu_list[offset * count:offset * count + count]: latest_msg = None mtd_msg_ids = set() senders = [] read_flag = True delete_flag = False resolution_flag = True last_resolved_by = None last_resolution_timestamp = 0 for m in v: if not latest_msg or m.msg_body.message.send_timestamp > latest_msg.send_timestamp: latest_msg = m.msg_body.message mtd_msg_ids.add(m.msg_body.message.id) ml.add(m.msg_body.message.id) senders.append({ 'id': m.msg_body.message.uuid, 'name': sender_name_safe(m.msg_body.message, m.sender_title) }) if m.msg_body.message.id in msg_id_list: read_flag = read_flag and m.read_flag if last_resolution_timestamp < m.msg_body.message.resolution_timestamp\ and m.msg_body.message._resolved_by: last_resolution_timestamp = m.msg_body.message.resolution_timestamp last_resolved_by = ' '.join([ m.msg_body.message._resolved_by.first_name, m.msg_body.message._resolved_by.last_name ]) if not m.msg_body.message._resolved_by_id: resolution_flag = False delete_flag = delete_flag or m.delete_flag msg = latest_msg msg.mtd_msg_ids = mtd_msg_ids msg.read_flag = read_flag msg.delete_flag = mbu.delete_flag msg.resolution_flag = resolution_flag msg.last_resolved_by = last_resolved_by msg.last_resolution_timestamp = last_resolution_timestamp msg.recipients_list = [] msg.ccs_list = [] msg.attachments = [] msg.sender_list = senders msg.sender_number = len(mtd_msg_ids) msg.refer_status = '' msg_list.append(msg) msg_reps = MessageRecipient.objects.filter(message__id__in=ml).select_related('message',\ 'user').extra(select={'title':'SELECT title FROM MHLUsers_mhluser \ WHERE MHLUsers_mhluser.user_ptr_id = Messaging_message_recipients.user_id' })\ .values('message__id', 'user__id', 'user__first_name', 'user__last_name','title') msg_ccs = MessageCC.objects.filter(message__id__in=ml).select_related('message',\ 'user').extra(select={'title':'SELECT title FROM MHLUsers_mhluser \ WHERE MHLUsers_mhluser.user_ptr_id = Messaging_message_ccs.user_id' })\ .values('message__id', 'user__id', 'user__first_name', 'user__last_name','title') msg_atts = MessageAttachment.objects.filter(message__id__in=ml).select_related('message')\ .values('uuid', 'suffix', 'size', 'filename', 'message__id') msg_refers = MessageRefer.objects.filter(message__id__in=ml).select_related('message__id')\ .values('message__id', 'status') for m in msg_list: for msg_rep in msg_reps: if msg_rep['message__id'] in m.mtd_msg_ids: rep_dict = { 'id': msg_rep['user__id'], 'name': get_fullname_bystr(msg_rep['user__last_name'], msg_rep['user__first_name'], msg_rep['title']) } if rep_dict not in m.recipients_list: m.recipients_list.append(rep_dict) for msg_cc in msg_ccs: if msg_cc['message__id'] in m.mtd_msg_ids: m.ccs_list.append({ 'id': m.uuid, 'name': get_fullname_bystr(msg_cc['user__last_name'], msg_cc['user__first_name'], msg_cc['title']) }) for msg_att in msg_atts: if msg_att['message__id'] in m.mtd_msg_ids: m.attachments.append({ 'id': msg_att['uuid'], 'suffix': msg_att['suffix'], 'size': msg_att['size'], 'filename': msg_att['filename'] }) for msg_refer in msg_refers: if msg_refer['message__id'] == m.id: m.refer_status = msg_refer['status'] msg_list.sort(key=lambda item: item.send_timestamp, reverse=True) return { 'total_count': total_msg_count, 'unread_count': unread_msg_count, 'query_count': query_count, 'msg_count': query_count, 'msgs': msg_list }
def message_view(request, message_id, type): """Process message view request: :param request: The HTTP message view request :type request: django.core.handlers.wsgi.WSGIRequest :param message_id: The message id :type message_id: int :returns: django.http.HttpResponse -- the JSON result in an HttpResonse object :raises: None """ resolved = request.GET['resolved'] thread_uuid = Message.objects.get(uuid=message_id).thread_uuid msgs = MessageBodyUserStatus.objects.filter(user=request.user, delete_flag=False, msg_body__message__thread_uuid=thread_uuid).order_by( '-msg_body__message__send_timestamp').\ select_related('msg_body', 'msg_body__message', 'msg_body__message__sender')\ .extra(select={'sender_title':"SELECT MHLUsers_mhluser.title \ FROM MHLUsers_mhluser INNER JOIN Messaging_message ON \ MHLUsers_mhluser.user_ptr_id = Messaging_message.sender_id \ INNER JOIN Messaging_messagebody ON \ Messaging_message.id = Messaging_messagebody.message_id \ WHERE Messaging_messagebody.id = Messaging_messagebodyuserstatus.msg_body_id"}) if (resolved == ''): pass elif str(resolved).lower() in ("true"): msgs = msgs.filter(msg_body__message__in=[m.msg_body.message for m in msgs if m.msg_body.message.resolved_by != None]) else: msgs = msgs.filter(msg_body__message__in=[m.msg_body.message for m in msgs if m.msg_body.message.resolved_by == None]) msgs.select_related('msg_body', 'msg_body__message', 'msg_body__message__sender',) msgs = list(msgs) context = get_context(request) user = request.session['MHL_Users']['MHLUser'] local_tz = getCurrentTimeZoneForUser(user, current_practice=context['current_practice']) is_received = type == 'received' current_user = getCurrentUserInfo(request) current_user_mobile = getCurrentUserMobile(current_user) call_enable = bool(current_user_mobile) and settings.CALL_ENABLE msgs_list = [] audio_list = [] for status_obj in msgs: try: read_flag = status_obj.read_flag body = decrypt_object(request, status_obj.msg_body) # TODO, this function need to refactor, when get threading message list, # don't need to decrypt every message body in the threading message. # When refactors, use following line while reading message body. # body = read_message(request, status_obj.msg_body) if not read_flag: status_obj.read_flag = read_flag status_obj.save() except KeyInvalidException: mail_admins(_('Message Body Decryption Error'), ''.join([ ('An error occurred decryption data for user '), request.user.username, (' on server '), settings.SERVER_ADDRESS, '.\n', ('Message ID: '), message_id ])) callbacks = CallbackLog.objects.filter(message=status_obj.msg_body.message).\ order_by('time').values('time') callbacks = [ { 'timestamp': _get_system_time_as_tz(c['time'], local_tz).strftime('%m/%d/%y %H:%M'), 'caller_name': 'Joe Bloggs', 'caller_id': 123, } for c in callbacks] msg_cc_maps = MessageCC.objects.filter(message=status_obj.msg_body.message).\ select_related('user').extra(select={'title':'SELECT title FROM MHLUsers_mhluser \ WHERE MHLUsers_mhluser.user_ptr_id = Messaging_message_ccs.user_id'})\ .only('user__first_name', 'user__last_name', 'message') ccs = '; '.join([get_fullname_bystr(msg_cc_map.user.last_name,\ msg_cc_map.user.first_name,msg_cc_map.title)\ for msg_cc_map in msg_cc_maps]) msg_to_maps = MessageRecipient.objects.filter(message=status_obj.msg_body.message).\ select_related('user').extra(select={'title':'SELECT title FROM MHLUsers_mhluser \ WHERE MHLUsers_mhluser.user_ptr_id = Messaging_message_recipients.user_id'})\ .only('user__first_name', 'user__last_name', 'message') recipients = '; '.join([get_fullname_bystr(msg_to_map.user.last_name,\ msg_to_map.user.first_name,msg_to_map.title)\ for msg_to_map in msg_to_maps]) to_recipient_ids = [] msg_sender = status_obj.msg_body.message.sender msg_sender_id = None if msg_sender: msg_sender_id = msg_sender.id to_recipient_ids.append(str(msg_sender_id)) for rec in msg_to_maps: if rec.user.id != request.user.id: to_recipient_ids.append(str(rec.user.id)) cc_recipient_ids = [] for cc in msg_cc_maps: cc_recipient_ids.append(str(cc.user.id)) is_read = status_obj.read_flag user_id = request.user.id read_recipients = [r.id for r in status_obj.msg_body.message.recipients.all()] read_ccs = [c.id for c in status_obj.msg_body.message.ccs.all()] if not is_read: if is_received: if user_id not in read_recipients + read_ccs: is_read = True else: if msg_sender_id != request.user.id: is_read = True is_sender = request.user.id == msg_sender_id if is_received and (request.user.id == msg_sender_id and user_id in read_recipients + read_ccs): is_sender = False result = { 'id':status_obj.msg_body.message.uuid, 'sender':sender_name_safe(status_obj.msg_body.message,title=status_obj.sender_title), 'sender_id':msg_sender_id, 'thread_uuid':status_obj.msg_body.message.thread_uuid, 'timestamp':formatTimeSetting(user, status_obj.msg_body.message.send_timestamp, local_tz), 'subject':conditional_escape(status_obj.msg_body.message.subject), 'body':replace_number(status_obj.msg_body.clear_data, call_enable), 'answering_service':status_obj.msg_body.message.message_type == 'ANS', 'callback_number': replace_number( status_obj.msg_body.message.callback_number, call_enable), 'callbacks': callbacks, 'urgent':status_obj.msg_body.message.urgent, 'ccs':ccs, 'recipients':recipients, 'to_recipient_ids':','.join(to_recipient_ids), 'cc_recipient_ids':','.join(cc_recipient_ids), 'is_sender':is_sender, 'is_resolved':status_obj.msg_body.message.resolved_by != None, 'read': 'true' if is_read else '' } attachments = MessageAttachment.objects.filter(message=status_obj.msg_body.message) result["attachments"] = [] for att in attachments: attach_dict = {'id': att.uuid, 'suffix': att.suffix, 'size': att.size, 'metadata': att.metadata, 'filename': att.decrypt_filename(request), 'msgId': status_obj.msg_body.message.uuid } result["attachments"].append(attach_dict) if att.suffix and att.suffix.lower() in ['mp3', 'wav']: audio_list.append(attach_dict) result["refer"] = _get_refer_from_mbus(status_obj, call_enable=call_enable) result["action_history"] = get_message_action_history( status_obj.msg_body.message.id, user, time_zone=local_tz) msgs_list.append(result) context['msgs'] = msgs_list context['audio_list'] = audio_list context['type'] = type return HttpResponse(render_to_string('DoctorCom/Messaging/MessageBody.html', context))
def sender_name_safe(message, title=None): if (message.sender): return get_fullname_bystr(message.sender.last_name, message.sender.first_name, title=title) else: return _('System Message')