Ejemplo n.º 1
0
def notify(sender, receptors, message, url, level=1, **kwargs):
    """
    receptors: list of user instances
    """
    notifications = []
    receptor_emails = []
    for receptor in receptors:
        notification = Notification(
            sender=sender,
            receptor=receptor,
            message=message,
            url=url,
            level=level,
        )
        notification.save()
        notifications.append(notification)
        receptor_emails.append(receptor.email)

    if level < EMAIL_THRESHOLD:
        send_mail(message,
                  url,
                  sender.email,
                  receptor_emails,
                  fail_silently=False)

    return notifications
Ejemplo n.º 2
0
    def get(self, page=None):
        current_user_object = self.get_current_user_object()
        if not page:
            page = 1
        page = int(page)

        mentions_marshalled = []
        mentions = Notification.mentions_for_user(current_user_object.id,
                                                  int(page))
        mentions_count = Notification.mentions_for_user_count(
            current_user_object.id)

        url_format = '/mentions/%d'
        for mention in mentions:
            c = Comment.get('id = %s and deleted = 0', mention.action_id)
            if c:
                sf = Sharedfile.get('id = %s and deleted = 0', c.sharedfile_id)
                if sf:
                    mentions_marshalled.append({
                        'comment': c,
                        'sharedfile': sf,
                    })

        # this clears all mentions. When you visit this page
        ns = Notification.where('type=%s and receiver_id=%s and deleted=0',
                                'mention', current_user_object.id)
        [n.delete() for n in ns]

        return self.render("conversations/mentions.html", mentions=mentions_marshalled, count=mentions_count, \
            page=page, url_format=url_format, selected='mentions')
Ejemplo n.º 3
0
    def post(self, shake_name=None):
        shake = Shake.get('name=%s', shake_name)
        current_user_object = self.get_current_user_object()
        requestor = User.get('id = %s', self.get_argument('user_id', None))
        
        if not shake:
            raise tornado.web.HTTPError(404)
            
        if not requestor:
            if self.get_argument('json', None):
                return self.write({'status':'error'})
            else:
                return self.redirect('/%s', shake.name)
        
        no = Notification.get('sender_id = %s and receiver_id = %s and action_id = %s and deleted = 0', requestor.id, current_user_object.id, shake.id)

        if not no:
            if self.get_argument('json', None):
                return self.write({'status':'error'})
            else:
                return self.redirect('/%s' % (shake.name))
        
        no.delete()
        
        if self.get_argument('json', None):
            return self.write({'status':'ok', 'count' : Notification.count_for_user_by_type(current_user_object.id, 'invitation_request')})
        else:
            return self.redirect('/%s' % (shake.name))
Ejemplo n.º 4
0
 def post(self, comment_id):
     session = get_current_session()
     if session.has_key('user'):
         message = helper.sanitizeHtml(self.request.get('message'))
         user = session['user']
         if len(message) > 0:
             try:
                 parentComment = db.get(comment_id)
                 comment = Comment(message=message,
                                   user=user,
                                   post=parentComment.post,
                                   father=parentComment)
                 comment.put()
                 comment.post.remove_from_memcache()
                 vote = Vote(user=user, comment=comment, target_user=user)
                 vote.put()
                 Notification.create_notification_for_comment_and_user(
                     comment, parentComment.user)
                 self.redirect('/noticia/' + str(parentComment.post.key()))
             except db.BadKeyError:
                 self.redirect('/')
         else:
             self.redirect('/responder/' + comment_id)
     else:
         self.redirect('/login')
Ejemplo n.º 5
0
    def post(self, post_id):
        session = get_current_session()
        if session.has_key('user'):
            message = helper.sanitizeHtml(self.request.get('message'))
            user = session['user']
            if len(message) > 0:
                try:
                    post = Post.all().filter(
                        'nice_url =', helper.parse_post_id(post_id)).get()
                    if post == None:  #If for some reason the post doesn't have a nice url, we try the id. This is also the case of all old stories
                        post = db.get(helper.parse_post_id(post_id))

                    post.remove_from_memcache()
                    comment = Comment(message=message, user=user, post=post)
                    comment.put()
                    vote = Vote(user=user, comment=comment, target_user=user)
                    vote.put()
                    Notification.create_notification_for_comment_and_user(
                        comment, post.user)
                    self.redirect('/noticia/' + post_id)
                except db.BadKeyError:
                    self.redirect('/')
            else:
                self.redirect('/noticia/' + post_id)
        else:
            self.redirect('/login')
Ejemplo n.º 6
0
def _invitations(shake, current_user):
    invitation = None
    invitation_requests = []

    if current_user:
        notification = Notification.invitation_to_shake_for_user(
            shake, current_user)
        if notification:
            sender = notification.sender()
            related_object = notification.related_object()
            invitation = {
                'sender': sender,
                'related_object': related_object,
                'id': notification.id
            }

    if current_user and current_user.id == shake.user_id:
        notifications = Notification.where(
            'type = %s and receiver_id = %s and action_id = %s and deleted = 0',
            'invitation_request', current_user.id, shake.id)
        if notifications:
            for notification in notifications:
                sender = notification.sender()
                related_object = notification.related_object()
                invitation_requests.append({
                    'sender': sender,
                    'related_object': related_object,
                    'id': notification.id
                })

    return (
        invitation,
        invitation_requests,
    )
Ejemplo n.º 7
0
Archivo: tests.py Proyecto: CYJ/mazu
class NotificationTestCase(CoreTestCase):

    def setUp(self):
        super(NotificationTestCase, self).setUp()
        self._create()

    def _create(self):
        self.subject = random_string(25)
        self.message = random_string(35)
        self.notification = Notification(
            user=self.user,
            subject=self.subject,
            message=self.message
        )
        self.notification.save()

    def test_can_list(self):
        response = self.client.get(reverse_lazy('notification.list'))
        self.assertEqual(response.status_code, 200)

        count = Notification.objects.filter(user=self.user).count()
        self.assertEqual(len(response.context['object_list']), count)

    def test_can_show_detail(self):
        self._create()
        url = reverse_lazy('notification.detail', args=[self.notification.id])
        response = self.client.get(url)
        self.assertEqual(response.context['object'].subject, self.notification.subject)
        self.assertEqual(response.context['object'].read, True)
Ejemplo n.º 8
0
    def post(self):
        if self.request.get('notification-route-entity-key'):
            user = users.get_current_user()
            email = user.email().lower()
            receiver = self.request.get('notification-contact')
            if str(self.request.get('daily-notification')) == "on":
                notification_type = 1
            else:
                notification_type = 0
            route_key = ndb.Key(
                urlsafe=str(self.request.get('notification-route-entity-key')))
            route = route_key.get()
            route_time = route.start_time
            notification_time = route_time - datetime.timedelta(hours=int(
                self.request.get("notification-hour"))) - datetime.timedelta(
                    minutes=int(self.request.get("notification-minute")))

            new_notification = Notification(parent=route_key,
                                            creator=email,
                                            receiver=receiver,
                                            time=notification_time,
                                            type=notification_type,
                                            message="")
            new_notification.put()
            notification_utils.add_notification_to_task_queue(new_notification)

            self.redirect('/'.join(self.request.referer.split("/")[:3]) +
                          "?route=" + str(route.key.urlsafe()))
        else:
            self.redirect('/')
Ejemplo n.º 9
0
 def post(self, request):
     data = request.POST
     timestamp = timezone.now()
     if 'oid' in data and data['oid'] and validate_oid(data['oid']):
         OID = data['oid']
     else:
         return HttpResponseBadRequest('Error: No valid OID provided')
     if 'iped' in data and data['iped'] and get_school(data['iped']):
         school = get_school(data['iped'])
         if not school.contact:
             errmsg = "Error: School has no contact."
             return HttpResponseBadRequest(errmsg)
         if Notification.objects.filter(institution=school, oid=OID):
             errmsg = "Error: OfferID has already generated a notification."
             return HttpResponseBadRequest(errmsg)
         notification = Notification(institution=school,
                                     oid=OID,
                                     timestamp=timestamp,
                                     errors=data['errors'][:255])
         notification.save()
         msg = notification.notify_school()
         callback = json.dumps({'result':
                                'Verification recorded; {0}'.format(msg)})
         response = HttpResponse(callback)
         return response
     else:
         errmsg = ("Error: No school found")
         return HttpResponseBadRequest(errmsg)
Ejemplo n.º 10
0
Archivo: views.py Proyecto: darxsys/PUS
    def post(self, request, *args, **kwargs):
        user_id = kwargs['user_id']
        sender = request.user.customuser
        user = CustomUser.objects.get(pk=user_id)
        if user == sender:
            raise HttpResponseForbidden("Can't add itself.")
        
        user_friends = user.friends.all() 
        sender_notifications = sender.notification.all()
        if sender not in user_friends:            
            # make notification only when adding first
            n = Notification(user=user, source=sender)
            n.save()
        else:
            # delete already generated notification for sender
            m = ""
            for notif in sender_notifications:
                if notif.source == user:
                    m = notif
            if not m == "":
                m.delete()

        sender.friends.add(user)
        sender.save()

        c = user_context(user, sender)
        return render(request, self.template_name, c)
Ejemplo n.º 11
0
  def post(self, post_id):
    session = get_current_session()
    if session.has_key('user'):
      message = helper.sanitizeHtml(self.request.get('message'))
      user = session['user']
      key = self.request.get('comment_key')
      if len(message) > 0 and key == keys.comment_key:
        try:
          post = Post.all().filter('nice_url =', helper.parse_post_id( post_id ) ).get()
          if post  == None: #If for some reason the post doesn't have a nice url, we try the id. This is also the case of all old stories
            post = db.get( helper.parse_post_id( post_id ) ) 

          post.remove_from_memcache()
          comment = Comment(message=message,user=user,post=post)
          comment.put()
          helper.killmetrics("Comment","Root", "posted", session, "",self)
          vote = Vote(user=user, comment=comment, target_user=user)
          vote.put()
          Notification.create_notification_for_comment_and_user(comment,post.user)
          self.redirect('/noticia/' + post_id)
        except db.BadKeyError:
          self.redirect('/')
      else:
        self.redirect('/noticia/' + post_id)
    else:
      self.redirect('/login')
Ejemplo n.º 12
0
def create_user():
    if not session.get('user_id'):
        flash("You need to be logged in to do that.", category="danger")
        return redirect(url_for('main.home'))
    user = User.query.filter_by(id=session['user_id']).one()
    if user.type != 1:
        flash("You need administrator priveledges to do that.", category="danger")
        return redirect(url_for('main.home'))
    form = CreateUserForm(request.form)
    random_password = str(uuid.uuid4())[:8]
    if request.method=="POST" and form.validate():
        newUser = User(type=int(form.admin.data), password=random_password, username=form.username.data, email=form.email.data)
        if User.query.filter_by(username=newUser.username).all():
            flash("A user with that username already exists!", category="danger")
        elif User.query.filter_by(email=newUser.email).all():
            flash("A user with that email already exists!", category="danger")
        else:
            db.session.add(newUser)
            db.session.commit()
            registered_notification = Notification(newUser.id, None, "PlantSpeak Registration Details", """You have successfully signed up for PlantSpeak.
             Your login details are as follows:
             USERNAME: %s
             PASSWORD %s""" % (newUser.username, random_password), newUser.email)
            registered_notification.send()
            flash("User created successfully!", category="success")
            return redirect(url_for('main.home'))
    return render_template("create_user.html", form=form)
Ejemplo n.º 13
0
    def get(self):
        session = get_current_session()
        if session.has_key('user'):
            user = session['user']
            page = helper.sanitizeHtml(self.request.get('pagina'))
            perPage = 10
            page = int(page) if page else 1
            realPage = page - 1
            inboxAll = True
            if realPage > 0:
                prevPage = realPage
            if (page * perPage) < Notification.all().filter(
                    "target_user ="******"target_user ="******"-created").fetch(perPage, perPage * realPage)
            prefetch.prefetch_refprops(notifications, Notification.post,
                                       Notification.comment,
                                       Notification.sender_user)
            self.response.out.write(
                template.render('templates/notifications.html', locals()))
        else:
            self.redirect('/login')
Ejemplo n.º 14
0
def dashboard():
    """
    The '/dashboard' route directs a user to view their dashboard.
    """
    if 'username' in session:
        if not session['type_of_user'] == "user":
            return render_template("access_denied.html")

        info = User.get_user_info(session['username'])
        if (info == None):
            return render_template("dashboard.html", first_name=" ")
        first_name = info['first_name']

        # Get notifications for this user.
        unread = Notification.get_number_of_unread(session['username'])
        notifications = Notification.get_notif_to_recipient(
            session['username'], 5)

        # If the user has no projects in history, they are a new user.
        user_type = User.get_user_info(session['username'])['type_of_user']
        recs = {
            "client_rec_des": "Most Active Clients",
            "dev_rec_des": "Most Active Developers",
            "client_rec": Client.get_most_active_clients(),
            "dev_rec": Developer.get_most_active_developers()
        }

        if user_type == 'client':
            if Client.get_info(
                    session['username'])['num_of_completed_projects'] > 0:
                recs = {
                    "client_rec_des":
                    "Clients with Similar Interests",
                    "dev_rec_des":
                    "Developers with Similar Interests",
                    "client_rec":
                    Client.get_similar_clients(session['username']),
                    "dev_rec":
                    Developer.get_similar_developers(session['username'])
                }
        elif user_type == 'developer':
            if Developer.get_info(
                    session['username'])['num_of_completed_projects'] > 0:
                recs = {
                    "client_rec_des":
                    "Clients with Similar Interests",
                    "dev_rec_des":
                    "Developers with Similar Interests",
                    "client_rec":
                    Client.get_similar_clients(session['username']),
                    "dev_rec":
                    Developer.get_similar_developers(session['username'])
                }
        return render_template("dashboard.html",
                               first_name=first_name,
                               notifications=notifications,
                               recs=recs,
                               unread=unread)
    else:
        return redirect(url_for('login'))
 def setUpTestData(cls):
     admin = User.objects.get(pk=1)
     group_foo = User.objects.filter(groups__name='group_foo')
     staff = User.objects.get_by_natural_key('staff')
     cls.admin_user = admin
     cls.n2_admin = Notification.send(
         [admin],
         'test notification to admin',
         'fa-info',
         Notification.COLOR_DANGER,
         url='http://www.google.com/'
         )
     cls.n2_staff = Notification.send(
         [staff],
         'test notifications to staff',
         'fa-bell',
         Notification.COLOR_DANGER,
     )
     cls.n2_group_foo = Notification.send(
         group_foo,
         'test notifications to client',
         'fa-bell',
         Notification.COLOR_WARNING,
         ''
     )
Ejemplo n.º 16
0
 def push_user_notification(self, event_uuid, team_id, user_id):
     ''' Push to one user '''
     if team_id in self.notify_connections and user_id in self.notify_connections[team_id]:
         json = Notification.by_event_uuid(event_uuid).to_json()
         for wsocket in self.notify_connections[team_id][user_id]:
             wsocket.write_message(json)
             Notification.delivered(wsocket.user_id, event_uuid)
Ejemplo n.º 17
0
def notify_user( notification_type, user=None, follower=None, photo=None):
    notification = Notification(notification_type=notification_type, user=follower, photo=photo)
    notification.save()
    user_notification = UserNotifications.objects.get(user=user)
    user_notification.notifications.add(notification)
    user_notification.save()
    return
Ejemplo n.º 18
0
 def delete(id):
     entity = Notification.get(id)
     if(entity is None):
         raise ValueError("Notification does not exists")
     else:
         entity.active = False
         Notification.save(entity)
Ejemplo n.º 19
0
    def save(entity):        
        if entity.key is None:            

            if not entity.notification_status:
                entity.notification_status = "unread"

            if not (entity.notification_status == "read" or entity.notification_status == "unread"):
                raise ValueError("notification_status can be only 'read' or 'unread'")

            entity = Notification.save(entity)
        else:
            
            if not (entity.notification_status == "read" or entity.notification_status == "unread"):
                raise ValueError("notification_status can be only 'read' or 'unread'")

            current = Notification.get(entity.key.urlsafe())
            if current is not None:
                current.company_key = entity.company_key
                current.user_key = entity.user_key
                current.notification_text = entity.notification_text
                current.notification_params = entity.notification_params
                current.notification_status = entity.notification_status
                current.notification_type = entity.notification_type
                entity = Notification.save(entity)
            else:
                raise ValueError("Notification does not exists")
        return entity
Ejemplo n.º 20
0
def create_introduction_notification(user):
    """
    """
    subject = "Welcome to Groupr"
    body = "Anything is possible at Groupr. The infinite is possible at Groupr. The unattainable is unknown at Groupr. This Groupr. This is Groupr."
    new_notif = Notification(recipient=user, subject=subject, text=body)
    new_notif.save()
Ejemplo n.º 21
0
 def mark_notifications_as_read(user_id: int):
     if user_id != g.user.id:
         abort(403)
     array_ids = validate_notifications_list_form(request.json)
     responses_array = []
     response_status = None
     for notification_id in array_ids:
         notification = Notification.get_notification_by_id(
             notification_id)
         if notification is None:
             notif_status = 404
         elif notification.user_id != user_id:
             notif_status = 403
         else:
             notification.mark_as_read()
             notif_status = 200
         responses_array.append({
             'id': notification_id,
             'status': notif_status
         })
         if response_status == 207 or response_status == notif_status:
             pass
         elif response_status is None:
             response_status = notif_status
         else:
             response_status = 207
     user = User.get_user_by_id(user_id)
     notifications = Notification.get_notifications_by_user(user)
     return jsonify({
         "notifications":
         [notification.as_dict() for notification in notifications]
     })
Ejemplo n.º 22
0
    def test_clears_all_subscriptions(self):
        user3 = User(name="user3",
                     email="*****@*****.**",
                     email_confirmed=1)
        user3.set_password('asdfasdf')
        user3.save()

        Subscription(user_id=self.sender.id, shake_id=2).save()
        Subscription(user_id=user3.id, shake_id=2).save()

        Notification.new_subscriber(self.sender, self.receiver, 1)
        Notification.new_subscriber(user3, self.receiver, 2)

        request = HTTPRequest(
            self.get_url('/account/clear-notification'), 'POST',
            {'Cookie': '_xsrf=%s;sid=%s' % (self.xsrf, self.receiver_sid)},
            '_xsrf=%s&type=subscriber' % (self.xsrf))
        self.http_client.fetch(request, self.stop)
        response = self.wait()

        j = json_decode(response.body)
        self.assertEqual(j['response'], "You have 0 new followers")
        ns = Notification.where('receiver_id=%s' % (self.receiver.id))
        for n in ns:
            self.assertTrue(n.deleted)
Ejemplo n.º 23
0
 def post(self, request):
     data = request.POST
     timestamp = timezone.now()
     if 'oid' in data and data['oid'] and validate_oid(data['oid']):
         OID = data['oid']
     else:
         return HttpResponseBadRequest('Error: No valid OID provided')
     if 'iped' in data and data['iped'] and get_school(data['iped']):
         school = get_school(data['iped'])
         if not school.contact:
             errmsg = "Error: School has no contact."
             return HttpResponseBadRequest(errmsg)
         if Notification.objects.filter(institution=school, oid=OID):
             errmsg = "Error: OfferID has already generated a notification."
             return HttpResponseBadRequest(errmsg)
         notification = Notification(institution=school,
                                     oid=OID,
                                     timestamp=timestamp,
                                     errors=data['errors'][:255])
         notification.save()
         msg = notification.notify_school()
         callback = json.dumps(
             {'result': 'Verification recorded; {0}'.format(msg)})
         response = HttpResponse(callback)
         return response
     else:
         errmsg = ("Error: No school found")
         return HttpResponseBadRequest(errmsg)
Ejemplo n.º 24
0
 def push_user_notification(self, event_uuid, team_id, user_id):
     ''' Push to one user '''
     if team_id in self.notify_connections and user_id in self.notify_connections[
             team_id]:
         json = Notification.by_event_uuid(event_uuid).to_json()
         for wsocket in self.notify_connections[team_id][user_id]:
             wsocket.write_message(json)
             Notification.delivered(wsocket.user_id, event_uuid)
Ejemplo n.º 25
0
def notify(course, user_id):
    course_id = course.course_id
    favs = course.favourite_by
    usernames = [fav.user_id for fav in favs]
    for username in usernames:
        if username != user_id:
            notify = Notification(user_id=username, course_id=course_id)
            notify.insert()
Ejemplo n.º 26
0
def reject_project(request, project_id):
    proj = Project.objects.get(id=int(project_id))
    new_notification = Notification(recipient=proj.client, subject="Project Rejected",
                                    text="The instructor decided that your project '{}' submission was not right for the" \
                                          " scope of the course and has decided not to allow students to bid on it.".format(proj.name))
    new_notification.save()
    proj.delete()
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Ejemplo n.º 27
0
    def test_deleting_favorite_notification(self):
        notification = Notification.new_favorite(sender=self.user2,
                                                 sharedfile=self.sharedfile)

        sent_notification = Notification.get("id=%s", notification.id)
        sent_notification.delete()
        check_delete_notification = Notification.get("id=%s", notification.id)
        self.assertTrue(check_delete_notification.deleted)
Ejemplo n.º 28
0
def reject_bid(request, bid_id):
    bid = Bid.objects.get(id=int(bid_id))
    new_notification = Notification(recipient=bid.student, subject="Bid Rejected",
                                    text="Your bid on the project '{}' was rejected by your instructors." \
                                         " Please browse and continue submitting more bids.".format(bid.project.name))
    new_notification.save()
    bid.delete()
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Ejemplo n.º 29
0
def reject_bid(request, bid_id):
    bid = Bid.objects.get(id=int(bid_id))
    new_notification = Notification(recipient=bid.student, subject="Bid on {} Rejected".format(bid.project.name),
                                    text="Your bid on the project {} was rejected by your instructor(s)." \
                                         "Please continue browsing and submitting more bids.")
    new_notification.save()
    bid.delete()
    return redirect_user_to_homepage(request.user.profile.user_type)
Ejemplo n.º 30
0
def award_bid(request, bid_id):
    bid = Bid.objects.get(id=int(bid_id))
    new_notification = Notification(recipient=bid.student, subject="Bid on {} Awarded!".format(bid.project.name),
                                    text="Your bid on the project {} was awarded by your instructor(s)!" \
                                         "This will be your project.  Contact your client at {}".format(bid.project.name, bid.project.client.email))
    new_notification.save()
    bid.delete()
    return redirect_user_to_homepage(request.user.profile.user_type)
Ejemplo n.º 31
0
 def push_team_notification(self, event_uuid, team_id):
     ''' Push to one team '''
     json = Notification.by_event_uuid(event_uuid).to_json()
     if team_id in self.notify_connections:
         for user_id in self.notify_connections[team_id].keys():
             for wsocket in self.notify_connections[team_id][user_id]:
                 wsocket.write_message(json)
                 Notification.delivered(wsocket.user_id, event_uuid)
Ejemplo n.º 32
0
def like(id, *args, **kwargs):
    currentUser = User.get().filter_by(id=kwargs['token']['id']).first()

    post = Post.get().filter_by(id=id).first()
    like = Post_Likes.get().filter(
        and_(Post_Likes.author == currentUser.id,
             Post_Likes.post == post.id)).first()

    not_id = str(db.session.execute(Sequence('notification_id_seq')))

    if like is not None:
        response = jsonify({'operation': 'disliked'})
        like.delete()
        body = 'unliked your post'
    else:
        response = jsonify({'operation': 'liked'})
        new_like = Post_Likes(post=post.id, author=currentUser.id)
        new_like.add()
        body = 'liked your post'

    not_check = Notification.get().filter_by(title=currentUser.name + ' ' +
                                             body).filter_by(
                                                 body=post.title).first()

    if not_check is None:
        notify = Notification(
            id=int(not_id),
            author=currentUser.id,
            user=post.author.id,
            type=2,
            title=post.title,
            body=currentUser.name + ' ' + body,
            link='/post/' +
            (str(post.title).replace(' ', '-')).replace('?', '') + '-' +
            str(post.id) + '?notification_id=' + not_id)
        notify.add()
    else:
        not_check.checked = False
        not_check.save()

    if post.author.status != 2:
        send_notification(
            post.author.id, {
                'text':
                currentUser.name + ' ' + body,
                'link':
                '/post/' +
                (str(post.title).replace(' ', '-')).replace('?', '') + '-' +
                str(post.id),
                'icon':
                currentUser.info.avatar_img,
                'id':
                not_id
            })

    socket.emit("notification", room="notification-{}".format(post.author.id))

    return make_response(response, 200)
Ejemplo n.º 33
0
def notification(request):
    '''
		View responsible for receiving a notification from PagSeguro and make a
		query to update the Payment.
	'''
    incoming_notification = Notification(code=request.POST['notificationCode'])
    incoming_notification.save()
    start_new_thread(incoming_notification.check, tuple())
    return HttpResponse("OK", mimetype="text/plain")
Ejemplo n.º 34
0
def send_notification():
	form = SendNotificationForm()
	if form.validate_on_submit():
		noti = Notification()
		noti.content = form.notification.data
		db.session.add(noti)
		db.session.commit()

	return redirect(url_for('notify.send_notification'))
Ejemplo n.º 35
0
 def post(self):
   notification = Notification(
       item_cl = Model.get(Key(self.request.get('key'))),
       message = self.request.get('message'),
       user = users.User(self.request.get('email')),
       is_cl = ("True" == self.request.get('is_cl')),
       time = datetime.now(),
       read = False)
   notification.put()
Ejemplo n.º 36
0
def notifyusers(userstonotify, parkingid):
    for user in userstonotify:
        notification = Notification()
        notification.userid = user
        message = "Your spot at " + str(parkingid) + " has been occupied"
        notification.message = message
        texthere(User.query.filter(User.id == user).first().phoneno, message)
        db.session.add(notification)
    db.session.commit()
Ejemplo n.º 37
0
def create_notification(text, entity, acting_user=None, recipient = None):
    try:
        notification = Notification(text = text, entity = entity, acting_user = acting_user, recipient=recipient)
        notification.save()
        return HttpResponse(_('Notification create successfully'))
    except:
        resp = HttpResponse(str(sys.exc_info()[1]))
        resp.status_code = 500
        return resp
Ejemplo n.º 38
0
def notification(request):
    """
		View responsible for receiving a notification from PagSeguro and make a
		query to update the Payment.
	"""
    incoming_notification = Notification(code=request.POST["notificationCode"])
    incoming_notification.save()
    start_new_thread(incoming_notification.check, tuple())
    return HttpResponse("OK", mimetype="text/plain")
Ejemplo n.º 39
0
 def _create(self):
     self.subject = random_string(25)
     self.message = random_string(35)
     self.notification = Notification(
         user=self.user,
         subject=self.subject,
         message=self.message
     )
     self.notification.save()
Ejemplo n.º 40
0
 def push_broadcast_notification(self, event_uuid):
     ''' Push to everyone '''
     json = Notification.by_event_uuid(event_uuid).to_json()
     for team_id in self.notify_connections.keys():
         for user_id in self.notify_connections[team_id].keys():
             for wsocket in self.notify_connections[team_id][user_id]:
                 wsocket.write_message(json)
                 if wsocket.user_id != '$public_user':
                     Notification.delivered(user_id, event_uuid)
Ejemplo n.º 41
0
def create_notification(notification: Notification) -> JSONResponse:
    """
    Adds a new notification.
    :param notification: the notification to add
    :return: status code and response data
    """
    db = _get_db()
    notification.notification_id = db["notifications"].find().count() + 1
    _get_db()["notifications"].insert_one(notification.to_dict())
    return JSONResponse(status_code=status.HTTP_201_CREATED, content=dumps([]))
Ejemplo n.º 42
0
def alert(users, notify_type, subject, url):
	'''Assesses whether or not a user's settings allow a notification, and creates a "smart link"
	notification if allowed
	'''
	
	users_permitting = (user for user in users if notify_type in user.notify_permissions)
	
	for user in users_permitting:
		n = Notification(recip=user, subject=subject, _url=url)
		n.save()
Ejemplo n.º 43
0
 def test_send_notification_to_group(self):
     """
     Tests that notification is sent to group.
     """
     group=Group.objects.get(name="test_group")
     notification = Notification(text="There is a new story in discussion", \
                                 group=group)
     notification.save()
     # Test that one message has been sent.
     self.assertEquals(len(mail.outbox), len([user for user in User.objects.all() if group in user.groups.all()]))
Ejemplo n.º 44
0
 def test_send_notification_to_user(self):
     """
     Tests that notification is sent to user.
     """
     notification = Notification(text="There is a new story in discussion", \
                                 recipient = User.objects.get(username="******"), \
                                 group = Group.objects.get(name="test_group"))
     notification.save()
     # Test that one message has been sent.
     self.assertEquals(len(mail.outbox), 1)
Ejemplo n.º 45
0
 def push_broadcast_notification(self, event_uuid):
     ''' Push to everyone '''
     json = Notification.by_event_uuid(event_uuid).to_json()
     for team_id in self.notify_connections:
         for user_id in self.notify_connections[team_id]:
             for wsocket in self.notify_connections[team_id][user_id]:
                 wsocket.write_message(json)
                 # Only mark delivered for non-public users
                 if wsocket.user_id != '$public_user':
                     Notification.delivered(user_id, event_uuid)
Ejemplo n.º 46
0
    def test_new_save_notification(self):
        notification = Notification.new_save(sender=self.user2,
                                             sharedfile=self.sharedfile)

        sent_notification = Notification.get("id=%s", notification.id)
        self.assertEqual(sent_notification.id, notification.id)
        self.assertEqual(sent_notification.sender_id, self.user2.id)
        self.assertEqual(sent_notification.receiver_id, self.user.id)
        self.assertEqual(sent_notification.action_id, 1)
        self.assertEqual(sent_notification.type, 'save')
Ejemplo n.º 47
0
 def push_broadcast_notification(self, event_uuid):
     """ Push to everyone """
     json = Notification.by_event_uuid(event_uuid).to_json()
     for team_id in self.notify_connections:
         for user_id in self.notify_connections[team_id]:
             for wsocket in self.notify_connections[team_id][user_id]:
                 wsocket.write_message(json)
                 # Only mark delivered for non-public users
                 if wsocket.user_id != "$public_user":
                     Notification.delivered(user_id, event_uuid)
Ejemplo n.º 48
0
def notificate_registry(new_user):
	users = User.objects.filter(is_superuser=True)

	for user in users:
		notification = Notification(
				user=user,
				message="El cliente "+new_user.first_name+" "+new_user.last_name+" se ha registrado en la plataforma.",
				short="Nuevo registro",
				icon="fa fa-user"
			)
		notification.save()
def newNotification(values):
	try:
		print values
		auxNotification = Notification(to=values["to"], _from=values["from"], send_date=values["send_date"], \
		 activity=values["activity"], message=values["message"], title=values["title"])
		auxNotification.save()
		return True
	except DatabaseError as e:
		return False
	except IntegrityError as e:
		return False
Ejemplo n.º 50
0
 def get_approval_notice(self):
     notice = Notification(
         channel=self,
         target=self.target,
         text="%s wants to send you notifications. Click here to approve/deny this request."
         % self.source.source_name,
     )
     notice.title = "New Notification Source"
     notice.link = "http://%s/sources" % WWW_HOST
     notice.icon = self.source.source_icon
     notice.sticky = "true"
     return notice
Ejemplo n.º 51
0
def notify_group(notification_type, group=None, photowalk=None):
    notification = Notification(notification_type=notification_type, group=group, photowalk=photowalk)
    if notification_type is 'group':
        to_notify = group.members.all()
    elif notification_type is 'photowalk':
        to_notify = photowalk.participants.all()
    notification.save()
    for user in to_notify:
        user_notification = UserNotifications.objects.get(user=user)
        user_notification.notifications.add(notification)
        user_notification.save()
    return 
 def test_seen(self):
     seen_befor = self.n2_admin[0].seen
     self.assertEqual(
         seen_befor,
         False
     )
     
     Notification.seen_all(self.admin_user)
     seen_after = Notification.objects.get(pk=self.n2_admin[0].pk).seen
     self.assertEqual(
         seen_after,
         True
     )
Ejemplo n.º 53
0
 def __create__(cls, user, title, message, category, event_uuid, icon=None):
     ''' Create a notification and save it to the database '''
     notification = Notification(
         user_id=user.id,
         event_uuid=event_uuid,
         title=unicode(title),
         message=unicode(message),
         category=category,
     )
     if icon is not None:
         notification.icon = icon
     dbsession.add(notification)
     dbsession.flush()
Ejemplo n.º 54
0
 def __anonymous__(cls, title, message, category, event_uuid, icon=None):
     ''' Creates anonysmous notification where user_id = NULL '''
     notification = Notification(
         user_id=None,
         event_uuid=event_uuid,
         title=unicode(title),
         message=unicode(message),
         category=category,
     )
     if icon is not None:
         notification.icon = icon
     dbsession.add(notification)
     dbsession.flush()
Ejemplo n.º 55
0
def notify(request, app, model, id, action):
    band = request.band
    ct = ContentType.objects.get(app_label=app, model=model)
    try:
        obj = ct.get_object_for_this_type(id=id)
    except:
        message = _("%(model)s with id %(id)s does not exist" %
                    dict(model=model, id=id))
        return dict(success=False, message=message)
    users = band.active_members
    notes = request.POST.get('notes') or None
    mail = request.POST.get('mail') or False
    Notification.notify(obj, action, users, notes=notes, mail=mail)
    return dict(success=True)
Ejemplo n.º 56
0
def notify_user(message):
    user = User.objects.get(id=int(message['user_id']))
    related_user = User.objects.get(id=int(message['related_user_id']))
    nc = user.notification_config(message['notification_type'])

    if nc.take_action:
        notification = Notification(user=user, type_id=notification_types[message['notification_type']],
                                    related_user=related_user, seen=not nc.notify, **message['data'])

    notification.save(only_if_should_notify=True, host_url=message['host_url'])

    if nc.email and message['host_url']:
        Channel('email_notification').send({
            'notification_id': notification.id,
            'host_url': message['host_url']
        })
Ejemplo n.º 57
0
    def persist_message(self, msg):
        notification = Notification()
        notification.sender = msg.sender
        notification.owner = users.User(utils.address_part(msg.sender))

        # TODO: Handle invalid delays
        delay = utils.email_in_path(self.request.path)
        notification.delay_str = delay
        notification.fire_time = datetime.datetime.now() + utils.parse_timedelta(delay)

        strip_cc(msg)
        try:
            strip_attachments(msg)
        except Exception, e:
            logging.warning('Found warning ' + str(e))
            pass
Ejemplo n.º 58
0
 def post(self):
     action = self.request.get('action')
     if action == 'delete':
         notice = Notification.get_by_hash(self.request.get('notification'))
         if self.account.key() == notice.target.key():
             notice.delete()
     self.redirect('/history')
Ejemplo n.º 59
0
 def post(self):
     action = self.request.get("action")
     if action == "delete":
         notice = Notification.get_by_hash(self.request.get("notification"))
         if self.account.key() == notice.target.key():
             notice.delete()
     self.redirect("/history")
Ejemplo n.º 60
0
 def get_notifications(self,tree_name=None,from_username=None):
     data = None
     if tree_name is not None:
         data = Notification.get_all_by_tree_name(tree_name)
     elif from_username is not None:
         data = Notification.get_all_by_from_username(from_username)
     elif self.current_user_info() is not None:
         #default to the users inbox
         data = Notification.get_all_by_to_username(self.current_user_info().username)
     else:
         return False,  [ 'unauthenticated' ]
         
     if data is not None:
         return True, data
     else:
         #if we could not get to the default, then the user must be logged out
         return False,  [ ]