Пример #1
0
 def test_notification_is_invalid_without_name(self):
     '''Test name is mandatory.'''
     invalid_notification = Notification(None, "hello", datetime.now(), 1,
                                         1)
     assert not invalid_notification.is_valid()
     invalid_notification = Notification("", "hello", datetime.now(), 1, 1)
     assert not invalid_notification.is_valid()
Пример #2
0
 def setUp(self):
     """Set variables for the other testcases."""
     self.reason1 = "status_changed"
     self.data_model = dict(
         metrics=dict(metric_type=dict(name="type")),
         sources=dict(quality_time=dict(parameters=dict(status=dict(
             api_values={
                 "target met (green)": "target_met",
                 "target not met (red)": "target_not_met"
             })))),
     )
     self.report_url = "https://report1"
     self.report = dict(title="report_title", url=self.report_url)
     metric1 = self.create_metric("default metric 1")
     metric2 = self.create_metric("default metric 2")
     self.metric_notification_data1 = MetricNotificationData(
         metric1, self.data_model, self.reason1)
     self.metric_notification_data2 = MetricNotificationData(
         metric2, self.data_model, self.reason1)
     metrics1 = [
         self.metric_notification_data1, self.metric_notification_data2
     ]
     metric3 = self.create_metric("default metric 3")
     metric4 = self.create_metric("default metric 4")
     metric_notification_data3 = MetricNotificationData(
         metric3, self.data_model, self.reason1)
     metric_notification_data4 = MetricNotificationData(
         metric4, self.data_model, self.reason1)
     metrics2 = [metric_notification_data3, metric_notification_data4]
     self.notifications = [
         Notification(self.report, metrics1, "uuid1",
                      dict(webhook="https://url/1")),
         Notification(self.report, metrics2, "uuid2",
                      dict(webhook="https://url/2")),
     ]
Пример #3
0
 def test_notification_is_invalid_without_msg(self):
     '''Test message is mandatory.'''
     invalid_notification = Notification("admin", None, datetime.now(), 1,
                                         1)
     assert not invalid_notification.is_valid()
     invalid_notification = Notification("admin", "", datetime.now(), 1, 1)
     assert not invalid_notification.is_valid()
Пример #4
0
 def extendPost(self, idPost, postDuration, typeAccountAuthor,
                usernameAuthorPost):
     if typeAccountAuthor == "owner":
         connectDatabase = ConnectDatabase()
         query_str = """
             UPDATE post SET postDuration = ?, statusPost = ?
             WHERE idPost = ? AND usernameAuthorPost = ?
             """
         connectDatabase.cursor.execute(query_str, postDuration, "extend",
                                        idPost, usernameAuthorPost)
         connectDatabase.connection.commit()
         connectDatabase.close()
         # thêm thông báo
         icon = "icon-post.png"
         titleNotification = "Gia hạn bài đăng"
         content = "Bài đăng " + str(
             idPost
         ) + " đang chờ chấp nhận gia hạn. Liên hệ sớm nhất với quản trị viên để thanh toán"
         Notification().create(titleNotification, usernameAuthorPost, icon,
                               content)
     else:
         connectDatabase = ConnectDatabase()
         query_str = "UPDATE post SET statusPost = ?, acceptDate = ?, expireDate = ? WHERE idPost = ? AND usernameAuthorPost = ?"
         connectDatabase.cursor.execute(
             query_str, "active", datetime.date(datetime.now()),
             datetime.date(datetime.now() + timedelta(days=postDuration)),
             idPost, usernameAuthorPost)
         connectDatabase.connection.commit()
         connectDatabase.close()
Пример #5
0
 def create(self, titlePost, contentPost, addressProvince, addressDistrict,
            addressWard, addressDetail, locationRelate, itemType, numOfRoom,
            priceItem, area, statusItem, bathroom, kitchen, aircondition,
            balcony, priceElectric, priceWater, otherUtility,
            usernameAuthorPost, typeAccountAuthor, postDuration,
            listImages):
     # typeAccountAuthor in ["owner", "admin"]
     connectDatabase = ConnectDatabase()
     connectDatabase.connection.autocommit = False
     if typeAccountAuthor == "owner":
         # chủ nhà trọ đăng bài => chờ admin duyệt
         statusPost = "handling"
         query_str = """
             INSERT INTO post(titlePost, contentPost, addressProvince, addressDistrict, addressWard, addressDetail, locationRelate, itemType, numOfRoom, priceItem, area, statusItem, bathroom, kitchen, aircondition, balcony, priceElectric, priceWater, otherUtility, usernameAuthorPost, typeAccountAuthor, postDuration, createDate, statusPost, statusHired)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
             """
         connectDatabase.cursor.execute(
             query_str, titlePost, contentPost, addressProvince,
             addressDistrict, addressWard, addressDetail, locationRelate,
             itemType, numOfRoom, priceItem, area, statusItem, bathroom,
             kitchen, aircondition, balcony, priceElectric, priceWater,
             otherUtility,
             usernameAuthorPost, typeAccountAuthor, postDuration,
             datetime.date(datetime.now()), statusPost, "ready")
     else:
         # admin đăng bài => không phải chờ duyệt
         statusPost = "active"
         query_str = """
             INSERT INTO post(titlePost, contentPost, addressProvince, addressDistrict, addressWard, addressDetail, locationRelate, itemType, numOfRoom, priceItem, area, statusItem, bathroom, kitchen, aircondition, balcony, priceElectric, priceWater, otherUtility, usernameAuthorPost, typeAccountAuthor, postDuration, createDate, acceptDate, expireDate, statusPost, statusHired)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
             """
         connectDatabase.cursor.execute(
             query_str, titlePost, contentPost, addressProvince,
             addressDistrict, addressWard, addressDetail, locationRelate,
             itemType, numOfRoom, priceItem, area, statusItem, bathroom,
             kitchen, aircondition, balcony, priceElectric, priceWater,
             otherUtility, usernameAuthorPost, typeAccountAuthor,
             postDuration, datetime.date(datetime.now()),
             datetime.date(datetime.now()),
             datetime.date(datetime.now() + timedelta(days=postDuration)),
             statusPost, "ready")
     query_str = "SELECT MAX(idPost) FROM post"
     idPost = connectDatabase.cursor.execute(query_str).fetchval()
     query_str = """
         INSERT INTO image_post(idPost, image)
         VALUES (?, ?)
         """
     for image in listImages:
         connectDatabase.cursor.execute(query_str, idPost, image)
     connectDatabase.connection.commit()
     connectDatabase.close()
     # thêm thông báo
     icon = "icon-post.png"
     titleNotification = "Đăng bài mới"
     if typeAccountAuthor == "admin":
         content = "Đăng bài thành công. Mã bài đăng: " + str(idPost)
     else:
         content = "Bài đăng " + str(idPost) + " đang chờ được duyệt"
     Notification().create(titleNotification, usernameAuthorPost, icon,
                           content)
Пример #6
0
def notification():
    if "type_account" not in session or session["type_account"] == "renter":
        time.sleep(10)
        return
    return app.response_class(json.dumps(Notification().getAllNotifications(
        session["username"])),
                              mimetype='application/json')
Пример #7
0
 def signup(self, username, password, fullname, phoneNumber, email,
            birthday, ID, imageID, addressProvince, addressDistrict,
            addressWard, addressDetail, typeAvt):
     """
     Đăng ký tài khoản của Chủ nhà trọ => Đưa vào danh sách chờ duyệt
     
     Parameters
     ----------
     None
         
     Returns
     ----------
     
     
     """
     query_str = """
         INSERT INTO owner(username, password, fullname, phoneNumber, email, birthday, ID, imageID, addressProvince, addressDistrict, addressWard, addressDetail, typeAvt, status, createDate)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
         """
     connectDatabase = ConnectDatabase()
     connectDatabase.cursor.execute(query_str, username, password, fullname,
                                    phoneNumber, email, birthday, ID,
                                    imageID, addressProvince,
                                    addressDistrict, addressWard,
                                    addressDetail, typeAvt, "handling",
                                    datetime.date(datetime.now()))
     connectDatabase.connection.commit()
     connectDatabase.close()
     # thêm thông báo
     icon = "icon-account.png"
     titleNotification = "Đăng kí tài khoản"
     content = "Tài khoản của bạn đang chờ admin phê duyệt. Trong khoảng thời gian này, bạn sẽ không thể đăng bài"
     Notification().create(titleNotification, username, icon, content)
Пример #8
0
 def test_unchanged_status_text(self):
     """Test that the text is correct."""
     scale = "count"
     metric1 = dict(type="metric_type",
                    name="Metric",
                    unit="units",
                    scale=scale,
                    recent_measurements=[
                        dict(count=dict(value=0, status="near_target_met")),
                        dict(count=dict(value=42, status="near_target_met"))
                    ])
     metric2 = dict(type="metric_type",
                    name="Metric",
                    unit="units",
                    scale=scale,
                    recent_measurements=[
                        dict(count=dict(value=5, status="target_met")),
                        dict(count=dict(value=10, status="target_not_met"))
                    ])
     metric_notification_data1 = MetricNotificationData(
         metric1, self.data_model, "status_long_unchanged")
     metric_notification_data2 = MetricNotificationData(
         metric2, self.data_model, "status_long_unchanged")
     notification = Notification(
         self.report,
         [metric_notification_data1, metric_notification_data2],
         "destination_uuid", {})
     text = build_notification_text(notification)
     self.assertEqual(
         "[Report 1](https://report1) has 2 metrics that are notable:\n\n"
         "* Metric has been yellow (near target met) for three weeks. Value: 42 units.\n"
         "* Metric has been red (target not met) for three weeks. Value: 10 units.\n",
         text)
Пример #9
0
def post_like(post_id):
    """
    make a like
    Return:dict of the recation id
    """
    if not request.get_json():
        return make_response(jsonify({'error': 'Not a JSON'}), 400)
    f = storage.get(Post, post_id)
    if f is None:
        abort(404)
    #<source_user_id>/<target_user_id>
    mydata = request.get_json()
    new = Reaction()
    for k, v in mydata.items():
        setattr(new, k, v)
    new.save()

    new_notif = Notification()
    new_notif.reciver_user_id = mydata["target_user_id"]
    new_notif.maker_user_id = mydata["source_user_id"]
    new_notif.type = "like"
    new_notif.reaction_id = str(new.id)
    new_notif.creation_date = datetime.utcnow()
    new_notif.save()

    my_post = storage.get(Post, post_id)
    new_react_num = my_post.number_of_reaction()
    rep = {}
    rep["num"] = new_react_num
    return make_response(jsonify(rep), 200)
Пример #10
0
def readAllNotification():
    if "type_account" not in session or session["type_account"] == "renter":
        time.sleep(10)
        return
    Notification().readAllNotifications(session["username"])
    return app.response_class(json.dumps({"message": "ok"}),
                              mimetype='application/json')
Пример #11
0
 def setUp(self):
     """Set variables for the other testcases."""
     destination = dict(frequency=60)
     destination_uuid = "dest_uuid"
     metrics = {}
     report = dict(title="title")
     self.notification = Notification(report, metrics, destination_uuid, destination)
Пример #12
0
    def createNotificationDisableFan(self, room):
        """
        creates disable fan notification

        Parameters
        ----------
        room: str
            room key as string

        Returns
        -------
        dict
            dictionary containing the Nofification Model as json
        """
        topic, topicdata = self.DB.getRoomActuatorTopicAndData(room, 'fan')
        topicdata['val'] = 'off'
        return {
            'notification':
            Notification(notificationType='disabelefan',
                         text='Disable Fan',
                         topic=topic,
                         topicdata=topicdata).getDict(),
            'room':
            room
        }
Пример #13
0
    def createNotificationEnableLight(self, room):
        """
        creates enable Light notification

        Parameters
        ----------
        room: str
            room key as string

        Returns
        -------
        dict
            dictionary containing the Nofification Model as json
        """
        topic, topicdata = self.DB.getRoomActuatorTopicAndData(room, 'light')
        topicdata['val'] = 'on'
        return {
            'notification':
            Notification(notificationType='enablelight',
                         text='Enable Light',
                         topic=topic,
                         topicdata=topicdata).getDict(),
            'room':
            room
        }
Пример #14
0
def AddNotification(user_id_data,message_data): # 通知を追加する
    session = Session()
    now_date = (datetime.datetime.now())
    now_date_str = now_date.strftime('%Y/%m/%d %H:%M:%S.%f')
    session.add_all([
        Notification( user_id = user_id_data , message = message_data ,created_at = now_date_str)
    ])
    session.commit()
    print("通知の追加が完了しました")
Пример #15
0
    def post(self):
        checksum = self.request.headers['X-Tba-Checksum']
        payload = self.request.body

        if hashlib.sha1('{}{}'.format(SECRET,
                                      payload)).hexdigest() != checksum:
            return

        Notification(payload=payload).put()
Пример #16
0
def addNotification(name, notification):
    user = db.session.query(User).filter_by(username=name).first()
    data = user.get_notifications()
    n = Notification(g.user.username, notification, datetime.now().replace(microsecond=0))

    if data == '[]':
        data = "[" + json.dumps(n.toJSON()) + "]"
    else:
        data = '[' + json.dumps(n.toJSON()) + ',' + data[1:]
    user.notifications=data
    db.session.commit()
Пример #17
0
def create_manager_notes(id):
    user = User.get_or_none(User.id == id)
    manager = User.get_or_none(User.id == user.manager_id)
    comments = request.form.get("manager_notes")
    review_date = request.form.get("review_date")
    Review(manager_notes=comments, executive_id=user.id,
           review_date=review_date).save()
    if user.id != current_user.id:
        Notification(notification_type=4, sender=current_user.id, recipient=user.id).save()
        flash("Manager commment added")
    return redirect(url_for('users.show_review', user=user, manager=manager, id=user.id))
Пример #18
0
 def changePasswordAndAvatar(self, username, new_password, new_typeAvt):
     query_str = "UPDATE owner SET password = ?, typeAvt = ? WHERE username = ?"
     connectDatabase = ConnectDatabase()
     connectDatabase.cursor.execute(query_str, new_password, new_typeAvt,
                                    username)
     connectDatabase.connection.commit()
     connectDatabase.close()
     # thêm thông báo
     icon = "icon-account.png"
     titleNotification = "Chỉnh sửa thông tin"
     content = "Avatar và/hoặc mật khẩu vừa được thay đổi"
     Notification().create(titleNotification, username, icon, content)
Пример #19
0
    def build_notification():
        """Return an object notification based on the POST parameters"""
        username = post_param('username', '')
        message = post_param('message', '')
        light = post_param('light', 1)
        sound = post_param('sound', 1)
        notification = Notification(username, message, datetime.now(), light,
                                    sound)

        if not notification.is_valid():
            raise HTTPResponse(body="Notification invalid", status=400)

        return notification
Пример #20
0
 def test_merge_notifications_with_same_destination_but_different_report(
         self):
     """Test that the metrics are merged into the correct notification."""
     report = dict(title="different_title", url="https://differentreport")
     metric1 = dict(metric_name="new_metric 1")
     metric2 = dict(metric_name="new_metric 2")
     metrics1 = [metric1, metric2]
     new_notifications = [Notification(report, metrics1, "uuid1", {})]
     outbox = Outbox(self.notifications)
     outbox.add_notifications(new_notifications)
     self.assertEqual(
         outbox.notifications[0].metrics,
         [self.metric_notification_data1, self.metric_notification_data2],
     )
Пример #21
0
	def post(self, pid):
		auth_token = request.headers.get('Authorization')
		current_app.logger.debug("auth_token: %s", auth_token)

		if not auth_token:
			return {'message': 'No Authorization token'}, 401

		resp = User.decode_auth_token(auth_token)
		if isinstance(resp, str):
			response = {
				'status': 'fail',
				'message': resp
			}
			return response, 401

		auth_user = User.query.filter_by(id=resp).first()
		if not auth_user:
			return {'message': 'Auth token does not correspond to existing user'}, 400

		post = Post.query.filter_by(pid=pid).first()
		if not post:
			return {'message': 'Post does not exist'}, 400

		json_data = request.get_json(force=True)
		if not json_data:
			return {'message', 'No input data provided'}, 400

		data, errors = comment_schema.load(json_data)
		if errors:
			return errors, 422

		timestamp = datetime.datetime.utcnow()

		comment = Comment(pid=post.pid, uid=auth_user.id, comment=data['comment'], timestamp=timestamp)
		db.session.add(comment)
		db.session.flush()

		if post.uid != auth_user.id:
			notification = Notification(uid=post.uid, message="{username} commented on your post.".format(username=auth_user.username),
										notif_type="C", link=pid, timestamp=timestamp)
			db.session.add(notification)
			
		db.session.commit()

		#TODO add hashtag and location stuff
		response = comment_schema.dump(comment).data
		response['user'] = auth_user.username

		return {'status': 'success', 'data': response}, 201
Пример #22
0
def create():
    compliment_badge = request.form['badgeId']
    compliment_recipient = request.form['recipientList']
    compliment_comment = request.form['comment']
    user = User.get_or_none(User.id == compliment_recipient)
    new_compliment = Compliment(compliment=compliment_comment,
                                sender_id=current_user.id,
                                recipient_id=compliment_recipient,
                                badge_id=compliment_badge)
    new_compliment.save()
    Notification(notification_type=2,
                 sender=current_user.id,
                 recipient=user.id).save()

    return redirect(url_for('compliments.new'))
Пример #23
0
 def adminDenyRequestPost(self, idPost, usernameOwner):
     # sử dụng khi bài từ chối đăng bài lần đầu và từ chối gia hạn bài viết
     connectDatabase = ConnectDatabase()
     query_str = "UPDATE post SET statusPost = ?, acceptDate = ? WHERE idPost = ?"
     connectDatabase.cursor.execute(query_str, "deny",
                                    datetime.date(datetime.now()), idPost)
     connectDatabase.connection.commit()
     connectDatabase.close()
     # thêm thông báo
     icon = "icon-post.png"
     titleNotification = "Bài đăng thất bại"
     content = "Bài đăng " + str(
         idPost
     ) + " bị từ chối do thông tin không hợp lý hoặc chưa thanh toán phí. Thử với bài đăng khác hoặc liên hệ lại với quản trị viên"
     Notification().create(titleNotification, usernameOwner, icon, content)
Пример #24
0
 def blockPost(self, idPost):
     connectDatabase = ConnectDatabase()
     query_str = "UPDATE post SET statusPost = ? WHERE idPost = ?"
     connectDatabase.cursor.execute(query_str, "block", idPost)
     connectDatabase.connection.commit()
     query_str = "SELECT usernameAuthorPost FROM post WHERE idPost = ?"
     usernameAuthorPost = connectDatabase.cursor.execute(query_str,
                                                         idPost).fetchval()
     connectDatabase.close()
     icon = "icon-post.png"
     titleNotification = "Bài đăng bị chặn"
     content = "Bài đăng " + str(
         idPost
     ) + " bị chặn do bị report. Mọi thắc mắc xin liên hệ lại với quản trị viên."
     Notification().create(titleNotification, usernameAuthorPost, icon,
                           content)
Пример #25
0
 def setEnableEditAccountOwner(self, username):
     query_str = "DELETE FROM owner_profile_scratch WHERE username = ? AND status = ?"
     connectDatabase = ConnectDatabase()
     connectDatabase.cursor.execute(query_str, username, "enable")
     connectDatabase.connection.commit()
     query_str = """
         INSERT INTO owner_profile_scratch(status, username) 
         VALUES (?, ?)
         """
     connectDatabase.cursor.execute(query_str, "enable", username)
     connectDatabase.connection.commit()
     connectDatabase.close()
     # thêm thông báo
     icon = "icon-account.png"
     titleNotification = "Chỉnh sửa tài khoản"
     content = "Tài khoản của bạn vừa được quản trị viên cấp quyền chỉnh sửa. Lưu ý chỉ chỉnh sửa được 1 lần, hãy thận trọng với những thông tin được sửa đổi. Nếu phát hiện thông tin bất thường, tài khoản của bạn có thể bị khóa hoặc xóa vĩnh viễn"    
     Notification().create(titleNotification, username, icon, content)
Пример #26
0
async def sendNotification(produto: Produto):
	locale.setlocale(locale.LC_MONETARY, "pt_BR.UTF-8")
	modelo: Modelo = modeloRepo.modelos.get(produto.modelo, None)
	marca: Marca = marcaRepo.marcas.get(modelo.marca, None) if modelo else None
	modelo = modelo.nome if modelo else ''
	marca = marca.nome if marca else ''
	title = f'{marca} {modelo}'
	pm = locale.currency(produto.precos[-2:][0][0], grouping=True)
	pa = locale.currency(produto.precos[-1:][0][0], grouping=True)
	content = f'{pm} -> {pa}'
	timestamp = produto.precos[-1:][0][1]
	notification = Notification(
		title,
		content,
		timestamp,
		key=produto._id
	)
	return notificationRepo.addNotification(notification)
Пример #27
0
 def adminActiveRequestPost(self, idPost, usernameOwner, postDuration):
     # sử dụng khi bài chấp nhận đăng bài lần đầu và gia hạn bài viết
     connectDatabase = ConnectDatabase()
     query_str = "UPDATE post SET statusPost = ?, acceptDate = ?, expireDate = ? WHERE idPost = ?"
     connectDatabase.cursor.execute(
         query_str, "active", datetime.date(datetime.now()),
         datetime.date(datetime.now() + timedelta(days=postDuration)),
         idPost)
     connectDatabase.connection.commit()
     connectDatabase.close()
     # thêm thông báo
     icon = "icon-post.png"
     titleNotification = "Đăng bài"
     content = "Bài đăng " + str(
         idPost) + " đã được đăng. Ngày hết hạn: " + '/'.join(
             str(
                 datetime.date(datetime.now() + timedelta(
                     days=postDuration))).split('-')[::-1])
     Notification().create(titleNotification, usernameOwner, icon, content)
Пример #28
0
    def createNotificationCloseWindow(self, room):
        """
        creates close window notification

        Parameters
        ----------
        room: str
            room key as string

        Returns
        -------
        dict
            dictionary containing the Nofification Model as json
        """
        return {
            'notification':
            Notification(notificationType='closewindow',
                         text='Close Window').getDict(),
            'room':
            room
        }
Пример #29
0
	def post(self, pid):
		auth_token = request.headers.get('Authorization')
		current_app.logger.debug("auth_token: %s", auth_token)

		if not auth_token:
			return {'message': 'No Authorization token'}, 401

		resp = User.decode_auth_token(auth_token)
		if isinstance(resp, str):
			response = {
				'status': 'fail',
				'message': resp
			}
			return response, 401

		auth_user = User.query.filter_by(id=resp).first()
		if not auth_user:
			return {'message': 'Auth token does not correspond to existing user'}, 400

		post = Post.query.filter_by(pid=pid).first()
		if not post:
			return {'message': 'Post does not exist'}, 400

		try:
			timestamp = datetime.datetime.utcnow()
			post_like = PostLike(pid=pid, uid=auth_user.id, timestamp=timestamp)
			db.session.add(post_like)
			db.session.flush()

			if post.uid != auth_user.id:
				notification = Notification(uid=post.uid, message="{username} liked your post.".format(username=auth_user.username),
											notif_type="L", link=pid, timestamp=timestamp)
				db.session.add(notification)

			db.session.commit()

		except Exception:
			return {'message': 'User already liked post'}, 400

		return {'status': 'success'}, 200
Пример #30
0
 def get_notifications(
         self, json,
         most_recent_measurement_seen: str) -> List[Notification]:
     """Return the reports that have a webhook and metrics that require notifying."""
     notifications = []
     for report in json["reports"]:
         notable_metrics = []
         for subject in report["subjects"].values():
             for metric_uuid, metric in subject["metrics"].items():
                 notable = self.get_notification(
                     metric, metric_uuid, most_recent_measurement_seen)
                 if notable:
                     notable_metrics.append(
                         MetricNotificationData(metric, self.data_model,
                                                notable))
         if notable_metrics:
             for destination_uuid, destination in report.get(
                     "notification_destinations", {}).items():
                 notifications.append(
                     Notification(report, notable_metrics, destination_uuid,
                                  destination))
     return notifications