def test_update_notification(self): ''' Test that we can set the seen state of a notification ''' # Set up notification1 = Notification(id=1, user='******', batchjob_id=1, seen=True) notification = Notification(id=2, user='******', batchjob_id=3, seen=False) db.session.add_all([notification1, notification]) db.session.commit() # Test response = self.client.put('/api/v0/notifications/%s' % notification.id, data=json.dumps({"seen": True}), content_type='application/json') # Check assert response.status_code == 200 notifications = Notification.query.filter_by( user='******').filter_by(seen=True) count = 0 for _ in notifications: count += 1 assert count == 2
def test_get_user_notifications(self): ''' Test when no user is specified ''' notification1 = Notification(user='******', batchjob_id=1, seen=True) notification2 = Notification(user='******', batchjob_id=2, seen=True) notification3 = Notification(user='******', batchjob_id=3, seen=False) db.session.add_all([notification1, notification2, notification3]) db.session.commit() response = self.client.get('/api/v0/users/testuser/notifications') assert len(response.json) == 3
def setUp(self): super().setUp() # add a user self.mitch = AppUser( phone_number=self.number, username='******', timezone=self.mitch_tz) self.db.session.add(self.mitch) # add exchange self.exchange = Exchange( router = RouterNames.DID_YOU_DO_IT, outbound = 'Did you do it?', user = self.mitch) self.db.session.add(self.exchange) # add a notif self.did_you_do_it_notif = Notification( router = RouterNames.DID_YOU_DO_IT, day_of_week = 'daily', hour = self.local_now.hour, minute = self.local_now.minute, active = True, user = self.mitch) self.db.session.add(self.did_you_do_it_notif) self.morning_conf_notif = Notification( router = RouterNames.MORNING_CONFIRMATION, day_of_week = 'daily', hour = self.local_now.hour, minute = self.local_now.minute, active = True, user = self.mitch) self.db.session.add(self.morning_conf_notif) self.week_reflection_notif = Notification( router = RouterNames.WEEK_REFLECTION, day_of_week = 'daily', hour = self.local_now.hour, minute = self.local_now.minute, active = True, user = self.mitch) self.db.session.add(self.week_reflection_notif) # add task self.task = Task( description='Win today', due_date = dt.datetime.now()+ dt.timedelta(minutes=1), active = True, exchange = self.exchange, user = self.mitch) self.db.session.add(self.task)
def setUp(self): context = tested_app.app_context() context.push() # set up the test DB self.db = tested_db self.db.create_all() self.db.session.add( Notification(senderID=1, receiverID=2, message="test message 1")) self.db.session.add( Notification(senderID=2, receiverID=1, message="test message 2")) self.db.session.commit() self.app = tested_app.test_client()
def notification(): if request.method == 'POST': notification = Notification() notification.message = request.form['message'] notification.subject = request.form['subject'] notification.status = 'Notifications submitted' notification.submitted_date = datetime.utcnow() logging.info("Record just created") try: db.session.add(notification) db.session.commit() ################################################## ## TODO: Refactor This logic into an Azure Function ## Code below will be replaced by a message queue ################################################# notification_id = notification.id msg = Message(str(notification_id)) queue_client.send(msg) ################################################# ## END of TODO ################################################# return redirect('/Notifications') except : logging.error('log unable to save notification') else: return render_template('notification.html')
def create_notification(product, shop): message = "%s is out of stock" % (product) Notification( shop=shop, message=message, ).save()
def create_notification(payment_id): """ Notify about payment status """ payment = db_session.query(Payment).get(payment_id) if not payment: abort(404) if not request.json or 'notification_url' not in request.json: logger.debug( 'Not enough data to create notification! Request data: {0}'.format( request.json)) abort(400) if payment.status in [ PaymentStatus.timeout, PaymentStatus.success, PaymentStatus.refused ]: logger.debug('Payment has already finished') return jsonify({'error': 'Payment has already finished'}), 400 user_data = request.json.get('user_data', {}) notification = Notification(payment.payment_id, request.json.get('notification_url'), user_data) payment.notifications.append(notification) db_session.add(payment) db_session.commit() return jsonify({'id': notification.notification_id}), 201
def finalizar_pedido(request, pk_pedido): try: pedido = Pedido.objects.get(id=pk_pedido) pedido.btn_finalizado = True pedido.save() motorista = Motorista.objects.get(user=request.user) motorista.ocupado = False motorista.save() message = "O motorista " + request.user.first_name + " finalizou por completo a ROTA ID #" + str( pedido.pk ) + ". Se desejar confirmar, ligue para o motorista: " + motorista.phone n = Notification(type_message='ALL_DELIVERED', to=pedido.estabelecimento.user, message=message) n.save() message = 'Voce concluiu a Rota, se voce estiver com algum material (maquineta ou bag) da Loja ' + pedido.estabelecimento.user.first_name + ', favor devolver. Obrigado!' messages.success(request, message) if motorista.configuration.plano == 'PREMIUM': return HttpResponseRedirect('/app/pedidos/motorista/premium/') return HttpResponseRedirect('/app/pedidos/motorista/') except: messages.error(request, 'Este pedido foi deletado pela Loja') if motorista.configuration.plano == 'PREMIUM': return HttpResponseRedirect('/app/pedidos/motorista/premium/') return HttpResponseRedirect('/app/pedidos/motorista/')
def confirm_email(token): # confirm user's new account via email # arg- token is jwt token if current_user.is_authenticated: return redirect(url_for('main.index')) user = User.verify_email_confirmation_token(token) if user is None: # invalid token flash('The confirmation link is invalid or has expired.', 'danger') return redirect(url_for('emails.resend_confirmation_email_request')) elif user.confirmed: # User's account is already confirmed flash('Your account is already confirmed. Please login.', 'success') return redirect(url_for('auth.login')) else: # account is confirmed make changes in db user.confirmed = True user.confirmed_on = datetime.now() # For finally confirmed users create notificationHub notificationHub = Notification(userID=user.id) db.session.add(notificationHub) db.session.commit() flash('your account has been confirmed. please login.', 'success') ## automatically connect user after successfull account confirmation login_user(user) next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('main.index') #TODO: -> flash to NAVBAR flash('You are now logged in!', 'success') return redirect(next_page)
def form_valid(self, form): data = form.cleaned_data requeriment = Requirement.objects.get(id=self.kwargs['requeriment_id']) requeriment.name = data['name_item'] requeriment.description = data['description'] common_user = self.object.commonuser common_user.cpf = data['cpf'] common_user.phone = data['phone'] common_user.anonymous = data['anonymous'] common_user.save() new_item = Item(owner=self.request.user, description=requeriment.description, name_item=requeriment.name) new_item.save() new_object = Object(item=new_item, type=requeriment.type) new_object.save() messages.success(self.request, "Novo Objeto cadastrado com sucesso!") match = Match(requirement=requeriment, item=new_item) match.save() notification = Notification(user=requeriment.owner, match=match) notification.save() donation = Donation( donator=self.request.user, institute=requeriment.owner, item=new_item, data=datetime.datetime.today().strftime('%Y-%m-%d'), is_completed=False) donation.save() messages.success(self.request, 'Muito Obrigado pela sua Doação!') return super(DonatorRequerimentView, self).form_valid(form)
def send_group_chat_notifications(target_url, current_user, chat_message, group_chat): """Create notifications for the newly created group chat message, store them in the database and emit to all clients in the socketio room. """ limit = 25 notification_schema = NotificationSchema() results = database_repository.get_group_chat_members( group_chat.community_id, group_chat.id, limit) for member in results["models"]: if member.id != current_user.id: notification = Notification( chat_message.timestamp.isoformat() + "-" + uuid4().hex, member.id, NotificationType.NEW_GROUP_CHAT_MESSAGE, f"{current_user.username} posted a new message in {group_chat.name}", target_url) database_repository.add_user_notification(notification) if member.socketio_session_id: emit( "new_notification", notification_schema.dumps(notification), room=member.socketio_session_id, )
def notification(): if request.method == 'POST': notification = Notification() notification.message = request.form['message'] notification.subject = request.form['subject'] notification.status = 'Notifications submitted' notification.submitted_date = datetime.utcnow() try: db.session.add(notification) db.session.commit() notification_id = notification.id print('Enqueueing notification_id: {} to queue: {}'.format( notification_id, app.config.get('SERVICE_BUS_QUEUE_NAME'))) sb_queue_client = QueueClient.from_connection_string(app.config.get('SERVICE_BUS_CONNECTION_STRING'), app.config.get('SERVICE_BUS_QUEUE_NAME')) msg = Message(str(notification_id)) print('notification ID to send $s', str(notification_id)) sb_queue_client.send(msg) print('notification_id: {} enqueued to queue: {}'.format( notification_id, app.config.get('SERVICE_BUS_QUEUE_NAME'))) return redirect('/Notifications') except : logging.error('log unable to save notification') else: return render_template('notification.html')
def notification(): if request.method == 'POST': notification = Notification() notification.message = request.form['message'] notification.subject = request.form['subject'] notification.status = 'Notifications submitted' notification.submitted_date = datetime.utcnow() try: db.session.add(notification) db.session.commit() queue = QueueClient.from_connection_string( app.config.get('SERVICE_BUS_CONNECTION_STRING'), app.config.get('SERVICE_BUS_QUEUE_NAME')) logging.error('msg str: %s', Message(int(notification.id))) queue.send(Message('{}'.format(notification.id))) return redirect('/Notifications') except: logging.error('log unable to save notification') else: return render_template('notification.html')
def post(self, request, *args, **kwargs): notifications = request.data['notifications'] notifications = notifications.strip('[').strip(']').split(',') print(notifications) user = self.request.user old_notifications = user.profile.notification_set.order_by('operate') for n in notifications: l = n.split('_') if len(l) != 3 or (int(l[0]) not in (0, 1, 2)) or (int( l[1]) not in (0, 1)) or (int(l[2]) not in (0, 1)): return Response({'message': 'params invalid'}) if old_notifications: for i in range(3): old_notifications[i].is_sms_active = notifications[i].split( '_')[1] old_notifications[i].is_email_active = notifications[i].split( '_')[2] old_notifications[i].save() else: for i in range(3): n = Notification(profile_id=user.profile) n.operate = notifications[i].split('_')[0] n.is_sms_active = notifications[i].split('_')[1] n.is_mail_active = notifications[i].split('_')[2] n.save() return Response({'message': 'save successfully'})
def push_collect_notification(collector, photo_id, receiver): message = '用户< href="%s">%s</a>收藏了你的<a href="%s">照片</a>' % \ (url_for('user.index', username=collector.username), collector.username, url_for('main.show_photo', photo_id=photo_id)) notification = Notification(message=message, receiver=receiver) db.session.add(notification) db.session.commit()
def test_should_set_status_for_all_send_notifications(notify_api, notify_db, notify_db_session, notify_config, mocker): mocker.patch('app.sms_wrapper.status', return_value="delivered") sent_at = datetime.utcnow() create_notification = Notification( id=1000, to="to", message="message", created_at=datetime.utcnow(), sent_at=sent_at, status='sent', method='sms', job_id=1234, sender_id="1", sender="twilio" ) db.session.add(create_notification) notification = Notification.query.get(1234) notification.status = 'sent' notification.sender_id = '2' notification.sender = 'twilio' db.session.add(notification) db.session.commit() fetch_sms_status() read_notification = Notification.query.get(1234) assert read_notification.status == 'delivered' assert read_notification.delivered_at >= read_notification.created_at sms_wrapper.status.assert_has_calls([call("1", "twilio"), call("2", "twilio")])
def notifications(self): """ Route activant le processus de rappatriement des nouvelles séries """ # Récupère la liste de série préférée de l'utilisateur et effectue une requete api pour chaque série series = current_user.query.join(Liste_series).with_entities(Liste_series.serie_id).all() series = [series[index][0] for index in range(len(series))] urls = ["https://api.betaseries.com/episodes/next?key=7c2f686dfaad&v=3.0&id={}".format(serie) for serie in series] requetes_series = Requete(series, ["episode" for i in range(len(series))], urls, series) requetes = requetes_series.run() # Nettoyage de la réponse : passage en datetime et ecriture dans la base notification s = [i[0] for i in self.querydb('select episode_id from notification where user_id=?', args=(current_user.get_id(),))] for i in requetes: try: if requetes[i]['show']['id'] not in s: h, m, s = map(int, requetes[i]['date'].split('-')) notifications = Notification(user_id=current_user.get_id(), serie_id=requetes[i]['show']['id'], date_diffusion=datetime(h, m, s), serie_name=requetes[i]['show']['title'], description=requetes[i]['description'], episode_id=requetes[i]['id'], code=requetes[i]['code'], title=requetes[i]['title']) db.session.add(notifications) except KeyError: pass except requests.exceptions.ConnectionError: return render_template('Connectezvous.html') db.session.commit() return (""), 204
def sample_email_notification(notify_db, notify_db_session): created_at = datetime.utcnow() service = create_service(check_if_service_exists=True) template = sample_email_template(notify_db, notify_db_session, service=service) job = sample_job(notify_db, notify_db_session, service=service, template=template) notification_id = uuid.uuid4() to = "*****@*****.**" data = { "id": notification_id, "to": to, "job_id": job.id, "job": job, "service_id": service.id, "service": service, "template_id": template.id, "template_version": template.version, "status": "created", "provider_response": None, "reference": None, "created_at": created_at, "billable_units": 0, "personalisation": None, "notification_type": template.template_type, "api_key_id": None, "key_type": KEY_TYPE_NORMAL, "job_row_number": 1, } notification = Notification(**data) dao_create_notification(notification) return notification
def notification(): if request.method == 'POST': notification = Notification() notification.message = request.form['message'] notification.subject = request.form['subject'] notification.status = 'Notifications submitted' notification.submitted_date = datetime.utcnow() try: db.session.add(notification) db.session.commit() ################################################## ## Refactor This logic into an Azure Function ## Code below will be replaced by a message queue ################################################# # Call servicebus queue_client to enqueue notification ID db.session.flush() msg = Message(notification.id) queue_client.send(msg) ################################################# ## END of TODO ################################################# return redirect('/Notifications') except: logging.error('log unable to save notification') else: return render_template('notification.html')
def test_send_notification_to_queue( notify_db, notify_db_session, research_mode, requested_queue, notification_type, key_type, expected_queue, expected_task, mocker, ): mocked = mocker.patch('app.celery.{}.apply_async'.format(expected_task)) Notification = namedtuple( 'Notification', ['id', 'key_type', 'notification_type', 'created_at']) notification = Notification( id=uuid.uuid4(), key_type=key_type, notification_type=notification_type, created_at=datetime.datetime(2016, 11, 11, 16, 8, 18), ) send_notification_to_queue(notification=notification, research_mode=research_mode, queue=requested_queue) mocked.assert_called_once_with([str(notification.id)], queue=expected_queue)
def notification(): if request.method == 'POST': notification = Notification() notification.message = request.form['message'] notification.subject = request.form['subject'] notification.status = 'Notifications submitted' notification.submitted_date = datetime.utcnow() try: db.session.add(notification) db.session.commit() notification_id = notification.id msg = Message(str(notification_id)) # Call servicebus queue_client to enqueue notification ID queue_client.send(msg) # attendees = Attendee.query.all() # for attendee in attendees: # subject = '{}: {}'.format(attendee.first_name, notification.subject) # send_email(attendee.email, subject, notification.message) # notification.completed_date = datetime.utcnow() # notification.status = 'Notified {} attendees'.format(len(attendees)) # db.session.commit() return redirect('/Notifications') except Exception as e: logging.error(e) logging.error('log unable to save notification') else: return render_template('notification.html')
def notification(): if request.method == 'POST': notification = Notification() notification.message = request.form['message'] notification.subject = request.form['subject'] notification.status = 'Notifications submitted' notification.submitted_date = datetime.utcnow() try: db.session.add(notification) db.session.commit() db.session.refresh(notification) notid = '{}'.format(notification.id) try: msg = Message(notid) sentResult = queue_client.send(msg) # logging.info(msg) print(msg) except Exception as e: logging.error( 'Error occurred while sending message to queue {}', str(e)) return redirect('/Notifications') except: logging.error('Unable to save notification') else: return render_template('notification.html')
def send_notification(): group_id = request.args.get('group_id', 0, type=int) group = Group.query.get_or_404(group_id) form = SendNotificationForm(group) if form.validate_on_submit(): if current_user.is_developer: abort(403) subject = form.subject.data body = form.body.data receiver_id = form.receiver.data if receiver_id == 0: receiver_id = group_id receiver_type = receiver_type_group parents = parents_of_group(receiver_id) else: receiver_type = receiver_type_student_in_group parents = parents_of_student_in_group(receiver_id) receivers = do_send_notification(parents, subject, body) is_ok = True # if receivers is not None: if is_ok: db.session.add( Notification(sender_id=current_user.id, receiver_type=receiver_type, receiver_id=receiver_id, subject=subject, body=body, receivers=receivers or '')) flash('уведомление отправлено!') else: flash( 'уведомление не отправлено, так как у родителей не выбраны типы уведомлений!' ) return redirect(url_for('.notifications_list')) return render_template('notifications/send.html', group=group, form=form)
def sendMsg(username): user = User.query.filter_by(username=username).first_or_404() messages = current_user.messageRecieved.order_by(Message.timestamp.desc()) chatLog = main(current_user.id, user.id) form = MessageForm() if form.validate_on_submit(): msg = Message(sender_id=current_user.id, recipient_id=user.id, body=form.message.data) sendNotif = Notification(sender_id = current_user.id, recipient_id = user.id, body = 'new message from', seenNotif = 0) db.session.add(sendNotif) db.session.add(msg) db.session.commit() flash('Message Sent') chatLog = main(current_user.id, user.id) i = 0 return redirect(url_for('sendMsg', username=username, )) image_file = url_for('static', filename = 'profile_pic/' + user.image_file) return render_template('SendMessage.html', title='Messaging', form=form, user=user, messages=messages, chatLog=chatLog, len=len(chatLog), current_user=current_user, image_file=image_file)
def test_send_notification_to_queue( notify_db, notify_db_session, research_mode, requested_queue, notification_type, key_type, reply_to_text, expected_queue, expected_task, mocker, ): if "." not in expected_task: expected_task = f"provider_tasks.{expected_task}" mocked = mocker.patch(f"app.celery.{expected_task}.apply_async") notification = Notification( id=uuid.uuid4(), key_type=key_type, notification_type=notification_type, created_at=datetime.datetime(2016, 11, 11, 16, 8, 18), reply_to_text=reply_to_text, ) send_notification_to_queue(notification=notification, research_mode=research_mode, queue=requested_queue) mocked.assert_called_once_with([str(notification.id)], queue=expected_queue)
def put(self, jobid): ''' Update job entry in database with new status and log_stream_name ''' # TODO: Secure with auth_tokens if not request.json: return '{"Status": "JSON not found"}', 200 job = BatchJob.query.filter_by(id=jobid).first() if not job: return '{"Status": "Job does not exist"}', 200 if 'log_stream_name' in request.json: if request.json['log_stream_name'] != job.log_stream_name: job.log_stream_name = request.json['log_stream_name'] if 'job_status' in request.json: job_status = request.json['job_status'] if job_status != job.status: if job_status == 'SUCCEEDED' or job_status == 'FAILED' or job_status == 'ERROR': job.viewed = False # Notify the user notification = Notification(user=job.user, batchjob_id=job.id, seen=False) db.session.add(notification) job.status = job_status db.session.add(job) db.session.commit() return self.get(jobid)
def get_notifications(id): if g.current_user.id != id: return error_response(401, 'You may only view/edit your own notifications') if request.method == 'GET': user = User.query.get_or_404(id) page = request.args.get('page', 1, type=int) per_page = min(request.args.get('per_page', 10, type=int), 100) data = Notification.to_collection_dict(user.notifications, page, per_page, 'api.get_notifications', id=id) return jsonify(data) if request.method == 'POST': data = request.get_json() or {} if validate_notification(data) == False: return bad_request( 'There was a problem with the data you supplied. Make sure that the entries you supply for each field exist in our database.' ) n = Notification() setattr(n, "user_id", id) n.from_dict(data, new_notification=True) db.session.add(n) db.session.commit() response = jsonify(n.to_dict()) response.status_code = 201 response.headers['Location'] = url_for('api.get_notification', user_id=id, notification_id=n.id) return response
def save_email_to_queue(*, notification_id, form, notification_type, api_key, template, service_id, personalisation, document_download_count, reply_to_text=None): data = { "id": notification_id, "template_id": str(template.id), "template_version": template.version, "to": form['email_address'], "service_id": str(service_id), "personalisation": personalisation, "notification_type": notification_type, "api_key_id": str(api_key.id), "key_type": api_key.key_type, "client_reference": form.get('reference', None), "reply_to_text": reply_to_text, "document_download_count": document_download_count, "status": NOTIFICATION_CREATED, "created_at": datetime.utcnow().strftime(DATETIME_FORMAT), } encrypted = encryption.encrypt(data) save_api_email.apply_async([encrypted], queue=QueueNames.SAVE_API_EMAIL) return Notification(**data)
def sample_email_notification(notify_db_session): created_at = datetime.utcnow() service = create_service(check_if_service_exists=True) template = create_template(service, template_type=EMAIL_TYPE) job = create_job(template) notification_id = uuid.uuid4() to = '*****@*****.**' data = { 'id': notification_id, 'to': to, 'job_id': job.id, 'job': job, 'service_id': service.id, 'service': service, 'template_id': template.id, 'template_version': template.version, 'status': 'created', 'reference': None, 'created_at': created_at, 'billable_units': 0, 'personalisation': None, 'notification_type': template.template_type, 'api_key_id': None, 'key_type': KEY_TYPE_NORMAL, 'job_row_number': 1 } notification = Notification(**data) dao_create_notification(notification) return notification
def finalizar_entrega(request, pk_ponto, pk_pedido): try: ponto = Ponto.objects.get(id=pk_ponto) pedido = Pedido.objects.get(id=pk_pedido) ponto.status = True ponto.save() try: if pedido.request_set.first(): reqs = pedido.request_set.all() for req in reqs: req.status_pedido = 'ENTREGUE' req.save() except (Exception, ): pass pto_entregues = len(pedido.ponto_set.filter(status=True)) if len(pedido.ponto_set.all()) == pto_entregues: pedido.is_complete = True pedido.save() messages.success( request, 'Tudo entregue! Finalize esta Rota para poder pegar outros.') if pedido.estabelecimento.is_online: message = "Motorista " + request.user.first_name + " entregou pedido ao cliente " + ponto.cliente + " no endereco " + ponto.full_address n = Notification(type_message='ORDER_DELIVERED', to=pedido.estabelecimento.user, message=message) n.save() return HttpResponseRedirect('/app/pedido/route/' + str(pedido.pk)) except: messages.error(request, 'Este pedido foi deletado pela Loja') return HttpResponseRedirect('/app/pedidos/motorista/')