コード例 #1
0
ファイル: models.py プロジェクト: Shopcaster/Connectsy-Server
 def invite(self, usernames=None, contacts=None, tz=None):
     if usernames is not None:
         #prevent people from inviting themselves
         if self[u'creator'] in usernames:
             usernames.remove(self[u'creator'])
         # convert usernames to user objects
         users = list(User.find({u'username': {'$in': usernames}}))
     else:
         users = list()
     ret = None
     if contacts is not None:
         registered, out_of_numbers, has_username = SMS.register(self, 
                 contacts, tz=tz)
         users += has_username
         users += [reg for reg in registered if reg not in users]
         if len(out_of_numbers) > 0:
             ret = out_of_numbers
     
     for user in users:
         Attendant(user=user[u'id'], event=self[u'id']).save()
         #send the invite notification
         if user[u'username'] is not None: name = user[u'username']
         else: name = user[u'id']
         
         notifications.send(name, {u'type': 'invite', 
                                   u'event_revision': self[u'revision'],
                                   u'event_id': self[u'id']})
     return ret
コード例 #2
0
ファイル: models.py プロジェクト: Baljan/cafesys-fork
def friendrequest_post_save(sender, instance=None, **kwargs):
    if instance is None:
        return
    fr = instance
    sent_to = fr.sent_to
    sent_by = fr.sent_by

    extra_msgs = []
    if fr.answered_at:
        extra_msgs.append('answered_at=%s' % fr.answered_at.strftime('%Y-%m-%d'))
        extra_msgs.append('accepted=%s' % fr.accepted)

    extra = ''
    if len(extra_msgs):
        extra = ', ' + ', '.join(extra_msgs)
    get_logger('baljan.friends').info(
            'friend request %s → %s saved%s' % (
                sent_by, sent_to, extra))

    if fr.answered_at:
        if fr.accepted:
            send_type = 'friend_request_accepted'
        else:
            send_type = 'friend_request_denied'
        notifications.send(send_type, sent_by, 
            requestee=sent_to.get_full_name())
    else:
        notifications.send('friend_request_received', 
            sent_to, requestor=sent_by.get_full_name())
コード例 #3
0
ファイル: sonar.py プロジェクト: salvatorelionetti/sonar
def sendNotification():
    global logging
    global lastTimeDistList
    
    msg = ''
    for el in lastTimeDistList:
        msg += "%s: %s\r\n"%(el[0], str(el[1]))

    notifications.send(logging, msg)

    logging.debug('Notifications sent!')
コード例 #4
0
ファイル: models.py プロジェクト: Baljan/cafesys-fork
def friendrequest_post_delete(sender, instance=None, **kwargs):
    if instance is None:
        return
    fr = instance
    sent_to = fr.sent_to
    sent_by = fr.sent_by

    get_logger('baljan.friends').info('friend request %s → %s deleted' % (
        fr.sent_by, fr.sent_to))
    if fr.answered_at:
        pass # a notification has already been sent in this case
    else:
        notifications.send('friend_request_canceled', 
            sent_to, requestor=sent_by.get_full_name())
コード例 #5
0
 def post(self, username):
     follow = self.body_dict().get(u'follow')
     if follow is None: raise HTTPError(403)
     
     follower = Follower.get({u'follower': self.get_user()[u'username'],
                              u'followee': username})
     
     if follow and follower is None:
         Follower(**{u'follower': self.get_user()[u'username'],
                     u'followee': username}).save()
         notifications.send(username, {u'type': u'follow', 
                                       u'username': self.get_user()[u'username']})
     elif not follow and follower is not None:
         follower.delete()
コード例 #6
0
ファイル: app.py プロジェクト: sefdrin/raspi_doorbell
 def handle_ring(self, channel=None):
     self.logger.info('bell is ringing!')
     for client in tornado_server.connections:
         client.write_message({'type': self.message_types['receive_bell']})
     if self._should_play_sound():
         pygame.mixer.music.play()
     else:
         self.logger.debug(
             'Not playing sound because in do-not-disturb-mode.')
     if self._should_send_notification():
         notifications.send(self.server_config.notifications)
     else:
         self.logger.debug(
             'Not sending notifications because volume is too high.')
コード例 #7
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')
コード例 #8
0
ファイル: models.py プロジェクト: Baljan/cafesys-fork
def traderequest_notice_save(tr):
    if tr.answered:
        pass 
    else:
        if tr.wanted_signup.shift.when < date.today():
            return
        if tr.offered_signup.shift.when < date.today():
            return

        requestee = tr.wanted_signup.user
        requestor = tr.offered_signup.user
        notifications.send('new_trade_request',
            requestee, 
            requestor=requestor.get_full_name(),
            wanted_shift=tr.wanted_signup.shift.name(),
            offered_shift=tr.offered_signup.shift.name(),
        )
コード例 #9
0
 def test_generic_poll_notification(self):
     
     self.register_for_notifications()
     
     notification_extra = uuid.uuid4().hex
     
     notifications.send(self.get_user()[u'username'], 
                        {u'type': 'test', u'extra': notification_extra})
     
     nots = self.get_new_notifications()
     
     self.assertEqual(len(nots), 1, 'one new notification')
     
     notification = nots[0]
     
     self.assertTrue(u'extra' in notification, 'notification has extra')
     
     self.assertEqual(notification[u'extra'], notification_extra, 
                      'notification extra matches')
コード例 #10
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})
コード例 #11
0
ファイル: main.py プロジェクト: BearchInc/spike-cookies
def send(app_id):
    cookies, home = apps[app_id].login()
    data = { 'cookies': cookies, 'provider_home': home, 'provider_domain': apps[app_id].domain }
    notification = {'title':'Permission', 'body':'I need permission to see nudes'}
    response = notifications.send(notification, notifications.browser, data)

    return {
        "response": response.status_code,
        "system": app_id,
        "cookies": cookies,
        "data": data
    }
コード例 #12
0
ファイル: main.py プロジェクト: BearchInc/spike-cookies
def approve(app_id):

    data = flask.request.get_json(True)
    cookies = data['cookies']
    data = { 'cookies': cookies, 'provider_home': apps[app_id].home, 'provider_domain': apps[app_id].domain }
    notification = {'title':'Permission', 'body':'I need permission to see nudes'}
    response = notifications.send(notification, notifications.browser, data)

    return {
        "response": response.status_code,
        "system": app_id,
        "cookies": cookies
    }
コード例 #13
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})
コード例 #14
0
ファイル: models.py プロジェクト: Baljan/cafesys-fork
def traderequest_notice_delete(tr):
    if tr.answered:
        cancel = False
        if tr.wanted_signup.shift.when < date.today():
            cancel = True
        if tr.offered_signup.shift.when < date.today():
            cancel = True
        if cancel:
            logger = get_logger('baljan.trades')
            logger.info('not sending message about trade request deletion because the offered or wanted shift was in the past')
            return

        if tr.accepted:
            send_type = 'trade_request_accepted'
        else:
            send_type = 'trade_request_denied'
        requestor = tr.offered_signup.user
        notifications.send(send_type,
            requestor,
            wanted_shift=tr.wanted_signup.shift.name(),
            offered_shift=tr.offered_signup.shift.name(),
        )
    else:
        pass # FIXME: notifications should be sent here as well
コード例 #15
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')
コード例 #16
0
ファイル: flag.py プロジェクト: abulte/transilien
def record(data):
    """Record a data row into DB and trigger alert if needed"""
    table = database.get()['results']

    data['type'] = 'NORMAL'
    etat = data.get('etat', False)
    if etat:
        if etat.startswith('Suppr') or etat == 'S':
            data['type'] = 'SUPPR'
        elif etat.startswith('Retard') or etat == 'R':
            data['type'] = 'RETARD'
        else:
            data['type'] = etat
    else:
        data['etat'] = ''

    # convert to ISO
    data['date'] = convert_to_iso(data['date'])
    data['weekday'] = get_datetime_from_iso(data['date']).isoweekday()

    limit_date = get_limit_date()
    # no duplicates
    # date can change for same train, num supposed unique each day
    try:
        existing = table.find_one(table.table.columns.date > limit_date,
                                  num=data['num'])
    # AttributeError on `date` when DB is empty (first run)
    except AttributeError:
        existing = None

    do_notif = False
    if existing is None:
        if data['type'] == 'SUPPR':
            do_notif = True
        table.insert(data)
    # type has changed, maybe suppr
    elif data['type'] != existing.type and data['type'] == 'SUPPR':
        do_notif = True
        table.update(
            {
                'id': existing.id,
                'etat': data['etat'],
                'type': data['type']
            }, ['id'])
    # date has changed, compute delay
    elif data['date'] != existing['date']:
        data['type'] = 'RETARD'
        delta = get_datetime_from_iso(data['date']) - get_datetime_from_iso(
            existing['date'])
        data['delay'] = delta.seconds
        table.update(
            {
                'id': existing.id,
                'etat': data['etat'],
                'type': data['type'],
                'delay': data['delay']
            }, ['id'])
    # no delay but RETARD??
    elif data['type'] != existing['type']:
        table.update(
            {
                'id': existing.id,
                'etat': data['etat'],
                'type': data['type']
            }, ['id'])
        # sometimes train are "uncancelled" apparently
        if existing['type'] == 'SUPPR':
            notifications.send(data, cancel=True)

    if do_notif:
        notifications.send(data)
コード例 #17
0
ファイル: apnspush.py プロジェクト: cvillers/apnspush
f = open(args.config)
config = json.load(f)
f.close()

###############################################################################

longMessage = ""

if (args.read_long_message):
    longMessage = sys.stdin.read()
else:
    longMessage = args.long_message

###############################################################################

clients = []

if args.clients == "all":
    clients = config["keys"].keys()
else:
    clients = args.clients.split(',')

for key in clients:
    if not key in config["keys"]:
        print("Unknown client %s" % key)
        sys.exit(2)
    notifications.send(config["keys"][key], args.message, args.title,
                       args.subtitle, longMessage, args.long_message_preview,
                       args.icon_url, args.message_level, args.silent_message,
                       args.button_text, args.command, args.sound, args.debug)
コード例 #18
0
ファイル: models.py プロジェクト: Baljan/cafesys-fork
def signup_notice_save(signup):
    if signup.shift.when < date.today():
        return
    notifications.send('added_to_shift', signup.user,
        shift=signup.shift.name())
コード例 #19
0
ファイル: models.py プロジェクト: Baljan/cafesys-fork
def signup_notice_delete(signup):
    if signup.shift.when < date.today():
        return
    notifications.send('removed_from_shift', signup.user,
        shift=signup.shift.name())