Exemple #1
0
def messages_add(request):
    log('本次请求的 method', request.method)
    data = request.form()
    if len(data) > 0:
        Message.new(data)
    body = template('message.html', messages=Message.all())
    return http_response(body)
    def get(self):
        msg = cgi.escape(self.request.get('message_content'))

        message = Message()
        message.id_message = "welcome_message"
        message.msg = msg
        message.put()
class TestMessageData(TestSuite):
    message1_dict = {
        'message_id': 3,
        'username': "******",
        'first': "Andrew",
        'last': "Jarombek",
        'group_name': 'alumni',
        'time': datetime.fromisoformat('2019-11-25'),
        'content': "Test Message 1",
        'deleted': None
    }

    message2_dict = {
        'message_id': 4,
        'username': "******",
        'first': "Andrew",
        'last': "Jarombek",
        'group_name': 'alumni',
        'time': datetime.fromisoformat('2019-11-25'),
        'content': "Test Message 2",
        'deleted': True
    }

    message1 = MessageData(Message(message1_dict))
    message1copy = MessageData(Message(message1_dict))

    message2 = MessageData(Message(message2_dict))

    def test_message_data_str(self) -> None:
        """
        Prove that the human readable string representation of a MessageData object is as expected.
        """
        log_str = 'MessageData: [message_id: 3, username: andy, first: Andrew, last: Jarombek, ' \
            "group_name: alumni, time: 2019-11-25 00:00:00, content: Test Message 1, deleted: None]"

        self.maxDiff = None
        self.assertEquals(str(self.message1), log_str)
        self.assertEquals(self.message1.__str__(), log_str)

    def test_message_data_repr(self) -> None:
        """
        Prove that the machine readable string representation of a MessageData object is as expected.
        """
        self.assertEquals(repr(self.message1), "<MessageData 3>")
        self.assertEquals(self.message1.__repr__(), "<MessageData 3>")

    def test_message_data_eq(self) -> None:
        """
        Prove that two MessageData objects with the same property values test positive for value equality.
        """
        self.assertTrue(self.message1 == self.message1copy)
        self.assertTrue(self.message1.__eq__(self.message1copy))

    def test_message_data_ne(self) -> None:
        """
        Prove that two MessageData objects with different property values test negative for value equality.
        """
        self.assertTrue(self.message1 != self.message2)
        self.assertTrue(self.message1.__ne__(self.message2))
Exemple #4
0
 def test_to_tuple_with_correct_data(self):
     message = Message("[21.10.17, 16:19:29] Christian: Hello Testing")
     self.assertEqual(
         message.to_tuple(),
         tuple([
             "Christian", "Hello Testing",
             datetime(2017, 10, 21, 16, 19, 29)
         ]))
Exemple #5
0
def messages_index(request):
    log('本次请求的 method', request.method)
    data = request.query
    if len(data) > 0:
        Message.new(data)
    # 处理msg便于输出
    body = template('message.html', messages=Message.all())
    return http_response(body)
def decodeTemporaryMessage(dict):
    message = Message(dict['message_id'],1, dict['intervention_session_id'])
    message.miniplan_id = dict['miniplan_temporary_id']
    message.time = dict['range_hour_start']
    message.channel = dict['channel']
    message.date = dict['range_day_start']
    message.attached_audio = dict['audio']
    message.attached_media = dict['media']
    message.message_text = dict['text']
    message.URL = dict['url']
    return message
	def update(self):
		# If there is any input from network, relay onto message bus
		try:
			data = self.sock.recv(256).decode('utf-8')
			data = data.split('~')
			if data[0] == "KEYDOWN":
				msg = Message(sender=self, target=None, msgType=MsgType.eMsgType_KeyPressed, data=data[1])
				self.msgBus.postMessage(msg)
			elif data[0] == "KEYUP":
				msg = Message(sender=self, target=None, msgType=MsgType.eMsgType_KeyReleased, data=data[1])
				self.msgBus.postMessage(msg)
		except:
			'''no data yet..'''
Exemple #8
0
 def update(self):
     for event in tdl.event.get():  # Iterate over recent events.
         if event.type == 'KEYDOWN':
             if event.keychar not in IGNORED_INPUTS:
                 msg = Message(sender=self,
                               target=None,
                               msgType=MsgType.eMsgType_KeyPressed,
                               data=event.keychar)
                 self.msgBus.postMessage(msg)
         if event.type == 'KEYUP':
             if event.keychar not in IGNORED_INPUTS:
                 msg = Message(sender=self,
                               target=None,
                               msgType=MsgType.eMsgType_KeyReleased,
                               data=event.keychar)
                 self.msgBus.postMessage(msg)
 def get(self):
     email = self.request.get('email')
     limit = self.request.get('limit')
     query = ""
     messages = []
     if len(email) > 0 :
         if len(limit) > 0 and int(limit) > 0: 
             query = "select * from Message where ANCESTOR IS :1 order by datetime desc limit %s" % limit
         else : 
             query = "select * from Message where ANCESTOR IS :1 order by datetime desc "
         messages = db.GqlQuery(query, Message.message_key(email))
     else : 
         if len(limit) > 0 and int(limit) > 0: 
             query = "select * from Message order by datetime desc limit %s" % limit
         else : 
             query = "select * from Message order by datetime desc limit 50" 
         messages = db.GqlQuery(query)
    
     retObject = []
     for message in messages:
         record = {} 
         record['email'] = message.email
         record['text'] = message.text
         record['DateTime'] = str(message.datetime)
         retObject.append(record)
     self.response.headers['Content-Type'] = 'application/json'
     self.response.out.write(json.dumps(retObject))
Exemple #10
0
 def move(self, entity, vector2D):
     msg = Message(sender=self,
                   target=None,
                   msgType=MsgType.eMsgType_MoveEntity,
                   data={
                       "entity": entity,
                       "vector2D": vector2D
                   })
     self.msgBus.postMessage(msg)
	def sayRequest(self, parsed_json, sourceAddress):
		try:
			if sourceAddress in self.manager.contactManager.users:
				user = self.manager.contactManager.users[sourceAddress]
				message = Message(parsed_json['content'], user, 'say')
				if 'target' in parsed_json:
					if parsed_json['target'] in self.manager.contactManager.users:
						message._to = self.manager.contactManager.users[parsed_json['target']].nickname()
					elif parsed_json['target'] == self.myIp:
						message._to = str(self.myIp)
					else:
						message._to = parsed_json['target']
				self.manager.myUI.messageReceived(message)
			else:
				print "Mensagem de um desconhecido: ", parsed_json['content']
		except KeyError as e:
			print "Error on Parser.sayRequest() could not parse ", e
		except Exception as e:
			print "Error on Parser.sayRequest(): ", e
Exemple #12
0
 def test_init_with_correct_data(self):
     message = Message(
         "[21.10.17, 16:19:29] Christian: Ähm i büd ma ei i hob gsogt i wü kan tequila mea, oba ds büd i ma wsl nua ei😂🙈"
     )
     self.assertEqual(
         message.body,
         "Ähm i büd ma ei i hob gsogt i wü kan tequila mea, oba ds büd i ma wsl nua ei😂🙈"
     )
     self.assertEqual(message.date_time, datetime(2017, 10, 21, 16, 19, 29))
     self.assertEqual(message.writer, "Christian")
Exemple #13
0
	def keyPressed(self, key):
		if key.upper() in MOVEMENT_KEYS:
			self.move(self.player, MOVEMENT_KEYS[key.upper()])
		elif key.upper() in ACTION_KEYS:
			self.action(self.player, ACTION_KEYS[key.upper()])
		elif key.upper() == "SHIFT":
			self.shiftModifier = True
		elif key.upper() == "Q":
			msg = Message(sender=self, target=None, msgType=MsgType.eMsgType_Quit)
			self.msgBus.postMessage(msg)
Exemple #14
0
	def init(self):
		Logic.init(self)

		# Init state of the game...
		self.player = Player(50, 50, "@", self.msgBus)#, aiType=AIType.AIType_Zombie)
		self.addEntity(self.player)

		# Force camera to follow player entity
		msg = Message(sender=self, target=None, msgType=MsgType.eMsgType_CameraFollowEntity, data=self.player)
		self.msgBus.postMessage(msg)

		self.generateMap(100, 100)
Exemple #15
0
    def sendPressed(self, inp=None):

        try:
            text = self.input.get()
            index = int(self.listbox.curselection()[0])
            if (self.checkWhisper.get()):
                message = Message(text, self.manager.myIp, 'whisper')
                users = self.manager.contactManager.users
                user = users[self.usersListBox[index]].nickname()
                self.manager.messageManager.client.sendTo(
                    self.usersListBox[self.listbox.curselection()[0]],
                    self.manager.messageManager.parser.codeWhisper(message))
                self.sendToUI("You -> " + user + ": " + message.content())

            else:
                message = Message(self.input.get(),
                                  self.manager.contactManager.mySelf, "say")
                if (int(self.listbox.curselection()[0]) != 0):
                    message._to = self.usersListBox[
                        self.listbox.curselection()[0]]
                self.printMessage(message)
                self.manager.messageManager.client.sendBroadcast(
                    self.manager.messageManager.parser.codeSay(message))
            self.input.delete(0, 'end')

        except Exception as e:
            print "Error on sendPressed: ", e
Exemple #16
0
	def removeEntityAt(self, x, y):
		toRemove = []
		for entity in self.entities:
			if entity.x == x and entity.y == y:
				msg = Message(sender=self, target=None, msgType=MsgType.eMsgType_RemoveEntity, data=entity)
				self.msgBus.postMessage(msg)

				# Mark for removal
				toRemove.append(entity)

		# Remove all entities from local cache
		for entity in toRemove:
			self.entities.remove(entity)
 def sendPressed(self, inp = None):
     
     try:
         text = self.input.get()
         index = int(self.listbox.curselection()[0])
         if(self.checkWhisper.get()):
             message = Message(text, self.manager.myIp, 'whisper')
             users = self.manager.contactManager.users
             user = users[self.usersListBox[index]].nickname()
             self.manager.messageManager.client.sendTo(self.usersListBox[self.listbox.curselection()[0]], self.manager.messageManager.parser.codeWhisper(message))
             self.sendToUI("You -> " + user + ": " + message.content())
             
         else:
             message = Message(self.input.get(), self.manager.contactManager.mySelf, "say")
             if(int(self.listbox.curselection()[0]) != 0):
                 message._to = self.usersListBox[self.listbox.curselection()[0]]
             self.printMessage(message)
             self.manager.messageManager.client.sendBroadcast(self.manager.messageManager.parser.codeSay(message))    
         self.input.delete(0, 'end')
                 
     except Exception as e:
         print "Error on sendPressed: ", e
 def _send_messages(self, me: Wizard, move: Move):
     if me.master:
         teammates = [
             w for w in self.W.wizards
             if w.faction == self.FRIENDLY_FACTION and not w.me
         ]
         self.log('found %d teammates' % len(teammates))
         if teammates:
             direction = [
                 Message(LaneType.MIDDLE, None, None),
                 Message(LaneType.TOP, None, None),
                 Message(LaneType.BOTTOM, None, None)
             ]
             index = 0
             msgs = []
             for i in range(0, len(teammates)):
                 msgs.append(direction[index])
                 index += 1
                 if index >= len(direction):
                     index = 0
             self.log('send %d msgs' % len(msgs))
             move.messages = msgs
Exemple #19
0
 def init(self, me, move, world):
     self.x = me.x
     self.y = me.y
     self.target_point_x, self.target_point_y = self.x, self.y
     self.faction = me.faction
     if self.faction == Faction.ACADEMY:
         self.enemy_faction = Faction.RENEGADES
     else:
         self.enemy_faction = Faction.ACADEMY
     if me.master:
         move.messages = [
             Message(LaneType.MIDDLE, None, None),
             Message(LaneType.BOTTOM, None, None),
             Message(LaneType.BOTTOM, None, None),
             Message(LaneType.BOTTOM, None, None)
         ]
         self.lane = LaneType.TOP
     '''Get enemy towers coordinates. Mirror own towers coordinate.
     for i in world.buildings:
         if i.faction == self.faction:
             [world.width - i.x, world.width - i.y])
     '''
     self.enemy_towers_coordinates = [[1687.8740025771563, 50.0],
                                      [2629.339679648397, 350.0],
                                      [2070.710678118655, 1600.0],
                                      [
                                          3097.386941332822,
                                          1231.9023805485235
                                      ], [3650.0, 2343.2513553373133],
                                      [3950.0, 1306.7422221916627]]
     for i in range(0, 17):
         if i <= 8:
             self.waypoints_TOP.append([200, 4000 - i * 400 - 250])
             self.waypoints_BOT.append([i * 400 + 250, 3750])
         else:
             self.waypoints_TOP.append([(i - 8) * 400 + 250, 250])
             self.waypoints_BOT.append([3750, 4000 - (i - 8) * 400 - 250])
     for i in range(0, 9):
         self.waypoints_MID.append([i * 400 + 250, 4000 - i * 400 - 250])
Exemple #20
0
 def __init__(self, initialX, initialY, char, msgBus, aiType=None):
     self.x = initialX
     self.y = initialY
     self.char = char
     self.aiType = aiType
     self.msgBus = msgBus
     self.moves = [[0, 1], [-1, 0], [1, 0], [0, -1]]
     self.sightRange = 5
     if aiType != None:
         msg = Message(sender=self,
                       target=None,
                       msgType=MsgType.eMsgType_SubscribeAI,
                       data=self)
         self.msgBus.postMessage(msg)
Exemple #21
0
 def get(self):
      msg = memcache.get('welcome_msg')
      if msg:
          print "exists bingo"
      else:
          print "not exist"
          welcome_msg = Message.getByIdMessage("welcome_message")
          if welcome_msg:
             msg = welcome_msg[0].msg
             memcache.add(key="welcome_msg", value=str(msg), time=3600)
      user = users.get_current_user()
      if user:
         self.response.write(globales.index.render(msg=msg, user=user))
      else:
          #self.redirect(users.create_login_url(self.request.uri))
          self.response.write(globales.index.render(msg=msg, user=None))
 def post(self):
     self.response.out.write(self.request)
     text = self.request.get('text')
     email = self.request.get('email')
     
     message = Message(parent=Message.message_key(email))
     self.response.out.write("message : %s" %message)
     message.text = text
     message.email = email
     message.put()
     self.redirect('/MessageSubmit?' + urllib.urlencode({'email' : email}))
Exemple #23
0
    def get_message(self, msg_id):
        # possible formats: ['full', 'metadata', 'minimal', 'raw']
        subject = None
        msg = self.service.users().messages().get(userId='me', id=msg_id).execute()

        # parse date
        date = float(msg['internalDate']) / 1000
        date = datetime.utcfromtimestamp(date)

        # parse subject
        headers = msg['payload']['headers']
        for header in headers:
            if header['name'] == 'Subject':
                subject = header['value']

        # parse attachments
        attachments_raw = []
        for part in msg['payload']['parts']:
            if part['filename']:
                attachments_raw.append((part['filename'], part['body']['attachmentId']))

        attachments = []
        for attachment in attachments_raw:
            att = self.service.users().messages().attachments().get(
                userId='me', id=attachment[1], messageId=msg_id).execute()
            data = att['data']

            file_data = base64.urlsafe_b64decode(data.encode('UTF-8'))

            attachments.append(Attachment(attachment[0], file_data))

        # parse body
        parts = msg['payload']['parts']

        data = self._get_data(parts)
        clean = base64.urlsafe_b64decode(data)
        soup = BeautifulSoup(clean, "lxml")
        body = soup.find_all('p')[0].text

        return Message(date, subject, body, attachments)
    def read_message(self):
        if not self.read_boolean():
            return None

        return Message(self.read_enum(LaneType), self.read_enum(SkillType),
                       self.read_byte_array(False))
Exemple #25
0
def parse_messages(fp):
    messages = extract_messages_lines(fp)
    messages = [Message(message) for message in messages]
    return messages
Exemple #26
0
def scheduleLogarithmic(request, resource, template, aged):
    '''
    Returns the miniplan scheduled with more frequency at the end of the interval
    It divides the interval for every msg with logaritmic growth:1 1/2 1/3 1/4
    Check on period(valid weeks): if request interval is larger that period then user period as interval
    Last message always sent the day before the event
    :param request: a request class
    :param template: a template class
    :param aged: a user class
    :return: a miniplan that is a list of messages class with all the fields completed
    '''
    print "Schedule Day"
    errors = {}

    if type(request.from_date) is not datetime:
        times = convertDatetime(request, template, resource)
        startime = times[0]
        endtime = times[1]
        period = times[2]
        expirationtime = times[3]
    else:
        startime = request.from_date
        endtime = request.to_date
        period = timedelta(days=template.period * 7)
        expirationtime = resource.to_date
        if expirationtime == None:
            expirationtime = endtime

    if template.nmsgmin != template.nmsgmax:
        nmsg = rnd.randrange(template.nmsgmin, template.nmsgmax + 1)
    else:
        nmsg = template.nmsgmax

    miniplan = [Message(count, aged.aged_id, intervention_session_id=1) for count in xrange(nmsg)]

    valid_interval = endtime - startime
    if valid_interval > period:
        valid_interval = period

    channels = getChannelsAvailable(template, aged)

    with open('csv/prova_import_messages.csv') as csvmessages:
        messages = csv.DictReader(csvmessages)
        msgs_tosend = getListMessages(messages, nmsg, resource, channels)

    er = checkForErrors(errors, endtime, expirationtime, startime, miniplan, nmsg, len(msgs_tosend))
    errors = er[0]
    miniplan = er[1]
    if er[2]:
        endtime = er[3]
    else:
        return errors, miniplan

    # length of the loop depending on the msgs found
    if len(msgs_tosend) < nmsg:
        lenloop = len(msgs_tosend)
    else:
        lenloop = nmsg

    valid_interval = timedelta(seconds=valid_interval.total_seconds())
    for i in range(0, lenloop):
        date = endtime - valid_interval

        miniplan[i].date = date.date()

        miniplan[i].time = scheduleHourFromDate(aged, date).time()

        miniplan[i].message_text = generate_message_text(aged, msgs_tosend[i]['Text'], msgs_tosend[i]['URL'])

        miniplan[i].attached_audio = msgs_tosend[i]['Audio']
        miniplan[i].attached_media = msgs_tosend[i]['Media']
        miniplan[i].URL = msgs_tosend[i]['URL']
        miniplan[i].channel = msgs_tosend[i]['Channel']

        valid_interval = timedelta(seconds=valid_interval.total_seconds() / (i + 2))

    miniplan = checkMsgsOneDay(miniplan, endtime)

    return errors, miniplan
def decodeMessage(dict):
    message = Message(dict['message_id'], dict['user_id'], dict['intervention_session_id'])
    message.miniplan_id = dict['miniplan_id']
    message.pilot_id = dict['pilot_id']
    message.time_2 = dict['time_2']
    message.time_1 = dict['time_1']
    message.time = dict['time']
    message.channel = dict['channel']
    message.date = dict['date']
    message.expiration_date = dict['expiration_date']
    message.attached_audio = dict['attached_audio']
    message.attached_media = dict['attached_media']
    message.message_text = dict['message_text']
    message.URL = dict['URL']
    return message
def mapMessage(message_dict):
    message = Message(message_dict['message_id'], message_dict['user_id'], message_dict['intervention_session_id'])
    message.URL = message_dict['URL']
    message.attached_media = message_dict['attached_media']
    message.attached_audio = message_dict['attached_audio']
    message.channel = message_dict['channel']
    message.message_text = message_dict['message_text']
    message.miniplan_id = message_dict['miniplan_id']
    message.pilot_id = message_dict['pilot_id']
    if message_dict['date'] != '':
        message.date = datetime.strptime(message_dict['date'], '%Y-%m-%d')
    if message_dict['time'] != '':
        message.time = datetime.strptime(message_dict['time'], '%H:%M:%S')
    return message
Exemple #29
0
def schedule(request, resource, template, aged):
    print "_______________SCHEDULE_______________"
    errors = {}

    if type(request.from_date) is not Pendulum:
        times = convertPendulum(request, template, resource)
        startime = times[0]
        endtime = times[1]
        period = times[2]
        expirationtime = times[3]
    else:
        startime = request.from_date
        endtime = request.to_date
        period = pendulum.Period(startime, startime.add(weeks=template.period))
        expirationtime = resource.to_date
        if expirationtime == None:
            expirationtime = endtime

    if template.nmsgmin != template.nmsgmax and template.nmsgmax > template.nmsgmin:
        nmsg = rnd.randrange(template.nmsgmin, template.nmsgmax + 1)
    else:
        nmsg = template.nmsgmax

    # creates miniplan that is a list of messages
    miniplan = [Message(count, aged.aged_id, intervention_session_id=1) for count in xrange(nmsg)]

    channels = getChannelsAvailable(template, aged)

    '''
    with open('csv/prova_import_messages.csv') as csvmessages:
        messages = csv.DictReader(csvmessages)
        msgs_tosend = getListMessages(messages, nmsg, resource, channels)
    '''

    messages = getResourceMessages(resource.resource_id)

    msgs_tosend = selectMessages(messages, nmsg, channels)

    er = checkForErrors(errors, endtime, None, startime, miniplan, nmsg, len(msgs_tosend))
    errors = er[0]
    miniplan = er[1]
    if er[2]:
        endtime = er[3]
    else:
        return errors, miniplan

    # length of the loop depending on the msgs found
    if len(msgs_tosend) < nmsg:
        lenloop = len(msgs_tosend)
    else:
        lenloop = nmsg

    for i in range(0, lenloop):
        miniplan[i].message_text = generate_message_text(aged, msgs_tosend[i]['Text'], msgs_tosend[i]['URL'])
        miniplan[i].attached_audio = msgs_tosend[i]['Audio']
        miniplan[i].attached_media = msgs_tosend[i]['Media']
        miniplan[i].URL = msgs_tosend[i]['URL']
        miniplan[i].channel = msgs_tosend[i]['Channel']

    miniplan = ED(miniplan, lenloop, startime, endtime, period, aged)

    miniplan = checkMsgsOneDay(miniplan, endtime)

    return errors, miniplan
Exemple #30
0
 def test_init_with_empty_body(self):
     message = Message("[21.10.17, 16:19:29] Christian:")
     self.assertEqual(message.body, "")
     self.assertEqual(message.date_time, datetime(2017, 10, 21, 16, 19, 29))
     self.assertEqual(message.writer, "Christian")
Exemple #31
0
def schedulePeriodic(request, resource, template, aged):
    print "Schedule Day"
    errors = {}

    if type(request.from_date) is not datetime:
        times = convertDatetime(request, template, resource)
        startime = times[0]
        endtime = times[1]
        period = times[2]
        expirationtime = times[3]
    else:
        startime = request.from_date
        endtime = request.to_date
        period = timedelta(days=template.period * 7)
        expirationtime = resource.to_date
        if expirationtime == None:
            expirationtime = endtime

    valid_interval = endtime - startime
    if valid_interval > period:
        endtime = startime + period

    if template.nmsgmin != template.nmsgmax:
        nmsg = rnd.randrange(template.nmsgmin, template.nmsgmax + 1)
    else:
        nmsg = template.nmsgmax

    miniplan = [Message(count, aged.aged_id, intervention_session_id=1) for count in xrange(nmsg)]

    channels = getChannelsAvailable(template, aged)

    with open('csv/prova_import_messages.csv') as csvmessages:
        messages = csv.DictReader(csvmessages)
        msgs_tosend = getListMessages(messages, nmsg, resource, channels)

    er = checkForErrors(errors, endtime, expirationtime, startime, miniplan, nmsg, len(msgs_tosend))
    errors = er[0]
    miniplan = er[1]
    if er[2]:
        endtime = er[3]
    else:
        return errors, miniplan

    day_of_event = mapDay(resource.on_day)
    if day_of_event == None:
        errors['ErrorNoDay'] = 'Error no day specified for periodic messages'
        miniplan = []
        return errors, miniplan

    # length of the loop depending on the msgs found
    if len(msgs_tosend) < nmsg:
        lenloop = len(msgs_tosend)
    else:
        lenloop = nmsg

    c = 0
    i = 0
    current_date = startime.date()
    while current_date < endtime.date():
        if current_date.weekday() == day_of_event - 1:
            if c % int(resource.every) == 0:
                if i > lenloop:
                    break
                miniplan[i].date = current_date
                miniplan[i].time = scheduleHour(aged, None)
                miniplan[i].attached_audio = msgs_tosend[i]['Audio']
                miniplan[i].attached_media = msgs_tosend[i]['Media']
                miniplan[i].URL = msgs_tosend[i]['URL']
                miniplan[i].channel = msgs_tosend[i]['Channel']
                miniplan[i].message_text = generate_message_text(aged, msgs_tosend[i]['Text'],
                                                                 msgs_tosend[i]['URL'])
                i += 1
            c += 1

        current_date += timedelta(days=1)

    miniplan = checkMsgsOneDay(miniplan, endtime)

    return errors, miniplan
 def get(self):
     email = self.request.get('email')
     messages = db.GqlQuery(
                            "select * from Message where ANCESTOR IS :1 order by datetime desc limit 1 ", Message.message_key(email))
     
     for message in messages: 
         self.response.out.write('Existing value for : <b>email: %s, text: %s, timestamp: %s</b>' % (message.email, message.text, message.datetime))
     
     self.response.out.write("""<html>
     <body>
         <form action="/Message_Post" method="post">
         <div>
             <textarea name="text" rows="1" cols="20"></textarea>
             <textarea name="email" rows="1" cols="20"></textarea>   
         </div>
         <div>
             <input type="submit" value="set text / email">
         </div>
         </form>
         
         To get data in json: go to <a href="/Message.json">Message.json</a> and pass email as a parameter. eg /message.json?email=rohan.shah 
         </body></html>""")
Exemple #33
0
def schedulePPendulum(request, resource, template, aged):
    errors = {}

    u = generateXMLDoc(aged)
    r = generateXMLDoc(resource)
    c = None  # per ora non usato
    template.message_structure
    templateInfo = {}
    templateInfo['tags'] = template.message_structure
    #todo il tone e' da aggiungere come parametro alla classe template--> template.tone
    #templateInfo['tone'] = template.tone
    templateInfo['tone'] = "Neutral"


    if type(request.from_date) is not Pendulum:
        times = convertPendulum(request, template, resource)
        startime = times[0]
        endtime = times[1]
        period = times[2]
        expirationtime = times[3]
    else:
        startime = request.from_date
        endtime = request.to_date
        period = pendulum.Period(startime, startime.add(weeks=template.period))
        expirationtime = resource.to_date
        if expirationtime == None:
            expirationtime = endtime

    valid_interval = endtime - startime
    if valid_interval > period:
        valid_interval = period

    if template.nmsgmin != template.nmsgmax:
        nmsg = rnd.randrange(template.nmsgmin, template.nmsgmax + 1)
    else:
        nmsg = template.nmsgmax

    miniplan = [Message(count, aged.aged_id, intervention_session_id=1) for count in xrange(nmsg)]

    miniplanID = uuid.uuid4()

    channels = getChannelsAvailable(template, aged)

    with open('csv/prova_import_messages.csv') as csvmessages:
        messages = csv.DictReader(csvmessages)
        msgs_tosend = getListMessages(messages, nmsg, resource, channels)

    er = checkForErrors(errors, endtime, expirationtime, startime, miniplan, nmsg, len(msgs_tosend))
    errors = er[0]
    miniplan = er[1]
    if er[2]:
        endtime = er[3]
    else:
        return errors, miniplan

    day_of_event = mapDay(resource.on_day)
    if day_of_event == None:
        errors['ErrorNoDay'] = 'Error no day specified for periodic messages'
        miniplan = []
        return errors, miniplan

    # length of the loop depending on the msgs found
    if len(msgs_tosend) < nmsg:
        lenloop = len(msgs_tosend)
    else:
        lenloop = nmsg

    c = 0
    i = 0
    for dt in valid_interval.range("days"):
        if dt.day_of_week == day_of_event:
            if c % int(resource.every) == 0:
                if i > lenloop:
                    break
                miniplan[i].miniplan_id = miniplanID
                miniplan[i].date = dt.date()
                miniplan[i].time_1 = dt.date()
                miniplan[i].time_2 = dt.subtract(days=1).date()
                miniplan[i].time = scheduleHour(aged, None)
                miniplan[i].attached_audio = msgs_tosend[i]['Audio']
                miniplan[i].attached_media = msgs_tosend[i]['Media']
                miniplan[i].URL = msgs_tosend[i]['URL']

                miniplan[i].channel = msgs_tosend[i]['Channel']
                #miniplan[i].message_text = generate_message_text(aged, msgs_tosend[i]['Text'],msgs_tosend[i]['URL'])
                message_body = msgs_tosend[i]['Text']
                m = createMessageJson(message_body, templateInfo)
                miniplan[i].message_text = composeMessage(u, r, c, m)

                miniplan[i].intervention_session_id = request.intervention_session_id
                miniplan[i].pilot_id = request.pilot_id

                i += 1
            c += 1

    miniplan = checkMsgsOneDay(miniplan, endtime)

    return errors, miniplan
Exemple #34
0
 def test_replacing_commas_without_commas(self):
     message = Message("[21.10.17, 16:19:29] Christian: Hello Testing")
     message.replace_commas()
     self.assertEqual(message.body, "Hello Testing")
Exemple #35
0
 def test_to_tuple_with_empty_body(self):
     message = Message("[21.10.17, 16:19:29] Christian:")
     self.assertEqual(
         message.to_tuple(),
         tuple(["Christian", "",
                datetime(2017, 10, 21, 16, 19, 29)]))
Exemple #36
0
def scheduleEquallyDividedPeriod(request, resource, template, aged):
    '''
    Returns the miniplan with the temporal interval between the msgs divided equally
    :param request: a request class
    :param template: a template class
    :param aged: a user class
    :return: a miniplan that is a list of messages class with all the fields completed
    '''
    print "Schedule Day"
    errors = {}

    if type(request.from_date) is not datetime:
        times = convertDatetime(request, template, resource)
        startime = times[0]
        endtime = times[1]
        period = times[2]
    else:
        startime = request.from_date
        endtime = request.to_date
        period = timedelta(days=template.period * 7)

    valid_interval = endtime - startime
    if valid_interval > period:
        valid_interval = period

    if template.nmsgmin != template.nmsgmax:
        nmsg = rnd.randrange(template.nmsgmin, template.nmsgmax + 1)
    else:
        nmsg = template.nmsgmax
    step_send_msg = valid_interval / nmsg

    # creates miniplan that is a list of messages
    miniplan = [Message(count, aged.aged_id, intervention_session_id=1) for count in xrange(nmsg)]

    channels = getChannelsAvailable(template, aged)

    with open('csv/prova_import_messages.csv') as csvmessages:
        messages = csv.DictReader(csvmessages)
        msgs_tosend = getListMessages(messages, nmsg, resource, channels)

    er = checkForErrors(errors, endtime, None, startime, miniplan, nmsg, len(msgs_tosend))
    errors = er[0]
    miniplan = er[1]
    if er[2]:
        endtime = er[3]
    else:
        return errors, miniplan

    # length of the loop depending on the msgs found
    if len(msgs_tosend) < nmsg:
        lenloop = len(msgs_tosend)
    else:
        lenloop = nmsg

    # for nmsg fill the miniplan msgs
    date = startime
    for i in range(0, lenloop):
        miniplan[i].date = date.date()
        miniplan[i].time = scheduleHour(aged, None)
        miniplan[i].message_text = generate_message_text(aged, msgs_tosend[i]['Text'], msgs_tosend[i]['URL'])
        miniplan[i].attached_audio = msgs_tosend[i]['Audio']
        miniplan[i].attached_media = msgs_tosend[i]['Media']
        miniplan[i].URL = msgs_tosend[i]['URL']
        miniplan[i].channel = msgs_tosend[i]['Channel']

        date += step_send_msg

    miniplan = checkMsgsOneDay(miniplan, endtime)

    return errors, miniplan
Exemple #37
0
 def test_init_with_empty_message_line(self):
     message = Message("")
     self.assertEqual(message.body, "")
     self.assertEqual(message.date_time, None)
     self.assertEqual(message.writer, "")