示例#1
0
class GCMNotifications(Notifications):
    def __init__(self):
        self.gcm = GCM(config.google_api_key)
        # return super(GCMNotifications, self).__init__()

    def notify(self, reg_id, data):
        self.gcm.plaintext_request(registration_id=reg_id, data=data)
示例#2
0
def checkDataAndNotify():
    profiles = Profile.objects.all()
    data = {}
    
    currentTime = time.time()
    recentTime = currentTime - 24 * 3600  
    
    for profile in profiles:
        dbName = "User_" + str(profile.id)
        collection = connection[dbName]["funf"]
        newNotifications = False
       
        recentEntries = collection.find({ "time": {"$gte": recentTime }})
        
        if (recentEntries.count() == 0):
            addNotification(profile, 1, "Stale behavioral data", "Analysis may not accurately reflect your behavior.", None)
            newNotifications = True
        #addNotification(profile, 2, "Survey", "Take this survey", "/survey/?survey=1");
        #newNotifications = True
        if (newNotifications and Device.objects.filter(datastore_owner = profile).count() > 0):
            gcm = GCM(settings.GCM_API_KEY)
            #addNotification(profile, 2, "Push successful", "Push notifications are working properly.")
            for device in Device.objects.filter(datastore_owner = profile):
                #pdb.set_trace() 
                gcm.plaintext_request(registration_id=device.gcm_reg_id,data= { "action":"notify" })
示例#3
0
文件: functions.py 项目: pm-str/Sked
def push_message(username, token, pk):
    print(token, pk)
    gcm = GCM(GCM_APIKEY)
    gcm.plaintext_request(registration_id=token,
                          data={},
                          collapse_key='new',
                          time_to_live=TIME_TO_LIVE)
示例#4
0
 def askForReplace(self, request, pk=None):
     queryset = Appointment.objects.get(id=pk)
     gcm = GCM("AIzaSyCEimvyhdLB38RIIOTITtZ6JwttrWO07JU")
     data = {
         'message':
         'Horario vago do dia ' + str(queryset.line.date) + ' as ' +
         str(queryset.time) + ' com o ' + queryset.line.medic.name +
         ' na clinica ' + queryset.line.clinic.name + '.',
         'year':
         str(queryset.line.date.year),
         'month':
         str(queryset.line.date.month),
         'day':
         str(queryset.line.date.day),
         'time':
         str(queryset.time),
         'clinic':
         str(queryset.line.clinic.id),
         'medic':
         str(queryset.line.medic.id)
     }
     reg_id = 'APA91bF0k32Tyqlhiy9DxfNO7B-6eKNSilMGtfKaehOQ3XV-suYwdwK-3meSTTlCKxUCc5U2B8eAGv5S9bbnAOLe5ww_eqmVyAm5fqVwYyy_dmZCQRRK9veZkZ22K6-Dsj9WNI2LTFeZ6OcwfsQ3NfSh4WyJ8S2tBQ'
     gcm.plaintext_request(registration_id=reg_id, data=data)
     queryset2 = Appointment.objects.filter(line__id=queryset.line.id,
                                            check=False,
                                            patient__isnull=False)
     for e in queryset2:
         reg_id = e.patient.gcm_id
         if reg_id is not None and not reg_id == "":
             gcm.plaintext_request(registration_id=reg_id, data=data)
     queryset.delete()
     return json_response({'message': 'deleted succefully'})
示例#5
0
def send_push(type, description):
  gcm = GCM('AIzaSyCxXaknhqHcNAxxSKGseYQrpgHB5COLF00')
  data = {'type': type, 'message': description}
  try:
    gcm.plaintext_request(registration_id='APA91bGxJ3Y2n4pExPc8kX1PAyuARTuA9p8a3LxwTj9d6LbAQ3aE4TYeaJ13nxqDohOtBW0ief8VdQl_H4Zz31gm5Csa61eT68RyeudpJH7lwJrzy-5yl3VmvZzYU3uIOnYMTfSGMozmhkV6DfEGblz6xUGmLrYBxQ', data=data, retries=10 )
  except:
    print 'fail'
示例#6
0
def check_new_issue():
    req = requests.get(url='http://www.themagpi.com/mps_api/mps-api-v1.php?mode=list_issues')
    json_issues = json.loads(req.text)
    last_issue = json_issues['data'][0]
    gcm = GCM(app_keys['gcm'])
    data = {}
    data['id'] = last_issue['title']
    data['editorial'] = last_issue['editorial'].encode('utf8')
    data['title'] = last_issue['title']
    data['link'] = last_issue['pdf']
    data['image'] = last_issue['cover']
    data['date'] = last_issue['date']
    devices, next_curs, more = Device.query().fetch_page(10)
    while next_curs:
        for device in devices:
            try:
                gcm.plaintext_request(registration_id=device.id_gcm, data=data)
            except GCMNotRegisteredException:
                pass
            except GCMInvalidRegistrationException:
                pass
            except GCMUnavailableException:
                pass
        devices, next_curs, more = Device.query().fetch_page(10, start_cursor=next_curs)
    return jsonify( { 'status' : 'success' } ) , 200
示例#7
0
    def post(self):
        super(NewResourceHandler, self).post()

        kind = self.data['kind']

        if kind == 'sms':
            key = self.account.send_message_to(
                phones=self.data['recipients'],
                content=self.data['content']
            )
        elif kind == 'link':
            key = self.account.send_link(
                url=self.data['url']
            )

        # Make a GCM call to phone with user's reg_id and
        # the entity key to retrieve from datastore
        if not DEBUG:
            gcm = GCM(API_KEY)
            gcm.plaintext_request(
                registration_id=self.account.registration_id,
                data={'key': key},
                collapse_key=str(key)
            )

        self.response.out.write("OK")
示例#8
0
def checkDataAndNotify():
    profiles = Profile.objects.all()
    data = {}

    currentTime = time.time()
    recentTime = currentTime - 24 * 3600

    for profile in profiles:
        dbName = "User_" + str(profile.id)
        collection = connection[dbName]["funf"]
        newNotifications = False

        recentEntries = collection.find({"time": {"$gte": recentTime}})

        if (recentEntries.count() == 0):
            addNotification(
                profile, 1, "Stale behavioral data",
                "Analysis may not accurately reflect your behavior.", None)
            newNotifications = True
        #addNotification(profile, 2, "Survey", "Take this survey", "/survey/?survey=1");
        #newNotifications = True
        if (newNotifications and
                Device.objects.filter(datastore_owner=profile).count() > 0):
            gcm = GCM(settings.GCM_API_KEY)
            #addNotification(profile, 2, "Push successful", "Push notifications are working properly.")
            for device in Device.objects.filter(datastore_owner=profile):
                #pdb.set_trace()
                gcm.plaintext_request(registration_id=device.gcm_reg_id,
                                      data={"action": "notify"})
示例#9
0
class PushThread(threading.Thread):
    def __init__(self):
        super(PushThread, self).__init__()
        self.gcm = GCM('AIzaSyC3CwECHoUqHKNQXbndpRWPjgauYhXTUEI')
        self.message_queue = Queue.Queue()
        self._break = False

    def stop_thread(self):
        self._break = True

    def run(self):
        print 'worker is running...'
        while not self._break:
            if not self.message_queue.empty():
                message = self.message_queue.get()

                try:
                    print 'worker does his job: ' + message.__str__()
                    reg_id=Contacts.ids[str(message.receiver)]
                    data = message.jsonify()
                    self.gcm.plaintext_request(registration_id=reg_id, data=data)
                except:
                    traceback.print_exc()
            else:
                time.sleep(5)
        print 'worker got off the work'

    def put_message(self, gcm_message):
        if isinstance(gcm_message, Message):
            self.message_queue.put(gcm_message)
        else:
            print 'put_message error'
示例#10
0
def notifyAll():
    for profile in Profile.objects.all():
        if Device.objects.filter(datastore_owner = profile).count() > 0:
            gcm = GCM(settings.GCM_API_KEY)
            for device in Device.objects.filter(datastore_owner = profile):
                try:
                    gcm.plaintext_request(registration_id=device.gcm_reg_id, data={"action":"notify"})
                except Exception as e:
                    print "Issue with sending notification to: %s, %s" % (profile.id, profile.uuid)
                    print e
示例#11
0
def _Start():
  assert options.options.id and options.options.data_key and options.options.data_value

  api_key = secrets.GetSecret(API_KEY_NAME)
  print 'API key: %s' % api_key
  g = GCM(api_key)
  data = {options.options.data_key: options.options.data_value}

  # Do not catch any of the exceptions for now, we'd like to see them.
  g.plaintext_request(registration_id=options.options.id, data=data)
示例#12
0
def send_push_gcm(token, content):
    google_api_key = "AAAAgGY9xAc:APA91bFwKXq9w7sB6EKzNGvIKInrc8VF8TRu3SInUM1zbisRmSX9gnlMcWFam4uIMoeAv0CGhNlwrEHvEI7htSbg6-2YHQ2hIgD0agKF95GZ_tEduz4pTDSJiQj2tpZ10hGPPLapIEvm"

    gcm = GCM(google_api_key)
    data = {'message': content, 'title': 'Chibe'}

    try:
        gcm.plaintext_request(registration_id=token, data=data)
    except:
        PushNotification.objects.filter(token=token).delete()
        pass
示例#13
0
    def send(self):
        gcm = GCM(self.app.android_key)
        payload = dict(message=str(self.content.get('alert')), custom=self.content.get('extra'))
        log.msg(payload)

        try:
            gcm.plaintext_request(registration_id=self.token, data=payload)
            log.msg('Notification sent to %s...' % self.token[:10])
        except:
            log.msg('Unable to sent to %s...' % self.token[:10])
            pass
示例#14
0
def send_android_silent(reg_id, message):
    print "send android silent notif"
    gcm = GCM(GCM_API_KEY)
    data = {'silent_push': message}
    try:
        gcm.plaintext_request(registration_id=reg_id, data=data)
        return True
    except:
        print "Unexpected error:", sys.exc_info()
        print "sending android notif failed"
        print "reg_id",  reg_id
示例#15
0
def addNotificationAndNotify(profile, notificationType, title, content, uri):
    addNotification(profile, notificationType, title, content, uri)
    if Device.objects.filter(datastore_owner = profile).count() > 0:
        gcm = GCM(settings.GCM_API_KEY)

        for device in Device.objects.filter(datastore_owner = profile):
            try:
                gcm.plaintext_request(registration_id=device.gcm_reg_id, data= {"action":"notify"})
            except Exception as e:
                print "Issue with sending notification to: %s, %s" % (profile.id, profile.uuid)
                print e
示例#16
0
def send_android_get_address_book(reg_id):
    print "send android get address book"
    gcm = GCM(GCM_API_KEY)
    data = {'get_address_book': "vas y coco"}
    print data
    try:
        gcm.plaintext_request(registration_id=reg_id, data=data)
        return True
    except:
        print "Unexpected error:", sys.exc_info()
        print "sending android get address book failed"
        print "reg_id",  reg_id
示例#17
0
def send_android_notification(reg_id, message):
    print "send android notif"
    gcm = GCM(GCM_API_KEY)
    data = {'receiver_reg_id': str(reg_id)}
    print data
    try:
        gcm.plaintext_request(registration_id=reg_id, data=data)
        return True
    except:
        print "Unexpected error:", sys.exc_info()
        print "sending android notif failed"
        print "reg_id",  reg_id
示例#18
0
文件: tasks2.py 项目: nmantri/openPDS
def notifyAll():
    for profile in Profile.objects.all():
        if Device.objects.filter(datastore_owner=profile).count() > 0:
            gcm = GCM(settings.GCM_API_KEY)
            for device in Device.objects.filter(datastore_owner=profile):
                try:
                    gcm.plaintext_request(registration_id=device.gcm_reg_id,
                                          data={"action": "notify"})
                except Exception as e:
                    print "Issue with sending notification to: %s, %s" % (
                        profile.id, profile.uuid)
                    print e
示例#19
0
文件: api.py 项目: iluminite/openPDS
 def obj_create(self, bundle, request=None, **kwargs):
     bundle = super(NotificationResource, self).obj_create(bundle, request, **kwargs)
     profile = Profile.objects.get(uuid = bundle.data["datastore_owner"]["uuid"])
     devices = Device.objects.filter(datastore_owner = profile)
     if devices.count() > 0:
         gcm = GCM(settings.ASSISTANT_GCM_API_KEY)
         for device in devices:
             try:
                 gcm.plaintext_request(registration_id=device.gcm_reg_id, data={"action":"notify"})
             except Exception as e:
                 print e
     return bundle
示例#20
0
    def send(self):
        gcm = GCM(self.app.android_key)
        payload = dict(message=str(self.content.get('alert')),
                       custom=self.content.get('extra'))
        log.msg(payload)

        try:
            gcm.plaintext_request(registration_id=self.token, data=payload)
            log.msg('Notification sent to %s...' % self.token[:10])
        except:
            log.msg('Unable to sent to %s...' % self.token[:10])
            pass
示例#21
0
def send_android_little_push(reg_id, message):
    print "send android little push"
    gcm = GCM(GCM_API_KEY)
    data = {'little_push': message}
    print data
    try:
        gcm.plaintext_request(registration_id=reg_id, data=data)
        return True
    except:
        print "Unexpected error:", sys.exc_info()
        print "sending android little push failed"
        print "reg_id",  reg_id
示例#22
0
文件: tasks2.py 项目: nmantri/openPDS
def addNotificationAndNotify(profile, notificationType, title, content, uri):
    addNotification(profile, notificationType, title, content, uri)
    if Device.objects.filter(datastore_owner=profile).count() > 0:
        gcm = GCM(settings.GCM_API_KEY)

        for device in Device.objects.filter(datastore_owner=profile):
            try:
                gcm.plaintext_request(registration_id=device.gcm_reg_id,
                                      data={"action": "notify"})
            except Exception as e:
                print "Issue with sending notification to: %s, %s" % (
                    profile.id, profile.uuid)
                print e
示例#23
0
文件: views.py 项目: meoooh/boo
def replyJjokji(request):
    message = request.DATA.get('message')
    reg_id = request.DATA.get('reg_id')

    jjokji = request.user.jjokji_set.create(contents=message)

    gcm = GCM(API_KEY)
    data = {'reg_id': reg_id,
            'message': (jjokji.contents).encode('utf8')}
    gcm.plaintext_request(
        registration_id=request.user.gcmId, data=data
    )

    return Response(status=204)
示例#24
0
 def obj_create(self, bundle, request=None, **kwargs):
     bundle = super(NotificationResource,
                    self).obj_create(bundle, request, **kwargs)
     profile = Profile.objects.get(
         uuid=bundle.data["datastore_owner"]["uuid"])
     devices = Device.objects.filter(datastore_owner=profile)
     if devices.count() > 0:
         gcm = GCM(settings.ASSISTANT_GCM_API_KEY)
         for device in devices:
             try:
                 gcm.plaintext_request(registration_id=device.gcm_reg_id,
                                       data={"action": "notify"})
             except Exception as e:
                 print e
     return bundle
示例#25
0
    def handle(self, *args, **options):
        gcm = GCM(settings.GOOGLE_API_KEY)

        for uuid in set(DeviceToken.objects.all().values_list('uuid', flat=True)):
            tok = DeviceToken.objects.filter(uuid=uuid).order_by('created_at')[0]

            payload = {}
            payload['title']="%s" % (get_district(tok.lat, tok.lng))
            payload['message']= "%s " % (get_weathersummary(tok.lat, tok.lng)[1])
            payload['timeStamp']=str(time.time())
            payload['lat']=str(tok.lat)
            payload['lng']=str(tok.lng)
            payload['notId']="101"

            try:
                canonical_id = gcm.plaintext_request(registration_id=tok.token, data=payload)
                if canonical_id:
                    token = DeviceToken.objects.filter(token=tok.token)
                    token.token = canonical_id
                    token.save()
                    self.stdout.write('Sent to [%s].' % tok.token, ending='')
            except :

                token = DeviceToken.objects.filter(token=tok.token)
                token.delete()
                self.stdout.write('Deleted  [%s].' % tok.token, ending='')
示例#26
0
def android_push(uuids, message):
    if not uuids:
        raise Exception("Registration_id is required.")

    # GCM Configuration
    from gcm import GCM

    api_key = "AIzaSyAheYj04o3dgHhG8MrN5NGQKY4HT8NhzKc"
    gcm = GCM(api_key)

    if type(uuids) is list:
        gcm.json_request(registration_ids=uuids, data=message)
    else:
        gcm.plaintext_request(registration_id=uuids, data=message)

    return ""
示例#27
0
def send_GCM_notification(token, data):

    logger.debug("Sending GCM Notification to [%s]..." % token)

    try:

        gcm = GCM(settings.GCM_API_KEY)

        # Plaintext request
        #response = gcm.plaintext_request( registration_id=token, collapse_key='Updated Steps', data=data, time_to_live=86400 ) <-- currently broken in library
        response = gcm.plaintext_request(registration_id=token, data=data)

        logger.debug("Sent Push to: [%s] sent: %s" % (token, response))
        return "Success"

    except GCMNotRegisteredException:
        logger.error("Token [%s] Not Registered!" % token)
        return "NotRegistered"

    except GCMMismatchSenderIdException:
        logger.error("Token [%s] Bad Sender error" % token)
        return "Mismatch"

    except GCMUnavailableException:
        logger.error("Failed for [%s]... try again" % token)
        return "Unavailable"

    except:
        LogTraceback()
        return "Error"
示例#28
0
文件: views.py 项目: meoooh/boo
def sendJjokji(request):
    message = request.DATA.get('message')
    latitude = request.DATA.get('latitude')
    longitude = request.DATA.get('longitude')

    try:
        booeonglee = request.user.booeonglee_set.filter(
            houseofbooeonglee__purposeOfUse=0
        ).filter(houseofbooeonglee__state=0)[0]
    except:
        return Response(status=400)

    try:
        location = models.Location.objects.create(latitude=latitude,
                                                longitude=longitude,
                                                content_object=booeonglee)
    except:
        return Response(status=400)

    jjokji = request.user.jjokji_set.create(contents=message)

    booeonglee.jjokji = jjokji
    booeonglee.save()

    houseofbooeonglee = booeonglee.houseofbooeonglee
    houseofbooeonglee.state = 1
    houseofbooeonglee.save()

    contentType = ContentType.objects.get(name='owl user')
    locations = models.Location.objects.filter(
        content_type=contentType
    ).order_by('?')

    for i in locations:
        if str('%.3f'%float(i.latitude)) == str('%.3f'%float(location.latitude)):
            if str('%.3f'%float(i.longitude)) == str('%.3f'%float(location.longitude)):
                data = {'reg_id': jjokji.writer.gcmId,
                        'message': (jjokji.contents).encode('utf8')}

                gcm = GCM(API_KEY)
                gcm.plaintext_request(
                    registration_id=i.content_object.gcmId, data=data
                )

                return Response(status=204)

    return Response(status=400)
示例#29
0
文件: functions.py 项目: Hoyuo/IMHMv2
def android_push(uuids, message):
    print str(uuids)
    if not uuids:
        return False

    from gcm import GCM

    g = GCM("AIzaSyAheYj04o3dgHhG8MrN5NGQKY4HT8NhzKc")

    try:
        if isinstance(uuids, list):
            g.json_request(registration_ids=uuids, data=message)
        elif isinstance(uuids, str):
            g.plaintext_request(registration_id=uuids, data=message)
    except Exception, e:
        print str(e)
        return False
def sendNotification(gcm_id, data, type):
	gcm_obj = GCM(API_KEY)
	try: 
		response = gcm_obj.plaintext_request(registration_id=gcm_id, data=data)
		return response
	except gcm.gcm.GCMInvalidRegistrationException: return {'error':'gcm.gcm.GCMInvalidRegistrationException'}
	except gcm.gcm.GCMNotRegisteredException: return {'error':'gcm.gcm.GCMNotRegisteredException'}
	except: return {'error':'oooops'}
示例#31
0
文件: xmpp.py 项目: geeknam/foneng.in
    def text_message(self, message):
        #Get sender's email
        idx = message.sender.index('/')
        email = message.sender[0:idx]

        # Get the latest sender's phone number
        account = Account.get_by_key_name(
            key_names=email
        )
        message_key = account.reply_to_last(message.arg)

        gcm = GCM(API_KEY)
        gcm.plaintext_request(
            registration_id=account.registration_id,
            data={'key': message_key},
            collapse_key=str(message_key)
        )
示例#32
0
class AlertNotifier(object):
    """
    Notifier for sending push notifications to a specified device.
    """
    def __init__(self, settings, device):
        self.gcm = GCM(settings['gcm_api_key'])
        self.device = device

    def notify(self, filename):
        """
        Notify about a certain filename, creates a timestamp in order inform
        the receive when the snapshot was created.
        """

        timestamp = datetime.datetime.now()
        timestamp = timestamp.strftime('%d. %B %Y at %I:%M%p')
        data = {'timestamp': timestamp, 'filename': filename}
        self.gcm.plaintext_request(registration_id=self.device, data=data)
示例#33
0
def manual(data):
    # movies = Movie.query()
    # for movie in movies.fetch(500, offset=int(offset)):
    #     movie.poster = clear_url(movie.poster)
    #     movie.put()
    # artists = Artist.query()
    # for artist in artists.fetch(500, offset=int(offset)):
    #     artist.photo = clear_url(artist.photo)
    #     artist.put()

    gcm = GCM("AIzaSyAPfZ91t379OWzTiyALsInNnYsWhemF_o0")
    data = {'message': data}

    reg_id = 'APA91bHoYzyf0npBXsbZ7GYcl5aR3j0Fz8EN2aATaid4hCgo8uGsq3M2XdUPC6FTxR-zJ0KFR0S3-yOeUQSlI6mWHD7w3n7-9u3zTZPjubpgpJdZNlHJJ8pYxNemwn6f0GQa-3hN1FDsK7T4OPuOwUSyxGp0So3GZQ'

    gcm.plaintext_request(registration_id=reg_id, data=data)

    return 'OK'
示例#34
0
class PushHandler():
    def __init__(self, _app):
        self.application = _app
        _config = BOOTSTRAP_DATA.get("gcm")
        _api_key = _config.get("api_key")
        self.gcm = None
        if _api_key != None:
            self.gcm = GCM(_api_key)
        return

    def _one(self, _token, _msg):
        if self.gcm == None:
            logging.error("no gcm")
            return
        self.gcm.plaintext_request(registration_id=_token,
                                   collapse_key='ppmessage',
                                   data=_msg)
        return

    def _push(self, _app_uuid, _body, _config):
        _type = _body.get("mt")
        _subtype = _body.get("ms")
        _count = _config.get("unacked_notification_count")
        _title = push_title(_type, _subtype, _body.get("bo"),
                            _config.get("user_language"))
        _token = _config.get("mqtt_android_token")
        _sound = None
        if not _config.get("user_silence_notification"):
            _sound = "beep.wav"
        _msg = {"title": _title, "sound": _sound, "count": _count}
        self._one(_token, _msg)
        return

    def task(self, _data):
        _config = _data.get("config")
        _body = _data.get("body")
        _app_uuid = _data.get("app_uuid")
        if _config == None or \
           _body == None or \
           _app_uuid == None:
            logging.error("Illegal request: %s." % str(_data))
            return
        self._push(_app_uuid, _body, _config)
        return
示例#35
0
class AlertNotifier(object):
    """
    Notifier for sending push notifications to a specified device.
    """

    def __init__(self, settings, device):
        self.gcm = GCM(settings['gcm_api_key'])
        self.device = device

    def notify(self, filename):
        """
        Notify about a certain filename, creates a timestamp in order inform
        the receive when the snapshot was created.
        """

        timestamp = datetime.datetime.now()
        timestamp = timestamp.strftime('%d. %B %Y at %I:%M%p')
        data = {'timestamp': timestamp, 'filename': filename}
        self.gcm.plaintext_request(registration_id=self.device, data=data)
示例#36
0
def notify():
    data = request.form
    AB0 = data['AB0']
    Rh = data['Rh']
    country = data['country']
    city = data['city']
    address = data['address']
    message = data['message']
    donors = userClass.get_eligible_donors_array(AB0, Rh, country, city)
    if not message: message = generateMessage(AB0, Rh, city, address)
    gcm = GCM('AIzaSyBK9OhEEvws_AFT47BA5fqsiUBHX1Oi6XQ')
    r = requests.get("http://maps.googleapis.com/maps/api/geocode/json?address=" + country + " " + city + " " + address)
    r = r.json()['results'][0]['geometry']['location']
    lat = r['lat']
    lng = r['lng']
    for donor in donors:
        if donor['token']:
            gcm.plaintext_request(donor['token'], {'message':message, 'lat':str(lat), 'lng':str(lng)})
    return redirect('/')
示例#37
0
    def update_song(self, request):
        #print(request.body)
        send_gcm = True
        j = json.loads(request.body)

        listener = Listener.objects.get(user=request.user);
        my_group = listener.active_queuegroup

        track = QueueTrack.objects.get(pk=j['pk'])
        if 'played' in j:
            track.played = j['played']
        if 'now_playing' in j:
            track.now_playing = j['now_playing']
        if 'vote' in j:
            if j['vote'] > 0 and (track.voted_up.filter(pk=listener.pk).first() is None):
                track.rating = track.rating + 1
                if track.voted_down.filter(pk=listener.pk).first() is not None:
                    track.voted_up.add(listener)
                track.voted_down.remove(listener)
            elif j['vote'] < 0 and (track.voted_down.filter(pk=listener.pk).first() is None):
                track.rating = track.rating - 1
                if track.voted_up.filter(pk=listener.pk).first() is not None:
                    track.voted_down.add(listener)
                track.voted_up.remove(listener)
            else:
                send_gcm = False
        track.save()

        if send_gcm:
            gcm = GCM(API_KEY)
            data = {'action': 'pull_group', 'group': my_group.pk}

            participants = Listener.objects.filter(active_queuegroup=my_group)
            #print(str(participants))
            #reg_ids = []
            for part in participants:
                gcm.plaintext_request(registration_id=part.gcm_id, data=data)
                #reg_ids.append(part.gcm_id)
            #print(str(reg_ids))

            #gcm.plaintext_request(registration_ids=reg_ids, data=data)

        return Response(self.get_serializer(my_group).data)
示例#38
0
def send_gcm(firstname, surname, receiver, message, sender_id):
    import gcm
    from gcm import GCM
    g = GCM(gcm_key)
    #log.debug("Gcm_key: " + gcm_key)
    data = {'message':message, 'sender_firstname':firstname,'sender_surname':surname, 'sender_id':str(sender_id)}

    try:
        #log.debug("Sending: ")
        #log.debug(data)
        #log.debug("Receiver: " + receiver)
        g.plaintext_request(registration_id=receiver,data=data)
    except gcm.gcm.GCMInvalidRegistrationException:
        #log.exception("Gcm failed: ")
        db = sql.getdb()
        cursor = db.cursor()
        cursor.execute("update user set gcm_id = null where gcm_id = %s", (receiver))
        db.commit()
        db.close()
示例#39
0
def testGCM(request):
    API_KEY = 'AIzaSyBIoZYJ1mOKB8x32svoYCqCSeS4yEhxbQM'
    gcm = GCM(API_KEY)
    data = {'title': '타이틀', 'content': '내용', 'ticker':'티'}

# Plaintext request
    reg_id = 'APA91bFFWd2KDbzx7I6amwY2GZBYF554kXqnd8VtApeqH7Iber0RuHY69VtEosUXvFENy6Oyr0T_SHT6mhbw4trrid_Jiti0wTDDP6jLKsWSejqjE0ytbrUTUu20rCK7nk9NoPLoA9yI'
    gcm.plaintext_request(registration_id=reg_id, data=data)

# JSON request
    reg_ids = ['APA91bFFWd2KDbzx7I6amwY2GZBYF554kXqnd8VtApeqH7Iber0RuHY69VtEosUXvFENy6Oyr0T_SHT6mhbw4trrid_Jiti0wTDDP6jLKsWSejqjE0ytbrUTUu20rCK7nk9NoPLoA9yI']
    response = gcm.json_request(registration_ids=reg_ids, data=data)
    return HttpResponse(response.success)
# Extra arguments
    res = gcm.json_request(
                           registration_ids=reg_id, data=data,
                           collapse_key='uptoyou', delay_while_idle=True, time_to_live=3600
                           )
    return HttpResponse(res)
示例#40
0
class PushHandler():

    def __init__(self, _app):
        self.application = _app
        _config = BOOTSTRAP_DATA.get("gcm")
        _api_key = _config.get("api_key")
        self.gcm = None
        if _api_key != None:
            self.gcm = GCM(_api_key)
        return
    
    def _one(self, _token, _msg):
        if self.gcm == None:
            logging.error("no gcm")
            return
        self.gcm.plaintext_request(registration_id=_token, collapse_key='ppmessage', data=_msg)
        return
    
    def _push(self, _app_uuid, _body, _config):
        _type = _body.get("mt")
        _subtype = _body.get("ms")
        _count = _config.get("unacked_notification_count")
        _title = push_title(_type, _subtype, _body.get("bo"), _config.get("user_language"))
        _token = _config.get("mqtt_android_token")
        _sound = None
        if not _config.get("user_silence_notification"):
            _sound = "beep.wav"
        _msg = {"title": _title, "sound": _sound, "count": _count}
        self._one(_token, _msg)
        return

    def task(self, _data):
        _config = _data.get("config")
        _body = _data.get("body")
        _app_uuid = _data.get("app_uuid")
        if _config == None or \
           _body == None or \
           _app_uuid == None:
            logging.error("Illegal request: %s." % str(_data))
            return
        self._push(_app_uuid, _body, _config)
        return
示例#41
0
def sendNotification(gcm_id, data, type):
    gcm_obj = GCM(API_KEY)
    try:
        response = gcm_obj.plaintext_request(registration_id=gcm_id, data=data)
        return response
    except gcm.gcm.GCMInvalidRegistrationException:
        return {'error': 'gcm.gcm.GCMInvalidRegistrationException'}
    except gcm.gcm.GCMNotRegisteredException:
        return {'error': 'gcm.gcm.GCMNotRegisteredException'}
    except:
        return {'error': 'oooops'}
示例#42
0
def pushNotification(plat, deviceID):
    if plat=="Android":
        gcm = GCM(apiKey, debug=True)
        data = {"title":"any notification string",
                "body":"This is the body"}
        response = gcm.plaintext_request(registration_id=deviceID, data=data)
        
        
    if plat=="iOS":
        messageToSend = {"devicePlatform":plat,"deviceId":deviceID}
        a = requests.post("http://192.168.1.89:8080/receivetoken",json=messageToSend)
示例#43
0
def push(user_id):
    # movies = Movie.query()
    # for movie in movies.fetch(500, offset=int(offset)):
    #     movie.poster = clear_url(movie.poster)
    #     movie.put()
    # artists = Artist.query()
    # for artist in artists.fetch(500, offset=int(offset)):
    #     artist.photo = clear_url(artist.photo)
    #     artist.put()

    user = User.get_by_id(user_id)
    data = "PRIMETIME4U ha nuove proposte per te"
    gcm = GCM("AIzaSyAPfZ91t379OWzTiyALsInNnYsWhemF_o0")
    data = {'message': data}

    reg_id = user.gcm_key

    if reg_id is not None and user.enable_notification is not False:
        gcm.plaintext_request(registration_id=reg_id, data=data)

    return 'OK'
示例#44
0
def upload_ringback_tone_friend(request):
	if request.method == "POST":
		if request.user.is_authenticated():
			user = request.user
			title = request.POST['title']
			ring_file = request.FILES['ringback_tone']
			friend_id = request.POST['friend_id']
			
			ringback_tone = RingbackTone.objects.create(user=user, title=title, url='www.allo.phone', ring_file=ring_file)
			
			friend = Friend.objects.get(id=friend_id)
			friend.ring_to_me = ringback_tone
			
			friend.save()
			update_friends = []
			update_friends.append({'nickname':friend.friend.user_profile.nickname, 'phone_number':friend.friend.user_profile.phone_number, 'friend_id':friend.id, 'ring_to_me_url':friend.ring_to_me.ring_file.url, 'ring_to_me_title':friend.ring_to_me.title, 'ring_to_friend_url':friend.ring_to_friend.ring_file.url, 'ring_to_friend_title':friend.ring_to_friend.title, 'is_new':False})


			
			friend_friend = Friend.objects.get(user=friend.friend, friend=user)
			friend_friend.ring_to_friend = ringback_tone
			friend_friend.is_update = True
			
			friend.friend.user_profile.is_update = True
			
			friend.friend.user_profile.save()
			friend_friend.save()
			# push friend

			gcm = GCM(API_KEY)
			data = {'nickname':friend.user.user_profile.nickname, 'title':friend.ring_to_me.title}
			reg_id = friend.friend.user_profile.device_uuid
			gcm.plaintext_request(registration_id=reg_id, data=data)


			return render_json({'status':'success', 'response':update_friends})
		else:
			return HttpResponse('not login')
	else:
		return HttpResponse('not post')
示例#45
0
文件: pq.py 项目: voidabhi/pq
def send_pn():
    (DOC_URL, API_KEY, REG_ID) = read_config()
    
    # bulding GCM object from API_KEY
    gcm = GCM(API_KEY)

    # downloading document from url
    rows = read_from_url(DOC_URL)
    
    # Plaintext request
    for row in rows:
        # build message
        row = prepare_msg(row)
        
        # making gcm request
        gcm.plaintext_request(registration_id=REG_ID, data=row)

    # Json request
    return gcm.json_request(
        registration_ids=reg_ids, data=data,
        collapse_key='uptoyou', delay_while_idle=True, time_to_live=3600
    )
示例#46
0
def testGCM(request):
    API_KEY = 'AIzaSyBIoZYJ1mOKB8x32svoYCqCSeS4yEhxbQM'
    gcm = GCM(API_KEY)
    data = {'title': '타이틀', 'content': '내용', 'ticker': '티'}

    # Plaintext request
    reg_id = 'APA91bFFWd2KDbzx7I6amwY2GZBYF554kXqnd8VtApeqH7Iber0RuHY69VtEosUXvFENy6Oyr0T_SHT6mhbw4trrid_Jiti0wTDDP6jLKsWSejqjE0ytbrUTUu20rCK7nk9NoPLoA9yI'
    gcm.plaintext_request(registration_id=reg_id, data=data)

    # JSON request
    reg_ids = [
        'APA91bFFWd2KDbzx7I6amwY2GZBYF554kXqnd8VtApeqH7Iber0RuHY69VtEosUXvFENy6Oyr0T_SHT6mhbw4trrid_Jiti0wTDDP6jLKsWSejqjE0ytbrUTUu20rCK7nk9NoPLoA9yI'
    ]
    response = gcm.json_request(registration_ids=reg_ids, data=data)
    return HttpResponse(response.success)
    # Extra arguments
    res = gcm.json_request(registration_ids=reg_id,
                           data=data,
                           collapse_key='uptoyou',
                           delay_while_idle=True,
                           time_to_live=3600)
    return HttpResponse(res)
示例#47
0
    def send(self, device_key, data):
        gcm_api_key = getattr(settings, 'PUSHY_GCM_API_KEY', None)
        if not gcm_api_key:
            raise PushGCMApiKeyException()

        gcm = GCM(gcm_api_key)

        # Plaintext request
        try:
            canonical_id = gcm.plaintext_request(registration_id=device_key,
                                                 data=data)
            if canonical_id:
                return self.PUSH_RESULT_SENT, canonical_id
            else:
                return self.PUSH_RESULT_SENT, 0
        except GCMNotRegisteredException:
            return self.PUSH_RESULT_NOT_REGISTERED, 0
        except IOError:
            return self.PUSH_RESULT_EXCEPTION, 0
        except PushException:
            return self.PUSH_RESULT_EXCEPTION, 0
示例#48
0
def notify(id, token):
	gcm = GCM("AIzaSyBk6qJ9tIij0GCezqDUfGu-IekXmbayE2k")
	data = {'id': id}
	gcm.plaintext_request(registration_id=token, data=data)
def sendNotification(idFacebook, message):
    try:
        cur = sql.cursor()
        cur.execute("SELECT id_cell FROM utenti WHERE id_user=%s",
                    (idFacebook, ))
        sql.commit()
        idReg = str(cur.fetchone()[0])
    except Exception, e:
        sql.rollback()
        return 'error2' + str(e)
    finally:
        cur.close()

    try:
        canonical_id = gcmSender.plaintext_request(registration_id=idReg,
                                                   data=message)

        if canonical_id:
            # Repace reg_id with canonical_id in your database
            try:
                cur = sql.cursor()
                cur.execute(
                    "UPDATE utenti SET id_cell = %s WHERE id_cell = %s",
                    (canonical_id, idReg))
                sql.commit()
            except Exception, e:
                sql.rollback()
                return 'error3 ' + str(e)
            finally:
                cur.close()
示例#50
0
def _send_push_notification(message, reg_ids):
    from gcm import GCM
    gcm = GCM('AIzaSyDvMYsVLk80XXo_omD7mjS1TfzTNDQkqFk')
    data = {'message': message}
    gcm.plaintext_request(registration_ids=reg_ids, data=data)
示例#51
0
def sendGCM(to, topic, message):
    gcm = GCM('AIzaSyD6-BUFptIOpKNrFv-Lz-6EHuHv07Hwg90')
    data = {'topic': topic, 'message': message}
    reg_id = to
    gcm.plaintext_request(registration_id=reg_id, data=data)
def send_push_notification(registration_id, message):
    gcm = GCM(API_KEY)
    resp = gcm.plaintext_request(registration_id=registration_id,
                                 data={'message': message})
示例#53
0
def messages(request):
    if request.method == 'POST':
        postString = str(request.POST).encode("utf-8")
        #        a = json.loads(request.POST)
        #        return HttpResponse(a)

        firstCutString = postString[15:]
        reversedString = ''.join(reversed(firstCutString))
        secondCutString = reversedString[10:]
        secondReversedString = ''.join(reversed(secondCutString))
        data = json.loads(secondReversedString)
        other_user_id = data['other_user_id']
        user_id = data['user_id']
        content = data['content']
        sellerString = data['seller']

        #        other_user_id = request.POST['other_user_id']
        #        user_id = request.POST['user_id']
        #        content = request.POST['content']
        #        seller = request.POST['seller']

        if sellerString == '1':
            seller = True
            unseller = False
        else:
            seller = False
            unseller = True

        other_user = User.objects.get(id=other_user_id)
        user = User.objects.get(id=user_id)
        try:
            chatRoom = ChatRoom.objects.get(user=user,
                                            other_user=other_user,
                                            seller=seller)
        except:
            chatRoom = ChatRoom.objects.create(user=user,
                                               other_user=other_user,
                                               seller=seller)
        try:
            other_chatRoom = ChatRoom.objects.get(user=other_user,
                                                  other_user=user,
                                                  seller=unseller)
        except:
            other_chatRoom = ChatRoom.objects.create(user=other_user,
                                                     other_user=user,
                                                     seller=unseller)

        if seller == 1:
            Message.objects.create(seller_chatRoom=chatRoom,
                                   buyer_chatRoom=other_chatRoom,
                                   content=content,
                                   seller=1)
        else:
            Message.objects.create(seller_chatRoom=other_chatRoom,
                                   buyer_chatRoom=chatRoom,
                                   content=content,
                                   seller=0)
        chatRoom.message_count = 0
        chatRoom.last_message = content
        other_chatRoom.message_count += 1
        other_chatRoom.last_message = content
        chatRoom.save()
        other_chatRoom.save()
        pushMessage = user.first_name + ':' + content
        if other_user.profile.device_type == 1:
            configure({'HOST': 'http://localhost:7077/'})
            provision(
                'univer',
                open('/home/projects/univer/univ/APNSWrapper/ck.pem').read(),
                'sandbox')
            notify('univer', other_user.profile.deviceToken, {
                'aps': {
                    'alert': pushMessage,
                    'badge': 10,
                    'sound': 'flynn.caf'
                }
            })
            return HttpResponse(str(chatRoom.id))
        elif other_user.profile.device_type == 2:
            API_KEY = 'AIzaSyBIoZYJ1mOKB8x32svoYCqCSeS4yEhxbQM'
            gcm = GCM(API_KEY)

            #            uni_title = user.first_name.decode('utf-8')
            uni_content = content.encode('utf-8')
            uni_name = user.first_name.encode('utf-8')
            ticker = uni_name + ':' + uni_content
            #            return HttpResponse(type(uni_content))
            #            ticker = user.first_name+':'+uni_content
            #            return HttpResponse(type(ticker))
            data = {
                'title': uni_name,
                'content': uni_content,
                'ticker': ticker
            }
            # Plaintext request
            reg_id = other_user.profile.deviceToken
            gcm.plaintext_request(registration_id=reg_id, data=data)
            # JSON request
            #            reg_ids = [reg_id]
            #            response = gcm.json_request(registration_ids=reg_ids, data=data)
            return HttpResponse('200')
        elif other_user.profile.device_type == 3:
            return HttpResponse('blackberry')
    elif request.method == 'PUT':
        return HttpResponse('put 요청입니다')
    elif request.method == 'DELETE':
        return HttpResponse('DELETE 요청입니다.')
    elif request.method == 'GET':
        return HttpResponse('get요청입니다.')
#!/usr/bin/env python3

from gcm import GCM

# Plain text request

API_KEY = "your api key"

gcm = GCM(API_KEY, debug=True)

registration_id = 'your push token'

data = {'param1': 'value1', 'param2': 'value2'}

response = gcm.plaintext_request(registration_id=registration_id, data=data)

print(response)
示例#55
0
# https://github.com/geeknam/python-gcm
import sys

from gcm import GCM

if __name__ == '__main__':
    gcm_token = sys.argv[1]
    device_id = sys.argv[2]

    gcm = GCM(gcm_token)
    data = {'message': 'hello'}
    reg_ids = [device_id]

    gcm.plaintext_request(registration_id=reg_ids, data=data)
示例#56
0
def sendGCM(to, type, data1, sid, qid):
    logging.log(logging.ERROR, 2)
    gcm = GCM('AIzaSyD6-BUFptIOpKNrFv-Lz-6EHuHv07Hwg90')
    data = {'type': type, 'data': data1, 'sid': sid, 'qid': qid}
    reg_id = to
    gcm.plaintext_request(registration_id=reg_id, data=data)