def test_formatTimeSetting(self): ts_int = 1359456033 cmp_dt = datetime(2013, 01, 29, 10, 40, 33, 0) cmp_dt1 = cmp_dt.strftime('%m/%d/%y %I:%M %p') cmp_dt2 = cmp_dt.strftime('%m/%d/%y %H:%M') local_tz = ('utc') self.mhluser.time_setting = True self.assertEqual(cmp_dt1, formatTimeSetting(self.mhluser, ts_int, local_tz)) self.mhluser.time_setting = False self.assertEqual(cmp_dt2, formatTimeSetting(self.mhluser, ts_int, local_tz))
def rx_message_list_data(request, from_timestamp, to_timestamp, count, resolved, read=None, exclude_id=None, is_threading=True, use_time_setting=True, thread_uuid=None): user = request.user local_tz = getCurrentTimeZoneForUser(user) if thread_uuid: is_threading = False msg_data = rx_msgs_by_timestamp(user, from_ts=from_timestamp, to_ts=to_timestamp, count=count, resolved=resolved, read=read, exclude_id=exclude_id, is_threading=is_threading, thread_uuid=thread_uuid) return { 'messages': [ { 'id': msg.uuid, 'sender': { 'name' : msg.sender_list[0]['name'] if msg.sender else "System Message", 'id': msg.sender.id if msg.sender else 0, }, 'recipients': msg.recipients_list if is_threading else[{ 'name': ' '.join([ u.first_name, u.last_name]), 'id': u.id, } for u in msg.recipients_list], 'ccs': msg.ccs_list if is_threading else[{ 'name': ' '.join([ u.first_name, u.last_name]), 'id':u.id, }for u in msg.ccs_list], 'threading_msg_count': '' if not is_threading else msg.sender_number, 'timestamp': formatTimeSetting(user, msg.send_timestamp, local_tz, use_time_setting), 'send_timestamp': msg.send_timestamp, 'send_time': formatTimeSetting(user, msg.send_timestamp, local_tz, use_time_setting), 'subject': get_subject(mark_safe(msg.subject), msg.refer_status), 'read_flag': msg.read_flag, 'resolution_flag': msg.resolution_flag, 'attachments': bool(msg.attachments), 'message_type':msg.message_type if msg.message_type else 'NM', 'callback_number':msg.callback_number, 'urgent':bool(msg.urgent), 'refer':msg.refer_status, 'thread_uuid': msg.thread_uuid, # used for checking whether clear message detail's cache 'action_history_count': get_message_action_history_count(msg.id) } for msg in msg_data['msgs']], 'total_message_count': msg_data['total_count'], 'unread_message_count': msg_data['unread_count'], 'query_count': msg_data['query_count'], }
def member_org_show_invite(request): context = get_context_for_organization(request) current_org_id = request.org.id pendings = Pending_Org_Association.objects.filter(from_practicelocation__id=current_org_id) context['total_count'] = len(pendings) user = request.session['MHL_Users']['MHLUser'] local_tz = getCurrentTimeZoneForUser(user, \ current_practice=context['current_practice']) context['index'] = index = int(request.REQUEST.get('index', 0)) context['count'] = count = int(request.REQUEST.get('count', 10)) # get member organization invitations context['member_org_invitations'] = [{ 'pending_id': pending.id, 'to_id': pending.to_practicelocation.id, 'to_name': pending.to_practicelocation.practice_name, 'provider_count': Provider.active_objects.filter(\ Q(practices=pending.to_practicelocation)).count(), 'to_logo': ImageHelper.get_image_by_type(\ pending.to_practicelocation.practice_photo, "Small", "Practice"), 'create_date': formatTimeSetting(user, pending.create_time, local_tz) } for pending in pendings[index*count:(index+1)*count]] return render_to_response('MHLOrganization/MemberOrg/member_org_invite_list.html', context)
def get_text_from_messge(request, msg, msg_body, practice): user = request.session['MHL_Users']['MHLUser'] local_tz = getCurrentTimeZoneForUser(user, current_practice=practice) msg_to_maps = MessageRecipient.objects.filter(message=msg).select_related('user').\ only('user__first_name', 'user__last_name', 'message') to_list = '; '.join([ ' '.join([to.user.first_name, to.user.last_name]) for to in msg_to_maps ]) msg_cc_maps = MessageCC.objects.filter(message=msg).select_related('user').\ only('user__first_name', 'user__last_name', 'message') ccs_list = '; '.join([ ' '.join([msg_cc_map.user.first_name, msg_cc_map.user.last_name]) for msg_cc_map in msg_cc_maps ]) result = '\n\n\n---------------------------------------------------------------------------------------\n' result += _('From: ') + sender_name_safe(msg_body.message) + '\n' result += _('Date: ') + formatTimeSetting(user, msg.send_timestamp, local_tz) + '\n' if to_list: result += _('To: ') + to_list + '\n' if ccs_list: result += _('Cc: ') + ccs_list + '\n' result += _('Subject: ') + conditional_escape( msg_body.message.subject) + '\n' result += '\n' + msg_body.decrypt(request) + '\n' return result
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 list_invites(request): # if (request.method != 'POST'): # return err_GE002() user_type = int(request.user_type) if USER_TYPE_OFFICE_STAFF == user_type: return err403(request) invites = Invitation.objects.filter( sender=request.user).order_by('requestTimestamp') response = { 'data': { 'invitations': [] }, 'warnings': {}, } invite_list = response['data']['invitations'] 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) for invite in invites: desc = '' if not invite.assignPractice: desc = _('Invite to DoctorCom') else: desc = _('Invite to %s') % invite.assignPractice.practice_name invite_list.append({ 'id': invite.id, 'recipient': invite.recipient, 'timestamp': formatTimeSetting(user, invite.requestTimestamp, local_tz, use_time_setting), 'request_timestamp': convertDatetimeToUTCTimestamp(invite.requestTimestamp), 'desc': desc, 'code': invite.code, }) return HttpResponse(content=json.dumps(response), mimetype='application/json')
def refer_tracking_detail_ajax(request, userID): page_index = 1 items_per_page = 10 try: page_index = int(request.POST['page_index']) items_per_page = int(request.POST['items_per_page']) except: pass number_end = page_index * items_per_page number_begin = number_end - items_per_page if (request.method == 'POST'): form = ReferTrackingForm(request.POST) if form.is_valid(): period_type = form.cleaned_data['period_type'] period_radio = form.cleaned_data['period_radio'] period_from = form.cleaned_data['period_from'] period_to = form.cleaned_data['period_to'] if(period_radio == '0'): period_from, period_to = get_peirod(period_type) q_refer = Q() refer_list_all = MessageRefer.objects.all().order_by('message__send_timestamp') recipients = MessageRecipient.objects.values('message').filter(user=userID) r_recipients = [rep['message'] for rep in recipients] q_refer.add(Q(message__in=r_recipients), Q.AND) if period_from: q_refer.add(Q(message__send_timestamp__gte=int(time.mktime(period_from.timetuple()))), Q.AND) if period_to: period_to_cal = period_to + datetime.timedelta(days=1) q_refer.add(Q(message__send_timestamp__lt=int(time.mktime(period_to_cal.timetuple()))), Q.AND) user = request.session['MHL_Users']['MHLUser'] refer_list = [{ #'time':timezone_conversion(refer.message.send_timestamp, # timezone(settings.TIME_ZONE)).strftime('%m/%d/%y %H:%M'), 'time':formatTimeSetting(user, refer.message.send_timestamp, timezone(settings.TIME_ZONE)), 'sender':sender_name_safe(refer.message), 'practice': refer.practice.practice_name if refer.practice else '', 'recipients':', '.join([' '.join([u.first_name, u.last_name]) for u in refer.message.recipients.all()]), } for refer in refer_list_all.filter(q_refer)[number_begin:number_end]] return HttpResponse(json.dumps({ 'referCount': refer_list_all.filter(q_refer).count() or 0, 'refers': sorted(refer_list, key=lambda k: k['time'], reverse=True) }))
def resend_invite(request, invitation_id): if (request.method != 'POST'): return err_GE002() user_type = int(request.user_type) if USER_TYPE_OFFICE_STAFF == user_type: return err403(request) note = '' if (request.method == 'POST'): form = ResendInviteForm(request.POST) if (not form.is_valid()): return err_GE031(form) if ('note' in form.cleaned_data): note = form.cleaned_data['note'] try: invite = Invitation.objects.get(pk=invitation_id, sender=request.user) except Invitation.DoesNotExist: raise Http404 if User.objects.filter(email=invite.recipient).exists(): return err_IN002() invite.resend_invite(msg=note) 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) response = { 'data': { 'id': invite.id, 'timestamp': formatTimeSetting(user, invite.requestTimestamp, local_tz, use_time_setting), 'request_timestamp': convertDatetimeToUTCTimestamp(invite.requestTimestamp), }, 'warnings': {}, } return HttpResponse(content=json.dumps(response), mimetype='application/json')
def get_resolved_info(user, thread_uuid, resolved, local_tz=None): """get resolved information of the message threading, :param user: is an instance of User/MHLUser. :param thread_uuid: message's thread_uuid. :param resolved: is None or not None :param local_tz: timezone object or string :return { 'resolved': resolve status of message threading, 'last_resolution_timestamp': last resolve timestamp of message threading, if time_zone is None, then don't format timestamp. if time_zone has value, then format timastamp with the time_zone 'last_resolved_by': last resolver of message threading. } """ mbus = get_threading_mbus(user, resolved, thread_uuid, None) resolved = True last_resolved_by = None last_resolution_timestamp = 0 for m in mbus: if m.msg_body.message.resolved_by == None: resolved = False break if last_resolution_timestamp < m.msg_body.message.resolution_timestamp: 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 ]) mhluser = None if user: if isinstance(user, MHLUser): mhluser = user elif isinstance(user, User): mhluser = list(MHLUser.objects.filter(pk=user.pk)) if mhluser and len(mhluser) > 0: mhluser = mhluser[0] return { "resolved": resolved, "last_resolution_timestamp": formatTimeSetting(mhluser, last_resolution_timestamp, local_tz)\ if local_tz and mhluser and last_resolution_timestamp else last_resolution_timestamp, "last_resolved_by": last_resolved_by }
def get_resolved_info(user, thread_uuid, resolved, local_tz=None): """get resolved information of the message threading, :param user: is an instance of User/MHLUser. :param thread_uuid: message's thread_uuid. :param resolved: is None or not None :param local_tz: timezone object or string :return { 'resolved': resolve status of message threading, 'last_resolution_timestamp': last resolve timestamp of message threading, if time_zone is None, then don't format timestamp. if time_zone has value, then format timastamp with the time_zone 'last_resolved_by': last resolver of message threading. } """ mbus = get_threading_mbus(user, resolved, thread_uuid, None) resolved = True last_resolved_by = None last_resolution_timestamp = 0 for m in mbus: if m.msg_body.message.resolved_by == None: resolved = False break if last_resolution_timestamp < m.msg_body.message.resolution_timestamp: 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]) mhluser = None if user: if isinstance(user, MHLUser): mhluser = user elif isinstance(user, User): mhluser = list(MHLUser.objects.filter(pk=user.pk)) if mhluser and len(mhluser) > 0: mhluser = mhluser[0] return { "resolved": resolved, "last_resolution_timestamp": formatTimeSetting(mhluser, last_resolution_timestamp, local_tz)\ if local_tz and mhluser and last_resolution_timestamp else last_resolution_timestamp, "last_resolved_by": last_resolved_by }
def resend_invite(request, invitation_id): if (request.method != 'POST'): return err_GE002() user_type = int(request.user_type) if USER_TYPE_OFFICE_STAFF == user_type: return err403(request) note = '' if (request.method == 'POST'): form = ResendInviteForm(request.POST) if (not form.is_valid()): return err_GE031(form) if ('note' in form.cleaned_data): note = form.cleaned_data['note'] try: invite = Invitation.objects.get(pk=invitation_id, sender=request.user) except Invitation.DoesNotExist: raise Http404 if User.objects.filter(email=invite.recipient).exists(): return err_IN002() invite.resend_invite(msg=note) 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) response = { 'data': { 'id': invite.id, 'timestamp': formatTimeSetting(user, invite.requestTimestamp, local_tz, use_time_setting), 'request_timestamp': convertDatetimeToUTCTimestamp(invite.requestTimestamp), }, 'warnings': {}, } return HttpResponse(content=json.dumps(response), mimetype='application/json')
def member_org_show_org(request): context = get_context_for_organization(request) member_orgs = OrganizationMemberOrgs.objects.filter(\ from_practicelocation__pk=request.org.id)\ .select_related('to_practicelocation')\ .order_by('to_practicelocation__practice_name') qf = Q() context['search_input'] = "" if request.method == "POST": search_input = request.POST.get("search_input", "") if search_input: context['search_input'] = search_input qf = Q(to_practicelocation__practice_name__icontains=search_input) member_orgs = member_orgs.filter(qf) context['member_org_count'] = len(member_orgs) user = request.session['MHL_Users']['MHLUser'] local_tz = getCurrentTimeZoneForUser(user, \ current_practice=context['current_practice']) context['index'] = index = int(request.REQUEST.get('index', 0)) context['count'] = count = int(request.REQUEST.get('count', 10)) return_set = [{ 'id': mo.id, 'to_name': mo.to_practicelocation.practice_name, 'provider_count': Provider.active_objects.filter(\ Q(practices=mo.to_practicelocation)).count(), 'to_logo': ImageHelper.get_image_by_type(\ mo.to_practicelocation.practice_photo, "Small", "Practice"), 'create_date': formatTimeSetting(user, mo.create_time, local_tz), 'billing_flag': mo.billing_flag } for mo in member_orgs[index*count:(index+1)*count]] context['member_orgs'] = return_set return render_to_response('MHLOrganization/MemberOrg/member_org_list.html', context)
def list_invites(request): # if (request.method != 'POST'): # return err_GE002() user_type = int(request.user_type) if USER_TYPE_OFFICE_STAFF == user_type: return err403(request) invites = Invitation.objects.filter(sender=request.user).order_by('requestTimestamp') response = { 'data': {'invitations':[]}, 'warnings': {}, } invite_list = response['data']['invitations'] 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) for invite in invites: desc = '' if not invite.assignPractice: desc = _('Invite to DoctorCom') else: desc = _('Invite to %s') % invite.assignPractice.practice_name invite_list.append({ 'id': invite.id, 'recipient': invite.recipient, 'timestamp': formatTimeSetting(user, invite.requestTimestamp, local_tz, use_time_setting), 'request_timestamp': convertDatetimeToUTCTimestamp(invite.requestTimestamp), 'desc' : desc, 'code': invite.code, }) return HttpResponse(content=json.dumps(response), mimetype='application/json')
def get_text_from_messge(request, msg, msg_body, practice): user = request.session['MHL_Users']['MHLUser'] local_tz = getCurrentTimeZoneForUser(user, current_practice=practice) msg_to_maps = MessageRecipient.objects.filter(message=msg).select_related('user').\ only('user__first_name', 'user__last_name', 'message') to_list = '; '.join([' '.join([to.user.first_name, to.user.last_name]) for to in msg_to_maps]) msg_cc_maps = MessageCC.objects.filter(message=msg).select_related('user').\ only('user__first_name', 'user__last_name', 'message') ccs_list = '; '.join([' '.join([msg_cc_map.user.first_name, msg_cc_map.user.last_name]) for msg_cc_map in msg_cc_maps]) result = '\n\n\n---------------------------------------------------------------------------------------\n' result += _('From: ') + sender_name_safe(msg_body.message) + '\n' result += _('Date: ') + formatTimeSetting(user, msg.send_timestamp, local_tz) + '\n' if to_list: result += _('To: ') + to_list + '\n' if ccs_list: result += _('Cc: ') + ccs_list + '\n' result += _('Subject: ') + conditional_escape(msg_body.message.subject) + '\n' result += '\n' + msg_body.decrypt(request) + '\n' return result
def refer_tracking_detail_ajax(request, userID): page_index = 1 items_per_page = 10 try: page_index = int(request.POST['page_index']) items_per_page = int(request.POST['items_per_page']) except: pass number_end = page_index * items_per_page number_begin = number_end - items_per_page if (request.method == 'POST'): form = ReferTrackingForm(request.POST) if form.is_valid(): period_type = form.cleaned_data['period_type'] period_radio = form.cleaned_data['period_radio'] period_from = form.cleaned_data['period_from'] period_to = form.cleaned_data['period_to'] if (period_radio == '0'): period_from, period_to = get_peirod(period_type) q_refer = Q() refer_list_all = MessageRefer.objects.all().order_by( 'message__send_timestamp') recipients = MessageRecipient.objects.values('message').filter(user=userID) r_recipients = [rep['message'] for rep in recipients] q_refer.add(Q(message__in=r_recipients), Q.AND) if period_from: q_refer.add( Q(message__send_timestamp__gte=int( time.mktime(period_from.timetuple()))), Q.AND) if period_to: period_to_cal = period_to + datetime.timedelta(days=1) q_refer.add( Q(message__send_timestamp__lt=int( time.mktime(period_to_cal.timetuple()))), Q.AND) user = request.session['MHL_Users']['MHLUser'] refer_list = [ { #'time':timezone_conversion(refer.message.send_timestamp, # timezone(settings.TIME_ZONE)).strftime('%m/%d/%y %H:%M'), 'time': formatTimeSetting(user, refer.message.send_timestamp, timezone(settings.TIME_ZONE)), 'sender': sender_name_safe(refer.message), 'practice': refer.practice.practice_name if refer.practice else '', 'recipients': ', '.join([ ' '.join([u.first_name, u.last_name]) for u in refer.message.recipients.all() ]), } for refer in refer_list_all.filter(q_refer)[number_begin:number_end] ] return HttpResponse( json.dumps({ 'referCount': refer_list_all.filter(q_refer).count() or 0, 'refers': sorted(refer_list, key=lambda k: k['time'], reverse=True) }))
def new_invite(request): if (request.method != 'POST'): return err_GE002() user_type = int(request.user_type) role_user = request.role_user if USER_TYPE_OFFICE_STAFF == user_type: return err403(request) form = NewInviteForm(request.POST) if (not form.is_valid()): return err_GE031(form) invite_user_type = int(form.cleaned_data['invite_user_type']) invite_type = int(form.cleaned_data['invite_type']) recipient = form.cleaned_data['email'] if USER_TYPE_OFFICE_MANAGER != user_type and 2 == invite_type: return err403(request) if User.objects.filter(email=recipient).exists(): return err_IN002() note = '' if ('note' in form.cleaned_data and form.cleaned_data['note']): note = form.cleaned_data['note'] # if (Invitation.objects.filter(recipient=form.cleaned_data['email']).exists()): # err_obj = { # 'errno': 'IN001', # 'descr': _('Recipient already has an outstanding invitation'), # } # return HttpResponseBadRequest(content=json.dumps(err_obj), mimetype='application/json') current_practice = role_user.current_practice invites = Invitation.objects.filter(sender=request.user, recipient=form.cleaned_data['email'], userType=invite_user_type) if 2 == invite_type and current_practice: invites = invites.filter(assignPractice=current_practice) else: invites = invites.filter(assignPractice=None) if (len(invites) > 0): invite = invites[0] invite.resend_invite(msg=note) else: invite = Invitation( sender=request.user, recipient=recipient, userType=invite_user_type, ) if 2 == invite_type and current_practice: invite.assignPractice = current_practice invite.save() invite.email_invite(msg=note) 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) response = { 'data': { 'id': invite.id, 'timestamp': formatTimeSetting(user, invite.requestTimestamp, local_tz, use_time_setting), 'request_timestamp': convertDatetimeToUTCTimestamp(invite.requestTimestamp), }, 'warnings': {}, } return HttpResponse(content=json.dumps(response), mimetype='application/json')
def getMessageLogic(request, message_id, ss=None): if (request.method != 'POST'): return err_GE002() msgs = list( MessageBodyUserStatus.objects.filter( user=request.user, delete_flag=False, msg_body__message__uuid=message_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 local_tz = timezone(settings.TIME_ZONE) status_obj = msgs[0] body = None try: # Get/set up data for KMS. request.session['key'] = request.device_assn.secret body = read_message(request, status_obj.msg_body, ss=ss) except KeyInvalidException: return err_GE021() if not body: return err_GE021() current_user = request.mhluser current_user_mobile = current_user.mobile_phone msg = status_obj.msg_body.message recipients = MessageRecipient.objects.filter(message__uuid=message_id).\ select_related('user').only('user__first_name', 'user__last_name') ccs = MessageCC.objects.filter(message__uuid=message_id).\ select_related('user').only('user__first_name', 'user__last_name') attachments = MessageAttachment.objects.filter(message=msg) ccs = MessageCC.objects.filter(message__uuid=message_id).select_related('user').\ only('user__first_name', 'user__last_name', 'message') user = request.mhluser local_tz = getCurrentTimeZoneForUser(user) data = { 'body': body, 'timestamp': formatTimeSetting(user, msg.send_timestamp, local_tz), 'sender': { 'name': ' '.join([ msg.sender.first_name, msg.sender.last_name]) \ if msg.sender else "System Message", 'id': msg.sender.id if msg.sender else 0, }, 'recipients': [{ 'name': ' '.join([ u.user.first_name, u.user.last_name]), 'id': u.user.id, } for u in recipients], 'ccs': [{ 'name': ' '.join([ u.user.first_name, u.user.last_name]), 'id': u.user.id, } for u in ccs], 'attachments': [ { 'id': att.uuid, 'filename': _get_attachment_filename(request, att, ss=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 } return HttpJSONSuccessResponse(data=data)
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_messages(request, type): """get_messages request: :param request: The HTTP update message request :type request: django.core.handlers.wsgi.WSGIRequest :param typ: The message id :type type: string :returns: django.http.HttpResponse -- the JSON result in an HttpResonse object :raises: None """ if (type != 'Sent' and type != 'Received'): raise Http404() request_data = request.REQUEST offset_form = MessageFetchForm_Offset(request_data) timestamp_form = MessageFetchForm_Timestamp(request_data) offset_form_validity = offset_form.is_valid() timestamp_form_validity = timestamp_form.is_valid() if (not offset_form_validity and not timestamp_form_validity): raise Exception(_('Invalid request')) if (offset_form_validity): form = offset_form else: form = timestamp_form request_time = int(time.time()) - 1 resolved = None if ('resolved' in request_data): resolved = form.cleaned_data['resolved'] user = request.session['MHL_Users']['MHLUser'] context = get_context(request) local_tz = getCurrentTimeZoneForUser( user, current_practice=context['current_practice']) count = 20 offset = 0 from_ts = None if (offset_form_validity): count = form.cleaned_data['count'] offset = form.cleaned_data['offset'] else: from_ts = form.cleaned_data['timestamp'] is_received_msg = type == 'Received' msg_data = get_msgs_for_threading(request.user, from_ts=from_ts, count=count, resolved=resolved, is_received_msg=is_received_msg, offset=offset) msgs = [{ 'id': msg.uuid, 'recipients': get_name_from_list(msg.recipients_list + msg.ccs_list), 'sender': get_name_from_list(msg.sender_list), 'sender_number': msg.sender_number, 'sender_id': sender_pk_safe(msg), 'subject': get_subject(msg.subject, msg.refer_status), 'timestamp': formatTimeSetting(user, msg.send_timestamp, local_tz), 'resolved': msg.resolution_flag, 'last_resolved_by': msg.last_resolved_by, 'last_resolution_timestamp': formatTimeSetting(user, msg.last_resolution_timestamp, local_tz), 'read': msg.read_flag, 'attachments': msg.attachments, 'urgent': msg.urgent, 'message_type': msg.message_type, 'callback_number': msg.callback_number, 'refer': msg.refer_status, 'thread_uuid': msg.thread_uuid, } for msg in msg_data['msgs']] return HttpResponse( json.dumps({ 'count': msg_data['query_count'], 'msgs': msgs, 'request_timestamp': request_time, 'unreadMsgs': msg_data['unread_count'] }))
def getMessageLogic(request, message_id, ss=None): if (request.method != 'POST'): return err_GE002() msgs = list(MessageBodyUserStatus.objects.filter(user=request.user, delete_flag=False, msg_body__message__uuid=message_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 local_tz = timezone(settings.TIME_ZONE) status_obj = msgs[0] body = None try: # Get/set up data for KMS. request.session['key'] = request.device_assn.secret body = read_message(request, status_obj.msg_body, ss=ss) except KeyInvalidException: return err_GE021() if not body: return err_GE021() current_user = request.mhluser current_user_mobile = current_user.mobile_phone msg = status_obj.msg_body.message recipients = MessageRecipient.objects.filter(message__uuid=message_id).\ select_related('user').only('user__first_name', 'user__last_name') ccs = MessageCC.objects.filter(message__uuid=message_id).\ select_related('user').only('user__first_name', 'user__last_name') attachments = MessageAttachment.objects.filter(message=msg) ccs = MessageCC.objects.filter(message__uuid=message_id).select_related('user').\ only('user__first_name', 'user__last_name', 'message') user = request.mhluser local_tz = getCurrentTimeZoneForUser(user) data = { 'body': body, 'timestamp': formatTimeSetting(user, msg.send_timestamp, local_tz), 'sender': { 'name': ' '.join([ msg.sender.first_name, msg.sender.last_name]) \ if msg.sender else "System Message", 'id': msg.sender.id if msg.sender else 0, }, 'recipients': [{ 'name': ' '.join([ u.user.first_name, u.user.last_name]), 'id': u.user.id, } for u in recipients], 'ccs': [{ 'name': ' '.join([ u.user.first_name, u.user.last_name]), 'id': u.user.id, } for u in ccs], 'attachments': [ { 'id': att.uuid, 'filename': _get_attachment_filename(request, att, ss=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 } return HttpJSONSuccessResponse(data=data)
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 tx_message_list_data(request, from_timestamp, to_timestamp, count, resolved, exclude_id=None, is_threading=True, use_time_setting=True, thread_uuid=None): user = request.user local_tz = getCurrentTimeZoneForUser(user) if thread_uuid: is_threading = False msg_data = tx_msgs_by_timestamp(user, from_ts=from_timestamp, to_ts=to_timestamp, count=count, resolved=resolved, exclude_id=exclude_id, is_threading=is_threading, thread_uuid=thread_uuid) return { 'messages': [ { 'id': msg.uuid, 'sender': { 'name': (msg.sender_list[0]['name'] if msg.sender else "System Message") if is_threading else (' '.join([msg.sender.first_name, msg.sender.last_name]) if msg.sender else "System Message"), 'id': msg.sender.id if msg.sender else 0, }, 'recipients': msg.recipients_list if is_threading else [{ 'name': ' '.join([u.first_name, u.last_name]), 'id': u.id, } for u in msg.recipients_list], 'ccs': msg.ccs_list if is_threading else [{ 'name': ' '.join([u.first_name, u.last_name]), 'id': u.id, } for u in msg.ccs_list], 'timestamp': formatTimeSetting(user, msg.send_timestamp, local_tz, use_time_setting), 'send_timestamp': msg.send_timestamp, 'send_time': formatTimeSetting(user, msg.send_timestamp, local_tz, use_time_setting), 'subject': get_subject(mark_safe(msg.subject), msg.refer_status), 'read_flag': msg.read_flag, 'resolution_flag': msg.resolution_flag, 'attachments': bool(msg.attachments), 'urgent': bool(msg.urgent), 'refer': msg.refer_status, 'thread_uuid': msg.thread_uuid, 'threading_msg_count': '' if not is_threading else msg.sender_number, # used for checking whether clear message detail's cache 'action_history_count': get_message_action_history_count(msg.id) } for msg in msg_data['msgs'] ], 'total_message_count': msg_data['total_count'], 'unread_message_count': msg_data['unread_count'], 'query_count': msg_data['query_count'], }
def get_messages(request, type): """get_messages request: :param request: The HTTP update message request :type request: django.core.handlers.wsgi.WSGIRequest :param typ: The message id :type type: string :returns: django.http.HttpResponse -- the JSON result in an HttpResonse object :raises: None """ if (type != 'Sent' and type != 'Received'): raise Http404() request_data = request.REQUEST offset_form = MessageFetchForm_Offset(request_data) timestamp_form = MessageFetchForm_Timestamp(request_data) offset_form_validity = offset_form.is_valid() timestamp_form_validity = timestamp_form.is_valid() if (not offset_form_validity and not timestamp_form_validity): raise Exception(_('Invalid request')) if (offset_form_validity): form = offset_form else: form = timestamp_form request_time = int(time.time()) - 1 resolved = None if ('resolved' in request_data): resolved = form.cleaned_data['resolved'] user = request.session['MHL_Users']['MHLUser'] context = get_context(request) local_tz = getCurrentTimeZoneForUser(user, current_practice=context['current_practice']) count = 20 offset = 0 from_ts = None if (offset_form_validity): count = form.cleaned_data['count'] offset = form.cleaned_data['offset'] else: from_ts = form.cleaned_data['timestamp'] is_received_msg = type == 'Received' msg_data = get_msgs_for_threading(request.user, from_ts=from_ts, count=count, resolved=resolved, is_received_msg=is_received_msg, offset=offset) msgs = [ { 'id': msg.uuid, 'recipients': get_name_from_list(msg.recipients_list + msg.ccs_list), 'sender': get_name_from_list(msg.sender_list), 'sender_number':msg.sender_number, 'sender_id':sender_pk_safe(msg), 'subject':get_subject(msg.subject, msg.refer_status), 'timestamp':formatTimeSetting(user, msg.send_timestamp, local_tz), 'resolved': msg.resolution_flag, 'last_resolved_by': msg.last_resolved_by, 'last_resolution_timestamp': formatTimeSetting(user, msg.last_resolution_timestamp, local_tz), 'read':msg.read_flag, 'attachments':msg.attachments, 'urgent':msg.urgent, 'message_type': msg.message_type, 'callback_number': msg.callback_number, 'refer': msg.refer_status, 'thread_uuid':msg.thread_uuid, } for msg in msg_data['msgs'] ] return HttpResponse(json.dumps({ 'count': msg_data['query_count'], 'msgs': msgs, 'request_timestamp': request_time, 'unreadMsgs': msg_data['unread_count'] }))
def new_invite(request): if (request.method != 'POST'): return err_GE002() user_type = int(request.user_type) role_user = request.role_user if USER_TYPE_OFFICE_STAFF == user_type: return err403(request) form = NewInviteForm(request.POST) if (not form.is_valid()): return err_GE031(form) invite_user_type = int(form.cleaned_data['invite_user_type']) invite_type = int(form.cleaned_data['invite_type']) recipient = form.cleaned_data['email'] if USER_TYPE_OFFICE_MANAGER != user_type and 2 == invite_type: return err403(request) if User.objects.filter(email=recipient).exists(): return err_IN002() note = '' if ('note' in form.cleaned_data and form.cleaned_data['note']): note = form.cleaned_data['note'] # if (Invitation.objects.filter(recipient=form.cleaned_data['email']).exists()): # err_obj = { # 'errno': 'IN001', # 'descr': _('Recipient already has an outstanding invitation'), # } # return HttpResponseBadRequest(content=json.dumps(err_obj), mimetype='application/json') current_practice = role_user.current_practice invites = Invitation.objects.filter(sender=request.user, recipient=form.cleaned_data['email'], userType=invite_user_type) if 2 == invite_type and current_practice: invites = invites.filter(assignPractice=current_practice) else: invites = invites.filter(assignPractice=None) if (len(invites) > 0): invite = invites[0] invite.resend_invite(msg=note) else: invite = Invitation( sender=request.user, recipient=recipient, userType=invite_user_type, ) if 2 == invite_type and current_practice: invite.assignPractice = current_practice invite.save() invite.email_invite(msg=note) 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) response = { 'data': { 'id':invite.id, 'timestamp': formatTimeSetting(user, invite.requestTimestamp, local_tz, use_time_setting), 'request_timestamp': convertDatetimeToUTCTimestamp(invite.requestTimestamp), }, 'warnings': {}, } return HttpResponse(content=json.dumps(response), mimetype='application/json')
def broker_tracking_ajax_message(request): broker_from = -1 broker_to_name = '' broker_to = '' directions = 1 period_from = '' period_to = '' page_index = 1 items_per_page = 10 try: page_index = int(request.POST['page_index']) items_per_page = int(request.POST['items_per_page']) except: pass number_end = page_index * items_per_page number_begin = number_end - items_per_page broker_list = [broker.user.id for broker in Broker.objects.all()] if (request.method == 'POST'): form = BrokerQueryForm(request.POST) if form.is_valid(): broker_from = int(form.cleaned_data['broker_from']) broker_to_name = form.cleaned_data['broker_to'] directions = int(form.cleaned_data['directions']) period_from = form.cleaned_data['period_from'] period_to = form.cleaned_data['period_to'] broker_to = get_id_by_name(broker_to_name) message_list_all = Message.objects.all().select_related('recipients') q_message = Q() if broker_from == -1: q_message.add(Q(sender__in=broker_list), Q.OR) q_message.add(Q(recipients__in=broker_list), Q.OR) if directions == 2: q_message.add(Q(recipients__in=broker_list), Q.AND) elif directions == 3: q_message.add(Q(sender__in=broker_list), Q.AND) else: q_message.add(Q(sender=broker_from), Q.OR) q_message.add(Q(recipients=broker_from), Q.OR) if directions == 2: q_message.add(Q(recipients=broker_from), Q.AND) elif directions == 3: q_message.add(Q(sender=broker_from), Q.AND) if broker_to_name: q_message.add(Q(sender=broker_to) | Q(recipients=broker_to), Q.AND) if directions == 2: q_message.add(Q(sender=broker_to), Q.AND) elif directions == 3: q_message.add(Q(recipients=broker_to), Q.AND) if period_from: q_message.add( Q(send_timestamp__gte=int(time.mktime(period_from.timetuple()))), Q.AND) if period_to: period_to_cal = period_to + datetime.timedelta(days=1) q_message.add( Q(send_timestamp__lt=int(time.mktime(period_to_cal.timetuple()))), Q.AND) user = request.session['MHL_Users']['MHLUser'] local_tz = getCurrentTimeZoneForUser(user) message_list = [{ 'time': formatTimeSetting(user, str(msg.send_timestamp), local_tz), 'sender': sender_name_safe(msg), 'recipients': ', '.join([ ' '.join([u.first_name, u.last_name]) for u in msg.recipients.all() ]), } for msg in message_list_all.filter(q_message)[number_begin:number_end]] return HttpResponse( json.dumps({ 'messageCount': message_list_all.filter(q_message).count(), 'messages': message_list }))
def broker_tracking_ajax_message(request): broker_from = -1 broker_to_name = '' broker_to = '' directions = 1 period_from = '' period_to = '' page_index = 1 items_per_page = 10 try: page_index = int(request.POST['page_index']) items_per_page = int(request.POST['items_per_page']) except: pass number_end = page_index * items_per_page number_begin = number_end - items_per_page broker_list = [broker.user.id for broker in Broker.objects.all()] if (request.method == 'POST'): form = BrokerQueryForm(request.POST) if form.is_valid(): broker_from = int(form.cleaned_data['broker_from']) broker_to_name = form.cleaned_data['broker_to'] directions = int(form.cleaned_data['directions']) period_from = form.cleaned_data['period_from'] period_to = form.cleaned_data['period_to'] broker_to = get_id_by_name(broker_to_name) message_list_all = Message.objects.all().select_related('recipients') q_message = Q() if broker_from == -1: q_message.add(Q(sender__in=broker_list), Q.OR) q_message.add(Q(recipients__in=broker_list), Q.OR) if directions == 2: q_message.add(Q(recipients__in=broker_list), Q.AND) elif directions == 3: q_message.add(Q(sender__in=broker_list), Q.AND) else: q_message.add(Q(sender=broker_from), Q.OR) q_message.add(Q(recipients=broker_from), Q.OR) if directions == 2: q_message.add(Q(recipients=broker_from), Q.AND) elif directions == 3: q_message.add(Q(sender=broker_from), Q.AND) if broker_to_name: q_message.add(Q(sender=broker_to) | Q(recipients=broker_to), Q.AND) if directions == 2: q_message.add(Q(sender=broker_to), Q.AND) elif directions == 3: q_message.add(Q(recipients=broker_to), Q.AND) if period_from: q_message.add(Q(send_timestamp__gte=int(time.mktime(period_from.timetuple()))), Q.AND) if period_to: period_to_cal = period_to + datetime.timedelta(days=1) q_message.add(Q(send_timestamp__lt=int(time.mktime(period_to_cal.timetuple()))), Q.AND) user = request.session['MHL_Users']['MHLUser'] local_tz = getCurrentTimeZoneForUser(user) message_list = [{ 'time':formatTimeSetting(user, str(msg.send_timestamp), local_tz), 'sender':sender_name_safe(msg), 'recipients':', '.join([' '.join([ u.first_name, u.last_name ]) for u in msg.recipients.all()]), } for msg in message_list_all.filter(q_message)[number_begin:number_end]] return HttpResponse(json.dumps({ 'messageCount': message_list_all.filter(q_message).count(), 'messages': message_list }))
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 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))