Esempio n. 1
0
    def save(self, sender, parent_msg=None):
        r = self.cleaned_data['recipient']
        subject = self.cleaned_data['subject']
        body = self.cleaned_data['body']
        message_list = []

        r = User.objects.get(id=r)

        msg = Message(
            sender=sender,
            recipient=r,
            subject=subject,
            body=body,
        )
        if parent_msg is not None:
            msg.parent_msg = parent_msg
            parent_msg.replied_at = datetime.datetime.now()
            parent_msg.save()
        msg.save()
        message_list.append(msg)
        if notification:
            if parent_msg is not None:
                notification.send([sender], "messages_replied", {
                    'message': msg,
                })
            else:
                notification.send([sender], "messages_sent", {
                    'message': msg,
                })
        return message_list
Esempio n. 2
0
    def post(self, request):
        ls = json.loads(request.body)
        # print ls
        # save list json from request into DB
        newList = List(owner=request.user, \
                title=ls["title"], \
                num_items=ls["number"], \
                privacy=ls["privacy"])

        newList.save()
        for listItem in ls["list"]:
            newListItem = ListItem(listid=newList, \
                    title=listItem["title"], \
                    descriptionhtml=listItem["description"], \
                    descriptionmeta=listItem["description_meta"])
            newListItem.save()

        slug_dict = {
            'slug': newList.slug
        }

        for tagChoiceID in ls["tags"]:
            newTopicTag = TopicTag(list=newList, topic=tagChoiceID)
            newTopicTag.save()

        friends = Friend.objects.friends(request.user)
        for friend in friends:
            list_notification = Message(type='LN', to_user=friend, from_user=request.user, content="I've added a new list called " + newList.title + ". Check it out!")
            list_notification.save()
        return HttpResponse(json.dumps(slug_dict), status=201, \
                content_type='application/json')
Esempio n. 3
0
    def save(self, sender, parent_msg=None):
        r = self.cleaned_data['recipient']
        subject = self.cleaned_data['subject']
        body = self.cleaned_data['body']
        message_list = []

        r = User.objects.get(id=r)

        msg = Message(
            sender = sender,
            recipient = r,
            subject = subject,
            body = body,
        )
        if parent_msg is not None:
            msg.parent_msg = parent_msg
            parent_msg.replied_at = datetime.datetime.now()
            parent_msg.save()
        msg.save()
        message_list.append(msg)
        if notification:
            if parent_msg is not None:
                notification.send([sender], "messages_replied", {'message': msg,})
            else:
                notification.send([sender], "messages_sent", {'message': msg,})
        return message_list
Esempio n. 4
0
 def save(self, sender, parent_msg=None):
     project = self.cleaned_data['project']
     try:
         project = Project.objects.get(id=int(project))
     except Project.DoesNotExist:
         raise forms.ValidationError(
             _(u'Hmm, that does not look like a valid course'))
     recipients = project.followers()
     subject = self.cleaned_data['subject']
     body = self.cleaned_data['body']
     message_list = []
     for r in recipients:
         msg = Message(
             sender=sender,
             recipient=r.user,
             subject=subject,
             body=body,
         )
         if parent_msg is not None:
             msg.parent_msg = parent_msg
             parent_msg.replied_at = datetime.datetime.now()
             parent_msg.save()
         msg.save()
         message_list.append(msg)
     return message_list
Esempio n. 5
0
    def save(self, sender, parent_msg=None):
        project = self.cleaned_data['project']
        try:
            project = Project.objects.get(id=int(project))
        except Project.DoesNotExist:
            raise forms.ValidationError(_(u'That study group does not exist.'))
        recipients = project.organizers()
        subject = "[%s] " % project.name[:20] + self.cleaned_data['subject']
        body = self.cleaned_data['body']
        body = '%s\n\n%s' % (
            self.cleaned_data['body'],
            _('You received this message through the Contact Organizer form '
              'at %(project)s: http://%(domain)s%(url)s') % {
                  'project': project.name,
                  'domain': Site.objects.get_current().domain,
                  'url': project.get_absolute_url()
              })

        message_list = []
        for r in recipients:
            msg = Message(
                sender=sender,
                recipient=r.user.user,
                subject=subject,
                body=body,
            )
            if parent_msg is not None:
                msg.parent_msg = parent_msg
                parent_msg.replied_at = datetime.datetime.now()
                parent_msg.save()
            msg.save()
            message_list.append(msg)
        return message_list
Esempio n. 6
0
def sendMessageFromiOS(request):
    print 'sendMessageFromiOS' 
    try:
        obj = simplejson.loads(request.raw_post_data)
        print obj
        msg = obj["message"]
        message_text = msg["messageText"]
        group = Group.objects.get(pk=obj["groupID"])
        recipients = extract_recipients(request.user, group, message_text)
        if "error" in recipients:
            # send error message back to sender
            send_message(recipients["error"], None, user, group)
            data = {"errorMessage": recipients["error"]}
            return HttpResponse(simplejson.dumps(error_code(50, data)),
                mimetype='application/json')
        recipients = recipients["recipients"]
               
        # Create Message model instance and send out message
        # TODO decomp this code chunk
        message = Message(message_text=message_text, sender=request.user,
            group=group)
        create_ios_push_notification(message)
        message.save()        
        for group_link in recipients:
            recipient = group_link.user
            message_link = MessageUserLink(message=message, recipient=recipient)
            message_link.save()
            send_message(message_text, request.user, recipient, group)
        data = {"messageID": message.id}
        return error_code(0, data)
    except Exception, e:
        print e
        traceback.print_exc()
        return error_code(1)    
Esempio n. 7
0
 def save(self, sender, parent_msg=None):
     project = self.cleaned_data['project']
     try:
         project = Project.objects.get(id=int(project))
     except Project.DoesNotExist:
         raise forms.ValidationError(
             _(u'That study group does not exist.'))
     recipients = project.participants()
     subject = "[p2pu-%s] " % project.slug + self.cleaned_data['subject']
     body = self.cleaned_data['body']
     message_list = []
     for r in recipients:
         msg = Message(
             sender=sender,
             recipient=r.user.user,
             subject=subject,
             body=body,
         )
         if parent_msg is not None:
             msg.parent_msg = parent_msg
             parent_msg.replied_at = datetime.datetime.now()
             parent_msg.save()
         msg.save()
         message_list.append(msg)
     return message_list
Esempio n. 8
0
    def save(self, sender, parent_msg=None):
        subject = self.cleaned_data['subject']
        body = self.cleaned_data['body']
        message_list = []
        for r in self.cleaned_data['recipient']:
            try:
                profile = r.get_profile()
                if profile.blocked_users.filter(id=sender.id).exists():
                    continue
            except:
                pass

            msg = Message(
                sender=sender,
                recipient=r,
                subject=subject,
                body=body,
            )
            if parent_msg is not None:
                msg.parent_msg = parent_msg
                parent_msg.replied_at = datetime.datetime.now()
                parent_msg.save()
            msg.save()
            message_list.append(msg)
            if notification:
                pass
            #                if parent_msg is not None:
            #                    notification.send([sender], "messages_replied", {'message': msg,})
            #                    notification.send([r], "messages_reply_received", {'message': msg,})
            #                else:
            #                    notification.send([sender], "messages_sent", {'message': msg,})
            #                    notification.send([r], "messages_received", {'message': msg,})
        return message_list
Esempio n. 9
0
 def save(self, sender, parent_msg=None):
     if parent_msg is None:
         recipients = sender.recipients.all()
     else:
         recipients = [parent_msg.sender]
     subject = self.cleaned_data['subject']
     body = self.cleaned_data['body']
     token=''
     message_list = []
     for r in recipients:
         msg = Message(
             sender = sender,
             recipient = r,
             subject = subject,
             body = body,
             token = token,
         )
         if parent_msg is not None:
             msg.parent_msg = parent_msg
             parent_msg.replied_at = datetime.datetime.now()
             parent_msg.save()
         msg.save()
         message_list.append(msg)
         if notification:
             if parent_msg is not None:
                 notification.send([sender], "messages_replied", {'message': msg,})
                 notification.send(recipients, "messages_reply_received", {'message': msg,})
             else:
                 notification.send([sender], "messages_sent", {'message': msg,})
                 notification.send(recipients, "messages_received", {'message': msg,})
     return message_list
Esempio n. 10
0
 def save(self, sender, parent_msg=None):
     project = self.cleaned_data['project']
     try:
         project = Project.objects.get(id=int(project))
     except Project.DoesNotExist:
         raise forms.ValidationError(
             _(u'Hmm, that does not look like a valid project'))
     recipients = project.followers()
     subject = self.cleaned_data['subject']
     body = self.cleaned_data['body']
     message_list = []
     for r in recipients:
         msg = Message(
             sender=sender,
             recipient=r.user,
             subject=subject,
             body=body,
         )
         if parent_msg is not None:
             msg.parent_msg = parent_msg
             parent_msg.replied_at = datetime.datetime.now()
             parent_msg.save()
         msg.save()
         message_list.append(msg)
     return message_list
Esempio n. 11
0
 def create_message(self):
     message = Message(sender=self.her,
                       recipient=self.me,
                       subject='Subject Text',
                       body='Body Text')
     message.save()
     return message
Esempio n. 12
0
def topic_delete(request, pk):
    topic = Topic.objects.get(pk=pk)
    
    if topic.tribe.deleted:
        raise Http404
    
    are_member = has_member(topic.tribe, request.user)
    
    if topic.tribe.private and not are_member:
        access = do_403_if_not_superuser(request)
        if access: 
            return access
       
    if request.method == "POST" and (topic.creator == request.user or admin_group_access): 
        if forums:
            ThreadedComment.objects.all_for_object(topic).delete()
        send_to = topic.creator
        topic.delete()
        
        msg = Message(
            sender = request.user,
            recipient = send_to,
            subject = ugettext("A topic has been deleted."),
            body = ugettext("Your topic '%(topic)s' in '%(tribe)s' has been deleted by %(user)s") % {'topic' : topic.title,
                                                                             'user'  : request.user,
                                                                             'tribe' : topic.tribe },
        )
        msg.save()
    return HttpResponseRedirect(request.POST["next"])
Esempio n. 13
0
def create_message(request):
	# only logged in users can write messages
	if request.user.is_authenticated():
		user_id = request.session['_auth_user_id']
		if request.method == "GET":
			context = {}
			context.update(csrf(request))
			if user_id:
				user = User.objects.get(id=user_id)	
				username = user.username
				context['username'] = username
			return render_to_response("create_message.html", context)
		else:
			content = request.POST['message'].strip()
			if content == '':
				context = {}
				context['error'] = "Message cannot be blank. Please try again."
				context.update(csrf(request))
				if user_id:
					user = User.objects.get(id=user_id)	
					username = user.username
					context['username'] = username
				return render_to_response("create_message.html", context)
			# create the message
			message = Message(message=content, user_id=user_id)
			message.save()
	return redirect('/')
Esempio n. 14
0
File: forms.py Progetto: wd5/Anklav
    def save(self, sender, parent_msg=None):
        subject = self.cleaned_data['subject']
        body = self.cleaned_data['body']
        message_list = []
        role = self.cleaned_data['recipient']
        user = role.profile.user
        msg = Message(
            sender = sender,
            recipient = user,
            subject = subject,
            body = body,
        )
        if parent_msg is not None:
            msg.parent_msg = parent_msg
            parent_msg.replied_at = datetime.datetime.now()
            parent_msg.save()
        msg.save()
        message_list.append(msg)

        send_mail(
            u"Анклав: новое сообщение в личных",
            u"Вам было послано сообщение. Вы можете прочитать его по ссылке http://%s%s" % (settings.DOMAIN, reverse('messages_inbox')),
            settings.DEFAULT_FROM_EMAIL,
            [user.email],
        )
        return message_list
Esempio n. 15
0
 def save(self, sender, parent_msg=None):
     project = self.cleaned_data['project']
     try:
         project = Project.objects.get(id=int(project))
     except Project.DoesNotExist:
         raise forms.ValidationError(_(u'That study group does not exist.'))
     recipients = project.organizers()
     subject = "[%s] " % project.name[:20] + self.cleaned_data['subject']
     body = self.cleaned_data['body']
     body = '%s\n\n%s' % (self.cleaned_data['body'], _('You received this message through the Contact Organizer form ' 
            'at %(project)s: http://%(domain)s%(url)s') % {'project':project.name,  
            'domain':Site.objects.get_current().domain, 'url':project.get_absolute_url()})
                    
     message_list = []
     for r in recipients:
         msg = Message(
             sender=sender,
             recipient=r.user.user,
             subject=subject,
             body=body,
         )
         if parent_msg is not None:
             msg.parent_msg = parent_msg
             parent_msg.replied_at = datetime.datetime.now()
             parent_msg.save()
         msg.save()
         message_list.append(msg)
     return message_list
Esempio n. 16
0
    def test_message_repr(self):
        """Does the REPR look how we expect"""
        m = Message(text="Test Message", user_id=self.u_id)
        db.session.add(m)
        db.session.commit()

        id = m.id
        self.assertEqual(m.__repr__(), f"<Message #{id}: u_id={self.u_id}>")
Esempio n. 17
0
 def setUp(self):
     self.client = Client()
     user = User.objects.create_user(username="******", password="******")
     self.client.login(username="******", password="******")
     self.chat = RandomChatFactory.create()
     self.chat.save()
     message = Message(chat=self.chat, user=user, content='test')
     message.save()
Esempio n. 18
0
def add(request):
    text = request.REQUEST['main_message_input']
    if '<a' in text:
        return HttpResponseRedirect('/?notification='+urllib.quote('No <a href=> links please. You might be a spam bot'))

    m = Message(text=text, votes=0, score=time.mktime(time.gmtime()))
    m.save()
    #return HttpResponseRedirect(reverse('messages.views.index'))
    return HttpResponseRedirect('/?notification='+urllib.quote('you added: '+m.text))
Esempio n. 19
0
 def setUp(self):
     self.user1 = User.objects.create_user('user3', '*****@*****.**', '123456')
     self.user2 = User.objects.create_user('user4', '*****@*****.**', '123456')
     self.msg1 = Message(sender=self.user1, recipient=self.user2, subject='Subject Text 1', body='Body Text 1')
     self.msg2 = Message(sender=self.user1, recipient=self.user2, subject='Subject Text 2', body='Body Text 2')
     self.msg1.sender_deleted_at = datetime.datetime.now()
     self.msg2.recipient_deleted_at = datetime.datetime.now()
     self.msg1.save()
     self.msg2.save()
Esempio n. 20
0
 def setUp(self):
     self.user1 = User.objects.create_user("user3", "*****@*****.**", "123456")
     self.user2 = User.objects.create_user("user4", "*****@*****.**", "123456")
     self.msg1 = Message(sender=self.user1, recipient=self.user2, subject="Subject Text 1", body="Body Text 1")
     self.msg2 = Message(sender=self.user1, recipient=self.user2, subject="Subject Text 2", body="Body Text 2")
     self.msg1.sender_deleted_at = datetime.datetime.now()
     self.msg2.recipient_deleted_at = datetime.datetime.now()
     self.msg1.save()
     self.msg2.save()
Esempio n. 21
0
 def setUp(self):
     self.user1 = User.objects.create_user('user1', '*****@*****.**',
                                           '123456')
     self.user2 = User.objects.create_user('user2', '*****@*****.**',
                                           '123456')
     self.msg1 = Message(sender=self.user1,
                         recipient=self.user2,
                         subject='Subject Text',
                         body='Body Text')
     self.msg1.save()
Esempio n. 22
0
def application_sent(application_pk):
    if getattr(settings, "MESSAGES_DISABLED", False):
        return
    from messages.models import Message
    from teams.models import Application, TeamMember
    application = Application.objects.get(pk=application_pk)
    notifiable = TeamMember.objects.filter(
        team=application.team,
        role__in=[TeamMember.ROLE_ADMIN, TeamMember.ROLE_OWNER])
    for m in notifiable:

        template_name = "messages/application-sent.txt"
        context = {
            "applicant": application.user,
            "url_base": get_url_base(),
            "team": application.team,
            "note": application.note,
            "user": m.user,
        }
        body = render_to_string(template_name, context)
        subject = ugettext(u'%(user)s is applying for team %(team)s') % dict(
            user=application.user, team=application.team.name)
        if m.user.notify_by_message:
            msg = Message()
            msg.subject = subject
            msg.content = body
            msg.user = m.user
            msg.object = application.team
            msg.author = application.user
            msg.save()
        Meter('templated-emails-sent-by-type.teams.application-sent').inc()
        send_templated_email(m.user, subject,
                             "messages/email/application-sent-email.html",
                             context)
    return True
Esempio n. 23
0
def team_application_denied(application_pk):

    if getattr(settings, "MESSAGES_DISABLED", False):
        return
    from messages.models import Message
    from teams.models import Application
    application = Application.objects.get(pk=application_pk)
    if not team_sends_notification(application.team,
                                   'block_application_denided_message'
                                   ) or not application.user.is_active:
        return False
    template_name = "messages/email/team-application-denied.html"
    context = {
        "team": application.team,
        "user": application.user,
        "url_base": get_url_base(),
        "note": application.note,
    }
    subject = fmt(ugettext(u'Your application to join the %(team)s '
                           u'team has been declined'),
                  team=application.team.name)
    if application.user.notify_by_message:
        msg = Message()
        msg.message_type = 'S'
        msg.subject = subject
        msg.content = render_to_string("messages/team-application-denied.txt",
                                       context)
        msg.user = application.user
        msg.object = application.team
        msg.save()
    send_templated_email(application.user, subject, template_name, context)
Esempio n. 24
0
 def show_mail_compose(self, request):
     try:
         if request.is_ajax():
             mail_sent_complete = False
             if request.method == 'POST':
                 form = ComposeMailForm(request.POST)
                 if form.is_valid():
                     new_mail = Message()
                     user = request.user
                     new_mail.id_sender = user
                     user2 = User.objects.get(id= form.cleaned_data['user_id'])
                     new_mail.id_receiver = user2
                     new_mail.datetime = datetime.now()
                     new_mail.id_conversation = 1
                     new_mail.text = form.cleaned_data['text']
                     new_mail.subject = form.cleaned_data['subject']
                     new_mail.save()
                     form = ComposeMailForm()
                     mail_sent_complete = MAILSENTCOMPLETE
             else: 
                 form = ComposeMailForm()
             week = {0:'Lunes',1:'Martes',2:'Miércoles',3:'Jueves',4:'Viernes',5:'Sábado',6:'Domingo'}
             month = {0: 'Enero', 1:'Febrero',2:'Marzo',3:'Abril',4:'Mayo',5:'Junio',6:'Julio',7:'Agosto',8:'Septiembre',9:'Octubre',10:'Noviembre',11:'Diciembre'}
             date_time = week[datetime.today().weekday()] + " " + str(datetime.today().day) + "/" + month[datetime.today().month - 1] + " " + str(datetime.today().year)
             c = { 'form': form , 'date_t':date_time, 'mail_sent_complete' : mail_sent_complete}
             c.update(csrf(request))
             return render_to_response('user_send_mail.html', c)
         else: return HttpResponseRedirect("/usuarios/profile/mail")
         
     except Exception as e: return self.show_error(e)
Esempio n. 25
0
def send_reject_notification(task_pk, sent_back):
    raise NotImplementedError()
    from teams.models import Task
    from videos.models import Action
    from messages.models import Message
    try:
        task = Task.objects.select_related(
            "team_video__video", "team_video", "assignee", "subtitle_version").get(
                pk=task_pk)
    except Task.DoesNotExist:
        return False

    if task.new_review_base_version:
        user = task.new_review_base_version.author
    else:
        user = version.author
    if not user.is_active:
        return False
    version = task.get_subtitle_version()
    subject = ugettext(u"Your subtitles were not accepted")
    task_language = get_language_label(task.language)
    reviewer = task.assignee
    video = task.team_video.video
    subs_url = "%s%s" % (get_url_base(), reverse("videos:translation_history", kwargs={
        'video_id': video.video_id,
        'lang': task.language,
        'lang_id': version.subtitle_language.pk,

    }))
    reviewer_message_url = "%s%s?user=%s" % (
        get_url_base(), reverse("messages:new"), reviewer.username)

    context = {
        "team":task.team,
        "title": version.subtitle_language.get_title(),
        "user":user,
        "task_language": task_language,
        "url_base":get_url_base(),
        "task":task,
        "reviewer":reviewer,
        "note":task.body,
        "sent_back": sent_back,
        "subs_url": subs_url,
        "reviewer_message_url": reviewer_message_url,
    }
    msg = None
    if user.notify_by_message:
        template_name = "messages/team-task-rejected.txt"
        msg = Message()
        msg.message_type = 'S'
        msg.subject = subject
        msg.content = render_to_string(template_name,context)
        msg.user = user
        msg.object = task.team
        msg.save()

    template_name = "messages/email/team-task-rejected.html"
    email_res =  send_templated_email(user, subject, template_name, context)
    Action.create_rejected_video_handler(version, reviewer)
    return msg, email_res
Esempio n. 26
0
 def post(self, request, username='', sortmethod=''):
     message_content = request.POST.get('message_content')
     to_user = User.objects.get(username=username)
     message = Message(
                 type='GN',
                 to_user=to_user,
                 from_user=request.user,
                 content=message_content
     )
     message.save()
     return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Esempio n. 27
0
 def run(self, form, messages, **kwargs):
     log = self.get_logger(**kwargs)
     log.debug("Sending email to %d user(s)." % (len(messages),))
     for message in messages:
         (sender, recipient, subject, body, parent) = message
         msg = Message(sender=sender, recipient=recipient, subject=subject, body=body)
         if parent is not None:
             msg.parent_msg = parent
             parent.replied_at = datetime.datetime.now()
             parent.save()
         msg.save()
Esempio n. 28
0
 def send_to_teams(self, team_ids, author):
     subject = self.cleaned_data['subject']
     content = self.cleaned_data['content']
     content = u''.join([content, '\n\n', ugettext('This message is from site administrator.')])
     users = User.objects.filter(teams__in=team_ids).exclude(pk=author.pk)
     for user in users:
         m = Message(author=author, user=user)
         m.subject = subject
         m.content = content
         m.save()
     return users.count()
Esempio n. 29
0
def home(request):
    if 'text' in request.GET:
        author_ = request.GET['author']
        text_ = request.GET['text']

        message = Message(author=author_, text=text_)
        message.save()

    messages = Message.objects.all()

    return render(request, 'home.html', {'messages': messages})
Esempio n. 30
0
def SendMessage(profile, otherUserFacebookID, messageBody):
    try:
        sender = profile
        recipient = Profile.objects.get(facebookID=otherUserFacebookID)
        body = messageBody
        message = Message(sender=sender, recipient=recipient,body=body)
        message.save()
        message_sent(message)
        return True
    except:
        return False
Esempio n. 31
0
 def test_view_message(self):
     """Test user can view message in inbox."""
     Relationship(source=self.user, target_user=self.user_two).save()
     message = Message(sender=self.user_two.user,
                       recipient=self.user.user,
                       subject='test message subject',
                       body='test message body')
     message.save()
     self.client.login(username=self.test_username,
                       password=self.test_password)
     response = self.client.get("/%s/messages/inbox/" % (self.locale, ))
     self.assertContains(response, 'test message body')
Esempio n. 32
0
 def run(self, form, messages, **kwargs):
     log = self.get_logger(**kwargs)
     log.debug("Sending email to %d user(s)." % (len(messages),))
     for message in messages:
         (sender, recipient, subject, body, parent) = message
         msg = Message(sender=sender, recipient=recipient,
                       subject=subject, body=body)
         if parent is not None:
             msg.parent_msg = parent
             parent.replied_at = datetime.datetime.now()
             parent.save()
         msg.save()
Esempio n. 33
0
def email_confirmed(user_pk):
    from messages.models import Message
    user = User.objects.get(pk=user_pk)
    subject = "Welcome aboard!"
    context = {"user": user}
    if user.notify_by_message:
        body = render_to_string("messages/email-confirmed.txt", context)
        message = Message(user=user, subject=subject, content=body)
        message.save()
    template_name = "messages/email/email-confirmed.html"
    Meter('templated-emails-sent-by-type.email-confirmed').inc()
    send_templated_email(user, subject, template_name, context)
    return True
Esempio n. 34
0
 def _create_message(self, to_user, message_type='M', reply_to=None):
     self.message = Message(user=to_user,
                        author=self.author,
                        subject=self.subject,
                        message_type=message_type,
                        content=self.body)
     if reply_to is not None:
         if reply_to.thread:
             self.message.thread = reply_to.thread
         else:
             self.message.thread = reply_to.pk
     self.message.save()
     return self.message
Esempio n. 35
0
 def test_view_message(self):
     """Test user can view message in inbox."""
     Relationship(source=self.user, target_user=self.user_two).save()
     message = Message(
         sender=self.user_two.user,
         recipient=self.user.user,
         subject='test message subject',
         body='test message body')
     message.save()
     self.client.login(username=self.test_username,
                       password=self.test_password)
     response = self.client.get("/%s/messages/inbox/" % (self.locale,))
     self.assertContains(response, 'test message body')
Esempio n. 36
0
    def save(self, sender, parent_msg=None):
        recipients = self.cleaned_data['recipient']
        subject = self.cleaned_data['subject']
        body = self.cleaned_data['body']
        send_to_email = self.cleaned_data['send_to_email']
        send_to_students = self.cleaned_data['send_to_students']
        send_to_mentors = self.cleaned_data['send_to_mentors']

        if isinstance(recipients, str):
            recipients = []

        if send_to_students:
            student_list = [stud.pk for stud in StudentProfile.objects.all()]
            students_as_users = [u for u in User.objects.all().filter(user__profile__pk__in=student_list)]
            recipients.extend(students_as_users)
        if send_to_mentors:
            mentor_list = [ment.pk for ment in MentorProfile.objects.all()]
            mentors_as_users = [u for u in User.objects.all().filter(user__profile__pk__in=mentor_list)]
            recipients.extend(mentors_as_users)

        # filter only unique users
        recipients = list(set(recipients))

        message_list = []

        if send_to_email:
            recipient_emails = [r.get_profile().email for r in recipients]
            for email in recipient_emails:
                send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, [email], priority="high")
        else:
            for r in recipients:
                msg = Message(
                    sender = sender,
                    recipient = r,
                    subject = subject,
                    body = body,
                )
                if parent_msg is not None:
                    msg.parent_msg = parent_msg
                    parent_msg.replied_at = datetime.datetime.now()
                    parent_msg.save()
                msg.save()
                message_list.append(msg)
                if notification:
                    if parent_msg is not None:
                        notification.send([sender], "messages_replied", {'message': msg,})
                        notification.send(recipients, "messages_reply_received", {'message': msg,})
                    else:
                        notification.send([sender], "messages_sent", {'message': msg,})
                        notification.send(recipients, "messages_received", {'message': msg,})
        return message_list
Esempio n. 37
0
def team_application_denied(application_pk):

    if getattr(settings, "MESSAGES_DISABLED", False):
        return
    from messages.models import Message
    from teams.models import Application
    application = Application.objects.get(pk=application_pk)
    template_name = "messages/email/team-application-denied.html"
    context = {
        "team": application.team,
        "user": application.user,
        "url_base": get_url_base(),
        "note": application.note,
    }
    if application.user.notify_by_message:
        msg = Message()
        msg.subject = ugettext(
            u'Your application to join the %s team has been declined' %
            application.team.name)
        msg.content = render_to_string("messages/team-application-denied.txt",
                                       context)
        msg.user = application.user
        msg.object = application.team
        msg.save()
    Meter('templated-emails-sent-by-type.teams.application-declined').inc()
    send_templated_email(msg.user, msg.subject, template_name, context)
    application.delete()
Esempio n. 38
0
    def save(self, new_data, request, user_to = None):
        # current date
        datetime_now = datetime.now()

        # save topic
        topic = Topic()
        topic.theme = new_data['theme']
        topic.user1 = request.user

        if user_to is None:
            user_to = User.objects.get(id = new_data['userToId'])
        topic.user2 = user_to

        topic.create_on = datetime_now
        topic.update_on = datetime_now
        topic.save()

        # save message
        message = Message()
        message.user_from = topic.user1
        message.user_to = topic.user2
        message.topic = topic
        message.body = new_data['body']
        message.sent_on = datetime.now()
        message.save()

        return message
Esempio n. 39
0
class DeleteTestCase(TestCase):
    def setUp(self):
        self.user1 = User.objects.create_user('user3', '*****@*****.**',
                                              '123456')
        self.user2 = User.objects.create_user('user4', '*****@*****.**',
                                              '123456')
        self.msg1 = Message(sender=self.user1,
                            recipient=self.user2,
                            subject='Subject Text 1',
                            body='Body Text 1')
        self.msg2 = Message(sender=self.user1,
                            recipient=self.user2,
                            subject='Subject Text 2',
                            body='Body Text 2')
        self.msg1.sender_deleted_at = datetime.datetime.now()
        self.msg2.recipient_deleted_at = datetime.datetime.now()
        self.msg1.save()
        self.msg2.save()

    def testBasic(self):
        self.assertEquals(Message.objects.outbox_for(self.user1).count(), 1)
        self.assertEquals(
            Message.objects.outbox_for(self.user1)[0].subject,
            'Subject Text 2')
        self.assertEquals(Message.objects.inbox_for(self.user2).count(), 1)
        self.assertEquals(
            Message.objects.inbox_for(self.user2)[0].subject, 'Subject Text 1')
        #undelete
        self.msg1.sender_deleted_at = None
        self.msg2.recipient_deleted_at = None
        self.msg1.save()
        self.msg2.save()
        self.assertEquals(Message.objects.outbox_for(self.user1).count(), 2)
        self.assertEquals(Message.objects.inbox_for(self.user2).count(), 2)
Esempio n. 40
0
def messages(request, user_id=None):
    context = {}

    message = Message()

    threads = Message.objects.filter(
        recipient=request.user
    ).values_list(
        'sender__user',
        'sender__user__first_name',
        'sender__user__last_name'
    ).distinct()

    if user_id is None and len(threads) > 0:
        first_message = Message.objects.filter(
            Q(recipient=request.user) | Q(sender=request.user)
        )[:1].get()

        current = first_message.recipient if first_message.sender == request.user else first_message.sender
    elif user_id is not None:
        current = user_id
    else:
        current = None

    if request.method == 'POST':
        message.sender = request.user.get_profile()
        message.recipient = UserProfile.objects.get(user__pk=user_id)

        form = MessageForm(request.POST, instance=message)
        form.save()

        return redirect('/messages/' + user_id)
    else:
        form = MessageForm(request.POST, instance=message)


    messages = Message.objects.filter(
        Q(sender=current, recipient=request.user) |
        Q(sender=request.user, recipient=current)
    ).order_by(
        'created'
    )

    context['user'] = request.user
    context['message_form'] = form
    context['current_thread'] = current
    context['threads'] = threads
    context['messages'] = messages

    return render(request, 'messages/index.html', context)
Esempio n. 41
0
def invite_send_message(sender, instance, created, **kwargs):
    if created:
        msg = Message()
        msg.subject = ugettext(u'Invitation to join a team')
        msg.user = instance.user
        msg.object = instance
        msg.author = instance.author
        msg.save()
Esempio n. 42
0
def team_invitation_sent(invite_pk):
    from messages.models import Message
    from teams.models import Invite, Setting, TeamMember
    invite = Invite.objects.get(pk=invite_pk)
    if not team_sends_notification(
            invite.team,
            'block_invitation_sent_message') or not invite.user.is_active:
        return False
    # does this team have a custom message for this?
    team_default_message = None
    messages = Setting.objects.messages().filter(team=invite.team)
    if messages.exists():
        data = {}
        for m in messages:
            data[m.get_key_display()] = m.data
        mapping = {
            TeamMember.ROLE_ADMIN: data['messages_admin'],
            TeamMember.ROLE_MANAGER: data['messages_manager'],
            TeamMember.ROLE_CONTRIBUTOR: data['messages_invite'],
        }
        team_default_message = mapping.get(invite.role, None)
    context = {
        'invite': invite,
        'role': invite.role,
        "user": invite.user,
        "inviter": invite.author,
        "team": invite.team,
        "invite_pk": invite_pk,
        'note': invite.note,
        'custom_message': team_default_message,
        'url_base': get_url_base(),
    }
    title = fmt(ugettext(u"You've been invited to team %(team)s on Amara"),
                team=invite.team.name)

    if invite.user.notify_by_message:
        body = render_to_string("messages/team-you-have-been-invited.txt",
                                context)
        msg = Message()
        msg.message_type = 'S'
        msg.subject = title
        msg.user = invite.user
        msg.object = invite
        msg.author = invite.author
        msg.content = body
        msg.save()
    template_name = 'messages/email/team-you-have-been-invited.html'
    return send_templated_email(invite.user, title, template_name, context)
Esempio n. 43
0
 def clean(self, *args, **kwargs):
     super(SendMessageForm, self).clean(*args, **kwargs)
     ticket = self.cleaned_data.get('ticket')
     sender = self.request.user
     other_user = self.cleaned_data.get('other_user')
     if Message.can_message(ticket, sender, other_user):
         forms.ValidationError('Sorry, you are not allowed to send a message for that ticket.')
Esempio n. 44
0
class SendTestCase(TestCase):
    def setUp(self):
        self.user1 = User.objects.create_user("user1", "*****@*****.**", "123456")
        self.user2 = User.objects.create_user("user2", "*****@*****.**", "123456")
        self.msg1 = Message(sender=self.user1, recipient=self.user2, subject="Subject Text", body="Body Text")
        self.msg1.save()

    def testBasic(self):
        self.assertEquals(self.msg1.sender, self.user1)
        self.assertEquals(self.msg1.recipient, self.user2)
        self.assertEquals(self.msg1.subject, "Subject Text")
        self.assertEquals(self.msg1.body, "Body Text")
        self.assertEquals(self.user1.sent_messages.count(), 1)
        self.assertEquals(self.user1.received_messages.count(), 0)
        self.assertEquals(self.user2.received_messages.count(), 1)
        self.assertEquals(self.user2.sent_messages.count(), 0)
Esempio n. 45
0
 def send_to_teams(self, team_ids, author):
     subject = self.cleaned_data['subject']
     content = self.cleaned_data['content']
     content = u''.join([
         content, '\n\n',
         ugettext('This message is from site administrator.')
     ])
     users = User.objects.filter(teams__in=team_ids).exclude(pk=author.pk)
     message_list = []
     for user in users:
         m = Message(author=author, user=user)
         m.subject = subject
         m.content = content
         message_list.append(m)
     Message.objects.bulk_create(message_list)
     return users.count()
Esempio n. 46
0
def send_message(template: MessageTemplate,
                 member,
                 db_session=None,
                 render_template=None,
                 **kwargs):

    if render_template is None:
        from flask import render_template

    subject = render_template(
        f"{template.value}.subject.html",
        public_url=get_public_url,
        member=member,
        **kwargs,
    )

    body = render_template(
        f"{template.value}.body.html",
        public_url=get_public_url,
        member=member,
        **kwargs,
    )

    if not db_session:
        from service.db import db_session

    db_session.add(
        Message(
            subject=subject,
            body=body,
            member_id=member.member_id,
            recipient=member.email,
            status=Message.QUEUED,
            template=template.value,
        ))
Esempio n. 47
0
class SendTestCase(TestCase):
    def setUp(self):
        self.user1 = User.objects.create_user('user1', '*****@*****.**', '123456')
        self.user2 = User.objects.create_user('user2', '*****@*****.**', '123456')
        self.msg1 = Message(sender=self.user1, recipient=self.user2, subject='Subject Text', body='Body Text')
        self.msg1.save()
        
    def testBasic(self):
        self.assertEquals(self.msg1.sender, self.user1)
        self.assertEquals(self.msg1.recipient, self.user2)
        self.assertEquals(self.msg1.subject, 'Subject Text')
        self.assertEquals(self.msg1.body, 'Body Text')
        self.assertEquals(self.user1.sent_messages.count(), 1)
        self.assertEquals(self.user1.received_messages.count(), 0)
        self.assertEquals(self.user2.received_messages.count(), 1)
        self.assertEquals(self.user2.sent_messages.count(), 0)
Esempio n. 48
0
def messages(request, association_pseudo):
    association = get_object_or_404(Association,pseudo=association_pseudo)
    if association.est_cachee_a(request.user.get_profile()):
        return redirect(index)
    membres = Adhesion.objects.filter(association__pseudo = association_pseudo).order_by('-ordre', 'eleve__last_name')
    list_messages = Message.accessibles_par(request.user.get_profile()).filter(association__pseudo=association_pseudo).order_by('-date')
    return render_to_response('association/messages.html', {'association' : association, 'list_messages': list_messages, 'membres': membres},context_instance=RequestContext(request))
Esempio n. 49
0
def comment_delete(request, object_id, model=ThreadedComment, extra_context = {}, context_processors = [], permission_callback=can_delete_comment):
    """
    Deletes the specified comment, which can be either a ``FreeThreadedComment`` or a
    ``ThreadedComment``.  If it is a POST request, then the comment will be deleted
    outright, however, if it is a GET request, a confirmation page will be shown.
    """
    tc = get_object_or_404(model, id=int(object_id))
    if not permission_callback(tc, request.user):
        login_url = settings.LOGIN_URL
        current_url = urlquote(request.get_full_path())
        return HttpResponseRedirect("%s?next=%s" % (login_url, current_url))
    if request.method == "POST":
        tc.delete()
        
        
        msg = Message(
            sender = request.user,
            recipient = tc.user,
            subject = ugettext("A comment has been deleted."),
            body = ugettext("A comment you made in the thread '%(thread)s' in '%(tribe)s' has been deleted by %(user)s") % {'thread' : tc.get_content_object().title,
                                                                             'user'  : request.user,
                                                                             'tribe' : tc.get_content_object().tribe },
        )
        msg.save()
        
        return HttpResponseRedirect(_get_next(request))
    else:
        if model == ThreadedComment:
            is_free_threaded_comment = False
            is_threaded_comment = True
        else:
            is_free_threaded_comment = True
            is_threaded_comment = False
        return render_to_response(
            'threadedcomments/confirm_delete.html',
            extra_context, 
            context_instance = RequestContext(
                request, 
                {
                    'comment' : tc, 
                    'is_free_threaded_comment' : is_free_threaded_comment,
                    'is_threaded_comment' : is_threaded_comment,
                    'next' : _get_next(request),
                },
                context_processors
            )
        )
Esempio n. 50
0
    def message(self, sender, subject, body, message_extra=""):

        if not self.active:
            return  # don't send messages to inactive members

        from messages.models import Message
        from django.core.mail import send_mail
        from django.core.urlresolvers import reverse
        from django.utils.translation import ugettext_lazy as _, ugettext

        m = Message(subject=subject, body=body, sender=sender, recipient=self)
        m.save()

        if self.cc_messages_to_email:
            # recipient wants emails cc-ed
            link = 'http://' + settings.DOMAIN_NAME + reverse('messages_all')
            settings_link = 'http://' + settings.DOMAIN_NAME + reverse(
                'acct_settings')
            main = _(""" 
%(sender)s has sent you a new message on %(account_name)s .

---------------------------------------------------------------

%(body)s

---------------------------------------------------------------


Click %(link)s to see your account.

If you do not want to receive emails when you receive messages on %(account_name)s, please change your settings here : %(settings_link)s

%(message_extra)s

""") % {
                'account_name': settings.SITE_NAME,
                'body': body,
                'link': link,
                'sender': sender.get_display_name(),
                'settings_link': settings_link,
                "message_extra": message_extra
            }

            self.email_user(subject, main, settings.SERVER_EMAIL)

        return m
Esempio n. 51
0
def moderate_queue(request, queue_id):
    '''send the moderator to a page which displays the current document sta
        and the proposed change for approval or denial
    '''
    from jaxerdoc.forms import QueueModerationForm
    from django.core.urlresolvers import reverse
    queue = QueuedItem.objects.get(pk=queue_id)

    if request.POST:
        if queue.is_moderated():
            return HttpResponseRedirect(reverse('jaxerdoc_queue_moderation'))
        form = QueueModerationForm(request.POST, instance=queue)
        if form.is_valid():

            form.save()
            m = 'you have successfully moderated: %s.' % queue
            # send a message to the person who submitted the edit
            from messages.models import Message

            
            if form.cleaned_data['moderate'] == 'approval': moderation = 'approved'
            else: moderation = 'rejected'
            message = render_to_string('jaxerdoc/wiki_%s_message.txt' % moderation, 
                                       {
                                            'moderation':moderation,
                                            'message':form.cleaned_data['mod_reason'],
                                            'from':request.user
                                        })
            if queue.action == 'new':
                sub ='Wiki Submission: %s %s' % (queue.add_title, moderation)
            else:
                sub ='Wiki Submission: %s %s' % (queue.content_object.name, moderation)
            pm = Message(subject = sub,
                         sender=request.user,
                         body=message,
                         recipient=queue.editor) 
            pm.save()             
            request.user.message_set.create(message=m) 
            return HttpResponseRedirect(reverse('jaxerdoc_queue_moderation'))
        else:
            form = QueueModerationForm(request.POST, instance=queue)   
    else:
        form = QueueModerationForm(instance=queue)
    return render_to_response('jaxerdoc/moderate_queueitem_%s.html' % queue.action,
                                  {'form':form, 'queueitem':queue},
                                  context_instance=RequestContext(request))
Esempio n. 52
0
 def send_complete_message(self):
     msg = Message()
     msg.user = self.user
     msg.subject = u'Your request was completed'
     msg.object = self
     msg.save()
     return msg
Esempio n. 53
0
def team_member_promoted(team_pk, user_pk, new_role):
    if getattr(settings, "MESSAGES_DISABLED", False):
        return
    from messages.models import Message
    from teams.models import Setting, TeamMember, Team
    user = User.objects.get(pk=user_pk)
    team = Team.objects.get(pk=team_pk)

    team_default_message = None
    messages = Setting.objects.messages().filter(team=team)
    if messages.exists():
        data = {}
        for m in messages:
            data[m.get_key_display()] = m.data
        mapping = {
            TeamMember.ROLE_ADMIN: data['messages_admin'],
            TeamMember.ROLE_MANAGER: data['messages_manager'],
        }
        team_default_message = mapping.get(new_role, None)

    if new_role == TeamMember.ROLE_ADMIN:
        role_label = "Admin"
    elif new_role == TeamMember.ROLE_MANAGER:
        role_label = "Manager"

    context = {
        'role': role_label,
        "user": user,
        "team": team,
        'custom_message': team_default_message,
        'url_base': get_url_base(),
    }
    title = fmt(ugettext(u"You are now a(n) %(role)s for the %(team)s team!"),
                role=role_label,
                team=team.name)
    body = render_to_string("messages/team-member-promoted.txt", context)
    msg = Message(user=user,
                  subject=title,
                  content=body,
                  message_type=SYSTEM_NOTIFICATION)
    msg.save()
    send_new_message_notification.delay(msg.id)
    if user.notify_by_email:
        template_name = 'messages/email/team-member-promoted.html'
        send_templated_email(user, title, template_name, context)
Esempio n. 54
0
 def create_messages(self):
     messages = [
         Message(user=user,
                 content=self.validated_data['content'],
                 subject=self.validated_data['subject'],
                 author=self.context['user']) for user in self.recipients()
         if user != self.context['user']
     ]
     Message.objects.bulk_create(messages)
Esempio n. 55
0
def videos_imported_message(user_pk, imported_videos):
    from messages.models import Message
    user = User.objects.get(pk=user_pk)
    subject = _(u"Your videos were imported!")
    url = "%s%s" % (get_url_base(), reverse("profiles:my_videos"))
    context = {
        "user": user,
        "imported_videos": imported_videos,
        "my_videos_url": url
    }

    if user.notify_by_message:
        body = render_to_string("messages/videos-imported.txt", context)
        message = Message(user=user, subject=subject, content=body)
        message.save()
    template_name = "messages/email/videos-imported.html"
    Meter('templated-emails-sent-by-type.videos-imported').inc()
    send_templated_email(user, subject, template_name, context)
Esempio n. 56
0
def _process_post_form_messages(form, logged_user, to_user):

    msg = Message(from_user=logged_user,
                  to_user=to_user,
                  post=form.post.data,
                  message_type=POST).save()
    Feed(user=logged_user, message=msg).save()
    MessageProcessor(message_obj=msg).post_message_to_all_friends_feeds()

    return msg