Exemplo n.º 1
0
 def test_comment_field_created(self):
     user = User(username='******',
                 password='******',
                 number='+16666666666')
     user.save()
     
     event = Event(**{
         u'where': 'test',
         u'when': timestamp(),
         u'what': 'test',
         u'broadcast': False,
         u'posted_from': [37.422834216666665, -122.08536667833332],
         u'creator': user[u'username'],
     })
     event.save()
     
     comment = 'the test comment'
     
     post = self.post('/events/%s/comments/' % event[u'id'], 
                          {'comment': comment})
     
     self.assertEqual(post.status, 200, 'comment POST 200')
     
     comment = Comment(user=self.get_user()[u'id'], event=event[u'id'])
     
     self.assertTrue(u'created' in comment, 'comment has created')
     
     get = self.get('/events/%s/comments/' % event[u'id'])
     self.assertEqual(get.status, 200, 'got comment')
     
     got_comment = json.loads(get.read())['comments'][0]
     self.assertTrue(u'created' in got_comment, 'comment has created')
Exemplo n.º 2
0
 def test_attendants_with_event(self):
     event = Event(broadcast=True, 
               what='This is a test',
               creator=self.get_user()[u'username'])
     event.save()
     
     att_user = self.make_user('att_user')
     Attendant(**{
         u'status': status.ATTENDING,
         u'timestamp': timestamp(),
         u'event': event[u'id'],
         u'user': att_user[u'id'],
     }).save()
     
     response = self.get('/events/%s/?attendants=true' % event[u'revision'])
     self.assertEqual(response.status, 200, 'event get success')
     
     body = json.loads(response.read())
     
     self.assertTrue(u'attendants' in body, 'response has attendants')
     self.assertEqual(len(body['attendants']), 1, 'event has 1 attendant')
     
     self.assertTrue(u'username' in body['attendants'][0], 'att has username')
     self.assertTrue(u'user' in body['attendants'][0], 'att has user id')
     self.assertTrue(u'event' in body['attendants'][0], 'att has event')
     self.assertTrue(u'status' in body['attendants'][0], 'att has status')
     self.assertTrue(u'timestamp' in body['attendants'][0], 'att has timestamp')
     
     for k, v in body['attendants'][0].iteritems():
         self.assertTrue(v is not None, '%s is not None' % k)
Exemplo n.º 3
0
 def prep_for_response_sms(self):
     user = User(username='******',
                 password='******',
                 number='+16666666666')
     user.save()
     
     event = Event(**{
         u'where': 'test',
         u'when': timestamp(),
         u'what': 'test',
         u'broadcast': False,
         u'posted_from': [37.422834216666665, -122.08536667833332],
         u'creator': user[u'username'],
     })
     event.save()
     
     smsuser = User(number='+16475555555', display_name='Testy Smoth')
     smsuser.save()
     
     Attendant(user=user[u'id'], event=event[u'id']).save()
     
     SMSRegister(contact_number=smsuser[u'number'], 
                 twilio_number=settings.TWILIO_NUMBERS[0], 
                 event=event[u'id'], 
                 expires=event[u'when'],
                 user=user[u'id']).save()
     
     return user, event, smsuser
Exemplo n.º 4
0
 def test_sms_notification_comment(self):
     if not settings.TEST_SMS: return
     
     event = Event(**{
         u'where': 'test',
         u'when': timestamp(),
         u'what': 'test',
         u'broadcast': False,
         u'posted_from': [37.422834216666665, -122.08536667833332],
         u'creator': self.get_user()[u'username'],
     })
     event.save()
     
     number = '+16475551234'
     name = 'Testy Smoth'
     
     reg, out, is_user = SMS.register(event, [{u'number':number, 
                                               u'name':name}])
     self.assertEqual(len(reg), 1, 'correct ammout registered')
     
     result = notifications.send(reg[0][u'id'], 
                                 {u'type': 'comment', 
                                  u'event_revision': event[u'revision'],
                                  u'event_id': event[u'id'],
                                  u'comment': 'my awesome comment',
                                  u'commenter': self.make_user()})
     
     self.assertEqual(len(result), 1, 'the correct number of notifications '
                                      'were sent')
     self.assertTrue(result[0], 'the notification was sent correctly')
Exemplo n.º 5
0
 def test_event_new_notification(self):
     
     to_invite = self.make_user(username='******')
     
     self.register_for_notifications(user=to_invite)
     
     event = Event(**{
         u'where': 'test',
         u'when': timestamp(),
         u'what': 'test',
         u'broadcast': False,
         u'posted_from': [37.422834216666665, -122.08536667833332],
         u'creator': self.get_user()[u'username'],
     })
     event.save()
     
     response = self.post('/events/%s/invites/' % event[u'id'], 
                          {'users': [to_invite[u'username']]})
     self.assertEqual(response.status, 200, 'user invited')
     
     nots = self.get_new_notifications(user=to_invite)
     
     self.assertEqual(len(nots), 1, 'one new notification')
     
     notification = nots[0]
     
     self.assertTrue(u'event_revision' in notification, 
                     'poll response has event rev')
     
     self.assertEqual(notification[u'event_revision'], event[u'revision'], 
                      'event has the corrrect revision')
Exemplo n.º 6
0
 def test_event_comment_notification(self):
     
     to_notify = self.make_user(username='******')
     
     self.register_for_notifications(user=to_notify)
     self.register_for_notifications()
     
     event = Event(**{
         u'where': 'test',
         u'when': timestamp(),
         u'what': 'test',
         u'broadcast': False,
         u'posted_from': [37.422834216666665, -122.08536667833332],
         u'creator': self.get_user()[u'username'],
     })
     event.save()
     
     Attendant(**{
         u'status': status.ATTENDING,
         u'timestamp': timestamp(),
         u'event': event[u'id'],
         u'user': to_notify[u'id'],
     }).save()
     
     comment = 'the test comment'
     
     response = self.post('/events/%s/comments/' % event[u'id'], 
                          {'comment': comment})
     self.assertEqual(response.status, 200, 'comments POST 200')
     
     nots = self.get_new_notifications(user=to_notify)
     
     self.assertEqual(len(nots), 1, 'one new notification')
     
     notification = nots[0]
     
     self.assertTrue(u'type' in notification, 
                     'poll response has type')
     self.assertEqual(notification[u'type'], 'comment', 
                      'event has the correct type')
     
     self.assertTrue(u'event_revision' in notification, 
                     'poll response has event rev')
     self.assertEqual(notification[u'event_revision'], event[u'revision'], 
                      'event has the correct revision')
     
     self.assertTrue(u'comment' in notification, 
                     'poll response has comment')
     self.assertEqual(notification[u'comment'], comment, 
                      'event has the correct comment')
     
     self.assertTrue(u'commenter' in notification, 
                     'poll response has commenter')
     self.assertEqual(notification[u'commenter'], self.get_user()[u'username'], 
                      'event has the correct commenter')
     
     nots = self.get_new_notifications()
     self.assertEqual(len(nots), 0, 'no notification for the poster')
Exemplo n.º 7
0
 def post(self):
     '''
     Creates a new event
     '''
     req_body = self.body_dict()
     event = Event(creator=self.get_session()[u'username'])
     
     #grab data from the user-supplied dict
     what = req_body.get(u'what')
     if what is None:
         self.output({'error': 'MISSING_FIELDS',
                      'field': 'what'}, 400)
         return
     elif len(what) > 140:
         self.output({'error': 'FIELD_LENGTH',
                      'field': 'what'}, 400)
         return
     event[u'what'] = what
     
     where = req_body.get(u'where')
     if where is not None and len(where) > 25:
         self.output({'error': 'FIELD_LENGTH',
                      'field': 'where'}, 400)
         return
     event[u'where'] = where
     
     #optional:
     event[u'broadcast'] = req_body.get(u'broadcast', True)
     event[u'when'] = req_body.get(u'when')
     event[u'posted_from'] = req_body.get(u'posted_from')
     event[u'location'] = req_body.get(u'location')
     event[u'category'] = req_body.get(u'category')
     event[u'client'] = req_body.get(u'client')
 
     event.save()
     resp = dict()
     resp_status = 201
     
     if event[u'broadcast']:
         usernames = self.get_user().followers()
     else:
         usernames = req_body.get(u'users', list())
     
     tz = req_body.get(u'timezone', 'America/Toronto')
     
     out_of_numbers = event.invite(usernames=usernames, 
                                   contacts=req_body.get(u'contacts'),
                                   tz=tz)
     if out_of_numbers is not None:
         resp = {'error': 'OUT_OF_NUMBERS',
                 'contacts': out_of_numbers,
                 'event_revision': event[u'revision']}
         resp_status = 409
     
     resp[u'revision'] = event[u'revision']
     resp[u'id'] = event[u'id']
     self.output(resp, resp_status)
Exemplo n.º 8
0
 def test_comment_validation(self):
     
     event = Event(**{
         u'what': 'test',
         u'broadcast': True,
         u'creator': self.get_user()[u'username'],
     })
     event.save()
     
     response = self.post('/events/%s/comments/' % event[u'id'], 
                          {'comment': ''})
     self.assertEqual(response.status, 400, 'comment POST 200')
Exemplo n.º 9
0
 def test_event_notification_attending_creator(self):
     
     to_attend = self.make_user(username='******')
     
     self.register_for_notifications(user=self.get_user())
     
     event = Event(**{
         u'where': 'test',
         u'when': timestamp(),
         u'what': 'test',
         u'broadcast': False,
         u'posted_from': [37.422834216666665, -122.08536667833332],
         u'creator': self.get_user()[u'username'],
     })
     event.save()
     
     # this attendant will trigger the notification
     Attendant(**{
         u'status': status.INVITED,
         u'timestamp': timestamp(),
         u'event': event[u'id'],
         u'user': to_attend[u'id'],
     }).save()
     
     response = self.post('/events/%s/attendants/' % event[u'id'], 
                          {u'status': status.ATTENDING}, 
                          auth_user=to_attend)
     self.assertEqual(response.status, 200, 'attendants POST 200')
     
     nots = self.get_new_notifications(user=self.get_user())
     
     self.assertEqual(len(nots), 1, 'one new notification')
     
     notification = nots[0]
     
     self.assertTrue(u'type' in notification, 
                     'poll response has type')
     self.assertEqual(notification[u'type'], 'attendant', 
                      'event has the correct type')
     
     self.assertTrue(u'event_revision' in notification, 
                     'poll response has event rev')
     self.assertEqual(notification[u'event_revision'], event[u'revision'], 
                      'event has the corrrect revision')
     
     self.assertTrue(u'attendant' in notification, 
                     'poll response has attendant')
     self.assertEqual(notification[u'attendant'], to_attend[u'username'], 
                      'event has the corrrect attendant')
Exemplo n.º 10
0
 def create_event(self):
     """
     Returns an instance of Event class
     :return:
     """
     center_location = self.test_data["events"]["centerLocation"]
     coords = [center_location["lat"], center_location["long"]]
     event_data = json.loads(
         self.test_data["events"]["eventData"]["eventData"])
     e = Event(
         category=event_data["category"],
         datetime=time.time() * 1000,
         description=event_data["description"],
         local_assistance=event_data["local_assistance"],
         location={
             u'coords':
             GeoPoint(event_data["location"]["coords"]["latitude"],
                      event_data["location"]["coords"]["longitude"]),
             u"geohash":
             encode(coords),
         },
         public={
             'share': event_data["public"]["share"],
             'view': event_data["public"]["view"]
         },
         reported_by={'original': {
             'anonymous': event_data["anonymous"]
         }},
         title=event_data["title"],
         images=[{
             'isNsfw': False,
             'isTrusted': True,
             'uuid': 'images__image__uuid'
         }])
     return e
Exemplo n.º 11
0
 def test_get_none(self):
     """
     Tests boundary condition when a Event does not exists in the DB
     :return:
     """
     _e = Event.get('dne', db)
     self.assertEqual(_e, None)
Exemplo n.º 12
0
    def post(self, event_id):
        #grab the event from the db
        event = Event.get(event_id)
        
        #make sure the event exists
        if event is None:
            raise HTTPError(404)

        #make sure the client is the event's owner
        if not event[u'creator'] == self.get_session()[u'username']:
            raise HTTPError(403)
            
        #make sure the request has the correct info in the body
        body = self.body_dict()
        if not body or (not u'users' in body and not u'contacts' in body):
            raise HTTPError(400)
        
        if u'users' in body or u'contacts' in body:
            users = body.get(u'users')
            #friends is a special case
            if users == u'friends':
                users = self.get_user().friends()
            
            out_of_numbers = event.invite(usernames=users, 
                                          contacts=body.get(u'contacts'))
            if out_of_numbers is not None:
                self.write(json.dumps({'error': 'OUT_OF_NUMBERS',
                                       'contacts': out_of_numbers,
                                       'event_revision': event[u'revision']}))
                self.set_status(409)
Exemplo n.º 13
0
 def get(self, event_id):
     event = Event.get({u'id': event_id})
     if not event: raise HTTPError(404)
     
     if not event.user_can_access(self.get_user()):
         raise HTTPError(401)
     self.output({u'attendants': Attendant.find({u'event': 
                                     event_id}).serializable(name=True)})
Exemplo n.º 14
0
 def test_event_revisioning(self):
     e = Event(broadcast=True, 
               what='This is a test',
               creator=self.get_user()[u'username'])
     self.assertEqual(e[u'revision'], None, 'unsaved event has no revision')
     
     e.save()
     
     self.assertTrue(e[u'revision'] is not None, 'saving creates revision')
     
     old_rev = e[u'revision']
     e[u'what'] = 'This is an edit'
     e.save()
     
     self.assertTrue(e[u'revision'] != old_rev, 'edits create new revisions')
     
     
Exemplo n.º 15
0
 def test_sms_comment(self):
     display_name = 'Test User display'
     user = User(number='+16666666666', 
                 display_name=display_name)
     user.save()
     
     event = Event(**{
         u'where': 'test',
         u'when': timestamp(),
         u'what': 'test',
         u'broadcast': False,
         u'posted_from': [37.422834216666665, -122.08536667833332],
         u'creator': user[u'username'],
     })
     event.save()
     
     comment = 'the test comment'
     
     Comment(**{
         u'comment': comment,
         u'event': event[u'id'],
         u'user': user[u'id']
     }).save()
     
     get = self.get('/events/%s/comments/' % event[u'id'])
     
     self.assertEqual(get.status, 200, 'comment GET 200')
     
     try:
         get = json.loads(get.read())
     except ValueError:
         self.assertTrue(False, 'comment GET not JSON')
     
     self.assertTrue('comments' in get, 
                     'comments returned')
     self.assertEqual(len(get['comments']), 1, 
                      'correct number of comments')
     
     self.assertFalse('username' in get['comments'][0], 
                     'username field unavailable')
     self.assertTrue('display_name' in get['comments'][0], 
                     'display_name field available')
     self.assertEqual(get['comments'][0]['display_name'], display_name, 
                      'display_name field set correctly')
Exemplo n.º 16
0
 def test_new_comment(self):
     user = User(username='******',
                 password='******',
                 number='+16666666666')
     user.save()
     
     event = Event(**{
         u'where': 'test',
         u'when': timestamp(),
         u'what': 'test',
         u'broadcast': False,
         u'posted_from': [37.422834216666665, -122.08536667833332],
         u'creator': user[u'username'],
     })
     event.save()
     
     comment = 'the test comment'
     
     post = self.post('/events/%s/comments/' % event[u'id'], 
                          {'comment': comment})
     
     self.assertEqual(post.status, 200, 'comment POST 200')
     
     get = self.get('/events/%s/comments/' % event[u'id'])
     
     self.assertEqual(get.status, 200, 'comment GET 200')
     
     try:
         get = json.loads(get.read())
     except ValueError:
         self.assertTrue(False, 'comment GET not JSON')
     
     self.assertTrue('comments' in get, 'comment GET has comments')
     self.assertEqual(len(get['comments']), 1, 'comment GET return 1 '
                      'comment')
     self.assertTrue('comment' in get['comments'][0], 'comment GET has '
                     'comments')
     self.assertEqual(get['comments'][0]['comment'], comment, 'comment GET '
                      'returned the right comment')
     self.assertTrue('username' in get['comments'][0], 
                     'comment GET has username')
     self.assertFalse('display_name' in get['comments'][0], 
                     'comment GET does not have display_name')
Exemplo n.º 17
0
 def test_get(self):
     """
     Creates, saves a test Event data. Then fetches it from DB and asserts
     that both should be key-value pairwise exactly the same
     :return:
     """
     e = self.create_event()
     key = e.save(db)
     _e = Event.get(key, db)
     self.assertEqual(e.to_dict(), _e.to_dict())
Exemplo n.º 18
0
 def test_sms_notification_creation(self):
     if not settings.TEST_SMS: return
     
     user = User(username='******',
                 password='******',
                 number='+16666666666')
     user.save()
     
     event = Event(**{
         u'where': 'test',
         u'when': timestamp(),
         u'what': 'test',
         u'broadcast': False,
         u'posted_from': [37.422834216666665, -122.08536667833332],
         u'creator': user[u'username'],
     })
     event.save()
     
     number = '+16475551234'
     name = 'Testy Smoth'
     
     reg, out, is_user = SMS.register(event, [{u'number':number, u'name':name},
                                              {u'number':user[u'number'], 
                                               u'name':name}])
     
     self.assertEqual(len(reg), 1, 'correct ammout registered')
     self.assertEqual(len(out), 0, 'correct ammout out of numbers')
     self.assertEqual(len(is_user), 1, 'correct ammout are already users')
     
     reged = reg[0]
     
     self.assertEqual(reged.__class__, User)
     self.assertTrue(u'id' in reged)
     
     result = notifications.send(reged[u'id'], 
                                 {u'type': 'invite', 
                                  u'event_revision': event[u'revision'],
                                  u'event_id': event[u'id']})
     
     self.assertEqual(len(result), 1, 'the correct number of notifications '
                                      'were sent')
     self.assertTrue(result[0], 'the notification was sent correctly')
Exemplo n.º 19
0
 def send(self, user, client_id, message):
     from api.events.models import Event
     
     if message[u'type'] not in (u'invite', u'comment'):
         return False
     
     smsee = SMSRegister.get({u'event': message[u'event_id'],
                              u'contact_number': client_id})
     if smsee is None: return False
     
     event = Event.get(message[u'event_id'])
     if event is None: return False
     
     account = twilio.Account(settings.TWILIO_ACCOUNT_SID,
                              settings.TWILIO_AUTH_TOKEN)
     
     texts = list()
     
     if message[u'type'] == u'invite':
         tz = smsee[u'tz'] or 'America/Toronto'
         
         t2 = ('%s shared a plan with you on '
               'Connectsy. ' % event[u'creator'])
         if event[u'where'] is not None:
             t2 += 'Where: %s' % event[u'where']
             if event[u'when'] is not None and event[u'when'] != 0:
                 t2 += ", "
             else:
                 t2 += ". "
         if event[u'when'] is not None and event[u'when'] != 0:
             t2 += 'When: %s. ' % format_date(event[u'when'], tz=tz)
         t2 += 'Reply to send a comment, include #in to join.'
         texts.append(t2)
         
         texts.append('What\'s the plan: %(what)s' % 
                      {'username': event[u'creator'], 
                       'what': event[u'what']})
         
     elif message[u'type'] == u'comment':
         texts.append('%(commenter)s commented: %(comment)s' % message)
         if len(texts[-1]) > 160:
             texts[-1] = texts[-1][:157]+"..."
     
     try:
         for text in texts:
             account.request(SMS_OUTPUT_URL, 'POST', {
                     'To': smsee[u'contact_number'],
                     'Body': text,
                     'From': smsee[u'twilio_number'],
                 })
         return True
     except HTTPError, e:
         print e.read()
         return False
Exemplo n.º 20
0
    def delete(self, revision):
        '''
        Deletes an event, if the current user it that event's owner.

        TODO - remove associated attendance
        '''
        event = Event.get({u'revision': revision})
        if event is None: 
            raise HTTPError(404)
        if event[u'creator'] != self.get_user()[u'username']: 
            raise HTTPError(403)

        db.objects.event.remove(event[u'id'], safe=True)
        self.finish()
Exemplo n.º 21
0
 def test_event_list_auth(self):
     user = self.get_user()
     user2 = self.make_user()
     
     event1 = Event(**{
         u'where': 'test',
         u'when': timestamp(),
         u'what': 'user2 created',
         u'broadcast': False,
         u'posted_from': [37.422834216666665, -122.08536667833332],
         u'creator': user2[u'username'],
     })
     event1.save()
     Attendant(user=user[u'id'], event=event1[u'id']).save()
     
     event2 = Event(**{
         u'where': 'test',
         u'what': 'user3 created',
         u'broadcast': False,
         u'creator': user2[u'username'],
     })
     event2.save()
     
     event3 = Event(**{
         u'where': 'test',
         u'what': 'user2 created, broadcast',
         u'broadcast': True,
         u'posted_from': [37.422834216666665, -122.08536667833332],
         u'creator': user2[u'username'],
     })
     event3.save()
     
     response = self.get('/events/?filter=creator'
                         '&username=%s' % user2[u'username'])
     self.assertEqual(response.status, 200, 'response OK')
     
     events = json.loads(response.read())[u'events']
     
     self.assertTrue(event1[u'revision'] in events, 'invited returned')
     self.assertTrue(event3[u'revision'] in events, 'broadcast returned')
     self.assertEqual(len(events), 2, 'correct number of events returned')
Exemplo n.º 22
0
    def test_save(self):
        """
        Saves the test image in the database and checks if the process is
        successful by comparing the dictionaries
        :return:
        """
        e = self.create_event()
        incident_id = e.save(db)

        i = create_image(uuid='image uuid', name='image.png')
        i.save(incident_id, db)

        e.images.append(i.to_dict())

        _e = Event.get(incident_id, db)
        self.assertEqual(e.to_dict(), _e.to_dict())
Exemplo n.º 23
0
 def test_geo_queries(self):
     """
     Tests the nearby geo spatial query
     :return:
     """
     coords = {
         "latitude": self.test_data["events"]["centerLocation"]["lat"],
         "longitude": self.test_data["events"]["centerLocation"]["long"]
     }
     max_distance = 2000
     events = Event.get_events_around(center=coords,
                                      max_distance=max_distance,
                                      cluster_threshold=100.0,
                                      db=db,
                                      collection_name=Event.collection_name)
     self.assertTrue(isinstance(events, list))
Exemplo n.º 24
0
 def test_event_new_created(self):
     response = self.post('/events/', {
         u'broadcast': True,
         u'what': 'Testin event creation',
     })
     self.assertEqual(response.status, 201, 'new event 201')
     
     response = self.post('/events/', {
         u'broadcast': True,
         u'what': 'Testin event creation',
     })
     self.assertEqual(response.status, 201, 'new event 201')
     
     events = Event.find({u'creator': self.get_user()[u'username']})
     self.assertEqual(len(events), 2, '2 events created')
     self.assertNotEqual(events[0][u'created'], events[1][u'created'], 
                         'created times are different')
Exemplo n.º 25
0
    def get(self, revision):
        '''
        TODO - enforce user restrictions
        '''
        #grab the event from the database
        event = Event.get({u'revision': revision})
        if event is None: raise HTTPError(404)
        
        if not event.user_can_access(self.get_user()):
            raise HTTPError(401)
        
        response = {'event': event.serializable()}

        #give the user the attendance info if they asked for it
        if self.request.arguments.get('attendants'):
            response['attendants'] = Attendant.find({u'event': 
                                         event[u'id']}).serializable(name=True)
        self.output(response)
Exemplo n.º 26
0
 def post(self, event_id):
     '''
     Updates an invitee's attendance
     '''
     body = self.body_dict()
     username = self.get_session()[u'username']
     user = User.get({u'username': username})
     #make sure the event exists
     event = Event.get(event_id)
     if not event: raise HTTPError(404)
     
     #try to grab the user's existing attendance status
     att = Attendant.get({u'event': event[u'id'],
                          u'user': user[u'id']})
     
     #if the user isn't invited, we need to error out if broadcast is off
     if att is None:
         if event[u'broadcast']:
             att = Attendant(user=user[u'id'], event=event[u'id'])
         else:
             raise HTTPError(403)
     
     # create a list of acceptable statuses
     valid_statuses = [v for k, v in status.__dict__.iteritems() if k[0] != '_']
     
     #make sure status is present and a correct value
     if body.get(u'status') not in valid_statuses:
         raise HTTPError(400)
     
     notify = (att[u'status'] == status.INVITED 
               and body[u'status'] == status.ATTENDING)
     
     att[u'status'] = body[u'status']
     att.save()
     
     if notify:
         #Send out the attendant notifications
         for uname in Attendant.to_notify(event, skip=[username]):
             notifications.send(uname, {u'type': 'attendant',
                                        u'event_revision': event[u'revision'],
                                        u'event_id': event[u'id'],
                                        u'attendant': username})
Exemplo n.º 27
0
 def post(self, event_id):
     #make sure the event exists
     event = Event.get(event_id)
     if not event: raise HTTPError(404)
     
     #grab the data
     body = self.body_dict()
     #comment body is required, and must have content
     if not u'comment' in body or len(body[u'comment']) == 0:
         raise HTTPError(400)
     
     #nonce is optional
     if u'nonce' in body:
         #if another comment exists with this nonce, it's a double-post
         if Comment.get({u'nonce': body[u'nonce'],
                         u'event': event[u'id'], 
                         u'user': self.get_session()[u'username']}):
             raise HTTPError(409)
     
     commenter = self.get_session()[u'username']
     
     #create the comment
     Comment(**{
         u'comment': body[u'comment'],
         u'event': event[u'id'],
         u'username': commenter,
     }).save()
     
     #Send out the comment notifications
     usernames = Attendant.to_notify(event, skip=[commenter])
     for username in usernames:
         notifications.send(username, {u'type': 'comment',
                                       u'event_revision': event[u'revision'],
                                       u'event_id': event[u'id'],
                                       u'comment': body[u'comment'],
                                       u'commenter': commenter})
Exemplo n.º 28
0
 def get(self, event_id):
     '''
     Gets all comments for a given event.
     '''
     #make sure the event exists
     if not Event.get(event_id): raise HTTPError(404)
     
     #show them comments!
     comments = Comment.find({u'event': event_id})
     comments.sort(u'timestamp', pymongo.ASCENDING)
     
     ret_coms = []
     for c in comments:
         user = User.get(c[u'user'])
         ret = c.__data__
         ret[u'username'] = user.__data__.get(u'username', None)
         if ret[u'username'] is None:
             del ret[u'username']
         ret[u'display_name'] = user.__data__.get(u'display_name', None)
         if ret[u'display_name'] is None:
             del ret[u'display_name']
         ret_coms.append(ret)
     
     self.output({u'comments': ret_coms})
Exemplo n.º 29
0
    def handle(self, *args, **options):
        # Event.objects.all().delete()
        # Match.objects.all().delete()
        # return

        client = GraphQLClient('https://vk-hackathon-gateway.trbna.com/ru/graphql/')

        for match_id in match_ids:
            query = base_query % (match_id, 'match_started', 'statMatchStarted')
            response = client.execute(query)
            print(response)
            response = json.loads(response)
            match_data = response.get('data', {}).get('stat_match')
            home_team_data = match_data.get('home')
            away_team_data = match_data.get('away')

            start_time = match_data.get('scheduledAt')
            status = match_data.get('status')
            minute = match_data.get('currentMinute')

            home_team, created = Team.objects.update_or_create(
                global_id=home_team_data.get('team', {}).get('id'),
                defaults=dict(
                    name=home_team_data.get('team', {}).get('name'),
                    logo = home_team_data.get('team', {}).get('logo').get('url'),
                )
            )

            away_team, created = Team.objects.update_or_create(
                global_id=away_team_data.get('team', {}).get('id'),
                defaults=dict(
                    name=away_team_data.get('team', {}).get('name'),
                    logo = away_team_data.get('team', {}).get('logo').get('url'),
                )
            )

            match, created = Match.objects.update_or_create(
                global_id=match_id,
                defaults=dict(
                    start_datetime=start_time, status=status, minute=minute,
                    home_team_score = home_team_data.get('score'),
                    away_team_score = away_team_data.get('score'),
                    home_team=home_team,
                    away_team=away_team
                )
            )

            for event_type in event_types:
                query = base_query % (match_id, event_type['code'], event_type['model'])
                result = client.execute(query)
                print(result)
                data = json.loads(result)
                events = data.get('data', {}).get('stat_match').get('events', [])

                for event_data in events:
                    time = event_data.get('time')
                    code = event_type['code']
                    if code is 'match_started':
                        match.real_start_datetime = time
                        match.save()
                        continue

                    try:
                        event = Event.objects.get(global_id=event_data.get('id'))
                    except Event.DoesNotExist:
                        event = Event(global_id=event_data.get('id'))
                    event.type = code
                    event.time = time
                    event.team = event_data.get('team')
                    event.match = match
                    event.match_time = event_data.get('value', {}).get('matchTime')
                    event.player_name = event_data.get('value', {}).get('player', {}).get('lastName')
                    event.player_avatar = event_data.get('value', {}).get('player', {}).get('avatar', {}).get('main')
                    event.home_score = event_data.get('value', {}).get('homeScore')
                    event.away_score = event_data.get('value', {}).get('awayScore')
                    event.method_score = event_data.get('value', {}).get('methodScore')
                    event.save()
Exemplo n.º 30
0
    def test_event_list_sort(self):
        t1 = timestamp()
        t2 = timestamp()
        t3 = timestamp()
        
        e1 = Event(**{
            u'when': t1,
            u'what': 'user2 created, broadcast',
            u'broadcast': True,
            u'creator': self.get_user()[u'username'],
            u'created': t1,
        })
        e1.save()
        
        e2 = Event(**{
            u'when': t2,
            u'what': 'user2 created, broadcast',
            u'broadcast': True,
            u'creator': self.get_user()[u'username'],
            u'created': t3,
        })
        e2.save()
        
        e3 = Event(**{
            u'when': t2,
            u'what': 'user2 created, broadcast',
            u'broadcast': True,
            u'creator': self.get_user()[u'username'],
            u'created': t2,
        })
        e3.save()
        
        e4 = Event(**{
            u'when': t3,
            u'what': 'user2 created, broadcast',
            u'broadcast': True,
            u'creator': self.get_user()[u'username'],
            u'created': t1,
        })
        e4.save()
        
        response = self.get('/events/?sort=soon&filter=creator&'
                            'username=%s' % self.get_user()[u'username'])
        self.assertEqual(response.status, 200, 'response OK')
        
        events = json.loads(response.read())[u'events']
        self.assertEqual(len(events), 4, 'correct number of events returned')
        
        self.assertEqual(events[0], e1[u'revision'], 
                         'event 1 when correct, primary sort')
        #unconnect to test secondary sort
#        self.assertEqual(events[1], e3[u'revision'], 
#                         'event 3 when correct, secondary sort')
#        self.assertEqual(events[2], e2[u'revision'], 
#                         'event 2 when correct, secondary sort')
        self.assertEqual(events[3], e4[u'revision'], 
                         'event 4 when correct, primary sort')
Exemplo n.º 31
0
 def test_event_list_invited(self):
     user = self.get_user()
     user2 = self.make_user(username='******')
     user3 = self.make_user(username='******')
     
     self.follow(user, user2, reciprocal=True)
     self.follow(user3, user, reciprocal=True)
     
     event1 = Event(**{
         u'where': 'test',
         u'when': timestamp(),
         u'what': 'user2 created',
         u'broadcast': False,
         u'posted_from': [37.422834216666665, -122.08536667833332],
         u'creator': user2[u'username'],
     })
     event1.save()
     Attendant(user=user[u'id'], event=event1[u'id']).save()
     
     event2 = Event(**{
         u'where': 'test',
         u'what': 'user3 created',
         u'broadcast': False,
         u'creator': user3[u'username'],
     })
     event2.save()
     Attendant(user=user[u'id'], event=event2[u'id'], 
               status=status.ATTENDING).save()
     
     event3 = Event(**{
         u'where': 'test',
         u'what': 'user2 created, broadcast',
         u'broadcast': True,
         u'posted_from': [37.422834216666665, -122.08536667833332],
         u'creator': user2[u'username'],
     })
     event3.save()
     
     event4 = Event(**{
         u'where': 'test',
         u'when': timestamp(),
         u'what': 'user3 created',
         u'broadcast': False,
         u'creator': user3[u'username'],
     })
     event4.save()
     
     response = self.get('/events/?filter=invited')
     self.assertEqual(response.status, 200, 'response OK')
     
     events = json.loads(response.read())[u'events']
     
     self.assertEqual(len(events), 3, 'correct number of events returned')
     self.assertTrue(event1[u'revision'] in events, 'event 1 returned')
     self.assertTrue(event2[u'revision'] in events, 'event 2 returned')
     self.assertTrue(event3[u'revision'] in events, 'event 3 returned')