コード例 #1
0
ファイル: forms.py プロジェクト: jakebarnwell/PythonGenerator
    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
コード例 #2
0
ファイル: views.py プロジェクト: UCR-CS179-Team7/ListVerse
    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')
コード例 #3
0
ファイル: tasks.py プロジェクト: thi517/unisubs
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)
コード例 #4
0
 def create_message(self):
     message = Message(sender=self.her,
                       recipient=self.me,
                       subject='Subject Text',
                       body='Body Text')
     message.save()
     return message
コード例 #5
0
ファイル: tasks.py プロジェクト: sanyaade-teachings/unisubs
def team_member_new(member_pk):
    if getattr(settings, "MESSAGES_DISABLED", False):
        return
    from messages.models import Message
    from teams.models import TeamMember
    member = TeamMember.objects.get(pk=member_pk)
    if not _team_sends_notification(member.team,
                                    'block_team_member_new_message'):
        return False
    from videos.models import Action
    from teams.models import TeamMember
    # the feed item should appear on the timeline for all team members
    # as a team might have thousands of members, this one item has
    # to show up on all of them
    Action.create_new_member_handler(member)
    # notify  admins and owners through messages
    notifiable = TeamMember.objects.filter(
        team=member.team,
        role__in=[TeamMember.ROLE_ADMIN,
                  TeamMember.ROLE_OWNER]).exclude(pk=member.pk)
    for m in notifiable:
        context = {
            "new_member": member.user,
            "team": member.team,
            "user": m.user,
            "role": member.role,
            "url_base": get_url_base(),
        }
        body = render_to_string("messages/team-new-member.txt", context)
        subject = ugettext("%s team has a new member" % (member.team))
        if m.user.notify_by_message:
            msg = Message()
            msg.subject = subject
            msg.content = body
            msg.user = m.user
            msg.object = m.team
            msg.save()
        template_name = "messages/email/team-new-member.html"
        Meter('templated-emails-sent-by-type.teams.new-member').inc()
        send_templated_email(m.user, subject, template_name, context)

    # now send welcome mail to the new member
    template_name = "messages/team-welcome.txt"
    context = {
        "team": member.team,
        "url_base": get_url_base(),
        "role": member.role,
        "user": member.user,
    }
    body = render_to_string(template_name, context)

    msg = Message()
    msg.subject = ugettext("You've joined the %s team!" % (member.team))
    msg.content = body
    msg.user = member.user
    msg.object = member.team
    msg.save()
    template_name = "messages/email/team-welcome.html"
    Meter('templated-emails-sent-by-type.teams.welcome').inc()
    send_templated_email(msg.user, msg.subject, template_name, context)
コード例 #6
0
def message_send(request, username):
    return_dict = {
        'status': 1,
    }
    if request.method == 'POST':
        try:
            friend_user = User.objects.get(username__exact=username)
        except:
            return_dict['status'] = 0
            return HttpResponse(json.dumps(return_dict))
        friend_member = friend_user.members

        message = Message(member1=request.user.members, member2=friend_member)
        message.content = request.POST['message']
        message.timestamp = datetime.utcnow().replace(tzinfo=utc)
        message.save()
        template_dict = {
            'message': message,
            'member': request.user.members,
        }
        return render_to_response(
            "user_pages/ajax_delivery/message_after_send.html",
            template_dict,
            context_instance=RequestContext(request))

    else:
        return_dict['status'] = 0
    return HttpResponse(json.dumps(return_dict))
コード例 #7
0
ファイル: forms.py プロジェクト: Suggsgested/lernanta
 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
コード例 #8
0
ファイル: views.py プロジェクト: gruizmir/trueque
 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)
コード例 #9
0
ファイル: forms.py プロジェクト: foxtrotcharlie/lernanta
    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
コード例 #10
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
コード例 #11
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()
コード例 #12
0
ファイル: forms.py プロジェクト: jakebarnwell/PythonGenerator
    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
コード例 #13
0
ファイル: models.py プロジェクト: adncentral/unisubs
 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
コード例 #14
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
コード例 #15
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
コード例 #16
0
ファイル: views.py プロジェクト: SheikGeek/squawker
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('/')
コード例 #17
0
ファイル: views.py プロジェクト: fangsterr/Planamo-Django
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)    
コード例 #18
0
ファイル: forms.py プロジェクト: 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
コード例 #19
0
ファイル: forms.py プロジェクト: su-danny/famdates
    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
コード例 #20
0
ファイル: models.py プロジェクト: forknfork/unisubs
 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
コード例 #21
0
ファイル: forms.py プロジェクト: livne/Random-Yes
 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
コード例 #22
0
ファイル: forms.py プロジェクト: phastafrican/lernanta
 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
コード例 #23
0
ファイル: forms.py プロジェクト: foxtrotcharlie/lernanta
 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
コード例 #24
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"])
コード例 #25
0
ファイル: forms.py プロジェクト: andrewkuzmych/litclub
    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
コード例 #26
0
ファイル: models.py プロジェクト: crodjer/mirosubs
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()
コード例 #27
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()
コード例 #28
0
ファイル: models.py プロジェクト: adncentral/unisubs
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()
コード例 #29
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))
コード例 #30
0
ファイル: tasks.py プロジェクト: thi517/unisubs
def team_member_leave(team_pk, user_pk):
    if getattr(settings, "MESSAGES_DISABLED", False):
        return
    from messages.models import Message
    from teams.models import TeamMember, Team
    user = User.objects.get(pk=user_pk)
    team = Team.objects.get(pk=team_pk)
    if not team_sends_notification(
            team, 'block_team_member_leave_message') or not user.is_active:
        return False
    # the feed item should appear on the timeline for all team members
    # as a team might have thousands of members, this one item has
    # to show up on all of them
    # notify  admins and owners through messages
    notifiable = TeamMember.objects.filter(
        team=team,
        user__is_active=True,
        role__in=[TeamMember.ROLE_ADMIN, TeamMember.ROLE_OWNER])
    subject = fmt(ugettext(u"%(user)s has left the %(team)s team"),
                  user=user,
                  team=team)
    for m in notifiable:
        context = {
            "parting_member": user,
            "team": team,
            "user": m.user,
            "url_base": get_url_base(),
        }
        body = render_to_string("messages/team-member-left.txt", context)
        if m.user.notify_by_message:
            msg = Message()
            msg.message_type = 'S'
            msg.subject = subject
            msg.content = body
            msg.user = m.user
            msg.object = team
            msg.save()
        send_templated_email(m.user, subject,
                             "messages/email/team-member-left.html", context)

    context = {
        "team": team,
        "user": user,
        "url_base": get_url_base(),
    }
    subject = fmt(ugettext("You've left the %(team)s team!"), team=team)
    if user.notify_by_message:
        template_name = "messages/team-member-you-have-left.txt"
        msg = Message()
        msg.message_type = 'S'
        msg.subject = subject
        msg.content = render_to_string(template_name, context)
        msg.user = user
        msg.object = team
        msg.save()
    template_name = "messages/email/team-member-you-have-left.html"
    send_templated_email(user, subject, template_name, context)
コード例 #31
0
ファイル: forms.py プロジェクト: appsembler/unisubs
 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()
コード例 #32
0
ファイル: tasks.py プロジェクト: quinoescobar/batucada
 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()
コード例 #33
0
ファイル: views.py プロジェクト: UCR-CS179-Team7/ListVerse
 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'))
コード例 #34
0
ファイル: forms.py プロジェクト: adncentral/unisubs
 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()
コード例 #35
0
ファイル: views.py プロジェクト: niggin/django-lectures
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})
コード例 #36
0
ファイル: sendMessage.py プロジェクト: munshikamran/mutuality
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
コード例 #37
0
ファイル: tasks.py プロジェクト: waytai/batucada
 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()
コード例 #38
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')
コード例 #39
0
def team_member_leave(team_pk, user_pk):
    if getattr(settings, "MESSAGES_DISABLED", False):
        return
    from messages.models import Message
    from teams.models import TeamMember, Team
    user = User.objects.get(pk=user_pk)
    team = Team.objects.get(pk=team_pk)
    from videos.models import Action
    # the feed item should appear on the timeline for all team members
    # as a team might have thousands of members, this one item has
    # to show up on all of them
    Action.create_member_left_handler(team, user)
    # notify  admins and owners through messages
    notifiable = TeamMember.objects.filter(
        team=team, role__in=[TeamMember.ROLE_ADMIN, TeamMember.ROLE_OWNER])
    subject = ugettext(u"%(user)s has left the %(team)s team" %
                       dict(user=user, team=team))
    for m in notifiable:
        context = {
            "parting_member": user,
            "team": team,
            "user": m.user,
            "url_base": get_url_base(),
        }
        body = render_to_string("messages/team-member-left.txt", context)
        if m.user.notify_by_message:
            msg = Message()
            msg.subject = subject
            msg.content = body
            msg.user = m.user
            msg.object = team
            msg.save()
        Meter('templated-emails-sent-by-type.teams.someone-left').inc()
        send_templated_email(m.user, subject,
                             "messages/email/team-member-left.html", context)

    context = {
        "team": team,
        "user": user,
        "url_base": get_url_base(),
    }
    subject = ugettext("You've left the %s team!" % (team))
    if user.notify_by_message:
        template_name = "messages/team-member-you-have-left.txt"
        msg = Message()
        msg.subject = subject
        msg.content = render_to_string(template_name, context)
        msg.user = user
        msg.object = team
        msg.save()
    template_name = "messages/email/team-member-you-have-left.html"
    Meter('templated-emails-sent-by-type.teams.you-left').inc()
    send_templated_email(user, subject, template_name, context)
コード例 #40
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
コード例 #41
0
ファイル: tests.py プロジェクト: benrito/batucada
 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')
コード例 #42
0
ファイル: forms.py プロジェクト: rmusina/mentorat-alumni-bbu
    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
コード例 #43
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)
コード例 #44
0
ファイル: tasks.py プロジェクト: thi517/unisubs
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)
コード例 #45
0
ファイル: tests.py プロジェクト: su-danny/famdates
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)
コード例 #46
0
ファイル: tests.py プロジェクト: TheProjecter/pinax-cohousing
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)
コード例 #47
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
            )
        )
コード例 #48
0
ファイル: moderate.py プロジェクト: esatterwhite/jaxer-org
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))
コード例 #49
0
ファイル: models.py プロジェクト: GunioRobot/hubplus
    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
コード例 #50
0
ファイル: tasks.py プロジェクト: thi517/unisubs
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)
コード例 #51
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)
コード例 #52
0
ファイル: views.py プロジェクト: fangsterr/Planamo-Django
def sendMessageFromTwilio(request):
    """
    View that Twilio visits when a Twilio phone number receives a SMS.
    Broadcasts a message sent by a user to relevant members of the group.
    
    Twilio API details: https://www.twilio.com/docs/api/twiml/sms/twilio_request
    """
    try:
        obj = request.POST
        print obj
        print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        sender_phone = normalize_phone_number(obj['From'])
        twilio_phone = normalize_phone_number(obj['To'])
        message_text = obj['Body']
    
        user_profile = get_object_or_404(UserProfile, phone_number=sender_phone)
        user = user_profile.user
        user_group_link = get_object_or_404(GroupUserLink, user=user,
            twilio_number=twilio_phone)
        group = user_group_link.group
    
        recipients = extract_recipients(user, group, message_text)
        if "error" in recipients:
            # send error message back to sender
            send_message(recipients["error"], None, user, group)
            return HttpResponse(Response(), mimetype='application/xml')
        recipients = recipients["recipients"]
        
        
        # Create Message model instance and send out the message
        message = Message(sender=user, group=group, message_text=message_text)
        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, user, recipient, group)
    
        return HttpResponse(Response(), mimetype='application/xml')
    except Exception, e:
        print e
        traceback.print_exc()
        return e
コード例 #53
0
ファイル: views.py プロジェクト: UCR-CS179-Team7/ListVerse
    def post(self, request):
        if request.user.is_authenticated():

            if(request.POST.get('accept_fr')):
                frequest_id = request.POST.get('accept_fr')
                frequest = FriendshipRequest.objects.get(id=frequest_id)
                frequest.accept()

            elif(request.POST.get('reject_fr')):
                frequest_id = request.POST.get('reject_fr')
                frequest = FriendshipRequest.objects.get(id=frequest_id)
                frequest.reject()

            elif(request.POST.get('delete_ln')):
                ln_id = request.POST.get('delete_ln')
                ln = Message.objects.filter(id=ln_id).delete()

            elif(request.POST.get('reply_gn_id')):
                gn_id = request.POST.get('reply_gn_id')
                gn_content = request.POST.get('reply_gn_content')

                # To user is the user who sent the message
                to_user = Message.objects.get(id=gn_id).from_user
                message = Message(
                            type='GN',
                            to_user=to_user,
                            from_user=request.user,
                            content=gn_content
                )
                message.save()
            circles = Circle.objects.filter(user=request.user)
            frequests = Friend.objects.unrejected_requests(user=request.user)
            myfriends = Friend.objects.friends(request.user)
            followers = Follow.objects.followers(request.user)
            following = Follow.objects.following(request.user)
            notifications = Message.objects.filter(to_user=request.user).order_by('-send_date')
            return render(request, 'home.html', {'frequests' : frequests,
                                                 'myfriends' : myfriends,
                                                 'followers': followers,
                                                 'following': following,
                                                 'circles': circles,
                                                 'notifications' : notifications})
        else:
            HttpResponseRedirect(reverse('account_login'))
コード例 #54
0
ファイル: forms.py プロジェクト: andrewkuzmych/litclub
    def save(self, new_data, request):
        # current date
        datetime_now = datetime.now()

        # retrieve current topic
        topic = Topic.objects.get(id = new_data['topicId'])
        topic.update_on = datetime_now
        topic.save()

        # save message
        message = Message()
        message.user_from = request.user
        message.user_to = topic.get_companion(request.user)
        message.topic = topic
        message.body = new_data['body']
        message.sent_on = datetime_now
        message.save()

        return message
コード例 #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:videos", kwargs={'user_id': user_pk}))
    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"
    send_templated_email(user, subject, template_name, context)
コード例 #56
0
ファイル: tasks.py プロジェクト: thi517/unisubs
def team_task_assigned(task_pk):
    from teams.models import Task
    from messages.models import Message
    try:
        task = Task.objects.select_related("team_video__video", "team_video",
                                           "assignee").get(
                                               pk=task_pk,
                                               assignee__isnull=False)
    except Task.DoesNotExist:
        return False
    task_type = Task.TYPE_NAMES[task.type]
    subject = ugettext(u"You have a new task assignment on Amara!")
    user = task.assignee
    if not team_sends_notification(
            task.team, 'block_task_assigned_message') or not user.is_active:
        return False
    task_language = None
    if task.language:
        task_language = get_language_label(task.language)
    context = {
        "team": task.team,
        "user": user,
        "task_type": task_type,
        "task_language": task_language,
        "url_base": get_url_base(),
        "task": task,
    }
    msg = None
    if user.notify_by_message:
        template_name = "messages/team-task-assigned.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-assigned.html"
    email_res = send_templated_email(user, subject, template_name, context)
    return msg, email_res
コード例 #57
0
ファイル: forms.py プロジェクト: forknfork/unisubs
    def save(self):
        messages = []
        
        team = self.cleaned_data['team']
        languages = self.cleaned_data['languages']

        members = team.users.exclude(pk=self.author.pk)
        
        if languages:
            members = members.filter(userlanguage__language__in=languages).distinct()

        for user in members:
            message = Message(user=user)
            message.author = self.author
            message.content = self.cleaned_data['content']
            message.subject = self.cleaned_data['subject']
            message.object = team
            message.save()
            messages.append(message)
            
        return messages
コード例 #58
0
 def save(self, sender):
     challenge = self.cleaned_data['challenge']
     try:
         challenge = Challenge.objects.get(id=int(challenge))
     except Challenge.DoesNotExist:
         raise forms.ValidationError(_(u'Not a valid challenge'))
     recipients = UserProfile.objects.filter(
         submissions__challenge=challenge).distinct()
     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,
         )
         msg.save()
         message_list.append(msg)
     return message_list