Example #1
0
def pusher(year, run_number, uuid, settings, summary):
    try:
        import pusher
    except:
        # if pusher not installed, just return
        return
    import socket

    p = pusher.Pusher(app_id='90082',
                      key=settings['pusher']['key'],
                      secret=settings['pusher']['secret'])
    host = settings['pusher']['host']
    sim_output = host + summary.zone_indicator_file
    parcel_output = host + summary.parcel_indicator_file
    p['urbansim'].trigger(
        'simulation_year_completed', {
            'year': year,
            'region': settings['pusher']['region'],
            'run_number': run_number,
            'hostname': socket.gethostname(),
            'uuid': uuid,
            'time': time.ctime(),
            'sim_output': sim_output,
            'field_name': 'residential_units',
            'table': 'diagnostic_outputs',
            'scale': 'jenks',
            'parcel_output': parcel_output
        })
Example #2
0
 def savebid(self,  **kwargs):
     cr, uid, context, pool = request.cr, request.uid, request.context, request.registry
     product_id = int(kwargs['data'].get('product_id','0') or '0')
     bid_amount = float(kwargs['data'].get('bid_amount','0.0') or '0.0')
     stone_bid = pool.get('stone.bid.ept')
     values = {
               'partner_id':uid,
               'product_id':product_id,
               'bid_amount':bid_amount,
               }
     new_bid_id = stone_bid.create(cr,uid,values,context=context) 
     
     #load product by id
     product_data = pool.get('product.product').read(cr,uid,product_id,['default_code','stone_bid_ids'])
     
     #set current bid of product
     #set extended time
     #save product
     #get bid count
     
     args = {}
     args.update({'product_id':product_id})
     args.update({'product_sku':product_data.get('default_code','')})
     args.update({'bid_amount':bid_amount})
     args.update({'current_time':datetime.now().strftime("%Y-%m-%d %H:%M:%S")})
     args.update({'product_bid_count':len(product_data.get('stone_bid_ids',[]))})
     args.update({'is_extend_time':'false'})
     args.update({'extend_time':''})
     args.update({'message':'Bid Update:- Stone: ' + product_data.get("default_code",'')+' Bid: ' + str(bid_amount)})
     
     
     p = pusher.Pusher(app_id='78177', key='83c063b15546d28a09c6', secret='918d17f38096033549ca')
     p['ocentag_bid_channel'].trigger('bidevent', args)
Example #3
0
 def __init__(self, simu_name):
     # app_id/key/secret might be linked to user TBC
     self.app_id = '178867'
     self.key    = 'c2d255356f53779e6020'
     self.secret = '9d41a54d45d25274df63'
     self.pusher = pusher.Pusher(app_id=self.app_id,key=self.key,secret=self.secret,ssl=True,port=443)
     self.channel = simu_name
Example #4
0
def add_point(map_id):
    try:
        state = False

        # Data Validation
        coords = map(float, request.values['coords'].split(','))
        if len(coords) != 2 or abs(coords[0]) > 180 or abs(coords[1]) > 90:
            raise ValueError("Invalid coordinates %s" % coords)
        if len(request.values['data']) > settings.DATA_MAX_SIZE:
            raise ValueError("Data size over limit (%s)" % settings.DATA_MAX_SIZE)

        # Insert into database
        doc = {
            'id' : uuid4().hex,
            'map': map_id,
            'coords': coords,
            'data': request.values['data'],
            'classid': request.values['classid'],
            'timestamp': int(time.time()),
        }
        g.couch.save(doc)

        # Send to websocket !
        if settings.PUSHER_ID:
            p = pusher.Pusher()
            p['points-%s' % map_id].trigger('add', doc)
        state = True
    except (KeyError, ValueError), e:
        pass
Example #5
0
def push(channel, data, event='misc', expo=False):

    assert None not in [channel, event, data]

    from square1.utils.configuration import get_configuration
    import pusher

    c = get_configuration()

    # Send to web clients
    try:

        data[
            'icon'] = c.merchant_favicon_large.url if c.merchant_logo_large else ""

        pusher_client = pusher.Pusher(app_id=c.pusher_app_id,
                                      key=c.pusher_key,
                                      secret=c.pusher_secret,
                                      cluster=c.pusher_cluster,
                                      ssl=True)

        pusher_client.trigger(channel, event, data)
    except Exception as e:
        logger.error(e)
        pass

    # Send to mobile clients
    if expo:
        try:
            import requests, json
            from config.models import ModelKeyVal

            recipients = ModelKeyVal.objects.filter(
                key='expo_notification_token')
            chunks = [
                recipients[x:x + 100] for x in range(0, len(recipients), 100)
            ]

            for chunk in chunks:

                data = [{
                    'to': recipient.value,
                    'body': data['body'],
                    'title': data['title'],
                    'sound': 'default',
                    'badge': 1,
                    'data': data['extra_data']
                } for recipient in chunk]
                data = json.dumps(data)

                requests.post("https://exp.host/--/api/v2/push/send",
                              headers={
                                  'host': 'exp.host',
                                  'accept': 'application/json',
                                  'accept-encoding': 'gzip, deflate',
                                  'content-type': 'application/json'
                              },
                              data=data)
        except Exception as e:
            logger.error(e)
def pusher_auth(request):
    '''
    employers have only access to private-{{employer-email}} channels,
    employer-email should match the current user
    '''
    socket_id = request.POST['socket_id']
    channel_name = request.POST['channel_name']

    start_index = len('private-')
    employer_email = channel_name[start_index:]

    if request.user.email == employer_email:
        pusher_client = pusher.Pusher(
                app_id = settings.APP_ID,
                key = settings.APP_KEY,
                secret = settings.APP_SECRET,
                cluster = settings.APP_CLUSTER
            )

        auth = pusher_client.authenticate(
                channel = channel_name,
                socket_id = socket_id
            )
        return JsonResponse(auth)
    else:
        return HttpResponseForbidden()
Example #7
0
 def build_client(self, alias):
     connection = self[alias]
     client = pusher.Pusher(app_id=connection['app_id'],
                            key=connection['key'],
                            secret=connection['secret'],
                            cluster=connection['cluster'])
     return client
 def __init__(self):
     if os.path.exists("./data.json"):
         with open('data.json', 'r') as openfile:
             json_object = json.load(openfile)
             pusherID = json_object["pusherAppID"]
             pusherKey = json_object["pusherKey"]
             pusherSecret = json_object["pusherSecret"]
             pusherCluster = json_object["pusherCluster"]
     #start a logging handler so we can see the raw communication data
     root = logging.getLogger()
     root.setLevel(logging.INFO)
     ch = logging.StreamHandler(sys.stdout)
     root.addHandler(ch)
     #end logging
     self.pusher_server = pysher.Pusher(key=pusherKey,
                                        cluster=pusherCluster)
     self.pusher_server.connection.bind('pusher:connection_established',
                                        self.__connect_handler)
     self.pusher_server.connect()
     try:
         self.pusher_client = pusher.Pusher(app_id=pusherID,
                                            key=pusherKey,
                                            secret=pusherSecret,
                                            cluster=pusherCluster)
     except ValueError as err:
         print(
             "Pusher Connection Failed. Check Your Credentials!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
         )
     while True:
         # Do other things in the meantime here...
         time.sleep(1)
Example #9
0
    def __init__(self):
        # Not Sure if pusher.Pusher object is thread safe, so assume it isn't
        self.push_lock = Lock()

        self.push, self.key, self.secret, self.app_id = (None, None, None,
                                                         None)

        url = os.environ.get(
            'PUSHER_URL',
            'http://*****:*****@api.pusherapp.com/apps/137638'
        )

        match = re.search('https?://(\w+):(\w+)@[\w\./]*?(\d+)$', url)

        if not match:
            print "Can Not Initialize pusher!!"
            return

        self.key, self.secret, self.app_id = match.groups()

        print self.key, self.secret, self.app_id

        self.push = pusher.Pusher(app_id=self.app_id,
                                  key=self.key,
                                  secret=self.secret,
                                  ssl=True,
                                  port=443)
Example #10
0
def pusher_auth(request):
    """
    header:
        Authorization: Token ...
    params:
        channel_name
        socket_id
    return:
        channel_name
        socket_id
    """
    channel = request.POST['channel_name']
    try:
        if not channel.startswith("private-customer-"):
            raise AssertionError("Unknown channel requested " + channel)
        split = channel.split('-')
        if len(split) != 3:
            raise AssertionError("Unknown channel requested " + channel)
        customer = Customer.objects.get(user=request.user)
        channel_id = int(split[2])
        if customer.id != channel_id:
            raise AssertionError("Requested unauthorized channnel")

        pusher_client = pusher.Pusher(app_id=PUSHER_APP_ID,
                                      key=PUSHER_KEY,
                                      secret=PUSHER_SECRET,
                                      cluster=PUSHER_CLUSTER)

        payload = pusher_client.authenticate(
            channel=request.POST['channel_name'],
            socket_id=request.POST['socket_id'])

        return JsonResponse(payload)
    except (Customer.DoesNotExist, ValueError, AssertionError, IndexError) as e:
        return HttpResponseForbidden()
Example #11
0
 def criar_conecao(self):
     self.pusher_client = pusher.Pusher(app_id='1193493',
                                        key='be00d08867dbcda17eb3',
                                        secret='693bb2a1cba35d01c782',
                                        cluster='mt1',
                                        ssl=True)
     return self.pusher_client
    def push_notify (self, song):
		pusher_client = pusher.Pusher(
	  		app_id=os.environ.get('PUSHER_APP_ID', None),
	  		key=os.environ.get('PUSHER_KEY', None),
	  		secret=os.environ.get('PUSHER_SECRET', None)
	  		ssl=True
	)
Example #13
0
    def sendPusherNotification(self, data):

        print("******* Send notification")

        pusher_client = pusher.Pusher(app_id='1175747',
                                      key='1082958fa2c8f9f47aa2',
                                      secret='9c8a0fe23892937b97c4',
                                      cluster='eu',
                                      ssl=True)

        # receivedSample = json.loads(data['received'])

        # if 'messages' in data['url']:
        #      top5 = receivedSample[:5]
        #      for item in top5:
        #          item['body'] = '_body_removed_by_demo_center_'

        example = {
            'date': '2016-05-03',
            # 'account_id': receivedSample[0]['account_id'],
            'status_code': data['status'],
            'method': data['method'],
            'endpoint': data['url'],
            'type': data['type'],
            'time': str(datetime.datetime.now()),
            'duration': data['elapsed'],
            'sent': {
                "message_id": ["23k7cyy79qi8bdk0mknaxtkhl"]
            },
            # 'response': top5
        }

        pusher_client.trigger('my-channel', 'my-event', example)
Example #14
0
 def __init__(cls):
     self.bitcoind = rpc.Proxy()
     self.pusher_client = pusher.Pusher(app_id,
                                        key,
                                        secret,
                                        cluster=u'cluster')
     return cls
Example #15
0
 def __init__(self):
     self.pusher = pusher.Pusher(
         app_id=APP_ID,
         key=KEY,
         secret=SECRET,
         cluster=CLUSTER,
     )
def pusher_notification(channel, event, data):
    pusher_client = pusher.Pusher(app_id=settings.PUSHER_APP_ID,
                                  key=settings.PUSHER_KEY,
                                  secret=settings.PUSHER_SECRET,
                                  cluster=settings.PUSHER_CLUSTER,
                                  ssl=True)
    pusher_client.trigger(channel, event, data)
Example #17
0
 def leaveroom(self, var=None, **params):
     room = str(urllib.unquote(cherrypy.request.params['room']))
     user = str(urllib.unquote(cherrypy.request.params['user']))
     p = pusher.Pusher()
     p["presence-" + room].trigger('leave', {'user': user})
     deluser(room, user)
     return "ok"
Example #18
0
 def __init__(self):
     self.__pusher_client = pusher_client = pusher.Pusher(
         app_id=settings.PUSHER_APP_ID,
         key=settings.PUSHER_KEY,
         secret=settings.PUSHER_SECRET,
         cluster="us2",
         ssl=True)
Example #19
0
def trigger_pusher_event(channels, event, data):
    if not TESTING:
        pusher_client = pusher.Pusher(app_id=PUSHER_APP_ID,
                                      key=PUSHER_KEY,
                                      secret=PUSHER_SECRET,
                                      cluster=PUSHER_CLUSTER)
        pusher_client.trigger(channels, event, data)
Example #20
0
    def test_trigger_with_data_value_containing_percent(self):
        my_pusher = pusher.Pusher(app_id=test_config.app_id,
                                  key=test_config.app_key,
                                  secret=test_config.app_secret)
        channel = my_pusher['test-channel']
        result = channel.trigger('test-event', {'message': "fish %"})

        eq_(result, True)
Example #21
0
    def test_trigger(self):
        my_pusher = pusher.Pusher(app_id=test_config.app_id,
                                  key=test_config.app_key,
                                  secret=test_config.app_secret)
        channel = my_pusher['test-channel']
        result = channel.trigger('test-event', {'message': 'hello world'})

        eq_(result, True)
Example #22
0
def push_stats(pres_slug, poll_id):
  poll = Poll.objects.get(id=poll_id)
  if poll.live:
    print('Sending Stats', poll.id, poll.question)
    pusher_client = pusher.Pusher(**settings.PUSHER)
    pusher_client.trigger(pres_slug, 'stats', poll.json_data())

    push_stats.schedule((pres_slug, poll_id), delay=2)
Example #23
0
    def get(self):
        def callback(response):
            print "Callback run."

        p = pusher.Pusher()
        p['a_channel'].trigger('an_event', {'some': 'data'}, callback=callback)

        self.write("Hello, world")
Example #24
0
def pusher_server():
    return pusher.Pusher(pInfo["app_id"],
                         pInfo["key"],
                         pInfo["secret"],
                         cluster=pInfo["cluster"],
                         host=pInfo["host"],
                         port=pInfo["port"],
                         ssl=False)
Example #25
0
 def __init__(self):
     # load .env from current directory
     load_dotenv(dotenv_path=Path(
         os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')))
     self.client = pusher.Pusher(app_id=os.getenv('PUSHER_APP_ID'),
                                 key=os.getenv('PUSHER_KEY'),
                                 secret=os.getenv('PUSHER_SECRET'),
                                 cluster=os.getenv('PUSHER_CLUSTER'))
    def push(self, event, data):
        pusher_client = pusher.Pusher(app_id=settings.PUSHER_APP_ID,
                                      key=settings.PUSHER_KEY,
                                      secret=settings.PUSHER_SECRET,
                                      cluster=settings.PUSHER_CLUSTER,
                                      ssl=True)

        print(pusher_client.trigger('theater', event, data))
Example #27
0
def connect():
    return pusher.Pusher(
        app_id=settings.PUSHER_APP_ID,
        key=settings.PUSHER_API_KEY,
        secret=settings.PUSHER_SECRET_KEY,
        cluster=settings.PUSHER_CLUSTER,
        ssl=settings.PUSHER_SSL
    )
Example #28
0
 def __init__(self):
     print("Initializing the GarageOpener")
     GarageOpener.pusherClient = pusher.Pusher(
         app_id=GarageOpener.PUSHER_APP_ID,
         key=GarageOpener.PUSHER_KEY,
         secret=GarageOpener.PUSHER_SECRET,
         cluster=GarageOpener.PUSHER_CLUSTER,
         ssl=True)
Example #29
0
def send_log_signal(message):
    pusher_client = pusher.Pusher(
        app_id='280345',
        key='e64252df238c8822e820',
        secret='d9370b1a7f2571afa019',
        ssl=True
    )
    pusher_client.trigger('inventory', 'user-note', {'message': message})
Example #30
0
def bla(request):
    pusher_client = pusher.Pusher(app_id=settings.PUSHER_APP_ID,
                                  key=settings.PUSHER_KEY,
                                  secret=settings.PUSHER_SECRET,
                                  cluster=settings.PUSHER_CLUSTER)
    pusher_client.trigger(u'a_channel', u'an_event',
                          {u'some': u'you look nice'})
    return render(request, 'message.html', {'text': 'Message sent'})