def message_detail(request, username, page=1, paginate_by=10, template_name="umessages/message_detail.html", extra_context=None, **kwargs): """ Returns a conversation between two users :param username: String containing the username of :class:`User` of whom the conversation is with. :param page: Integer of the active page used for pagination. Defaults to the first page. :param paginate_by: Integer defining the amount of displayed messages per page. Defaults to 50 messages per per page. :param extra_context: Dictionary of variables that will be made available to the template. :param template_name: String of the template that is rendered to display this view. If the result is paginated, the context will also contain the following variables. ``paginator`` An instance of ``django.core.paginator.Paginator``. ``page_obj`` An instance of ``django.core.paginator.Page``. """ recipient = get_object_or_404(User, username__iexact=username) queryset = Message.objects.get_conversation_between( request.user, recipient) # Update all the messages that are unread. message_pks = [m.pk for m in queryset] unread_list = MessageRecipient.objects.filter(message__in=message_pks, user=request.user, read_at__isnull=True) now = get_datetime_now() unread_list.update(read_at=now) if not extra_context: extra_context = dict() extra_context['recipient'] = recipient return list_detail.object_list(request, queryset=queryset, paginate_by=paginate_by, page=page, template_name=template_name, extra_context=extra_context, template_object_name="message", **kwargs)
def read(self, request,): """ 与某人的沟通记录 ``GET`` `messages/history/ <http://192.168.1.222:8080/v1/messages/history>`_ :param uid: 用户 id """ params = request.GET user_id = request.GET.get("uid") try: recipient = User.objects.get(pk=user_id) except User.DoesNotExist: return rc.NOT_HERE messages = Message.objects.get_conversation_between(request.user, recipient) # Update all the messages that are unread. message_pks = [m.pk for m in messages] unread_list = MessageRecipient.objects.filter(message__in=message_pks, user=request.user, read_at__isnull=True) now = get_datetime_now() unread_list.update(read_at=now) return query_range_filter(params, messages, "messages")
def delete_message(request): """删除消息""" message_pks = request.POST.getlist('message_pks') if message_pks: # Check that all values are integers. valid_message_pk_list = set() for pk in message_pks: try: valid_pk = int(pk) except (TypeError, ValueError): pass else: valid_message_pk_list.add(valid_pk) # Delete all the messages, if they belong to the user. now = get_datetime_now() changed_message_list = set() for pk in valid_message_pk_list: message = get_object_or_404(MessageRecipient, pk=pk).message # Check if the user is the owner if message.sender == request.user: message.sender_deleted_at = now message.save() changed_message_list.add(message.pk) # Check if the user is a recipient of the message if request.user in message.recipients.all(): mr = message.messagerecipient_set.get(user=request.user, message=message) mr.deleted_at = now mr.save() changed_message_list.add(message.pk) if changed_message_list: messages.success(request, u"删除消息成功") return redirect("oa_message_list")
def delete(self, request): """ 删除一条信息 ``POST`` `messages/destroy/ <http://192.168.1.222:8080/v1/messages/destroy>`_ :param id: 该信息的 id """ message_id = request.POST.get("id") if not message_id: return rc.BAD_REQUEST try: message = Message.objects.get(pk=message_id) except Message.DoesNotExist: return rc.NOT_HERE now = get_datetime_now() if message.sender == request.user: message.sender_deleted_at = now message.save() if request.user in message.recipients.all(): mr = message.messagerecipient_set.get(user=request.user, message=message) mr.deleted_at = now mr.save() return rc.accepted({"result": True})
def _update_unread_messages(self, queryset): message_pks = [m.pk for m in queryset] unread_list = MessageRecipient.objects.filter( message__in=message_pks, user=self.request.user, read_at__isnull=True ) now = get_datetime_now() unread_list.update(read_at=now)
def _update_unread_messages(self, queryset): message_pks = [m.pk for m in queryset] unread_list = MessageRecipient.objects.filter(message__in=message_pks, user=self.request.user, read_at__isnull=True) now = get_datetime_now() unread_list.update(read_at=now)
def create_user(self, username, email, password, active=False, send_email=True): """ A simple wrapper that creates a new :class:`User`. :param username: String containing the username of the new user. :param email: String containing the email address of the new user. :param password: String containing the password for the new user. :param active: Boolean that defines if the user requires activation by clicking on a link in an e-mail. Defaults to ``False``. :param send_email: Boolean that defines if the user should be sent an email. You could set this to ``False`` when you want to create a user in your own code, but don't want the user to activate through email. :return: :class:`User` instance representing the new user. """ now = get_datetime_now() new_user = get_user_model().objects.create_user( username, email, password) new_user.is_active = active new_user.save() userena_profile = self.create_userena_profile(new_user) # All users have an empty profile profile_model = get_profile_model() try: new_profile = new_user.get_profile() except profile_model.DoesNotExist: new_profile = profile_model(user=new_user) new_profile.save(using=self._db) # Give permissions to view and change profile for perm in ASSIGNED_PERMISSIONS['profile']: assign(perm[0], new_user, new_profile) # Give permissions to view and change itself for perm in ASSIGNED_PERMISSIONS['user']: assign(perm[0], new_user, new_user) if send_email: userena_profile.send_activation_email() return new_user
def create_user(self, username, email, password, active=False, send_email=True, first_name=None, last_name=None): """ A simple wrapper that creates a new :class:`User`. :param username: String containing the username of the new user. :param email: String containing the email address of the new user. :param password: String containing the password for the new user. :param active: Boolean that defines if the user requires activation by clicking on a link in an e-mail. Defaults to ``False``. :param send_email: Boolean that defines if the user should be sent an email. You could set this to ``False`` when you want to create a user in your own code, but don't want the user to activate through email. :return: :class:`User` instance representing the new user. """ now = get_datetime_now() new_user = User.objects.create_user(username, email, password) new_user.is_active = active if first_name is not None: new_user.first_name = first_name if last_name is not None: new_user.last_name = last_name new_user.save() userena_profile = self.create_userena_profile(new_user) # All users have an empty profile profile_model = get_profile_model() try: new_profile = new_user.get_profile() except profile_model.DoesNotExist: new_profile = profile_model(user=new_user) new_profile.save(using=self._db) # Give permissions to view and change profile for perm in ASSIGNED_PERMISSIONS['profile']: assign(perm[0], new_user, new_profile) # Give permissions to view and change itself for perm in ASSIGNED_PERMISSIONS['user']: assign(perm[0], new_user, new_user) if send_email: userena_profile.send_activation_email() return new_user
def message_detail(request, username, page=1, paginate_by=10, template_name="umessages/message_detail.html", extra_context=None, **kwargs): """ Returns a conversation between two users :param username: String containing the username of :class:`User` of whom the conversation is with. :param page: Integer of the active page used for pagination. Defaults to the first page. :param paginate_by: Integer defining the amount of displayed messages per page. Defaults to 50 messages per per page. :param extra_context: Dictionary of variables that will be made available to the template. :param template_name: String of the template that is rendered to display this view. If the result is paginated, the context will also contain the following variables. ``paginator`` An instance of ``django.core.paginator.Paginator``. ``page_obj`` An instance of ``django.core.paginator.Page``. """ recipient = get_object_or_404(User, username__iexact=username) queryset = Message.objects.get_conversation_between(request.user, recipient) # Update all the messages that are unread. message_pks = [m.pk for m in queryset] unread_list = MessageRecipient.objects.filter(message__in=message_pks, user=request.user, read_at__isnull=True) now = get_datetime_now() unread_list.update(read_at=now) if not extra_context: extra_context = dict() extra_context['recipient'] = recipient return list_detail.object_list(request, queryset=queryset, paginate_by=paginate_by, page=page, template_name=template_name, extra_context=extra_context, template_object_name="message", **kwargs)
def post(self, request): user = request.user new_email = request.data.get('email', None) try: if not new_email: raise AccountException(constants.INVALID_PARAMETERS) if new_email.lower() == user.email: raise AccountException(constants.EMAIL_NOT_CHANGED) if User.objects.filter(email__iexact=new_email): raise AccountException(constants.EMAIL_IN_USE) # the following is a rewritten version of user.userena_signup.change_email(new_email) user.userena_signup.email_unconfirmed = new_email salt, hash = generate_sha1(user.username) user.userena_signup.email_confirmation_key = hash user.userena_signup.email_confirmation_key_created = get_datetime_now() user.userena_signup.save() # the purpose is rewriting the following part where the emails are sent out email_change_url = settings.USER_BASE_URL +\ settings.MAIL_EMAIL_CHANGE_CONFIRM_URL.format(user.userena_signup.email_confirmation_key) context = { 'user': user, 'email_change_url': email_change_url } # mail to new email account mails.send_mail( subject_template_name=settings.MAIL_CHANGE_EMAIL_NEW_SUBJECT, email_template_name=settings.MAIL_CHANGE_EMAIL_NEW_TEXT, html_email_template_name=settings.MAIL_CHANGE_EMAIL_NEW_HTML, to_email=user.userena_signup.email_unconfirmed, from_email=settings.BEAM_MAIL_ADDRESS, context=context ) context['support'] = settings.BEAM_SUPPORT_MAIL_ADDRESS context['new_email'] = user.userena_signup.email_unconfirmed # mail to old email account mails.send_mail( subject_template_name=settings.MAIL_CHANGE_EMAIL_OLD_SUBJECT, email_template_name=settings.MAIL_CHANGE_EMAIL_OLD_TEXT, html_email_template_name=settings.MAIL_CHANGE_EMAIL_OLD_HTML, to_email=user.email, from_email=settings.BEAM_MAIL_ADDRESS, context=context ) return Response() except AccountException as e: return Response({'detail': e.args[0]}, status=status.HTTP_400_BAD_REQUEST)
def unread_count(self, request): """ 获取某个用户的各种消息未读数 ``GET`` `remind/unread_count/ <http://192.168.1.222:8080/v1/remind/unread_count>`_ """ user = request.user class_id = request.GET.get("class_id") try: teacher = user.teacher if teacher: tile_count = 0 push_tile_count = 0 except Teacher.DoesNotExist: tile_count = Tile.objects.count_unread_tiles_for(user) push_tile_count = Tile.objects.count_unread_push_tiles_for(user) if class_id: now = get_datetime_now() try: group = Group.objects.get(pk=class_id) except Group.DoesNotExist: return rc.NOT_HERE group_user = [] teacher_user = [t.user for t in group.teachers.all()] group_user.extend(teacher_user) student_user = [s.user for s in group.students.all()] group_user.extend(student_user) messages_count = MessageRecipient.objects.filter(user=user,read_at__isnull=True,message__sent_at__lte=now,\ deleted_at__isnull=True,message__sender__in=group_user).count() else: messages_count = MessageRecipient.objects.count_unread_messages_for(request.user) unread_contact = {} try: unread_list = MessageRecipient.objects.filter(user=request.user,read_at__isnull=True,deleted_at__isnull=True) unread_list.update(no_need_send=1) for m in unread_list: sender_id = m.message.sender.id unread_contact.setdefault(sender_id,0) for m in unread_list: sender_id = m.message.sender.id unread_contact[sender_id] += 1 except: pass notify_count = Notification.objects.count_notify_group(user) return {"messages": messages_count,'tile_count':tile_count,'push_tile_count':push_tile_count,'notify_count':notify_count,'messages_info':unread_contact}
def activation_key_expired(self): """ Checks if activation key is expired. Returns ``True`` when the ``activation_key`` of the user is expired and ``False`` if the key is still valid. The key is expired when it's set to the value defined in ``USERENA_ACTIVATED`` or ``activation_key_created`` is beyond the amount of days defined in ``USERENA_ACTIVATION_DAYS``. """ expiration_days = datetime.timedelta(days=userena_settings.USERENA_ACTIVATION_DAYS) expiration_date = self.user.date_joined + expiration_days the_datetime_now = get_datetime_now() get_datetime_now_is_aware = is_aware(the_datetime_now) expiration_date_is_aware = is_aware(expiration_date) if is_aware(the_datetime_now) and is_naive(expiration_date): expiration_date = pytz.utc.localize(expiration_date) if self.activation_key == userena_settings.USERENA_ACTIVATED: return True if get_datetime_now() >= expiration_date: return True return False
def upload_to_mugshot(instance, filename): """ Uploads a mugshot for a user to the ``USERENA_MUGSHOT_PATH`` and saving it under unique hash for the image. This is for privacy reasons so others can't just browse through the mugshot directory. """ extension = filename.split('.')[-1].lower() salt, hash = generate_sha1(instance.id) path = userena_settings.USERENA_MUGSHOT_PATH % {'username': instance.user.username, 'id': instance.user.id, 'date': instance.user.date_joined, 'date_now': get_datetime_now().date()} return '%(path)s%(hash)s.%(extension)s' % {'path': path, 'hash': hash[:10], 'extension': extension}
def upload_to_mugshot(instance, filename): """ Uploads a mugshot for a user to the ``USERENA_MUGSHOT_PATH`` and saving it under unique hash for the image. This is for privacy reasons so others can't just browse through the mugshot directory. """ extension = filename.split(".")[-1].lower() salt, hash = generate_sha1(instance.id) path = userena_settings.USERENA_MUGSHOT_PATH % { "username": instance.user.username, "id": instance.user.id, "date": instance.user.date_joined, "date_now": get_datetime_now().date(), } return "%(path)s%(hash)s.%(extension)s" % {"path": path, "hash": hash[:10], "extension": extension}
def user_message_history(request, user_id,compose_form=ComposeForm,\ success_url=None,template_name="oa/message_history.html"): """消息记录""" recipient = User.objects.get(id=user_id) queryset = Message.objects.get_conversation_between(request.user, recipient).filter(is_send=True) # history 页面可以直接发送信息 initial_data = dict() initial_data["to"] = recipient form = compose_form(initial=initial_data) # 发布私信 if request.method == "POST": form = compose_form(request.POST) if form.is_valid(): # requested_redirect = request.REQUEST.get("next", False) message = form.save(request.user) message.is_send = True message.save() recipients = form.cleaned_data['to'] if userena_settings.USERENA_USE_MESSAGES: messages.success(request, _('Message is sent.'),fail_silently=True) # return redirect("oa_message_history") # Update all the messages that are unread. page = int(request.GET.get("page", '1')) start = (page - 1) * 10 end = page * 10 message_pks = [m.pk for m in queryset[start:end]] unread_list = MessageRecipient.objects.filter(message__in=message_pks, user=request.user, read_at__isnull=True) now = get_datetime_now() unread_list.update(read_at=now) ctx = dict() ctx['recipient'] = recipient ctx["form"] = form message_list = queryset ctx.update({"message_list":message_list}) return render(request, template_name, ctx)
def upload_to_thumbnail(instance, filename): """ 103,143 Uploads a thumbnail for a user to the ``EBOOK_THUMBNAIL_PATH`` and saving it under unique hash for the image. This is for privacy reasons so others can't just browse through the mugshot directory. """ #extension = filename.split('.')[-1].lower() extension = 'jpg_103' salt, hash = generate_sha1(instance.id) path = ebook_settings.EBOOK_THUMBNAIL_PATH % {'username': instance.created_by.username, 'id': instance.created_by.id, 'date': instance.created_by.date_joined, 'date_now': get_datetime_now().date()} return 'thumbnail/products/%(path)s_%(hash)s.%(extension)s' % {'path': path, 'hash': hash[:10], 'extension': extension}
def reissue_activation(activation_key): ''' Rewritten version of UserenaSignup.objects.reissue_activation() to customize the sent email ''' try: userena = UserenaSignup.objects.get(activation_key=activation_key) except UserenaSignup.objects.model.DoesNotExist: return None try: salt, new_activation_key = generate_sha1(userena.user.username) userena.activation_key = new_activation_key userena.save(using=UserenaSignup.objects._db) userena.user.date_joined = get_datetime_now() userena.user.save(using=UserenaSignup.objects._db) return new_activation_key except Exception: return None
def activation_key_expired(self): """ Checks if activation key is expired. Returns ``True`` when the ``activation_key`` of the user is expired and ``False`` if the key is still valid. The key is expired when it's set to the value defined in ``USERENA_ACTIVATED`` or ``activation_key_created`` is beyond the amount of days defined in ``USERENA_ACTIVATION_DAYS``. """ expiration_days = datetime.timedelta( days=userena_settings.USERENA_ACTIVATION_DAYS ) expiration_date = self.user.date_joined + expiration_days if self.activation_completed or (get_datetime_now() >= expiration_date): return True return False
def upload_to_mugshot(instance, filename): """ Uploads a mugshot for a user to the ``USERENA_MUGSHOT_PATH`` and saving it under unique hash for the image. This is for privacy reasons so others can't just browse through the mugshot directory. """ extension = filename.split(".")[-1].lower() path = userena_settings.USERENA_MUGSHOT_PATH % { "username": instance.user.username, "id": instance.user.id, "date": instance.user.date_joined, "date_now": get_datetime_now().date(), } return "{path}{hash}.{extension}".format( path=path, hash=generate_nonce()[:10], extension=extension, )
def change_email(self, email): """ Changes the email address for a user. A user needs to verify this new email address before it becomes active. By storing the new email address in a temporary field -- ``temporary_email`` -- we are able to set this email address after the user has verified it by clicking on the verification URI in the email. This email gets send out by ``send_verification_email``. :param email: The new email address that the user wants to use. """ self.email_unconfirmed = email salt, hash = generate_sha1(self.user.username) self.email_confirmation_key = hash self.email_confirmation_key_created = get_datetime_now() self.save()
def reissue_activation(self, activation_key): """ Creates a new ``activation_key`` resetting activation timeframe when users let the previous key expire. :param activation_key: String containing the secret nonce activation key. """ try: userena = self.get(activation_key=activation_key) except self.model.DoesNotExist: return False try: userena.activation_key = generate_nonce() userena.save(using=self._db) userena.user.date_joined = get_datetime_now() userena.user.save(using=self._db) userena.send_activation_email() return True except Exception: return False
def change_email(self, email): """ Changes the email address for a user. A user needs to verify this new email address before it becomes active. By storing the new email address in a temporary field -- ``temporary_email`` -- we are able to set this email address after the user has verified it by clicking on the verification URI in the email. This email gets send out by ``send_verification_email``. :param email: The new email address that the user wants to use. """ self.email_unconfirmed = email salt, hash = generate_sha1(self.user.username) self.email_confirmation_key = hash self.email_confirmation_key_created = get_datetime_now() self.save() # Send email for activation self.send_confirmation_email()
def reissue_activation(self, activation_key): """ Creates a new ``activation_key`` resetting activation timeframe when users let the previous key expire. :param activation_key: String containing the secret SHA1 activation key. """ try: userena = self.get(activation_key=activation_key) except self.model.DoesNotExist: return False try: salt, new_activation_key = generate_sha1(userena.user.username) userena.activation_key = new_activation_key userena.save(using=self._db) userena.user.date_joined = get_datetime_now() userena.user.save(using=self._db) userena.send_activation_email() return True except Exception: return False
def update_unread_message(request,): try: userid = request.GET['userid'] recipientid = request.GET['recipientid'] user = get_object_or_404(User,pk=userid) recipient = get_object_or_404(User,pk=recipientid) # 找到 user 发给 recipient 的消息。 queryset = Message.objects.filter(Q(sender=user, recipients=recipient, messagerecipient__deleted_at__isnull=True)) message_pks = [m.pk for m in queryset] # 更新 user 发给 recipient 的未读消息 unread_list = MessageRecipient.objects.filter(message__in=message_pks, user=recipient, read_at__isnull=True) now = get_datetime_now() unread_list.update(read_at=now) return ajax_ok('消息发送成功') except: return ajax_error('消息发送失败')
def message_remove(request, undo=False): """ A ``POST`` to remove messages. :param undo: A Boolean that if ``True`` unremoves messages. POST can have the following keys: ``message_pks`` List of message id's that should be deleted. ``next`` String containing the URI which to redirect to after the keys are removed. Redirect defaults to the inbox view. The ``next`` value can also be supplied in the URI with ``?next=<value>``. """ message_pks = request.POST.getlist('message_pks') redirect_to = request.REQUEST.get('next', False) if message_pks: # Check that all values are integers. valid_message_pk_list = set() for pk in message_pks: try: valid_pk = int(pk) except (TypeError, ValueError): pass else: valid_message_pk_list.add(valid_pk) # Delete all the messages, if they belong to the user. now = get_datetime_now() changed_message_list = set() for pk in valid_message_pk_list: message = get_object_or_404(Message, pk=pk) # Check if the user is the owner if message.sender == request.user: if undo: message.sender_deleted_at = None else: message.sender_deleted_at = now message.save() changed_message_list.add(message.pk) # Check if the user is a recipient of the message if request.user in message.recipients.all(): mr = message.messagerecipient_set.get(user=request.user, message=message) if undo: mr.deleted_at = None else: mr.deleted_at = now mr.save() changed_message_list.add(message.pk) # update contact last message recipient_id = request.POST.get('recipient', False) if recipient_id: recipient = get_object_or_404(User, pk=recipient_id) if recipient: if message.sender == request.user: to_user = recipient from_user = request.user else: to_user = request.user from_user = recipient message_list = Message.objects.get_conversation_between(request.user, recipient)[:1] print message_list,"===============" if message_list: for one in message_list: print one,"oooooooooooo" MessageContact.objects.update_contact(request.user,recipient,one) else: contact = MessageContact.objects.get(Q(from_user=request.user, to_user=recipient)) print contact,"===========2222222" if contact: contact.delete() # Send messages if (len(changed_message_list) > 0) and userena_settings.USERENA_USE_MESSAGES: if undo: message = ungettext('Message is succesfully restored.', 'Messages are succesfully restored.', len(changed_message_list)) else: message = ungettext('Message is successfully removed.', 'Messages are successfully removed.', len(changed_message_list)) if request.is_ajax(): return ajax_ok(message) else: messages.success(request, message, fail_silently=True) if redirect_to: return redirect(redirect_to) else: return redirect(reverse('userena_umessages_list'))
def message_remove(request, undo=False): """ """ message_pks = request.POST.getlist('message_pks') if message_pks: # Check that all values are integers. valid_message_pk_list = set() for pk in message_pks: try: valid_pk = int(pk) except (TypeError, ValueError): pass else: valid_message_pk_list.add(valid_pk) # Delete all the messages, if they belong to the user. now = get_datetime_now() changed_message_list = set() print valid_message_pk_list,'valid_message_pk_list' for pk in valid_message_pk_list: message = get_object_or_404(Message, pk=pk) # Check if the user is the owner if message.sender == request.user: if undo: message.sender_deleted_at = None else: message.sender_deleted_at = now message.save() changed_message_list.add(message.pk) # Check if the user is a recipient of the message if request.user in message.recipients.all(): mr = message.messagerecipient_set.get(user=request.user, message=message) if undo: mr.deleted_at = None else: mr.deleted_at = now mr.save() changed_message_list.add(message.pk) # update contact last message recipient_id = request.POST.get('recipient', False) if recipient_id: recipient = get_object_or_404(User, pk=recipient_id) if recipient: if message.sender == request.user: to_user = recipient from_user = request.user else: to_user = request.user from_user = recipient message_list = Message.objects.get_conversation_between(request.user, recipient)[:1] if message_list: for one in message_list: MessageContact.objects.update_contact(request.user,recipient,one) else: contact = MessageContact.objects.get(Q(from_user=request.user, to_user=recipient)) if contact: contact.delete() # Send messages if (len(changed_message_list) > 0) and userena_settings.USERENA_USE_MESSAGES: if undo: message = ungettext('Message is succesfully restored.', 'Messages are succesfully restored.', len(changed_message_list)) else: message = ungettext('Message is successfully removed.', 'Messages are successfully removed.', len(changed_message_list))
def message_remove(request, undo=False): """ A ``POST`` to remove messages. :param undo: A Boolean that if ``True`` unremoves messages. POST can have the following keys: ``message_pks`` List of message id's that should be deleted. ``next`` String containing the URI which to redirect to after the keys are removed. Redirect defaults to the inbox view. The ``next`` value can also be supplied in the URI with ``?next=<value>``. """ message_pks = request.POST.getlist("message_pks") redirect_to = request.GET.get(REDIRECT_FIELD_NAME, request.POST.get(REDIRECT_FIELD_NAME, False)) if message_pks: # Check that all values are integers. valid_message_pk_list = set() for pk in message_pks: try: valid_pk = int(pk) except (TypeError, ValueError): pass else: valid_message_pk_list.add(valid_pk) # Delete all the messages, if they belong to the user. now = get_datetime_now() changed_message_list = set() for pk in valid_message_pk_list: message = get_object_or_404(Message, pk=pk) # Check if the user is the owner if message.sender == request.user: if undo: message.sender_deleted_at = None else: message.sender_deleted_at = now message.save() changed_message_list.add(message.pk) # Check if the user is a recipient of the message if request.user in message.recipients.all(): mr = message.messagerecipient_set.get(user=request.user, message=message) if undo: mr.deleted_at = None else: mr.deleted_at = now mr.save() changed_message_list.add(message.pk) # Send messages if (len(changed_message_list) > 0) and userena_settings.USERENA_USE_MESSAGES: if undo: message = ungettext( "Message is succesfully restored.", "Messages are succesfully restored.", len(changed_message_list) ) else: message = ungettext( "Message is successfully removed.", "Messages are successfully removed.", len(changed_message_list) ) messages.success(request, message, fail_silently=True) if redirect_to: return redirect(redirect_to) else: return redirect(reverse("userena_umessages_list"))
def message_remove(request, undo=False): """ A ``POST`` to remove messages. :param undo: A Boolean that if ``True`` unremoves messages. POST can have the following keys: ``message_pks`` List of message id's that should be deleted. ``next`` String containing the URI which to redirect to after the keys are removed. Redirect defaults to the inbox view. The ``next`` value can also be supplied in the URI with ``?next=<value>``. """ message_pks = request.POST.getlist('message_pks') redirect_to = request.REQUEST.get('next', False) if message_pks: # Check that all values are integers. valid_message_pk_list = set() for pk in message_pks: try: valid_pk = int(pk) except (TypeError, ValueError): pass else: valid_message_pk_list.add(valid_pk) # Delete all the messages, if they belong to the user. now = get_datetime_now() changed_message_list = set() for pk in valid_message_pk_list: message = get_object_or_404(Message, pk=pk) # Check if the user is the owner if message.sender == request.user: if undo: message.sender_deleted_at = None else: message.sender_deleted_at = now message.save() changed_message_list.add(message.pk) # Check if the user is a recipient of the message if request.user in message.recipients.all(): mr = message.messagerecipient_set.get(user=request.user, message=message) if undo: mr.deleted_at = None else: mr.deleted_at = now mr.save() changed_message_list.add(message.pk) # Send messages if (len(changed_message_list) > 0) and userena_settings.USERENA_USE_MESSAGES: if undo: message = ungettext('Message is succesfully restored.', 'Messages are succesfully restored.', len(changed_message_list)) else: message = ungettext('Message is successfully removed.', 'Messages are successfully removed.', len(changed_message_list)) messages.success(request, message, fail_silently=True) if redirect_to: return redirect(redirect_to) else: return redirect(reverse('userena_umessages_list'))
def message_history(request, username, page=1, paginate_by=10, compose_form=ComposeForm, success_url=None, template_name="umessages/message_history.html", extra_context=None, **kwargs): """ Returns a conversation between two users :param username: String containing the username of :class:`User` of whom the conversation is with. :param page: Integer of the active page used for pagination. Defaults to the first page. :param paginate_by: Integer defining the amount of displayed messages per page. Defaults to 50 messages per per page. :param extra_context: Dictionary of variables that will be made available to the template. :param template_name: String of the template that is rendered to display this view. If the result is paginated, the context will also contain the following variables. ``paginator`` An instance of ``django.core.paginator.Paginator``. ``page_obj`` An instance of ``django.core.paginator.Page``. """ type = request.GET.get("type",'') try: recipient = User.objects.get(username__iexact=username) if request.user == recipient: return redirect(reverse('userena_umessages_list')) except: return redirect(reverse('userena_umessages_list')) queryset = Message.objects.get_conversation_between(request.user, recipient) # history 椤甸潰鍙互鐩存帴鍙戦�淇℃伅 initial_data = dict() initial_data["to"] = recipient form = compose_form(initial=initial_data) # 鍙戝竷绉佷俊 if request.method == "POST": form = compose_form(request.POST) if form.is_valid(): requested_redirect = request.REQUEST.get("next", False) message = form.save(request.user) recipients = form.cleaned_data['to'] if userena_settings.USERENA_USE_MESSAGES: messages.success(request, _('Message is sent.'), fail_silently=True) requested_redirect = request.REQUEST.get(REDIRECT_FIELD_NAME, False) # Redirect mechanism redirect_to = reverse('userena_umessages_list') if requested_redirect: redirect_to = requested_redirect elif success_url: redirect_to = success_url elif len(recipients) == 1: redirect_to = reverse('userena_umessages_history', kwargs={'username': recipients[0].username}) redirect_to = redirect_to + '?type=' + type #actions = {'title':'鏂版秷鎭�,'href':redirect_to} #notify.send(request.user, verb='鏂版秷鎭�, action_object=message, recipient=recipient, actions=actions) return redirect(redirect_to) # Update all the messages that are unread. message_pks = [m.pk for m in queryset] unread_list = MessageRecipient.objects.filter(message__in=message_pks, user=request.user, read_at__isnull=True) now = get_datetime_now() unread_list.update(read_at=now) if not extra_context: extra_context = dict() extra_context['recipient'] = recipient extra_context['type'] = type extra_context["form"] = form message_list = queryset ctx = extra_context ctx.update({"message_list":message_list,"paginate_by":paginate_by}) return render(request, template_name, ctx) # 浠ヤ笅鏄痙jango鑷甫鐨勫垎绫� return list_detail.object_list(request, queryset=queryset, paginate_by=paginate_by, page=page, template_name=template_name, extra_context=extra_context, template_object_name="message", **kwargs)
def create_user( self, username, sns_name, email, password, active=False, send_email=True, university="", school="", year_of_study="", ): """ A simple wrapper that creates a new :class:`User`. :param username: String containing the username of the new user. :param email: String containing the email address of the new user. :param password: String containing the password for the new user. :param active: Boolean that defines if the user requires activation by clicking on a link in an e-mail. Defaults to ``False``. :param send_email: Boolean that defines if the user should be sent an email. You could set this to ``False`` when you want to create a user in your own code, but don't want the user to activate through email. :return: :class:`User` instance representing the new user. """ now = get_datetime_now() new_user = User.objects.create_user(username, email, password) new_user.is_active = active new_user.save() userena_profile = self.create_userena_profile(new_user) # All users have an empty profile profile_model = get_profile_model() try: new_profile = new_user.get_profile() except profile_model.DoesNotExist: new_profile = profile_model( user=new_user, snsName=sns_name, university=university, school=school, year_of_study=year_of_study ) new_profile.socialImageUrl = new_profile.get_mugshot_url() new_profile.socialBigImageUrl = new_profile.get_mugshot_url() new_profile.save(using=self._db) # Give permissions to view and change profile for perm in ASSIGNED_PERMISSIONS["profile"]: assign(perm[0], new_user, new_profile) # Give permissions to view and change itself for perm in ASSIGNED_PERMISSIONS["user"]: assign(perm[0], new_user, new_user) if send_email: userena_profile.send_activation_email() return new_user