def create(cls, follower, followee): from server.models.message import Message existing = Follow.read(follower, followee) if existing: return existing newFollow = Follow( follower=follower.id, followee=followee.id, ) newFollow.id = Follow.makeId(follower.id, followee.id) newFollow.store(core.connect()) json = { "fromId": "shiftspace", "toId": followee.id, "title": "%s has started following your shifts!" % (follower.userName), "text": "%s has started following your shifts!" % (follower.userName), "meta": "follow", "content": { "followerId": follower.id } } Message.create(**json) return newFollow
def add_message(): try: data = json.loads(request.data) user_to = data['to'] message_self = data['message_self'] message_to = data['message_to'] encode_self = message_self.encode('utf-8') encode_to = message_to.encode('utf-8') if len(message_self) > 2048 or len(message_to) > 2048: return { "success": False, "message": "Message exceeds 2048 character limit." } user_from = get_username(session["id"]) message_self = Message(original=user_from, username_to=user_to, username_from=user_from, message=encode_self) message_to = Message(original=user_to, username_to=user_to, username_from=user_from, message=encode_to) db.session.add(message_self) db.session.add(message_to) db.session.commit() nMessages = get_messages_history(user_from, user_from, user_to) return {"success": True, "messages": nMessages} except json.decoder.JSONDecoderError: return {"error": "Malformed request"}, 400
def renew_database(): from werkzeug.security import generate_password_hash, check_password_hash Chat.objects.delete() Message.objects.delete() User.objects.delete() user1 = User(name="user1", email='*****@*****.**', password=generate_password_hash("test", method='sha256')).save() user2 = User(name="user2", email='*****@*****.**', password=generate_password_hash("test", method='sha256')).save() user3 = User(name="user3", email='*****@*****.**', password=generate_password_hash("test", method='sha256')).save() user4 = User(name="user4", email='*****@*****.**', password=generate_password_hash("test", method='sha256')).save() chat1 = ChatCreation.create_new(members=[user1, user2]) chat2 = ChatCreation.create_new(members=[user1, user3]) Message(text="Zprava user1", author=user1, chat=chat1).save() Message(text="Zprava user2", author=user2, chat=chat1).save() Message(text="Zprava user1", author=user1, chat=chat1).save() Message(text="Zprava user1 chat 2", author=user1, chat=chat2).save() Message(text="Zprava user2 chat2", author=user3, chat=chat2).save()
def unreadCount(self): from server.models.message import Message db = core.connect("shiftspace/shared") syscount = core.value(Message.system_count(db, key=self.id)) or 0 tocount = core.value(Message.count_by_user(db, key=self.id)) or 0 readcount = core.value(Message.read_count_by_user(db, key=self.id)) or 0 return (syscount+tocount)-readcount
def create_conversations(): user1 = User.objects(name="test").first() user2 = User.objects(name="test2").first() try: ChatCreation.create_new(members=[user1, user2]) conv1 = Chat.objects(members=[user1, user2]).first() Message(text="Testovací zpráva autora test", author=user1, chat=conv1).save() Message(text="Testovací zpráva autora test3", author=user2, chat=conv1).save() Message(text="1. Testovací zpráva autora test", author=user1, chat=conv1).save() m1 = Message(text="3. Testovací zpráva autora test", author=user1, chat=conv1).save() conv1.update(last_message_date=m1.date_created) except Exception as e: print(str(e))
def shareWith(self, userIds, fromUser=None): from server.models.message import Message from server.models.ssuser import SSUser users = core.fetch(keys=userIds) if fromUser: userName = fromUser.userName else: userName = SSUser.read(self.createdBy).userName for user in users: json = { "fromId": self.createdBy, "toId": user["_id"], "title": "%s has shared a shift with you!" % userName, "text": "%s has shared a shift titled '%s' with you!" % (userName, self.summary), "meta": "share", "content": { "type": "shift", "_id": self.id, "href": self.href, "summary": self.summary } } Message.create(**json)
def markUnread(self, id): loggedInUser = helper.getLoggedInUser() theMessage = Message.read(id, userId=loggedInUser) if theMessage != None: theMessage.markRead(False) return data(Message.read(id, loggedInUser)) else: return error("Operation not permitted. You don't have permission to mark that message", PermissionError)
def unreadCount(self): from server.models.message import Message db = core.connect("shiftspace/shared") syscount = core.value(Message.system_count(db, key=self.id)) or 0 tocount = core.value(Message.count_by_user(db, key=self.id)) or 0 readcount = core.value(Message.read_count_by_user(db, key=self.id)) or 0 return (syscount + tocount) - readcount
def create(cls, userId, shiftId, text, subscribe=False): from server.models.ssuser import SSUser from server.models.shift import Shift from server.models.message import Message # first try the public feed theShift = Shift.load(core.connect("shiftspace/shared"), shiftId) shiftAuthor = SSUser.load(core.connect(), theShift.createdBy) theUser = SSUser.load(core.connect(), userId) server = core.sharedServer() # create the comment db if necessary dbexists = True if not theShift.hasThread(): server.create(Comment.db(shiftId)) dbexists = False # get the db db = core.connect(Comment.db(shiftId)) # if db just created, sync the views and subscribe shift author if not dbexists: Comment.by_created.sync(db) Comment.all_subscribed.sync(db) shiftAuthor.subscribe(theShift) # subscribe the user making the comment if not theUser.isSubscribed(theShift) and subscribe: theUser.subscribe(theShift) # create comment and comment stub json = { "createdBy": userId, "shiftId": shiftId, "shiftAuthor": theShift.createdBy, "text": text, } newComment = Comment(**utils.clean(json)) newComment.store(db) subscribers = theShift.subscribers() # make a private copy # TODO: need to think about the implications of a private copy here - David newComment.copyTo(SSUser.privateDb(theUser.id)) # send each subscriber a message if len(subscribers) > 0: # TODO: needs to be optimized with a fast join - David for subscriber in subscribers: if subscriber != userId: astr = ((subscriber == theShift.createdBy) and "your") or ("%s's" % shiftAuthor.userName) json = { "fromId": userId, "toId": subscriber, "title": "%s just commented on %s shift!" % (theUser.userName, astr), "text": "%s just commented on %s shift!" % (theUser.userName, astr), "meta": "comment" } Message.create(**utils.clean(json)) # TODO: don't replicate if peer - David 11/21/09 core.replicate(Comment.db(shiftId), "shiftspace/shared") return newComment
def create(cls, userId, shiftId, text, subscribe=False): from server.models.ssuser import SSUser from server.models.shift import Shift from server.models.message import Message # first try the public feed theShift = Shift.load(core.connect("shiftspace/shared"), shiftId) shiftAuthor = SSUser.load(core.connect(), theShift.createdBy) theUser = SSUser.load(core.connect(), userId) server = core.server() # create the comment db if necessary dbexists = True if not theShift.hasThread(): server.create(Comment.db(shiftId)) dbexists = False # get the db db = core.connect(Comment.db(shiftId)) # if db just created, sync the views and subscribe shift author if not dbexists: Comment.by_created.sync(db) Comment.all_subscribed.sync(db) shiftAuthor.subscribe(theShift) # subscribe the user making the comment if not theUser.isSubscribed(theShift) and subscribe: theUser.subscribe(theShift) # create comment and comment stub json = { "createdBy": userId, "shiftId": shiftId, "shiftAuthor": theShift.createdBy, "text": text, } newComment = Comment(**utils.clean(json)) newComment.store(db) subscribers = theShift.subscribers() # make a private copy # TODO: need to think about the implications of a private copy here - David newComment.copyTo(SSUser.privateDb(theUser.id)) # send each subscriber a message if len(subscribers) > 0: # TODO: needs to be optimized with a fast join - David for subscriber in subscribers: if subscriber != userId: astr = ((subscriber == theShift.createdBy) and "your") or ("%s's" % shiftAuthor.userName) json = { "fromId": userId, "toId": subscriber, "title": "%s just commented on %s shift!" % (theUser.userName, astr), "text": "%s just commented on %s shift!" % (theUser.userName, astr), "meta": "comment" } Message.create(**utils.clean(json)) # TODO: don't replicate if peer - David 11/21/09 core.replicate(Comment.db(shiftId), "shiftspace/shared") return newComment
def messages(self, start=None, end=None, limit=25): from server.models.message import Message results = Message.by_created(core.connect(SSUser.messagesDb(self.id)), limit=limit) messages = [] if start and not end: messages = core.objects(results[start:]) elif not start and end: message = core.objects(results[:end]) elif start and end: messages = core.objects(results[start:end]) else: messages = core.objects(results) return Message.joinData(messages, userId=self.id)
def inviteUser(self, aUser, otherUser): from server.models.permission import Permission from server.models.message import Message Permission.create(aUser.id, self.id, otherUser.id, 0) json = { "fromId": aUser.id, "toId": otherUser.id, "title": "%s invited you to join the group %s!" % (aUser.userName, self.longName), "text": "%s invited you to join the group %s!" % (aUser.userName, self.longName), "meta": "invite", "content": {"type": "group", "_id": self.id}, } Message.create(**json)
def inviteUser(self, aUser, otherUser): from server.models.permission import Permission from server.models.message import Message Permission.create(aUser.id, self.id, otherUser.id, 0) json = { "fromId": aUser.id, "toId": otherUser.id, "title": "%s invited you to join the group %s!" % (aUser.userName, self.longName), "text": "%s invited you to join the group %s!" % (aUser.userName, self.longName), "meta": "invite", "content": { "type": "group", "_id": self.id } } Message.create(**json)
def read(self, id): from server.models.ssuser import SSUser theMessage = Message.read(id, loggedInUser) if theMessage and theMessage.toId == loggedInUser: return data(theMessage) else: return error("Operation not permitted. You don't have permission to read this message.", PermissionError)
def delete(self, id): chat = Chat_db.objects(id=id).first() if not chat: return {"success": False, "message": "Chat not exist"} else: Chat_db.objects(id=id).delete() Message.objects(chat=id).delete() chat = Chat_db.objects(id=id).first() if not chat: return {"success": True, "message": "Chat was deleted"} return {"success": False, "message": "Delete failed, try it again"}
def test_thing(self): User( name="FooBar1", email="*****@*****.**", password=os.urandom(16), ).save() current_user = User.objects().first() users = User.objects() con = Chat(members=users).save() Message(text="Message test text", author=current_user.id, conversation=con).save() message = Message.objects().first() self.assertEqual(message.author.id, current_user.id)
def delete_chat(id): chat = Chat_db.objects(id=id).first() if not chat: return jsonify({"success": False, "message": "Chat not exist"}), 400 else: Chat_db.objects(id=id).delete() Message.objects(chat=id).delete() chat = Chat_db.objects(id=id).first() if not chat: return jsonify({"success": True, "message": "Chat was deleted"}), 200 return jsonify({ "success": False, "message": "Delete failed, try it again" }), 200
def create(cls, follower, followee): from server.models.message import Message existing = Follow.read(follower, followee) if existing: return existing newFollow = Follow( follower = follower.id, followee = followee.id, ) newFollow.id = Follow.makeId(follower.id, followee.id) newFollow.store(core.connect()) json = { "fromId": "shiftspace", "toId": followee.id, "title": "%s has started following your shifts!" % (follower.userName), "text": "%s has started following your shifts!" % (follower.userName), "meta": "follow", "content": { "followerId": follower.id } } Message.create(**json) return newFollow
def load_messages(id): """ Get messages :param id: chat id :return: last 50 messages """ if current_user.is_authenticated: chat = Chat.objects(id=id).first() chat_members_ids = [member.id for member in chat.members] if current_user["id"] not in chat_members_ids: emit('all_messages', [False], room=id) else: messages = Message.objects(chat=id) messages = list(messages)[-50:] messages.sort(key=lambda x: x.id, reverse=False) all_messages = [] status = "" for message in messages: user = User.objects(name=current_user["name"]).first() # if message.author.id == user.id: # status = "sent" # else: # status = "replies" all_messages.append([ message.author.name, message.text, str(message.date_created), status ]) emit('all_messages', all_messages, room=id) # message_dict = {} # for message in messages: # user = User.objects(name=current_user["name"]).first() # if message.author.id == user.id: # status = "sent" # else: # status = "replies" # # message_dict[str(message.id)] = {"text": message.text, "status": status, # "author": message.author.name} # print("message ", message) else: #print("LOAD messages not authenticated") emit('all_messages', [False], room=id)
def post(self, id): author = request.get_json().get('author') text = request.get_json().get('text') chat = Chat_db.objects(id=id).first() user = User.objects(name=author).first() if user not in chat.members: return { "success": False, "message": "This user is not part of current chat" } message = Message(author=user, chat=chat, text=text).save() if message is not None: return {"success": True, "message": "Message was sent"}
def handle_message(msg, room): user = User.objects(name=msg['author']).first() chat = Chat.objects(id=room).first() Message(author=user, chat=chat, text=msg['text']).save() status = "" if current_user.is_authenticated: # if msg["author"] == current_user["name"]: # status = "sent" # else: # status = "replies" message = [msg["author"], msg["text"], str(1), status] send(message, room=room) else: send(False, room=room)
def get(self, id): messages = Message.objects(chat=id) message_dict = {} for message in messages: user = User.objects(name=current_user["name"]).first() if message.author.id == user.id: status = "sent" else: status = "replies" message_dict[str(message.date_created)] = { "text": message.text, "status": status, "author": message.author.name } return message_dict
def save_message(data): Message(author=data['author'], text=data['text'], chat=data['chat']).save()