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)
def set_as_seen(form): user = User.find_by("username", form["username"]) if not user: abort(404) Notification.setAsSeen(user.getId()) return jsonify("DONE")
def send_email_notification(notification: Notification): try: assert notification.channel is NotificationChannel.EMAIL recipient_email_address = validate_email(notification.recipient).email email = Mail( from_email=Config['notifications']['email_default_from_address'], to_emails=recipient_email_address, subject=notification.subject or 'This is a test Vol Portal Email', html_content=notification.message or '<strong>Test email with message</strong> <p>E-mail is working!</p>' ) response = email_client.send(email) if response.status_code < 300: notification.status = NotificationStatus.SENT notification.sent_date = datetime.utcnow() else: notification.status = NotificationStatus.FAILED except Exception as e: logging.error(e) notification.status = NotificationStatus.FAILED
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")), ]
def create_like(user_id): liked_user = User.get_by_id(user_id) # Check if user exists has_photo = Like.able_to_like( g.current_user.id) # Check if user has profile image is_blocked = User.user_is_blocked(g.current_user.id, user_id) # Check if user was blocked if is_blocked: abort(http.HTTPStatus.FORBIDDEN) if not has_photo: abort(http.HTTPStatus.FORBIDDEN) if liked_user and has_photo: Like.like(g.current_user.id, user_id) # If user is not blocked [blocked, blocker] # Notification if not is_blocked: text = Notification.notification_text('like', g.current_user) notification = Notification.from_dict({ "user_id": user_id, "text": text, "type": "like" }) notification.create() return jsonify(ok=True) abort(http.HTTPStatus.BAD_REQUEST)
def update(): Notification.update(read=True).where( Notification.recipient_id == current_user.id).execute() response = { "success": True, "read": True } return jsonify(response)
def create(username): user = User.get_or_none(User.name == username) obj = request.form.get("objective") Objective.create(objective=obj, user=user.id) if user.id != current_user.id: Notification.create(notification_type=1, sender=current_user.id, recipient=user.id) flash("Objective succesfully added") return redirect(url_for('users.show', username=username))
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)
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()
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
def send_slack_notification(notification: Notification): try: assert notification.channel is NotificationChannel.SLACK slack_client.chat_postMessage(channel=notification.recipient, text=notification.message) # WebClient automatically raises a SlackApiError if response.ok is False; no need to check notification.status = NotificationStatus.SENT notification.sent_date = datetime.utcnow() except Exception as e: logging.error(e) notification.status = NotificationStatus.FAILED
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')
def read_oldest_file(): """Read the oldest file and return a notification""" filelist = [ os.path.join(FOLDER, f) for f in os.listdir(FOLDER) if os.path.isfile(os.path.join(FOLDER, f)) and f[0] != '.' ] if len(filelist) > 0: oldest = min(filelist, key=lambda x: os.stat(x).st_mtime) try: with open(oldest) as oldest_file: notification = Notification.from_json(oldest_file.read()) return notification except IOError as e: #errno, strerror = e.args #print("I/O error({0}): {1}".format(errno,strerror)) #return None raise IOError except: #print("Unexpected error:", sys.exc_info()[0]) #return None raise return None
def sorted_notification(self): from models.notification import Notification return [ notifications for notifications in Notification.select().where(( Notification.recipient_id == self.id )).order_by(Notification.id.desc()).limit(5) ]
def unread_notification(self): from models.notification import Notification return [ notifications for notifications in Notification.select().where((Notification.recipient_id == self.id) & (Notification.read == False)) ]
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)
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 }
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 }
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)
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')
def list_notifications(form): user = User.find_by("username", form["username"]) if not user: abort(404) notifications = Notification.where("user_id", user.getId()) return jsonify(notifications)
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()
def mark_as_read(notification_id): notification = Notification.get_by_id(notification_id) if not notification or notification.user_id != g.current_user.id: abort(http.HTTPStatus.NOT_FOUND) notification.is_read = True notification.update() return jsonify(ok=True)
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)
def unread_notifications(form): user = User.find_by("username", form["username"]) if not user: abort(404) notifications = Notification.where("user_id", user.getId()) unread_notifications = [n for n in notifications if n['seen'] == 0] return jsonify(unread_notifications)
def AddNotification(self): rootKeyUrlsafe = self.request.get('rootKey') notifyReasonCode = self.request.get('notifyReasonCode') sourceUserUrlsafe = self.request.get('userKey') additionalText = self.request.get('additionalText') pointRootKey = ndb.Key(urlsafe=rootKeyUrlsafe) sourceUserKey = ndb.Key(urlsafe=sourceUserUrlsafe) follows = Follow.getActiveFollowsForPoint(pointRootKey) for f in follows: if f.user != sourceUserKey: Notification.createNotificationFromFollow(self, f, pointRootKey, sourceUserKey, int(notifyReasonCode), additionalText, )
def remove_like(user_id): liked_user = User.get_by_id(user_id) # Check if user exists if liked_user: Like.unlike(g.current_user.id, user_id) # If user is not blocked [blocked, blocker] # Notification if not User.user_is_blocked(g.current_user.id, user_id): text = Notification.notification_text('unlike', g.current_user) notification = Notification.from_dict({ "user_id": user_id, "text": text, "type": "like" }) notification.create() return jsonify(ok=True) abort(http.HTTPStatus.BAD_REQUEST)
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("通知の追加が完了しました")
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()
def get_user_by_id(user_id): user = User.get_by_id(user_id) if user: payload = user.get_view("public") if request.args.get('with_images'): user_images = Image.get_user_images(user.id) payload['images'] = [] if user_images: payload['images'] = [{ "src": i.image_src, "id": i.id } for i in user_images] if request.args.get('with_like'): has_like = Like.is_liked(g.current_user.id, user_id) likes_me = Like.is_liked(user_id, g.current_user.id) payload['has_like'] = has_like payload['likes_me'] = likes_me # If I blocked this user [blocked, blocker] if User.user_is_blocked(user_id, g.current_user.id): u_is_blocked = True else: u_is_blocked = False if request.args.get('with_block'): payload['is_blocked'] = u_is_blocked # If user didn't block me [blocked, blocker] # Send notification if not User.user_is_blocked(g.current_user.id, user_id): if g.current_user.id != user_id: text = Notification.notification_text('view', g.current_user) notification = Notification.from_dict({ "user_id": user_id, "text": text, "type": "view" }) notification.create() # View history if g.current_user.id != user_id: History.add_to_history(g.current_user.id, user_id) return jsonify(user=payload) abort(404)
def makeTemplateValues(self, user, profileUser): viewingOwnPage = False if user and profileUser.url == user.url: viewingOwnPage = True template_values = { 'user': self.current_user, 'profileUser': profileUser, 'viewingOwnPage': viewingOwnPage, 'createdPoints' : profileUser.getCreated(), 'editedPoints': profileUser.getEdited(), 'currentArea':self.session.get('currentArea') } if viewingOwnPage: template_values['recentlyViewed'] = profileUser.getRecentlyViewed() template_values['notifications'] = Notification.getAllNotificationsForUser(profileUser.key) return template_values
def clearNotifications(self, latest, earliest=None): Notification.clearNotifications(self.key, latest, earliest)
def getActiveNotifications(self): self._notifications = Notification.getActiveNotificationsForUser(self.key) return self._notifications
def get(self): notifications = Notification.query().order(-Notification.created).fetch() template_values = {'notifications': notifications} path = os.path.join(os.path.dirname(__file__), "templates/notification_list_webhook.html") self.response.write(template.render(path, template_values))
def getActiveNotifications(self): self._notifications, self._newNotificationCount, \ self._moreNotificationsExist = \ Notification.getLatestNotificationsForUser(self.key) return self._notifications
def getUnreadNotifications(self): self._notifications, self._newNotificationCount, \ self._moreNotificationsExist = \ Notification.getUnreadNotificationsForUser(self.key) return self._notifications
def getUnreadNotificationsAfter(self, afterDate): self._notifications, self._newNotificationCount, \ self._moreNotificationsExist = \ Notification.getUnreadNotificationsForUserAfterDate(self.key, afterDate) return self._notifications