Exemple #1
0
 def __init__(self, bot, event):
     self.bot = bot
     self.event = event
     self.pusher = Pusher(
             app_id=config.APP_ID,
             key=config.KEY,
             secret=config.SECRET)
 def initPusher(self):
     self.pusher = Pusher(app_id=os.getenv('PUSHER_APP_ID', None), key=os.getenv('PUSHER_APP_KEY', None), secret=os.getenv('PUSHER_APP_SECRET', None), cluster=os.getenv('PUSHER_APP_CLUSTER', None))
     # инициализирую новый Pysher клиент передавая APP_KEY
     self.clientPusher = pysher.Pusher(os.getenv('PUSHER_APP_KEY', None), os.getenv('PUSHER_APP_CLUSTER', None))
     # Связываюсь с соеденением событием и передаю connectHandler в качестве обратного вызова
     self.clientPusher.connection.bind('pusher:connection_established', self.connectHandler)
     self.clientPusher.connect()
def file_download_task(data, user_id, host):
    no_of_files = len(data)
    d = []
    for i in range(no_of_files):
        file_name = str(i) + '.csv'
        file_path = str(settings.STATIC_ROOT) + file_name
        myfile = open(file_path, 'w+')
        wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
        if i == 0:
            heading = ["employee_name", "address"]
        else:
            heading = ["org_name", "org_address", "org_owner", "org_type"]
        wr.writerow(heading)
        for j in data[i]:
            wr.writerow(j.values())
        d.append('http://' + host + '/static/' + file_name)
    print(d)
    pusher = Pusher(app_id="690177",
                    key="d8672e8e8ba4f85cd510",
                    secret="c343542380b9410015da",
                    cluster="ap2")
    channel = "download_channel"
    event_data = {"files_path": d}
    pusher.trigger([
        channel,
    ], "download_event", event_data)
Exemple #4
0
    def render_to_response(self, context, **response_kwargs):

        channel = u"{model}_{pk}".format(model=self.object._meta.model_name,
                                         pk=self.object.pk)

        data = self.__object_to_json_serializable(self.object)

        try:
            pusher_cluster = settings.PUSHER_CLUSTER
        except AttributeError:
            pusher_cluster = 'mt1'

        pusher = Pusher(app_id=settings.PUSHER_APP_ID,
                        key=settings.PUSHER_KEY,
                        secret=settings.PUSHER_SECRET,
                        cluster=pusher_cluster)
        pusher.trigger([
            channel,
        ], self.pusher_event_name, {
            'object': data,
            'user': self.request.user.username
        })

        return super(PusherMixin,
                     self).render_to_response(context, **response_kwargs)
Exemple #5
0
class Plugin():
    def __init__(self, bus):
        self.bus = bus
        with open(CLIENT_SECRETS_FILE) as data_file:
            self.data = json.load(data_file)

        # self.log_events = ['people_start_playing', 'people_stop_playing',
        #                   'score_goal', 'win_game', 'set_players',
        #                   'score_reset','set_game_mode','start_game']

        # self.bus.subscribe(self.process_event, thread=True,subscribed_events=self.log_events)
        self.bus.subscribe(self.process_event, thread=True)

    def run(self):
        while True:
            time.sleep(1)

    def process_event(self, ev):
        if ev.data != None:
            d = ev.data
        else:
            d = {}
        self.pusher = Pusher(app_id=self.data['pusher']['app_id'],
                             key=self.data['pusher']['key'],
                             secret=self.data['pusher']['secret'])
        self.pusher.trigger(config.pusher_channel_out, ev.name, d)
Exemple #6
0
def pusher_auth(request):
    profile = ModelFactory.profile_from_request(request)

    log.debug('Pusher Auth called.')
    if request.method != 'POST':
        raise Http404('Unexpected method type for Pusher access.')

    p = Pusher(
    app_id=os.environ['PUSHER_APP_ID'],
        key=os.environ['PUSHER_APP_KEY'],
        secret=os.environ['PUSHER_APP_SECRET'],
        ssl=True,
        port=443
    )

    channel_name = request.POST.get('channel_name')
    socket_id = request.POST.get('socket_id')
    log.debug('Pusher Auth Channel_Name: {}'.format(channel_name))
    log.debug('Pusher Auth Socket ID: {}'.format(socket_id))
    data = {
        'user_id': str(profile.uuid),
        'user_info': {
            'name': profile.get_full_name(),
            'avatar_cropped_url': profile.avatar_cropped.url
        }
    }

    auth = p.authenticate(channel=channel_name, socket_id=socket_id, custom_data=data)
    return JsonResponse(auth)
Exemple #7
0
def sns_handler(request):

    messageType = request.META['HTTP_X_AMZ_SNS_MESSAGE_TYPE']
    parsed_body = json.loads(request.body)
    if messageType == "SubscriptionConfirmation":
        url = parsed_body["SubscribeURL"]
        serialized_data = urllib2.urlopen(url).read()
    elif messageType == "Notification":
        message = parsed_body["Message"]
        j_msg = json.loads(message)
        print(type(j_msg['coordinates']))
        print(j_msg['coordinates'])
        j_msg['coordinates'] = j_msg['coordinates']['coordinates']
        print(j_msg)
        message = str(json.dumps(j_msg))
        print(message)

        pusher_client = Pusher(app_id='xxx', key='xxx', secret='xxx', ssl=True)
        pusher_client.trigger('test_channel', 'my_event', {'message': message})

        es = Elasticsearch(['xxx'],
                           use_ssl=True,
                           verify_certs=True,
                           connection_class=RequestsHttpConnection)
        es.create(index="tweets", doc_type="tweet", body=j_msg)

    return HttpResponse('', status=200)
Exemple #8
0
    def __init__(self,
                 app_id,
                 key,
                 secret,
                 channel_name,
                 cluster=None,
                 encrypted=None):
        """Initializes the server object."""
        if cluster is None:
            cluster = 'mt1'

        if encrypted is None:
            encrypted = True

        self.pusher = Pusher(app_id,
                             key,
                             secret,
                             cluster=cluster,
                             ssl=encrypted)

        self.app_id = app_id
        self.key = key
        self.secret = secret
        self.channel_name = channel_name
        self.cluster = cluster
        self.encrypted = encrypted
        self.socket_id = u"1234.12"
        self.auth = self.join_channel()
Exemple #9
0
def pusher_info(sender, instance=None, created=False, **kwargs):
    pusher = Pusher(app_id=PUSHER_ID, key=PUSHER_KEY, secret=PUSHER_SECRET,
                    ssl=True)
    if created:
        if instance.group.channel:
            pusher.trigger(instance.group.channel, instance.group.event, {'message': instance.message})
        else:
            pusher.trigger(instance.group.channel, instance.group.event, {'message': instance.message})
Exemple #10
0
def receive_votes(request):
    pusher = Pusher(
        app_id=os.environ.get('PUSHER_APP', ''),
        key="ca2bcf928a3d000ae5e4",
        secret=os.environ.get('PUSHER_SECRET', '')
        )
    json_response = {"success": False}
    row = Voting.objects.get(pk=1)
    try:
        if request.method == "GET":
            data = request.GET
            if data["vote"] == "up":
                row.score = row.score + 1
                row.total_votes = row.total_votes + 1
                row.save()
                pusher.trigger(
                    "voting_channel",
                    "new_vote",
                    {"score": row.score}
                    )
                # success
                json_response = {"success": True}
                return HttpResponse(
                    json.dumps(json_response),
                    content_type="application/json"
                    )
            elif data["vote"] == "down":
                row.score = row.score - 1
                row.total_votes = row.total_votes + 1
                row.save()
                pusher.trigger(
                    "voting_channel",
                    "new_vote",
                    {"score": row.score}
                    )
                # success
                json_response = {"success": True}
                return HttpResponse(
                    json.dumps(json_response),
                    content_type="application/json"
                    )
            else:
                return HttpResponse(
                    json.dumps(json_response),
                    content_type="application/json"
                    )

        else:
            return HttpResponse(
                json.dumps(json_response),
                content_type="application/json"
                )
    except Exception as e:
        json_response = {"success": False, "error": str(e)}
        return HttpResponse(
            json.dumps(json_response),
            content_type="application/json"
            )
Exemple #11
0
 def initiate_pusher(self):
     self.pusher = Pusher(app_id=os.getenv('PUSHER_APP_ID', None),
                          key=os.getenv('PUSHER_APP_KEY', None),
                          secret=os.getenv('PUSHER_APP_SECRET', None),
                          cluster=os.getenv('PUSHER_APP_CLUSTER', None))
     self.client_pusher = pysher.Pusher(key=os.getenv('PUSHER_APP_KEY', None),
                                        cluster=os.getenv('PUSHER_APP_CLUSTER', None))
     self.client_pusher.connection.bind('pusher:connection_established', self.connection_manager)
     self.client_pusher.connect()
Exemple #12
0
 def initPusher(self):
     self.pusher = Pusher(app_id="PUSHER_APP_ID",
                          key="PUSHER_KEY",
                          secret="PUSHER_SECRET",
                          cluster="PUSHER_CLUSTER")
     self.clientPusher = pysher.Pusher("PUSHER_KEY", "PUSHER_CLUSTER")
     self.clientPusher.connection.bind('pusher:connection_established',
                                       self.connectHandler)
     self.clientPusher.connect()
    def handle(self, *args, **options):
        # Referenced https://pusher.com/docs/javascript_quick_start#/lang=python
        p = Pusher(app_id=settings.PUSHER_APP_ID,
                   key=settings.PUSHER_KEY,
                   secret=settings.PUSHER_SECRET)

        p.trigger(u'test_channel', u'my-event', {u'message': u'hello world'})

        self.stdout.write('Successful')
    def test_port_behaviour(self):
        conf = Pusher(app_id=u'4', key=u'key', secret=u'secret', ssl=True)
        self.assertEqual(conf.port, 443, u'port should be 443 for ssl')

        conf = Pusher(app_id=u'4', key=u'key', secret=u'secret', ssl=False)
        self.assertEqual(conf.port, 80, u'port should be 80 for non ssl')

        conf = Pusher(app_id=u'4', key=u'key', secret=u'secret', ssl=False, port=4000)
        self.assertEqual(conf.port, 4000, u'the port setting override the default')
Exemple #15
0
 def process_event(self, ev):
     if ev.data != None:
         d = ev.data
     else:
         d = {}
     self.pusher = Pusher(app_id=self.data['pusher']['app_id'],
                          key=self.data['pusher']['key'],
                          secret=self.data['pusher']['secret'])
     self.pusher.trigger(config.pusher_channel_out, ev.name, d)
Exemple #16
0
    def stopService(self):
        self.stopped = True
        for k in self.connects:
            c = self.connects[k]
            if c.pushclient is not None:
                c.pushclient.stop()
                c.pushclient = None

        Pusher.stopService(self)
Exemple #17
0
   def stopService(self):
      self.stopped = True
      for k in self.connects:
         c = self.connects[k]
         if c.pushclient is not None:
            c.pushclient.stop()
            c.pushclient = None

      Pusher.stopService(self)
Exemple #18
0
 def start_engine(self):
     self.pusher = Pusher(app_id=self.PUSHER_APP_ID,
                          key=self.PUSHER_APP_KEY,
                          secret=self.PUSHER_APP_SECRET,
                          cluster=self.PUSHER_APP_CLUSTER)
     self.clientPusher = pysher.Pusher(self.PUSHER_APP_KEY,
                                       self.PUSHER_APP_CLUSTER)
     self.clientPusher.connection.bind('pusher:connection_established',
                                       self.connectHandler)
     self.clientPusher.connect()
Exemple #19
0
def socketio_view(request):
	print "called"
	p = Pusher(
	  app_id='135314',
	  key='92e6deea4ee5542dc495',
	  secret='712204ca7293ef75bd11',
	  ssl=True,
	  port=443
	)
	p.trigger('test_channel', 'my_event', {'message': 'hello world'})
Exemple #20
0
    def __init__(self):
        connection = pymongo.MongoClient(settings['MONGODB_HOST'],
                                         settings['MONGODB_PORT'])
        db = connection[settings['MONGODB_DB']]
        self.collection = db[settings['MONGODB_COLLECTION']]

        if settings['PUSHER_ENABLED']:
            self.pusher = Pusher(app_id=settings['PUSHER_APP_ID'],
                                 key=settings['PUSHER_KEY'],
                                 secret=settings['PUSHER_SECRET'],
                                 ssl=True)
Exemple #21
0
def sendNotification(channel, message):
  if (PUSHER_URL != ''):
  
      pusher = Pusher(
      app_id=APP_ID, 
      key=PUSHER_KEY,
      secret=SECRET,
      cluster=CLUSTER,
      )

      pusher.trigger(channel, u'my-event', {u'message': message})
Exemple #22
0
    def startService(self):
        Pusher.startService(self)

        self.stopped = False
        self.connects = {}
        self.dbpool.runInteraction(self.recache)

        ## current statistics
        self.stats = {}
        self.stats[None] = self._createPushStat(None)
        self.publishPusherStats()
    def _publish(self, action):
        serializer = self.serializer_class(instance=self)
        data = serializer.serialize()

        pusher = Pusher(
            app_id=settings.PUSHER_APP_ID,
            key=settings.PUSHER_KEY,
            secret=settings.PUSHER_SECRET
        )

        pusher.trigger(self.channel_name, action, data)
Exemple #24
0
    def handle(self, *args, **options):
        message = ' '.join(options['message'])
        print(message)

        pusher = Pusher(
          app_id='121933',
          key='f1ebb516981a3315e492',
          secret='d9f31be884b8be02bcbc'
        )

        pusher.trigger('test_channel', 'my_event', {'message': message})
Exemple #25
0
   def startService(self):
      Pusher.startService(self)

      self.stopped = False
      self.connects = {}
      self.dbpool.runInteraction(self.recache)

      ## current statistics
      self.stats = {}
      self.stats[None] = self._createPushStat(None)
      self.publishPusherStats()
    def test_host_behaviour(self):
        conf = Pusher(app_id=u'4', key=u'key', secret=u'secret', ssl=True)
        self.assertEqual(conf.host, u'api.pusherapp.com', u'default host should be correct')

        conf = Pusher(app_id=u'4', key=u'key', secret=u'secret', ssl=True, cluster=u'eu')
        self.assertEqual(conf.host, u'api-eu.pusher.com', u'host should be overriden by cluster setting')

        conf = Pusher(app_id=u'4', key=u'key', secret=u'secret', ssl=True, host=u'foo')
        self.assertEqual(conf.host, u'foo', u'host should be overriden by host setting')

        conf = Pusher(app_id=u'4', key=u'key', secret=u'secret', ssl=True, cluster=u'eu', host=u'plah')
        self.assertEqual(conf.host, u'plah', u'host should be used in preference to cluster')
Exemple #27
0
def notify(request):
    if request.method == 'POST':
        pusher = Pusher(app_id=str(settings.PUSHER_APP_ID),
                        key=str(settings.PUSHER_KEY),
                        secret=str(settings.PUSHER_SECRET))
        pusher.trigger('test_channel', 'notification', {
            'message': 'First Notification',
        })
    context = {
        "title": 'Notification Manager',
    }
    return render(request, "manager/notification_manager.html", context)
Exemple #28
0
    def form_valid(self, form):
        message = form.cleaned_data['message']

        pusher = Pusher(
            app_id=settings.PUSHER_APP_ID,
            key=settings.PUSHER_KEY,
            secret=settings.PUSHER_SECRET,
        )

        pusher.trigger('test_channel', 'my_event', {'message': message})

        return HttpResponse()
    def __init__(self,
                 queue,
                 manager_dict,
                 app_id=DEFAULT_APP_ID,
                 key=DEFAULT_KEY,
                 secret=DEFAULT_SECRET,
                 cluster=DEFAULT_CLUSTER,
                 channel=DEFAULT_CHANNEL,
                 event=DEFAULT_EVENT,
                 observation_types=DEFAULT_OBSERVATION_TYPES,
                 post_interval=DEFAULT_POST_INTERVAL,
                 max_backlog=sys.maxint,
                 stale=60,
                 log_success=False,
                 log_failure=True,
                 timeout=DEFAULT_TIMEOUT,
                 max_tries=DEFAULT_MAX_TRIES,
                 retry_wait=DEFAULT_RETRY_WAIT):
        """
        Initializes an instance of PusherThread.

        :param app_id: The 'App ID' of your Pusher application.
        :param key: The 'key' of your Pusher application.
        :param secret: The 'secret' of your Pusher application.
        :param channel: The name of the channel to push the weather data to.
        :param event: The name of the event that is pushed to the channel.
        :param post_interval: The interval in seconds between posts.
        :param max_backlog: Max length of Queue before trimming. dft=sys.maxint
        :param stale: How old a record can be and still considered useful.
        :param log_success: Log a successful post in the system log.
        :param log_failure: Log an unsuccessful post in the system log.
        :param max_tries: How many times to try the post before giving up.
        :param timeout: How long to wait for the server to respond before fail.
        """
        super(PusherThread, self).__init__(queue,
                                           protocol_name='pusher',
                                           manager_dict=manager_dict,
                                           post_interval=post_interval,
                                           max_backlog=max_backlog,
                                           stale=stale,
                                           log_success=log_success,
                                           log_failure=log_failure,
                                           timeout=timeout,
                                           max_tries=max_tries,
                                           retry_wait=retry_wait)

        self.pusher = Pusher(app_id=app_id,
                             key=key,
                             secret=secret,
                             cluster=cluster)
        self.channel = channel
        self.event = event
        self.observation_types = observation_types
Exemple #30
0
 def initPusher(self):
     print(os.getenv('PUSHER_APP_ID', None))
     self.pusher = Pusher(app_id=os.getenv('PUSHER_APP_ID', None),
                          key=os.getenv('PUSHER_APP_KEY', None),
                          secret=os.getenv('PUSHER_APP_SECRET', None),
                          cluster=os.getenv('PUSHER_APP_CLUSTER', None))
     self.clientPusher = pysher.Pusher(
         os.getenv('PUSHER_APP_KEY', None),
         os.getenv('PUSHER_APP_CLUSTER', None))
     self.clientPusher.connection.bind('pusher:connection_established',
                                       self.connectHandler)
     self.clientPusher.connect()
Exemple #31
0
def scheduled_task():

    channel = "petfeed"
    event = "Need to add one later"

    pusherEvent = PusherEvent(app_id="440480",
                              key="0053280ec440a78036bc",
                              secret="7bbae18dfe3989d432a6",
                              cluster="mt1")
    try:
        #print("Inside scheduled task")
        while 1:
            today_day = datetime.now().strftime("%A")
            today_time = datetime.now().strftime("%H:%M:%S")
            print(today_day + ' ' + today_time)

            with connection.cursor() as cursor:
                query = "SELECT * FROM schedules WHERE day=%s AND time=%s"
                cursor.execute(query, (today_day, today_time))

                schedule = cursor.fetchone()
                if schedule is not None:
                    scheduled_time = today_time
                    #print("inside found schedule")
                    #break
                    # CALL THE DEVICE FEED FUNCTION THAT CONTROLS THE PI SERVO
                    device_feed()
                    user_id = schedule['user_id']

                    query = "SELECT DISTINCT email, id FROM users WHERE id = %s"
                    cursor.execute(query, user_id)

                    user = cursor.fetchone()

                    pusherEvent.trigger(
                        channel, event, {
                            'user': user['email'],
                            'status': 'success',
                            'data': {
                                'feeding_date': scheduled_time,
                                'user': user['email'],
                            }
                        })
            time.sleep(1)

    except:
        pusherEvent.trigger(
            channel, event, {
                'connection': 'global',
                'status': 'error',
                'message': 'Internal error occurred while reading schedule'
            })
Exemple #32
0
def save_read(sender, instance, created, raw, **kwargs):
    if not raw:
        if created:
            instance.user.num_unread_notis += 1
            instance.user.save()
            user = instance.user
            channel = "notification_" + user.user.username
            pusher = Pusher("216867", "df818e2c5c3828256440",
                            "5ff000997a9df3464eb5")

            serializer = A2AUserSerializer(user)
            event_data = serializer.data
            pusher.trigger(channel, 'new_noti', event_data)
Exemple #33
0
 def send_message(self, message):
     try:
         pusher_client = Pusher(app_id=self.channel.app_id,
                                key=self.channel.key,
                                secret=self.channel.secret,
                                cluster=self.channel.cluster,
                                ssl=True)
         channel_name = self.channel.channel_name
         event_name = self.event_name
         pusher_client.trigger(channel_name, event_name,
                               {'message': message})
     except:
         print('error in send message ')
Exemple #34
0
def save_read(sender, instance, created, raw, **kwargs):
    if not raw:
        if created:
            instance.user.num_unread_notis += 1
            instance.user.save()
            user = instance.user
            channel = "notification_" + user.user.username
            pusher = Pusher("216867", "df818e2c5c3828256440",
                            "5ff000997a9df3464eb5")

            serializer = A2AUserSerializer(user)
            event_data = serializer.data
            pusher.trigger(channel, 'new_noti', event_data)
Exemple #35
0
def remove_tentative_seat(request, movie_pk, seat_id):
    channel = u"movie_%s" % movie_pk

    pusher = Pusher(app_id=settings.PUSHER_APP_ID,
                    key=settings.PUSHER_KEY,
                    secret=settings.PUSHER_SECRET,
                    cluster=settings.PUSHER_CLUSTER)
    pusher.trigger([
        channel,
    ], 'add_tentative_seat', {
        'seat_id': seat_id,
    })
    destroy_tentative_seat(movie_pk, int(seat_id))
    return HttpResponse('')
Exemple #36
0
class Trigger():
    def __init__(self, bot, event):
        self.bot = bot
        self.event = event
        self.pusher = Pusher(
                app_id=config.APP_ID,
                key=config.KEY,
                secret=config.SECRET)

    def push(self, content):
        self.pusher.trigger(
                self.bot,
                self.event,
                { u'content' : content }
            )
Exemple #37
0
 def send(self, message_s):
     channelevent = self.channelevent
     try:
         pusher_client = Pusher(app_id=channelevent.channel.app_id,
                                key=channelevent.channel.key,
                                secret=channelevent.channel.secret,
                                cluster=channelevent.channel.cluster,
                                ssl=True)
         channel_name = channelevent.channel.channel_name
         event_name = channelevent.event_name
         pusher_client.trigger(channel_name, event_name,
                               {'message': message_s})
     except:
         print(self.channelevent.channel.channel_name)
         print('error in send message ')
Exemple #38
0
    def on_data(self, data):
        pusher = Pusher(
            app_id=u'',
            key=u'',
            secret=u''
        )

        temp_tokens = []

        if self.collection.count() == max_tweets:
            self.disconnect()

        data_dict = json.loads(data)
        self.collection.insert(json.loads(data))
        if 'retweeted_status' not in data_dict:
            text = data_dict['text']
            tweets = self.collection.count()

            encoded_text = text.encode('ascii', 'ignore').lower()
            temp_tokens.extend(regexp_tokenize(encoded_text, self.regex, gaps=False))
            filtered_tokens = [term for term in temp_tokens if not term in self.stop_words]

            num_tokens = len(filtered_tokens)
            print 'Tweet num: ' + str(self.collection.count()) + '\n' + encoded_text
            print 'Parsed and filtered: ' + str(filtered_tokens) + ' words'

            self.num_words += num_tokens

            print 'Total tokens: ' + str(self.num_words)

            self.tokens.extend(filtered_tokens)
            self.top_monograms = get_monograms_freqdist(self.tokens)
            self.top_bigrams = get_bigrams_freqdist(self.tokens)
            self.top_trigrams = get_trigrams_freqdist(self.tokens)

            colldata = get_dataframe_dict(self.top_monograms, 5, {}, tweets, self.collection)

            dataframe = colldata[0]
            labels = list(colldata[0].columns.values)
            # print str(time)
            print os.getcwd()

            # with open(os.getcwd() + '\wordstream\static\js\keywords.json', 'w') as outfile:
            #     json.dump(labels, outfile)

            pusher.trigger('my-channel', 'my-event', {
                'message': labels
            })
    def test_initialize_from_env(self):
        with mock.patch.object(os, 'environ', new={'PUSHER_URL':'https://*****:*****@somehost/apps/42'}):
            pusher = Pusher.from_env()
            self.assertEqual(pusher.ssl, True)
            self.assertEqual(pusher.key, u'plah')
            self.assertEqual(pusher.secret, u'bob')
            self.assertEqual(pusher.host, u'somehost')
            self.assertEqual(pusher.app_id, u'42')

        with mock.patch.object(os, 'environ', new={'PUSHER_DSN':'https://*****:*****@somehost/apps/42'}):
            pusher = Pusher.from_env('PUSHER_DSN')
            self.assertEqual(pusher.ssl, True)
            self.assertEqual(pusher.key, u'plah')
            self.assertEqual(pusher.secret, u'bob')
            self.assertEqual(pusher.host, u'somehost')
            self.assertEqual(pusher.app_id, u'42')
Exemple #40
0
 def __init__(self, **kwargs):
     self.client = Pusher(app_id=getattr(settings, 'PUSHER_APP_ID'),
                          key=getattr(settings, 'PUSHER_KEY'),
                          secret=getattr(settings, 'PUSHER_SECRET'),
                          host=getattr(settings, 'PUSHER_HOST', u'127.0.0.1'),
                          port=getattr(settings, 'PUSHER_SEND_PORT', 4567),
                          ssl=getattr(settings, 'PUSHER_SEND_USE_SSL', False),)
    def test_validate_webhook_bad_time(self):
        pusher = Pusher.from_url(u'http://*****:*****@host/apps/4')

        body = u'{"time_ms": 1000000}'
        signature = six.text_type(hmac.new(pusher.secret.encode('utf8'), body.encode('utf8'), hashlib.sha256).hexdigest())

        with mock.patch('time.time', return_value=1301):
            self.assertEqual(pusher.validate_webhook(pusher.key, signature, body), None)
    def test_initialize_from_url(self):
        self.assertRaises(TypeError, lambda: Pusher.from_url(4))
        self.assertRaises(Exception, lambda: Pusher.from_url(u"httpsahsutaeh"))

        conf = Pusher.from_url(u"http://*****:*****@host/apps/4")
        self.assertEqual(conf.ssl, False)
        self.assertEqual(conf.key, u"foo")
        self.assertEqual(conf.secret, u"bar")
        self.assertEqual(conf.host, u"host")
        self.assertEqual(conf.app_id, u"4")

        conf = Pusher.from_url(u"https://*****:*****@host/apps/4")
        self.assertEqual(conf.ssl, True)
        self.assertEqual(conf.key, u"foo")
        self.assertEqual(conf.secret, u"bar")
        self.assertEqual(conf.host, u"host")
        self.assertEqual(conf.app_id, u"4")
    def test_authenticate_for_private_channels(self):
        pusher = Pusher.from_url(u'http://*****:*****@host/apps/4')

        expected = {
            u'auth': u"foo:89955e77e1b40e33df6d515a5ecbba86a01dc816a5b720da18a06fd26f7d92ff"
        }

        self.assertEqual(pusher.authenticate(u'private-channel', u'345.23'), expected)
Exemple #44
0
  def put(self, request, filename="image.png", format=None):
    pusher = Pusher(app_id=u'160687', key=u'0eb2780d9a8a875c0727', secret=u'b45f1f052cd3359c9ceb')

    username = request.data['username']
    names_file = request.data['names_file']
    prices_file = request.data['prices_file']

    user = User.objects.get(username=username)
    new_receipt = user.receipt_set.create(
      names_image = names_file, 
      prices_image = prices_file
    )

    p1 = subprocess.Popen(['tesseract', new_receipt.names_image.path, 'stdout', '-psm', '6'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    names_file_ocr = p1.communicate()[0]

    p2 = subprocess.Popen(['tesseract', new_receipt.prices_image.path, 'stdout', '-psm', '6'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    prices_file_ocr = p2.communicate()[0]

    names_split = names_file_ocr.decode().split('\n')
    prices_split = prices_file_ocr.decode().split('\n')

    print(names_split)
    print(prices_split)

    names_split = [x for x in names_split if x != '']
    prices_split = [x for x in prices_split if x != '']

    print(names_split)
    print(prices_split)

    for i in range(0, len(names_split)):
      name = names_split[i]

      price = prices_split[i]
      strippedPrice = ''.join([c for c in price if c in '1234567890.'])

      new_receipt.receiptitem_set.create(
        name = name,
        price = Decimal(strippedPrice),
      )

      pusher.trigger(u'receipt_channel', u'new_receipt', { "username": username })

    return Response(status=204)
Exemple #45
0
def pushNotification(request,email,data,time,img,event):
    channel = u"customuser_{pk}".format(
        pk=email
    )
    pusher = Pusher(app_id=settings.PUSHER_APP_ID,
                    key=settings.PUSHER_KEY,
                    secret=settings.PUSHER_SECRET)
    event_data = {
        'object' : data,
        'user': request.user.email
    }
    if time != None:
        event_data.update({'time' : time,'img' : img})
    pusher.trigger(
        [channel,],
        event,
        event_data
    )
 def test_x_pusher_library_header(self):
     conf = Pusher.from_url(u'http://*****:*****@somehost/apps/4')
     req = Request(conf._pusher_client, u'GET', u'/some/obscure/api', {u'foo': u'bar'})
     self.assertTrue('X-Pusher-Library' in req.headers)
     pusherLib = req.headers['X-Pusher-Library']
     regex = r'^pusher-http-python \d+(\.\d+)+(rc\d+)?$'
     if sys.version_info < (3,):
         self.assertRegexpMatches(pusherLib, regex)
     else:
         self.assertRegex(pusherLib, regex)
    def test_validate_webhook_bad_signature(self):
        pusher = Pusher.from_url(u'http://*****:*****@host/apps/4')

        body = u'some body'
        signature = u'some signature'

        with mock.patch('time.time') as time_mock:
            self.assertEqual(pusher.validate_webhook(pusher.key, signature, body), None)

        time_mock.assert_not_called()
    def test_validate_webhook_bad_key(self):
        pusher = Pusher.from_url(u'http://*****:*****@host/apps/4')

        body = u'some body'
        signature = six.text_type(hmac.new(pusher.secret.encode(u'utf8'), body.encode(u'utf8'), hashlib.sha256).hexdigest())

        with mock.patch('time.time') as time_mock:
            self.assertEqual(pusher.validate_webhook(u'badkey', signature, body), None)

        time_mock.assert_not_called()
Exemple #49
0
 def __init__(self, bot, event, query, message):
     self.bot = bot
     self.event = event
     self.query = query
     self.message = message
     self.pusher = Pusher(
             app_id=u'144525',
             key=u'f87e45c335b6d8004e51',
             secret=u'37f03e68c7e0900fb045'
             )
Exemple #50
0
class PusherService(object):
    def __init__(self, **kwargs):
        self.client = Pusher(app_id=getattr(settings, 'PUSHER_APP_ID'),
                             key=getattr(settings, 'PUSHER_KEY'),
                             secret=getattr(settings, 'PUSHER_SECRET'),
                             host=getattr(settings, 'PUSHER_HOST', u'127.0.0.1'),
                             port=getattr(settings, 'PUSHER_SEND_PORT', 4567),
                             ssl=getattr(settings, 'PUSHER_SEND_USE_SSL', False),)

    def send(self, channel, event, **kwargs):
        return self.client.trigger(unicode(channel), unicode(event), kwargs)
Exemple #51
0
class Trigger():
    def __init__(self, bot, event, query, message):
        self.bot = bot
        self.event = event
        self.query = query
        self.message = message
        self.pusher = Pusher(
                app_id=u'144525',
                key=u'f87e45c335b6d8004e51',
                secret=u'37f03e68c7e0900fb045'
                )

    def push(self):
        self.pusher.trigger(
                self.bot,
                self.event,
                {
                    u'query' : self.query,
                    u'message' : self.message
                }
            )
Exemple #52
0
def main():
    if any(not value for value in (APP_KEY, APP_ID, APP_SECRET)):
        print('Please, configure the credentials for your PushJS app.')
        return

    pusher = Pusher(
        app_id=APP_ID,
        key=APP_KEY,
        secret=APP_SECRET,
        cluster=APP_CLUSTER,
    )

    while True:
        delay_secs = random.randint(DELAY_SECS_MIN, DELAY_SECS_MAX)
        time.sleep(delay_secs)

        user_message = {
            'message': random.choice(SENTENCES),
            'username': names.get_first_name(),
        }
        logger.info('Sending message: {}'.format(user_message))
        pusher.trigger(CHANNEL_NAME, 'user_message', user_message)
Exemple #53
0
    def render_to_response(self, context, **response_kwargs):

        channel = u"{model}_{pk}".format(
            model=self.object._meta.model_name,
            pk=self.object.pk
        )
        
        data = self.__object_to_json_serializable(self.object)
        
        pusher = Pusher(app_id=settings.PUSHER_APP_ID,
                        key=settings.PUSHER_KEY,
                        secret=settings.PUSHER_SECRET)
        pusher.trigger(
            [channel, ],
            self.pusher_event_name,
            {
                'object': data,
                'user': self.request.user.username
            }
        )

        return super(PusherMixin, self).render_to_response(context, **response_kwargs)
    def test_validate_webhook_bad_types(self):
        pusher = Pusher.from_url(u'http://*****:*****@host/apps/4')

        pusher.validate_webhook(u'key', u'signature', u'body')

        # These things are meant to be human readable, so enforcing being text is
        # sensible.

        with mock.patch('time.time') as time_mock:
            self.assertRaises(TypeError, lambda: pusher.validate_webhook(4, u'signature', u'body'))
            self.assertRaises(TypeError, lambda: pusher.validate_webhook(u'key', 4, u'body'))
            self.assertRaises(TypeError, lambda: pusher.validate_webhook(u'key', u'signature', 4))

        time_mock.assert_not_called()
    def test_get_signature_generation(self):
        conf = Pusher.from_url(u'http://*****:*****@somehost/apps/4')

        expected = {
            u'auth_key': u'key',
            u'auth_signature': u'5c49f04a95eedc9028b1e0e8de7c2c7ad63504a0e3b5c145d2accaef6c14dbac',
            u'auth_timestamp': u'1000',
            u'auth_version': u'1.0',
            u'body_md5': u'd41d8cd98f00b204e9800998ecf8427e',
            u'foo': u'bar'
        }

        with mock.patch('time.time', return_value=1000):
            req = Request(conf, u'GET', u'/some/obscure/api', {u'foo': u'bar'})
            self.assertEqual(req.query_params, expected)
Exemple #56
0
def sns_handler(request):
	
	messageType = request.META['HTTP_X_AMZ_SNS_MESSAGE_TYPE']
	parsed_body = json.loads(request.body)
	if messageType == "SubscriptionConfirmation":
		url = parsed_body["SubscribeURL"]
		serialized_data = urllib2.urlopen(url).read()
	elif messageType == "Notification":
		message = parsed_body["Message"]
		j_msg = json.loads(message)
		print (type(j_msg['coordinates']))
		print (j_msg['coordinates'])
		j_msg['coordinates'] = j_msg['coordinates']['coordinates']
		print(j_msg)
		message = str(json.dumps(j_msg))
		print(message)

		pusher_client = Pusher(
	  		app_id='xxx',
	  		key='xxx',
	  		secret='xxx',
	  		ssl=True
		)
		pusher_client.trigger('test_channel', 'my_event', {'message': message})
		
		es = Elasticsearch(
  			[
  			'xxx'
			  ],
			  use_ssl=True,
			  verify_certs=True,
			  connection_class = RequestsHttpConnection
		)
		es.create(index="tweets", doc_type="tweet", body=j_msg)
  			
	return HttpResponse('', status=200)
Exemple #57
0
    def init_app(self, app):
        app.config.setdefault('PUSHERAPP_ID', '')
        app.config.setdefault('PUSHERAPP_KEY', '')
        app.config.setdefault('PUSHERAPP_SECRET', '')

        self.pusher_client = Pusher(
            app_id=app.config['PUSHERAPP_ID'],
            key=app.config['PUSHERAPP_KEY'],
            secret=app.config['PUSHERAPP_SECRET'],
            ssl=True
        )

        if not hasattr(app, "extensions"):
            app.extensions = {}
        app.extensions['state_notifier'] = self
    def setUp(self):
        class JSONEncoder(json.JSONEncoder):
            def default(self, o):
                if isinstance(o, Decimal):
                    return str(o)
                return super(JSONEncoder, self).default(o)

        constants = {"NaN": 99999}

        class JSONDecoder(json.JSONDecoder):
            def __init__(self, **kwargs):
                super(JSONDecoder, self).__init__(parse_constant=constants.__getitem__)

        self.pusher = Pusher.from_url(u'http://*****:*****@somehost/apps/4',
                                      json_encoder=JSONEncoder,
                                      json_decoder=JSONDecoder)