Ejemplo n.º 1
0
def addFriendView(request):
    creator = request.user
    friend_name = request.GET.get('friend', '')
    action = request.GET.get('accepted', '')
    friend = dbUser.objects.get(username=friend_name)
    if (action == 'false'):
        Friendship.objects.filter(creator=friend, friend=creator).delete()
        return redirect('/friends/')
    if not Friendship.objects.filter(creator=creator, friend=friend):
        if Friendship.objects.filter(creator=friend, friend=creator).exists():
            friendship1 = Friendship.objects.get(creator=friend,
                                                 friend=creator)
            friendship1.status = 'accepted'
            friendship2 = Friendship(creator=creator,
                                     friend=friend,
                                     status='accepted')
            friendship1.save()
            notification1 = Notification(
                user=friend,
                user2=creator,
                notification_type="friend-accept",
                date=datetime.date.today(),
                time=datetime.datetime.now().strftime('%H:%M:%S'),
                notification="You are now friends with %s" % creator.username)
            notification2 = Notification(
                user=creator,
                user2=friend,
                notification_type="friend-accept",
                date=datetime.date.today(),
                time=datetime.datetime.now().strftime('%H:%M:%S'),
                notification="You are now friends with %s" % friend.username)
            notification1.save()
            notification2.save()
        else:
            friendship2 = Friendship(creator=creator, friend=friend)
            notification = Notification(
                user=friend,
                user2=creator,
                notification_type="friend-request",
                date=datetime.date.today(),
                time=datetime.datetime.now().strftime('%H:%M:%S'),
                notification="You have a friend request from %s" %
                creator.username)
            notification.save()
        friendship2.save()

    sent = True
    context_dict = {'sent': sent}
    return redirect('/friends/')
Ejemplo n.º 2
0
def protest_approval(warning_id):
    """
    The '/protest_approval/<warning_id>' route directs a superuser to approve a protest against a warning
    with the id of [warning_id].
    """
    if session['type_of_user'] == 'user':
        return redirect(url_for('dashboard'))
    if session['type_of_user'] == 'applicant':
        return redirect(url_for('dashboard_applicant'))

    warning_id = int(warning_id)
    info = SystemWarning.get_warning_info(warning_id)
    username = info['warned_user']
    type_of_user = User.get_user_info(username)['type_of_user']
    avg_rating = 0
    if type_of_user == 'client':
        avg_rating = Client.get_info(username)['avg_rating']
    elif type_of_user == 'developer':
        avg_rating = Developer.get_info(username)['avg_rating']

    form = ProtestApprovalForm()

    if request.method == 'GET':
        return render_template("protestApproval.html",
                               warning_id=warning_id,
                               info=info,
                               form=form,
                               avg_rating=avg_rating)
    if request.method == 'POST':
        if form.validate():
            if form.decision.data == 'remove':
                SystemWarning.remove_warning(warning_id)
                Notification(
                    username, session['username'],
                    'Your protest for warning#' + str(warning_id) +
                    ' was approved. Your warning has been deleted.')
            else:
                SystemWarning.keep_warning(warning_id)
                Notification(
                    username, session['username'],
                    'Your protest for warning#' + str(warning_id) +
                    ' was not approved. Your warning remains.')
            return redirect(url_for('dashboard_superuser'))
        else:
            return render_template("protestApproval.html",
                                   warning_id=warning_id,
                                   info=info,
                                   form=form,
                                   avg_rating=avg_rating)
Ejemplo n.º 3
0
def delete_account_approval(delete_request_id):
    """
    The '/delete_acount_approval' route directs a superuser to a form where they can approve/deny an account deletion request.
    """
    if 'username' not in session:
        return redirect(url_for('login'))
    if session['type_of_user'] == 'user':
        return redirect(url_for('dashboard'))
    if session['type_of_user'] == 'applicant':
        return redirect(url_for('dashboard_applicant'))

    form = DeleteAccountApprovalForm()
    delete_request_id = int(delete_request_id)
    info = DeleteRequest.get_delete_request_info(delete_request_id)

    if request.method == 'GET':
        return render_template("deleteAccountApproval.html",
                               form=form,
                               info=info)
    if request.method == 'POST':
        if form.validate():
            if form.decision.data == 'approve':
                DeleteRequest.approve_delete_request(delete_request_id)
            else:
                DeleteRequest.deny_delete_request(delete_request_id)
                Notification(
                    info['username'], session['username'],
                    'Your delete account request (ID#' +
                    str(info['delete_request_id']) + ') was denied.')
            return redirect(url_for('dashboard_superuser'))
        else:
            return render_template("deleteAccountApproval.html",
                                   form=form,
                                   info=info)
Ejemplo n.º 4
0
def send_sms(user: models.User, recipients: List[str], message: str):

    api_key = str(settings.AFRICASTALKING_API_KEY)
    api_username = str(settings.AFRICASTALKING_API_USERNAME)

    data = {
        'username': api_username,
        'to': ','.join(recipients),
        'message': message,
        # 'from': str(settings.AFRICASTALKING_API_SENDER_ID)
    }
    headers = {
        'apiKey': api_key,
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }

    # logger.debug('SMS send request : {}'.format(data))

    response = requests.post(settings.AFRICASTALKING_API_URL,
                             data=data,
                             headers=headers)

    try:
        response = response.json()
    except Exception as error:
        logger.debug(error)
        raise HTTPException(status_code=response.status_code,
                            detail=response.text)
    else:
        sms_message_data = response['SMSMessageData']
        notification = Notification(user=user, metadata=sms_message_data)
        logger.debug(notification)

    return response
Ejemplo n.º 5
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.º 6
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.º 7
0
def due():
    tenants = Tenants.query.filter_by(tenant_status="1").all()

    for t in tenants:
        a = 0
        pays = Pays.query.filter(
            and_(Pays.tenantID == t.tenantID,
                 Pays.stallID == t.stallID)).all()
        for p in pays:
            month = date_cut(p.date_issued, [5, 6])
            year = date_cut(p.date_issued, [0, 1, 2, 3])

            if year == date_cut(now, [0, 1, 2, 3]):
                if month == date_cut(now, [5, 6]):
                    a = a + 1
        print a

        if a == 0:
            notifier = Notification.query.filter(
                and_(
                    and_(Notification.tenant_id == t.tenantID,
                         Notification.stall_id == t.stallID),
                    Notification.status == 1)).first()
            if notifier is None:
                name = t.last_name + ', ' + t.first_name + ' ' + t.mid_name
                notif = Notification(
                    name=name,
                    description="Have not yet done any payment this month",
                    date=str(now),
                    tenant_id=t.tenantID,
                    stall_id=t.stallID)
                dbase.session.add(notif)
                dbase.session.commit()
Ejemplo n.º 8
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
 def post(self):
     notification_category_dict = request.get_json()
     if not notification_category_dict:
         response = {'message': 'No input data provided'}
         return response, HttpStatus.bad_request_400.value
     errors = notification_schema.validate(notification_category_dict)
     if errors:
         return errors, HttpStatus.bad_request_400.value
     try:
         notification_category_name = notification_category_dict[
             'notification_category']['name']
         notification_category = NotificationCategory.query.filter_by(
             name=notification_category_name).first()
         if notification_category is None:
             # Create a new NotificationCategory
             notification_category = NotificationCategory(
                 name=notification_category_name)
             orm.session.add(notification_category)
         # Now that we are sure we have a notification category,
         # we can create a new Notification
         notification = Notification(
             message=notification_category_dict['message'],
             ttl=notification_category_dict['ttl'],
             notification_category=notification_category)
         notification.add(notification)
         query = Notification.query.get(notification.id)
         dump_result = notification_schema.dump(query).data
         return dump_result, HttpStatus.created_201.value
     except SQLAlchemyError as e:
         orm.session.rollback()
         response = {"error": str(e)}
         return response, HttpStatus.bad_request_400.value
Ejemplo n.º 10
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.º 11
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.º 12
0
def up():
    for item in seed:
        notification = Notification(**item["init"])

        db.session.add(notification)

    db.session.commit()
Ejemplo n.º 13
0
def buy(item_id):
    """lets the user buys a specific item"""
    # get the item from database
    item_to_buy = Item.query.get(item_id)
    # If no such item return error message
    if not item_to_buy:
        return render_template("mes.html", error="there is no such item")
    # If the item is sold return error message
    if item_to_buy.sold:
        return render_template("mes.html", \
        error="the item that you are trying to buy is already sold")
    # If the user is trying to buy his own item return error message
    if item_to_buy.user_id == session['user_id']:
        return render_template("mes.html",
                               error="you can't buy your own item.")
    # add notification to the item's owner telling him that his item was sold.
    notification = Notification(user_id=item_to_buy.user_id,
                                item_id=item_to_buy.id)
    db.session.add(notification)
    # mark item as sold and add the buying_user to the database then commit
    item.sold = True
    item.buying_user = session["user_id"]
    db.session.commit()
    flash('You have successfully bought the item')
    return redirect(url_for("index"))
Ejemplo n.º 14
0
def unblock_api_key(requested_key):
    try:
        if requested_key.blocked is True:
            requested_key.blocked = False
            new_notification = Notification(
                user=requested_key.developer,
                by_user=current_user.email,
                body=f"Your API Key has been unblocked by {current_user.name}.",
                date=generate_date(),
                category='unblock',
                user_name=current_user.name)
            db.session.add(new_notification)
            db.session.commit()
            flash("This API Key has been unblocked successfully.")
            return redirect(
                url_for('user_operations.user_page',
                        current_mode='api',
                        user_id=requested_key.developer_id))
        else:
            flash("This API Key is not blocked.")
            return redirect(
                url_for('user_operations.user_page',
                        current_mode='api',
                        user_id=requested_key.developer_id))
    except AttributeError:
        return abort(400)
 def handle_post(self, email, account_info):
     if self.request.get("project_entity_key"):
         project_key_str = self.request.get("project_entity_key")
         project_key = ndb.Key(urlsafe=project_key_str)
         project = project_key.get()
         potential_invitees = self.request.get_all("project_collaborator")
         for potential_user in potential_invitees:
             if potential_user and potential_user != utils.get_profile_for_email(
                     email).name:
                 profile_query = Profile.query(
                     Profile.name == potential_user)
                 for profile in profile_query:
                     user_key = profile.key.parent()
                 user = user_key.get()
                 if user_key not in project.users:
                     notification_count = Notification.query(
                         Notification.project_key == project_key,
                         ndb.OR(Notification.sender == user_key,
                                Notification.receiver == user_key)).count()
                     if notification_count == 0:
                         notification = Notification(parent=user_key)
                         notification.sender = account_info.key
                         notification.receiver = user_key
                         notification.project_key = project_key
                         notification.message = utils.get_profile_for_email(
                             email
                         ).name + " would like you to join " + project.title
                         notification.put()
     self.redirect(self.request.referer)
Ejemplo n.º 16
0
def make_user_administrator(token, user, reason):
    load_token(token, salt='make-auth')
    if user:
        try:
            user.author = False
        except AttributeError:
            return abort(400)
        set_notification('administrator', user.email, user.name,
                         current_user.name, reason)
        user.admin = True
        new_notification = Notification(
            user=user,
            by_user=current_user.email,
            user_name=current_user.name,
            body=f"You were set as an administrator by {current_user.name}.",
            date=generate_date(),
            category='new')
        db.session.add(new_notification)
        db.session.commit()
        flash(
            "The user has been set as an administrator, a notification has been sent to the user."
        )
        return redirect(url_for('user_operations.user_page', user_id=user.id))
    else:
        return abort(400)
Ejemplo n.º 17
0
 def post(self, request):
     data = request.POST
     timestamp = timezone.now()
     if data.get('oid') and validate_oid(data['oid']):
         OID = data['oid']
     else:
         return HttpResponseBadRequest('Error: No valid OID provided')
     if data.get('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,
             url=data['URL'].replace('#info-right', ''),
             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.º 18
0
def add_time_off(parkingSpotId):
    form = AddTimeOffForm()

    if form.validate_on_submit():
        timeOff = TimeOff(startDate=form.startDate.data,
                          endDate=form.endDate.data,
                          idParkingSpot=parkingSpotId)
        parkingSpot = ParkingSpot.query.filter_by(id=parkingSpotId).first()
        parkingSpot.available = True
        # for deleting old time off
        TimeOff.query.filter_by(idParkingSpot=parkingSpotId).delete()
        affected = Booking.query.filter_by(idParkingSpot=parkingSpotId).all()
        for entry in affected:
            newMsg = Notification(
                idUser=entry.idUser,
                message="Your booking for the dates: " + str(entry.startDate) +
                " - " + str(entry.endDate) +
                " has been canceled because the parking " +
                "spot was updated. Please check the new dates and book again if it's still fine for you.",
                msgType=3,
                msgDate=date.today())
            db.session.add(newMsg)
        Booking.query.filter_by(idParkingSpot=parkingSpotId).delete()
        db.session.add(timeOff)
        db.session.commit()

        return redirect(url_for('manage_spots'))

    return render_template('add_time_off.html',
                           title='Add Time Off',
                           form=form)
Ejemplo n.º 19
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.º 20
0
def create_new_notification(recipient_id, report, description=None):
    notification = Notification(
        recipient_id=recipient_id,
        description=description or
        f'דיווח חדש מסוג "{report.category}" התקבל מאת צוות {current_user.team_id}',
        report_id=report.id)
    db.session.add(notification)
    db.session.commit()
Ejemplo n.º 21
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.º 22
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.º 23
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.º 24
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.º 25
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.º 26
0
def transaction_approval(transaction_id):
    """
    The '/transaction_approval/<transaction_id>' route directs a superuser to approve a transaction with
    the id of [transaction_id].
    """
    if 'username' not in session:
        return redirect(url_for('login'))
    if session['type_of_user'] == 'user':
        return redirect(url_for('dashboard'))
    if session['type_of_user'] == 'applicant':
        return redirect(url_for('dashboard_applicant'))

    form = TransactionApprovalForm()
    info = Transaction.get_transaction_info(transaction_id)
    transaction_id = int(transaction_id)

    if request.method == 'GET':
        enough_money = User.does_user_have_enough_money(
            info['sender'], int(info['amount']))
        return render_template("transactionApproval.html",
                               form=form,
                               transaction_id=transaction_id,
                               info=info,
                               enough_money=enough_money)
    if request.method == 'POST':
        if form.validate():
            if form.decision.data == 'approve':
                Transaction.approve_transaction(transaction_id)
                Notification(
                    info['sender'], session['username'],
                    'Your transaction (Transaction#' + str(transaction_id) +
                    ') was approved.')
            else:
                Transaction.deny_transaction(transaction_id)
                Notification(
                    info['sender'], session['username'],
                    'Your transaction (Transaction#' + str(transaction_id) +
                    ') was denied.')
            return redirect(url_for('dashboard_superuser'))
        else:
            return render_template("protestApproval.html",
                                   warning_id=warning_id,
                                   info=info,
                                   form=form,
                                   avg_rating=avg_rating)
Ejemplo n.º 27
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.º 28
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.º 29
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.º 30
0
def award_bid(request, bid_id):
    bid = Bid.objects.get(id=int(bid_id))
    new_notification = Notification(recipient=bid.student, subject="Bid Awarded",
                                    text="Your bid on the project '{}' was awarded by your instructors!" \
                                         " This will be your project. Contact your client at {}".format(bid.project.name, bid.project.client.email))
    new_notification.save()
    bid.project.is_assigned = True
    bid.student.profile.bids.all().delete()
    Bid.objects.filter(project=bid.project).delete()
    bid.project.save()
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))