def message_ajax(request): if request.method == 'POST': message = request.POST.get('message', '') if len(message) > 0: username = request.user.username #now = timezone.now() now = datetime.now() m = MessageModel(username=username, message=message, creation_date=now) m.save() # create push event with the data of a new message pusher_client = pusher.Pusher( app_id='187082', key='5729b7b62f550fc1c6ff', secret='a267a54361c086c8107d', cluster='eu', ssl=True ) pusher_client.trigger('message_channel', 'message_save_event', {'username': m.username, 'message': m.message, 'date_string': m.date_string }) return HttpResponse('message sent through pusher') # old no real time shit #messages = MessageModel.objects.order_by('-creation_date')[:5] #return render(request, 'message_board/messages_template.html', { # 'messages': messages }) return HttpResponse('message not created, not sent')
def post(self): parser = reqparse.RequestParser() parser.add_argument('message', type=str, required=True, help='Message cannot be blank!' ) parser.add_argument('duration', type=int, required=True, help='Duration cannot be blank!' ) parser.add_argument('message_category', type=str, required=True, help='Message category cannot be blank!' ) args = parser.parse_args() message = MessageModel(message=args['message'], duration=args['duration'], creation_date=datetime.now(utc), message_category=args['message_category'] ) message_manager.insert_message(message) return message, status.HTTP_201_CREATED
def get(self): message_id = request.values.get('id', None) if message_id is None: abort(400, message="Bad Request. Message 'id' was not provided.") message = MessageModel.get_by_id(int(message_id)) if message is None: abort(404, message="Message '%s' was not found." % message_id) return {'message': message.to_dict()}
def send_loop_messages( user, type_message='', context='', data_model={}): #atrae los documentos, itera y envia mensajes messages = MessageModel.find_by_order(type=type_message, context=context) for message in messages: send_messages(user, message, data_model)
def mutate(self, info, input): data = input_to_dictionary(input) data['created'] = datetime.utcnow() data['edited'] = datetime.utcnow() message = MessageModel(**data) db_session.add(message) db_session.commit() #middleware 처리할 return CreateMessage(message=message)
def mutate(self, info, input): data = input data['date'] = datetime.datetime.utcnow() message = MessageModel(**data) db_session.add(message) db_session.commit() return SendMessage(message=message)
def get(self, user_id): auth_user = self.auth.get_user_by_session() user_auth_key = ndb.Key('UserModel', auth_user['user_id']) user_key = ndb.Key('UserModel', int(user_id)) query = ndb.OR(ndb.AND(MessageModel.sender == user_auth_key, MessageModel.receiver == user_key), ndb.AND(MessageModel.sender == user_key, MessageModel.receiver == user_auth_key)) messages = MessageModel.query(query).order(-MessageModel.datetime).fetch() return Response(messages)
def __init__(self,application): self._app = application self._client_map = {} self._user_map = {} self._users = UserModel() self._devices = DeviceModel() self._tokens = TokenModel() self._messages = MessageModel() self._redis = RedisTools()
def org_message(request,org_id): org_id = int(org_id) form = MessageForm() org = OrgModel.objects.get(id=org_id) #第一次访问,此时无表单 if not request.method == "POST": return render_to_response('org_message_submit.html', { 'org':org, 'form':form, }, context_instance=RequestContext(request) ) #验证表单合法性 form = MessageForm(request.POST) if not form.is_valid(): return render_to_response('org_note_submit.html', { 'org':org, 'form':form, }, context_instance=RequestContext(request) ) #保存读书笔记 data = form.cleaned_data message = MessageModel( date=date.today(), time=time.strftime('%H:%M:%S', time.localtime(time.time()) ), user=request.user.get_profile(), org = org, title = data['title'], content = data['content'], hasPass = False, showNote = False, score=0, score_times=0, click_number=0) message.save() return HttpResponseRedirect("/org/"+org_id+"/")
def post(self): ip = request.remote_addr name = request.values.get('name', None) city = request.values.get('city', None) email = request.values.get('email', None) message = request.values.get('message', None) new_message = MessageModel( ip=ip, name=name, city=city, email=email, message=message ) try: new_message.put() except CapabilityDisabledError: logging.error(u'App Engine Datastore is currently in read-only mode.') abort(500) return {'id': new_message.key.id()}, 200, {'Access-Control-Allow-Origin': '*'}
def _create_message(self, guest_id, host_id, message): user = "******" if message.user_id() == host_id else "guest" new_msg = MessageModel( guest_id=guest_id, user=user, message=message.message(), channel="airbnb", sent=message.sent(), ) self.db.add_message(host_id, new_msg)
def test_create_message_by_guest(sync, mock_message_one): expected_message = MessageModel( guest_id="002", sent=mock_message_one.sent(), message=mock_message_one.message(), user="******", channel="airbnb", ) sync._create_message("002", "001", mock_message_one) sync.db.add_message.assert_called_once_with("001", expected_message)
def delete(self): message_id = request.values.get('id', None) if message_id is None: abort(400, message="Please provide a message id.") try: id = int(message_id) messages = MessageModel.get_by_id(id) except ValueError: if message_id == 'all': messages = MessageModel.query().fetch(500) else: abort(400, message="Id should be a number.") if messages is None: abort(404, message="Message '%s' was not found." % message_id) if type(messages) is list: for message in messages: message.key.delete() else: messages.key.delete() return {'message': "Message '%s' was deleted successfully." % message_id}
def test_update_message_empty_db(sync, mock_message_one): sync.db.messages_by_host_guest.return_value = [] sync._update_message("002", "001", mock_message_one) expected_message = MessageModel( guest_id="002", sent=mock_message_one.sent(), message=mock_message_one.message(), user="******", channel="airbnb", ) sync.db.add_message.assert_called_once_with("001", expected_message)
def test_update_message_existing_same_message(sync, mock_message_one): existing_msg = MessageModel( guest_id="002", sent=mock_message_one.sent(), message=mock_message_one.message(), user="******", channel="airbnb", ) sync.db.messages_by_host_guest.return_value = [existing_msg] sync._update_message("002", "001", mock_message_one) assert not (sync.db.add_message.called)
def test_update_message_existing_different_message(sync, mock_message_one, mock_message_two): existing_msg = MessageModel( guest_id="002", sent=mock_message_one.sent(), message=mock_message_one.message(), user="******", channel="airbnb", ) sync.db.messages_by_host_guest.return_value = [existing_msg] sync._update_message("002", "001", mock_message_two) expected_message = MessageModel( guest_id="002", sent=mock_message_two.sent(), message=mock_message_two.message(), user="******", channel="airbnb", ) sync.db.add_message.assert_called_once_with("001", expected_message)
def add_message(self, host_id: str, message: MessageModel): guest_id, sent = message.guest_id, message.sent data = self._query_table("msg", f"{host_id}#{guest_id}#{sent}", ["itemData"]) suffix = len(data) key = "#".join([host_id, guest_id, str(sent), str(suffix)]) self.table.put_item(Item={ "itemType": "msg", "itemID": key, "itemData": message.dict(), })
def get(self): max = 500 query = MessageModel.query().order(-MessageModel.date) messages = query.fetch(max) aaData = [] for message in messages: aaData.append({ "ip": message.ip, "date": message.date.isoformat(), "name": message.name, "city": message.city, "message": message.message, "email": message.email, "id": message.key.id() }) return {'aaData': aaData}
def messages(self): result = {} data = self._query_table("msg") data = [(MessageModel(**item["itemData"]), item["itemID"]) for item in data] for message, key in data: host_id, guest_id, *_ = key.split("#") if host_id not in result: result[host_id] = {} if guest_id not in result[host_id]: result[host_id][guest_id] = [] result[host_id][guest_id].append(message) return result
def post(self, user_id): auth_user = self.auth.get_user_by_session() user_auth_key = ndb.Key('UserModel', auth_user['user_id']) user_key = ndb.Key('UserModel', int(user_id)) data = json.decode(self.request.body) form = MessageForm(**data) if not form.validate(): return ResponseBadRequest(form.errors) message = MessageModel() message.sender = user_auth_key message.receiver = user_key message.text = form.text.data message.put() return Response(message)
def add(): "添加日程" if request.method == "GET": g.title = u"添加日程" g.submit = u"添加" return render_template("notes/edit.html") else: remindDate = request.form.get("remindDate", None) message = request.form.get("message", None) uid = session.get("uid", None) dao = MessageModel(uid, message, remindDate) dbSession = sessionMaker() dbSession.add(dao) try: dbSession.commit() r = True except: dbSession.rollback() r = False finally: dbSession.close() return redirect(url_for("notes.index"))
def send_loop_messages(user, type_message='', context='', data_model={}): messages = MessageModel.find_by_order(type=type_message, context=context) for message in messages: send_messages(user, message, data_model)
class MessageServer(object): def __init__(self,application): self._app = application self._client_map = {} self._user_map = {} self._users = UserModel() self._devices = DeviceModel() self._tokens = TokenModel() self._messages = MessageModel() self._redis = RedisTools() def add_client(self,conn): self._client_map[conn] = {} def remove_client(self,conn): user_id = self._client_map.pop(conn) if user_id: self._user_map.pop(user_id) def register(self,conn,message): #TODO:add user to database device = { "device_type":message.device_type, "device_token":message.device_token, "device_uuid":message.device_uuid, "system_version":message.system_version } user_id,token = self._devices.new_device(device) #TODO:check device type rep = login.Response() rep.err = login.Response.SUCCESS rep.user_id = str(user_id) rep.user_token = token conn.send(app.make_packet(rep)) def login(self,conn,message): user_id = message.user_id user_token = message.user_token chk_res = self._token.check_token(user_id,user_token) if chk_res: self._user_map[user_id] = conn self._client_map[conn]["user_id"] = user_id rep = login.Result() rep.err = login.Result.SUCCESS if chk_res else login.Result.TOKEN_NOT_AVAILABLE rep.token = "test_token" conn.send(app.make_packet(rep)) def on_chat(self,conn,message): to_id = message.to_user u_msg_id = message.message_id content = message.content message_id = self._messages.new_message({ "msg_id":u_msg_id, "from_user":self._client_map[conn]["user_id"], "to_user":to_id, "content":content }) self._redis.send_message(message_id) #TODO:give client send success message #need add chat.Response proto def send_message(self,message_id): message = self._message.get_message(message_id) to_user = message["to_user"] conn = self._user_map[to_user] if not conn: #FIXME:if other server hold this user,shouldn't push self._redis.push_message(message) return packet = chat.Receive() packet.message_id = message["msg_id"] packet.from_user = message["from_user"] packet.content = message["content"] conn.send(app.make_packet(packet))
def messages_by_host_guest(self, host_id: str, guest_id: str): data = self._query_table("msg", f"{host_id}#{guest_id}", ["itemData"]) data = [item["itemData"] for item in data] data = [MessageModel(**message) for message in data] return data