def create_request_offer(request): # todo there is no validation here if request.POST: if request.is_ajax(): offer_id = request.POST.get('offer_id') # OFFER if offer_id: offer_project = Request.objects.get(pk=offer_id) offer_instance = Offer(project=offer_project, offer_by=request.user) offer_instance.save() # reputation change for offering offered_by_profile = UserProfile.objects.get(user=request.user) if offered_by_profile: offered_by_profile.reputation += OFFERING_REPUTATION_POINT offered_by_profile.save() notification = Notification(for_user=offer_project.created_by, extra=offer_instance, type=200, action_url="/projects/" + str(offer_project.slug), message="You have received an offer ", ) notification.save() # REQUEST return project_create(request) else: return HttpResponseRedirect("/dashboard/") else: return HttpResponseRedirect("/dashboard/")
def offer(request, slug): project = get_object_or_404(Request, slug=slug) offered_by = request.user # todo validations # can't offer my own project if (offered_by == project.created_by): # messages.add_message(request, messages.INFO, 'Hmmm this is your project!') return HttpResponseRedirect("/projects/" + str(slug) + "/") # todo check if this user has already sent offer request ... sent_request = Offer.objects.filter(project=project, offer_by=offered_by) if sent_request: messages.add_message(request, messages.INFO, 'Your have already sent offer request for this project!') return HttpResponseRedirect("/projects/" + str(slug) + "/") # reputation change for offering offered_by_profile = UserProfile.objects.get(user=offered_by) if offered_by_profile: offered_by_profile.reputation += OFFERING_REPUTATION_POINT offered_by_profile.save() offer = Offer(project=project, offer_by=offered_by) offer.save() notification = Notification(for_user=project.created_by, extra=offer, type=200, action_url="/projects/" + str(slug), message="You have received an offer ", ) notification.save() # todo show offer processed message and redirect messages.add_message(request, messages.SUCCESS, 'Your Offer has been sent!') return HttpResponseRedirect("/projects/" + str(slug) + "/")
def comment(self, sender_name, post_id, content): post = Post.get(post_id) user = User.get(post.author_id) header = self._comment_header.format( sender_name, post.id, post.title) Notification.create( sender_name, user.username, 'comment', header, content) notification.publish(user.username, json_encode({'unread': 1}))
def delete_receiver(): uid = request.form.get('uid') if not uid: return jsonify({'status': 'error', 'msg': 'invalid email address'}) try: Notification.unsubscribe(uid) return jsonify({'status': 'ok'}) except Exception, e: return jsonify({'status': 'error', 'msg': 'server error'})
def at(self, sender_name, usernames, post_id, content): post = Post.get(post_id) for username in usernames: header = self._at_header.format( sender_name, post.id, post.title) Notification.create( sender_name, username, 'at', header, content) notification.publish(username, json_encode({'unread': 1}))
def test_send_sms_messages_to_queue_adds_message_queue(notify_api): q = set_up_mock_queue('sms') sms = Notification(to='+441234512345', message='hello world', job_id=1234) q.send_message(MessageBody=json.dumps(sms.serialize()), MessageAttributes={'type': {'StringValue': 'sms', 'DataType': 'String'}}) messages = [notification] b = send_messages_to_queue('sms', messages) assert b is True
def test_should_by_able_to_update_status_by_reference(sample_email_template, ses_provider): data = _notification_json(sample_email_template, status='sending') notification = Notification(**data) dao_create_notification(notification) assert Notification.query.get(notification.id).status == "sending" notification.reference = 'reference' dao_update_notification(notification) updated = update_notification_status_by_reference('reference', 'delivered') assert updated.status == 'delivered' assert Notification.query.get(notification.id).status == 'delivered'
def save_model(self, request, obj, form, change): if obj.pk: obj.save() logging.warning('Modifying the change, notifications are omitted...') return obj.save() logging.warning('A new change was created, notifications will be sent.') integrations = Integration.objects.filter(integrate__project_id=obj.project.pk) responsible_users=[] for i in integrations: responsible = User.objects.filter(responsable__project__integrate__integration_id=i.id) responsible_users = list(set(responsible_users) | set(responsible)) logging.info("Found responsible: %s" % responsible_users) emails=[] messages_to_responsible = () link_to_change = "%s%s%s" % (settings.BASE_URL, '/admin/app/change/', obj.pk) message_subject = "%s '%s'" % (_('message_updated_project'),obj.project.name) message_from = settings.EMAIL_FROM message_content = "%s: %s\n\n" % (_('message_updated_project'),obj.project.name) message_content += "%s: %s\n\n" % (_('message_change'), obj.name) message_content += "%s: \n%s\n\n" % (_('message_description'),obj.description) message_content += "%s: %s\n" % (_('message_created_at'), obj.created_at.strftime("%d/%m/%Y %H:%M")) message_content += "%s: %s\n" % (_('message_updated_at'), obj.updated_at.strftime("%d/%m/%Y %H:%M")) message_content += "%s: %s\n" % (_('message_confirm_change'),link_to_change) for u in responsible_users: g = Notification(change=obj,user=u) g.save() if u.email: message_to = (message_subject, message_content, message_from, ["%s" % u.email]) messages_to_responsible += (message_to,) try: sent_messages = send_mass_mail(messages_to_responsible, fail_silently=False) messages.info(request,_('message_mails_sent') % {'emails':sent_messages} ) logging.info("Sent messages: %s" % sent_messages) except Exception as e: logging.error("ERROR to sent messajes. %s" % e)
def rejectOffer(request): if request.method == 'GET': id = request.GET['offer_id'] offer = Offer.objects.get(pk=id) if offer: offer.is_seen = True offer.save() notification = Notification(for_user=offer.offer_by, type=202, action_url="/projects/" + offer.project.slug, extra=offer, message="Your offer has been rejected.") notification.save() messages.add_message(request, messages.SUCCESS, 'You have rejected an offer!') return HttpResponseRedirect("/projects/" + str(offer.project.slug) + "/") else: return HttpResponse('Bad request!')
def add_receiver(): email = request.form.get('email') if not email: return jsonify({'error': 'invalid email address'}) try: user = Notification.subscribe(email) data = {'status':'ok', 'user': {'id': user.id, 'email': user.email}} except Exception, e: data = {'status': 'error', 'msg': e}
def set_up_mock_queue(): # set up mock queue boto3.setup_default_session(region_name='eu-west-1') conn = boto3.resource('sqs') q = conn.create_queue(QueueName='gov_uk_notify_email_queue') notification = Notification(id=1234, to='*****@*****.**', sender='*****@*****.**', message='notification message', status='created', method='email', created_at=datetime.utcnow(), job=Job(id=1234, name='jobname', filename='filename', created_at=datetime.utcnow(), service_id=1234)) q.send_message(MessageBody=json.dumps(notification.serialize()), MessageAttributes={'type': {'StringValue': 'email', 'DataType': 'String'}}) return q
def get(self): type_ = self.get_argument('type', None) unread = bool(self.get_argument('unread', True)) username = self.current_user ntfs = yield gen.maybe_future( Notification.list_by_user_and_type(username, type_, unread)) result = { 'total': len(ntfs), 'messages': [n.to_dict() for n in ntfs], } raise gen.Return(result)
def acceptOffer(request): if request.method == 'GET': id = request.GET['offer_id'] offer = Offer.objects.get(pk=id) if offer: offer.is_accepted = True offer.is_seen = True offer.project.collaborators.add(offer.offer_by) offer.save() notification = Notification(for_user=offer.offer_by, type=201, action_url="/projects/" + offer.project.slug, extra=offer, message="Your offer has been accepted.") notification.save() # update user reputation profile = UserProfile.objects.get(user=offer.offer_by) profile.reputation += REQUEST_ACCEPTED_REPUTATION_POINT profile.save() messages.add_message(request, messages.SUCCESS, 'You have accepted an offer!') return HttpResponseRedirect("/projects/" + str(offer.project.slug) + "/") else: return HttpResponse('bad request')
def liberar_corrida(request, pk_pedido): pedido = Pedido.objects.get(id=pk_pedido) pedido.coletado = True pedido.save() try: if pedido.request_set.first(): reqs = pedido.request_set.all() for req in reqs: req.status_pedido = 'ENTREGANDO' req.save() except (Exception, ): pass if Motorista.objects.get(user=pedido.motorista).is_online: message = "Voce foi liberado pela loja para realizar a(s) entrega(s). Sua Rota atual esta no menu ENTREGAS. Quando terminar uma entrega, marque finalizar. Qualquer problema, ligue para a loja: " + pedido.estabelecimento.phone n = Notification(type_message='ENABLE_ROTA', to=pedido.motorista, message=message) n.save() try: logger(request.user, "Foi liberada a Rota #" + str(pedido.pk)) except (Exception, ): pass return redirect('/app/acompanhar')
def save_email_or_sms_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'] if notification_type == EMAIL_TYPE else form['phone_number'], "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) if notification_type == EMAIL_TYPE: save_api_email.apply_async([encrypted], queue=QueueNames.SAVE_API_EMAIL) elif notification_type == SMS_TYPE: save_api_sms.apply_async([encrypted], queue=QueueNames.SAVE_API_SMS) return Notification(**data)
def post(self): json_data = request.get_json() if not json_data: raise RequestException("No input data", 400) try: data = notification_schema.load(json_data) except ValidationError as err: raise RequestException("Invalid input data", 400, err.messages) notification = Notification.create(**data) result = notification_schema.dump(notification) response = jsonify({ APIConst.MESSAGE: 'created new notification', APIConst.DATA: result }) return response
def test_send_notification_to_queue(notify_db, notify_db_session, research_mode, requested_queue, expected_queue, notification_type, key_type, mocker): mocked = mocker.patch('app.celery.provider_tasks.deliver_{}.apply_async'.format(notification_type)) 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 test_send_notification_to_correct_queue_to_lookup_contact_info( client, mocker, notification_type, id_type, expected_queue, expected_task, sample_template, sample_email_template): mocker.patch( 'app.v2.notifications.post_notifications.accept_recipient_identifiers_enabled', return_value=True) mocked = mocker.patch( 'app.celery.contact_information_tasks.{}.apply_async'.format( expected_task)) notification = Notification(id=str(uuid.uuid4()), notification_type=notification_type) send_to_queue_for_recipient_info_based_on_recipient_identifier( notification, id_type) mocked.assert_called_once_with([notification.id], queue=expected_queue)
def test_get_notifications(flask_client): user = User.create( email="[email protected]", password="******", name="Test User", activated=True ) db.session.commit() # create api_key api_key = ApiKey.create(user.id, "for test") db.session.commit() # create some notifications Notification.create(user_id=user.id, message="Test message 1") Notification.create(user_id=user.id, message="Test message 2") db.session.commit() r = flask_client.get( url_for("api.get_notifications", page=0), headers={"Authentication": api_key.code}, ) assert r.status_code == 200 assert r.json["more"] is False assert len(r.json["notifications"]) == 2 for n in r.json["notifications"]: assert n["id"] > 0 assert n["message"] assert n["read"] is False assert n["created_at"] # no more post at the next page r = flask_client.get( url_for("api.get_notifications", page=1), headers={"Authentication": api_key.code}, ) assert r.json["more"] is False assert len(r.json["notifications"]) == 0
def notification_route(notification_id): notification = Notification.get(notification_id) if not notification: flash("Incorrect link. Redirect you to the home page", "warning") return redirect(url_for("dashboard.index")) if notification.user_id != current_user.id: flash( "You don't have access to this page. Redirect you to the home page", "warning", ) return redirect(url_for("dashboard.index")) if request.method == "POST": notification_title = notification.title or notification.message[:20] Notification.delete(notification_id) Session.commit() flash(f"{notification_title} has been deleted", "success") return redirect(url_for("dashboard.index")) else: return render_template("dashboard/notification.html", notification=notification)
def notifications(): form = get_notification_form() if form.validate_on_submit(): notification = Notification(label=form.label.data, grade=str(form.grade.data), subject=str(form.subject.data), language=str(form.language.data), campus=str(form.campus.data), receiver=current_user) db.session.add(notification) db.session.commit() flash('Notification \'{}\' has been added!'.format(form.label.data)) return redirect(url_for('main.index', username=current_user.username)) return render_template('notifications.html', heading="Add Notification", form=form)
def accept_corrida(request, pk_pedido): try: pedido = Pedido.objects.get(id=pk_pedido) if pedido.motorista: try: messages.error( request, 'O motorista ' + pedido.motorista.first_name + ' pegou esta entrega antes de você') except (Exception, ): messages.error( request, 'Outro Motorista pegou esta entrega antes de você') return HttpResponseRedirect('/app/pedidos/motorista/') else: pedido.status = False pedido.motorista = request.user pedido.save() motorista = Motorista.objects.get(user=request.user) motorista.ocupado = True motorista.save() if pedido.estabelecimento.is_online: message = "O motorista " + str( motorista.user.first_name ) + " aceitou fazer a entrega do Pedido ID #" + str( pedido.pk ) + ". Qualquer problema, ligue para o motorista: " + motorista.phone n = Notification(type_message='ACCEPT_ORDER', to=pedido.estabelecimento.user, message=message) n.save() message = 'A Loja ' + pedido.estabelecimento.user.first_name + ', localizado na ' + pedido.estabelecimento.full_address + ', esta aguardando a coleta.' no = Notification( type_message='DELETE_LOJA', to=pedido.motorista, message=message) # está delete loja por enquanto. no.save() try: logger(request.user, "Aceitou fazer a Rota #" + str(pedido.pk)) except (Exception, ): pass return HttpResponseRedirect('/app/pedido/route/' + str(pedido.pk)) except (Exception, ): messages.error(request, 'Este pedido foi deletado pela Loja') return HttpResponseRedirect('/app/pedidos/motorista/')
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: notification.completed_date = datetime.utcnow() notification.status = 'Notification submitted' db.session.add(notification) db.session.commit() ################################################## ## TODO: Refactor This logic into an Azure Function ## Code below will be replaced by a message queue ################################################# # 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 = 'Notification submitted' # db.session.commit() # TODO Call servicebus queue_client to enqueue notification ID notification_id = Notification.query.order_by( Notification.id.desc()).first() 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 post_notification(): if not current_user.is_authenticated: return redirect(url_for('admin_login')) notification = request.form['notification'] sender = request.form.get('sender') if sender is None: flash( 'Select one of the following option [Student/Teacher, Teacher, Student]' ) return redirect(url_for('administrator')) message = Notification(notification=notification, sender=sender) db.session.add(message) db.session.commit() flash('Notifiaction is send to the {}'.format(sender)) return redirect(url_for('get_notification'))
def notifications_route(): page = 0 if request.args.get("page"): page = int(request.args.get("page")) notifications = ( Notification.filter_by(user_id=current_user.id).order_by( Notification.read, Notification.created_at.desc()).limit( PAGE_LIMIT + 1) # load a record more to know whether there's more .offset(page * PAGE_LIMIT).all()) return render_template( "dashboard/notifications.html", notifications=notifications, page=page, last_page=len(notifications) <= PAGE_LIMIT, )
def _filter_query(query, filter_dict=None): if filter_dict is None: return query multidict = MultiDict(filter_dict) # filter by status statuses = multidict.getlist('status') if statuses: statuses = Notification.substitute_status(statuses) query = query.filter(Notification.status.in_(statuses)) # filter by template template_types = multidict.getlist('template_type') if template_types: query = query.filter(Notification.notification_type.in_(template_types)) return query
def get_notifications(): """ Get notifications Input: - page: in url. Starts at 0 Output: - more: boolean. Whether there's more notification to load - notifications: list of notifications. - id - message - title - read - created_at """ user = g.user try: page = int(request.args.get("page")) except (ValueError, TypeError): return jsonify(error="page must be provided in request query"), 400 notifications = ( Notification.filter_by(user_id=user.id).order_by( Notification.read, Notification.created_at.desc()).limit( PAGE_LIMIT + 1) # load a record more to know whether there's more .offset(page * PAGE_LIMIT).all()) have_more = len(notifications) > PAGE_LIMIT return ( jsonify( more=have_more, notifications=[{ "id": notification.id, "message": notification.message, "title": notification.title, "read": notification.read, "created_at": notification.created_at.humanize(), } for notification in notifications[:PAGE_LIMIT]], ), 200, )
def sample_notification(notify_db_session): created_at = datetime.utcnow() service = create_service(check_if_service_exists=True) template = create_template(service=service) api_key = ApiKey.query.filter(ApiKey.service == template.service, ApiKey.key_type == KEY_TYPE_NORMAL).first() if not api_key: api_key = create_api_key(template.service, key_type=KEY_TYPE_NORMAL) notification_id = uuid.uuid4() to = '+447700900855' data = { 'id': notification_id, 'to': to, 'job_id': None, 'job': None, 'service_id': service.id, 'service': service, 'template_id': template.id, 'template_version': template.version, 'status': 'created', 'reference': None, 'created_at': created_at, 'sent_at': None, 'billable_units': 1, 'personalisation': None, 'notification_type': template.template_type, 'api_key': api_key, 'api_key_id': api_key and api_key.id, 'key_type': api_key.key_type, 'sent_by': None, 'updated_at': None, 'client_reference': None, 'rate_multiplier': 1.0, 'normalised_to': None, 'postage': None, } notification = Notification(**data) dao_create_notification(notification) return notification
def mark_as_read(notification_id): """ Mark a notification as read Input: notification_id: in url Output: 200 if updated successfully """ user = g.user notification = Notification.get(notification_id) if not notification or notification.user_id != user.id: return jsonify(error="Forbidden"), 403 notification.read = True db.session.commit() return jsonify(done=True), 200
def create_notifications(id): incoming = request.get_json() if "postId" not in incoming: postId = None else: postId = incoming["postId"] notification = Notification(post_id=postId, user_id=incoming["friendId"], friend_id=id, type_id=incoming["typeId"], created_at=incoming["createdAt"], status=1) db.session.add(notification) db.session.commit() return {'msg': 'notification created successfully'}
def test_send_notification_to_correct_queue_to_lookup_contact_info( client, mocker, notification_type, id_type, expected_tasks ): mocked_chain = mocker.patch('app.notifications.process_notifications.chain') notification = Notification( id=str(uuid.uuid4()), notification_type=notification_type ) send_to_queue_for_recipient_info_based_on_recipient_identifier(notification, id_type) args, _ = mocked_chain.call_args for called_task, expected_task in zip(args, expected_tasks): assert called_task.name == expected_task.name
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() ################################################## # TODO: Refactor This logic into an Azure Function # Code below will be replaced by a message queue ################################################# # 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() # TODO Call servicebus queue_client to enqueue notification ID notification_id = notification.id servicebus_client = ServiceBusClient.from_connection_string( conn_str=app.config.get("SERVICE_BUS_CONNECTION_STRING"), logging_enable=True) with servicebus_client: sender = servicebus_client.get_queue_sender( queue_name=app.config.get("SERVICE_BUS_QUEUE_NAME")) with sender: message = ServiceBusMessage(str(notification_id)) sender.send_messages(message) logging.info("MSG Queue sent") ################################################# # END of TODO ################################################# return redirect('/Notifications') except: logging.error('log unable to save notification') else: return render_template('notification.html')
def form_valid(self, form): data = form.cleaned_data item = Item.objects.get(id=self.kwargs['item_id']) item.name_item = data['name'] item.description = data['description'] object = Object.objects.get(item=item) object.type = data['type'] requeriment = Requirement(name=item.name_item, type=object.type, status=True, owner=self.request.user, description=item.description) requeriment.save() match = Match(requirement=requeriment, item=item) match.save() donation = Donation(donator=item.owner, institute=requeriment.owner, item=item, data=datetime.datetime.today().strftime('%Y-%m-%d'), is_completed=False) donation.save() notification = Notification(user=requeriment.owner, match=match) notification.save() notification = Notification(user=item.owner, match=match) notification.save() messages.success(self.request, "Nova Necessidade cadastrada com sucesso!") return super(NewItemRequerimentView, self).form_valid(form)
def send_private_chat_notifications(target_url, current_user, chat_message, private_chat): """Create notifications for the newly created private chat message, store them in the database and emit to other client in the room. """ notification_schema = NotificationSchema() other_user = private_chat.get_other_user(current_user.id) notification = Notification( chat_message.timestamp.isoformat() + "-" + uuid4().hex, other_user.id, NotificationType.NEW_PRIVATE_CHAT_MESSAGE, f"{current_user.username} sent you a new message", target_url) database_repository.add_user_notification(notification) if other_user.socketio_session_id: emit( "new_notification", notification_schema.dumps(notification), room=other_user.socketio_session_id, )
def submit_message(request, pk_pedido): text = request.GET['text'] motorista = None pedido = Pedido.objects.get(id=pk_pedido) loja = None try: motorista = Motorista.objects.get(user=request.user) except: loja = Estabelecimento.objects.get(user=request.user) if motorista: mess = Message(u_from=motorista.user, u_to=pedido.estabelecimento.user, text=text, pedido=pedido, is_read=False) mess.save() message = "Nova Mensagem" n = Notification(type_message='MOTORISTA_MESSAGE', to=pedido.estabelecimento.user, message=message) n.save() elif loja: mess = Message(u_from=loja.user, u_to=pedido.motorista, text=text, pedido=pedido, is_read=False) mess.save() message = "Nova Mensagem" n = Notification(type_message='LOJA_MESSAGE', to=pedido.motorista, message=message) n.save() return return_to_get_chat(request, pedido.pk)
def test_only_send_notifications_in_created_state(notify_api, notify_db, notify_db_session, notify_config, mocker): mocker.patch('app.sms_wrapper.send', return_value=("1234", "twilio")) sent_at = datetime.utcnow() create_notification = Notification( id=1000, to="to", message="message", created_at=datetime.utcnow(), sent_at=sent_at, status='sent', sender='twilio', method='sms', job_id=1234, sender_id="999" ) db.session.add(create_notification) db.session.commit() q = set_up_mock_queue() send_message_to_mock_queue(q, Notification.query.get(1234)) send_sms() # new one read_notification_1 = Notification.query.get(1000) print(read_notification_1.sender) assert read_notification_1.status == 'sent' assert read_notification_1.sender_id == '999' assert read_notification_1.sender == 'twilio' assert read_notification_1.sent_at == sent_at # normal test session one read_notification_2 = Notification.query.get(1234) assert read_notification_2.status == 'sent' assert read_notification_2.sender_id == '1234' assert read_notification_2.sender == 'twilio' assert read_notification_2.sent_at >= read_notification_2.created_at # sms calls made correctly sms_wrapper.send.assert_called_once_with('phone-number', 'this is a message', 1234)
def test_should_send_sms_all_notifications(notify_api, notify_db, notify_db_session, notify_config, mocker): mocker.patch('app.sms_wrapper.send', return_value=("1234", "twilio")) create_notification = Notification( id=1000, to="to", message="message", created_at=datetime.utcnow(), status='created', method='sms', job_id=1234 ) db.session.add(create_notification) db.session.commit() read_notification_2 = Notification.query.get(1234) q = set_up_mock_queue() send_message_to_mock_queue(q, create_notification) send_message_to_mock_queue(q, read_notification_2) send_sms() # new one read_notification_1 = Notification.query.get(1000) assert read_notification_1.status == 'sent' assert read_notification_1.sent_at >= read_notification_1.created_at assert read_notification_1.sender_id == "1234" assert read_notification_1.sender == "twilio" # normal test session one read_notification_2 = Notification.query.get(1234) assert read_notification_2.status == 'sent' assert read_notification_2.sent_at >= read_notification_2.created_at assert read_notification_2.sender_id == "1234" assert read_notification_2.sender == "twilio" # sms calls made correctly sms_wrapper.send.assert_has_calls([call('phone-number', 'this is a message', 1234), call("to", "message", 1000)], any_order=True)
def import_noti_from_result_2nd(): tmp = {} for result in Result.query.filter(Result.id >= 11147).all(): if not result.user in tmp: tmp[result.user] = [] if result.date in tmp[result.user]: print("REPEAT", result.user, result.date) continue tmp[result.user].append(result.date) print("[{}]".format(result.id)) noti_dict = loads(result.raw).get('Notification') if noti_dict: for lat, sub_text, app, timestamp, text, lon, title, ticker, send_esm in \ zip(noti_dict['latitude_cols'], noti_dict['subText_cols'], noti_dict['app_cols'], noti_dict['timestamps'], \ noti_dict['n_text_cols'], noti_dict['longitude_cols'], noti_dict['title_cols'], noti_dict['tickerText_cols'], \ noti_dict['sendForm_cols']): if Notification.query.filter_by(device_id=result.user).filter_by(timestamp=timestamp).filter_by(ticker_text=ticker).first(): print("\t\talready have", timestamp) continue elif ticker and (app=='com.facebook.orca' or app=='jp.naver.line.android'): print("\t{}".format(ticker)) new_noti = Notification( timestamp = timestamp, device_id = result.user, latitude = lat, longitude = lon, app = app, title = title, sub_text = sub_text, text = text, ticker_text = ticker, send_esm = True if send_esm == '1' else False) db.session.add(new_noti) try: db.session.commit() except Exception as e: print("WTF") db.session.rollback()
def addNotification(target, causer: User, type: NotificationType, title: str, url: str, package: Package = None): try: iter(target) for x in target: addNotification(x, causer, type, title, url, package) return except TypeError: pass if target.rank.atLeast(UserRank.NEW_MEMBER) and target != causer: Notification.query.filter_by(user=target, causer=causer, type=type, title=title, url=url, package=package).delete() notif = Notification(target, causer, type, title, url, package) db.session.add(notif)
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', '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 test_create_complaint_should_return_complaint_with_correct_info( mocker, notify_api): request = get_govdelivery_request('1111', 'blacklisted') test_email = '*****@*****.**' mocker.patch( 'app.notifications.notifications_govdelivery_callback.save_complaint') test_notification = Notification(id=uuid.uuid4(), to=test_email, service_id=uuid.uuid4()) expected_complaint = Complaint(notification_id=test_notification.id, service_id=test_notification.service_id, feedback_id=request['sid'], complaint_type=request['message_type'], complaint_date=parser.parse( request['completed_at'])) with notify_api.app_context(): complaint = create_complaint(request, test_notification) assert_complaints_are_equal(expected_complaint, complaint)
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_client.send(Message('{}'.format(notification.id))) 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_client = QueueClient.from_connection_string( app.config.get('SERVICE_BUS_CONNECTION_STRING'), app.config.get('SERVICE_BUS_QUEUE_NAME')) message = Message(str(notification.id)) queue_client.send(message) return redirect('/Notifications') except: logging.error('log unable to save notification') else: return render_template('notification.html')
def settings(): users = Notification.get_all_recievers() fire_value = Settings.get_fire_value() alert = Settings.get_alert_switch_value() return render_template('settings.html', users=users, fire_value=fire_value, alert=alert)
def fire_reached(self): msg = '达到预警温度!当前机房温度%d°C\n查看实时温度 %s' % (self.fire_value, app.config.get('SERVER_URL')) app.logger.info(msg) if self.should_alarm and not self.firing: Notification.send_notification('机房温度警报', msg) self.firing = True
def fire_gone(self): msg = '温度警报解除,当前机房温度%d°C\n查看实时温度 %s' % (self.fire_value, app.config.get('SERVER_URL')) app.logger.info(msg) if self.should_alarm and self.firing: Notification.send_notification('机房温度警报解除', msg) self.firing = False
def test_status_conversion_handles_failed_statuses(initial_statuses, expected_statuses): converted_statuses = Notification.substitute_status(initial_statuses) assert len(converted_statuses) == len(expected_statuses) assert set(converted_statuses) == set(expected_statuses)
def run(self, filenames, postproc_funcs, reduced_record_ctx): self.key_concat_seq = reduced_record_ctx['key_concat_seq'] reader = RecordsReader(filenames, 0) """ Run all the postproc funcs using results as args """ for group_key, records in self.group_records(reader).iteritems(): grp_part = [] if group_key == '__stub__' else group_key.split(self.key_concat_seq) for fname in postproc_funcs: func = handler_for_name(fname) processed = [] for t in func(records): processed.append(t) records = processed for k, v in records: groupings = list(grp_part) if k: groupings.append(k) logging.warn("set for storage (%s,%s)" % (groupings, v)) store_reduced_record(groupings, v, reduced_record_ctx) # Actualiza las propiedades de control del indicator_entry indicator_entry = IndicatorEntry.get(reduced_record_ctx['indicator_entry']) indicator_entry.status = u'calculated' indicator_entry.num_reduced_records = indicator_entry.number_reduced_records() indicator_entry.calculated_date = datetime.datetime.now() indicator_entry.put() # Crea la notificacion para el usuario user = SystemUser.get(reduced_record_ctx['user_key']) if user: notification = Notification( user=user.key(), type='miscelaneous', title=_('INDICATOR_ENTRY_CALCULATED'), message=render_template('indicator_entry_completed', { 'indicator_entry_key': str(indicator_entry.key()), 'indicator_entry_name': indicator_entry.name, 'num_reduced_records': indicator_entry.num_reduced_records }) ) notification.put() # Obtiene todas las opciones de los niveles y las guarda en el indicator_entry indicator_path = indicator_entry.indicator_path levels = {} number_levels = len(indicator_path.grouping_mappings) for i in range(1, number_levels + 1): levels['level%s' % i] = [] limit = 100 offset = 0 while True: reduced_records = ReducedRecord.all().filter('indicator_path =', indicator_path.key()).fetch(limit=limit, offset=offset) if len(reduced_records) == 0: break for reduced_record in reduced_records: for i in range(1, number_levels + 1): levels['level%s' % i].append(getattr(reduced_record, 'level%s' % i)) offset += 100 new_levels = {} for key, value in levels.iteritems(): value = unique(value) value.sort() new_levels[key] = value del levels indicator_entry.level_options = json.encode(new_levels) indicator_entry.put()