Exemple #1
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)
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 #3
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 #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
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 #6
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"
            )
    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')
Exemple #8
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 #9
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})
    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 #11
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 #12
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 #13
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()
Exemple #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
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 sendNotification(channel, message):
    if (PUSHER_URL != ''):
        cluster = 'eu'

        secret = PUSHER_URL.replace('http://', '').split('@')[0].split(':')[1]
        app_id = PUSHER_URL.split('/apps/')[1]
        #print("key={} | secret={} | app_id={}".format(key, secret, app_id))

        pusher = Pusher(
            app_id=app_id,
            key=PUSHER_KEY,
            secret=secret,
            cluster=cluster,
        )

        pusher.trigger(channel, u'my-event', {u'message': message})
Exemple #23
0
class PusherProxy(object):
    """
    This class provides a wrapper to Pusher so that we can mock it or disable it easily
    """
    def __init__(self, *args, **kwargs):
        self._pusher = Pusher(*args, **kwargs)
        self._disabled = False

        if hasattr(settings, "DRF_MODEL_PUSHER_DISABLED"):
            self._disabled = settings.DRF_MODEL_PUSHER_DISABLED

    def trigger(self, channels, event_name, data):
        if self._disabled:
            return

        self._pusher.trigger(channels, event_name, data)
Exemple #24
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 #25
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 destroy_tentative_seat(movie_pk, seat_id):
    try:
        movie = Movie.objects.get(pk=movie_pk)
        movie.tentative_booked.remove(seat_id)
        movie.save()
        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,
        ], 'destroy_tentative_seat', {
            'seat_id': seat_id,
        })
    except Exception:
        pass
def tentative_to_booked(movie_pk, seats):
    seats = eval(seats)
    movie = Movie.objects.get(pk=movie_pk)
    movie.tentative_booked = [
        x for x in movie.tentative_booked if x not in seats
    ]
    movie.booked_seats.extend(seats)
    movie.save()
    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,
    ], 'tentative_to_booked', {
        'seats': seats,
    })
Exemple #28
0
def add_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,
    })
    movie = Movie.objects.get(pk=movie_pk)
    movie.tentative_booked.append(seat_id)
    movie.save()
    destroy_tentative_seat.apply_async(
        (movie_pk, int(seat_id)),
        countdown=settings.FREE_TENTATIVE_BOOKED_TIME)
    return HttpResponse('')
Exemple #29
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 #30
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 #31
0
class Sender:
    """Pusher send side logic."""
    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()

    def join_channel(self):
        """ Authenticates for the channel and return auth"""
        return self.pusher.authenticate(self.channel_name, self.socket_id)

    def send_message(self, event, message, channel=None):
        """Send an event to the channel"""
        if channel is None:
            channel = self.channel_name
        self.pusher.trigger(channel, event, message)
Exemple #32
0
class MongoDBPipeline(object):
    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)

    def process_item(self, item, spider):
        for data in item:
            if not data:
                raise DropItem('Missing data!')

        doc = self.collection.find_one({'url': item['url']})
        if doc == None:
            #self.collection.update({'url': item['url']}, dict(item), upsert=True)
            doc = {
                'url': item['url'],
                'title': item['title'],
                'status': item['status'],
                'crawled': item['crawled']
            }
            #html = response.body[:1024 * 256]
            self.collection.insert_one(doc)
            logging.debug("New document in MongoDB: %s" % doc['url'])

            if settings['PUSHER_ENABLED']:
                self.pusher.trigger(
                    'urls', 'new_url', {
                        'id': str(ObjectId(doc['_id'])),
                        'url': doc['url'],
                        'crawled': doc['crawled']
                    })

        return item
Exemple #33
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)
Exemple #34
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)
def send_pusher_event(signal,
                      sender,
                      instance,
                      channel,
                      event_name,
                      data,
                      socket_id=None,
                      **kwargs):
    """
    Send a pusher event from a signal
    """
    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], event_name, data)
Exemple #36
0
    def notify(self):
        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)

        #first, see if there are any users (if not, don't bother notifying)
        if not pusher.channel_info(self.channel(), ['occupied'])['occupied']:
            return

        pusher.trigger(
            [
                self.channel(),
            ],
            "update",
            {
                'object': self.get_state(),  #implemented in child class
            })
Exemple #37
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 #38
0
class Engine():
    def __init__(self, name, room, cls):
        self.cls = cls
        self.user = name
        self.chatroom = room
        self.known_users = []
        self.get_keys()

    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()

    def prepare_to_game(self):
        print('READY TO PLAY', self.chatroom, self.known_users)

    def agreed_handshake(self, by_who):
        self.cls.seed_number = randint(0, 100000)

        message = 'seed%{}'.format(self.cls.seed_number)
        self.pusher.trigger(self.chatroom, u'newmessage', {
            'user': self.user,
            'message': message,
            'service': True
        })

        message = '$connect%{}$'.format(by_who)
        self.pusher.trigger(self.chatroom, u'newmessage', {
            'user': self.user,
            'message': message,
            'service': True
        })
        self.cls.start_popup.dismiss()
        self.cls.connected(self.user, by_who)

    def close_chatroom(self):
        self.clientPusher.unsubscribe('search_room')

    def connectHandler(self, data):
        self.channel = self.clientPusher.subscribe(self.chatroom)
        self.channel.bind('newmessage', self.got_message)
        # saying hi to chatroom
        message = '$im_in$'
        self.pusher.trigger(self.chatroom, u'newmessage', {
            'user': self.user,
            'message': message,
            'service': True
        })

    def call_player(self, button):
        message = '$i_call%{}$'.format(button.text)
        self.pusher.trigger(self.chatroom, u'newmessage', {
            'user': self.user,
            'message': message,
            'service': True
        })

    def i_called(self, by_who):
        self.cls.handshake_popup(by_who)

    def check_if_service(self, message):

        if message['service'] == False:
            return False

        if message['user'] == self.user:
            return True
        else:
            if message['message'] == '$im_in$' and message[
                    'user'] not in self.known_users:
                self.known_users.append(message['user'])
                other_user = message['user']
                self.cls.ids.griddy.add_widget(
                    Button(text=other_user,
                           on_press=lambda x: self.call_player(x)))
                message = '$im_in$'
                self.pusher.trigger(self.chatroom, u'newmessage', {
                    'user': self.user,
                    'message': message,
                    'service': True
                })
                return True

            if message['message'] == '$im_in$' and message[
                    'user'] in self.known_users:
                return True

            if message['message'] == '$i_call%{}$'.format(self.user):
                self.i_called(message['user'])
                return True

            if message['message'] == '$connect%{}$'.format(self.user):
                self.cls.connected(self.user, message['user'])
                return True

            if message['message'].split('%')[0] == 'seed':
                self.cls.seed_number = int(message['message'].split('%')[1])
                return True

            if message['message'].split('%')[0] == 'damage':
                self.cls.got_hit(int(message['message'].split('%')[1]))

            if message['message'] == 'win':
                self.cls.current = 'win_screen'

            return False

    def got_message(self, message):
        print('I, ', self.user, ' recieved a message ', message)
        message = json.loads(message)

        if not self.check_if_service(message):
            print(message)

    def send_message(self, message):
        print('I want to send a message')
        self.pusher.trigger(self.chatroom, u'newmessage', {
            'user': self.user,
            'message': message,
            'service': True
        })
        print('I did it!', self.user)

    def get_keys(self):
        #with open("auth_key.json", "r") as f:
        #   keys = json.load(f)

        #self.auth_key = keys['auth_key']
        #self.url = keys['url']

        #self.PUSHER_APP_ID = keys['PUSHER_APP_ID']
        #self.PUSHER_APP_KEY = keys['PUSHER_APP_KEY']
        #self.PUSHER_APP_SECRET = keys['PUSHER_APP_SECRET']
        #self.PUSHER_APP_CLUSTER = keys['PUSHER_APP_CLUSTER']

        self.PUSHER_APP_ID = '853308'
        self.PUSHER_APP_KEY = "a7d3caa6f11e8e40b649"
        self.PUSHER_APP_SECRET = "9618775036978ef089a7"
        self.PUSHER_APP_CLUSTER = 'eu'
import serial, time, io
import redis
from pusher import Pusher

ser = serial.Serial('/dev/ttyUSB0', 9600)

# r = redis.StrictRedis(host='localhost', port=6379, db=0)
# p = r.pubsub()
pusher = Pusher(
    app_id=u'4',
    key=u'765ec374ae0a69f4ce44',
    secret=u'your-pusher-secret',
    host=u'localhost',
    port=4567,
    ssl=False,
)

while 1:
    serial_line = ser.readline()
    movement = serial_line.decode().strip('\r\n')
    print(movement)
    if movement:
        # r.publish('movement', '1')
        try:
            pusher.trigger(u'movement', u'movement-detected', {})
        except:
          pass

ser.close()
Exemple #40
0
    def run(self):
        print "Starting " + self.filename

        tags = callvisionapi(self.filename)

        dt = time.time() - watsonThread.lastaction_time
        print dt
        if(dt > 10):
            watsonThread.lastaction = "empty"
        watsonThread.lastaction_time = time.time()


        if ("scores" in tags["images"][0]):
            tag = tags["images"][0]["scores"][0]["name"]

            # optimization
            if (tag == "empty" and len(tags["images"][0]["scores"]) > 1):
                tag = tags["images"][0]["scores"][1]["name"]

            print json.dumps(tags["images"][0]["scores"])

            pusher = Pusher(
                app_id='185391',
                key='99c8766f736643bbdfa2',
                secret='68a32b237af4cb110394',
                cluster='eu',
                ssl=True
            )

            print("received tag: ")
            print(tag)

            if (tag != watsonThread.lastaction):
                if (tag == "empty"):
                    watsonThread.lastaction = "empty"
                elif (tag == "inside_fridge" or tag == "hand_empty"):

                    if (watsonThread.lastaction != "empty" and watsonThread.lastaction != "hand_empty" and watsonThread.lastaction != "inside_fridge"):
                        # ADDING PRODUCT INTO FRIDGE

                        with self.app.app_context():
                            prod = Product.query.filter_by(tag=watsonThread.lastaction).first()
                            if (prod != None):
                                prod.add(1)

                        with self.app.app_context():
                            allProds = Product.query.all()
                            productMap = {}
                            for product in allProds:
                                productMap[product.tag] = product.count

                        # notify UI
                        sendNotification()
                        notification = {'tag': watsonThread.lastaction, 'filename': watsonThread.productpicture,
                                        'name': 'nothing', 'action': 'add',
                                        'productMap': productMap}
                        pusher.trigger('messages', 'new_product', notification)

                    watsonThread.lastaction = "inside_fridge"

                else:
                    watsonThread.productpicture = self.filename
                    # PRODUCT
                    if (watsonThread.lastaction == "inside_fridge"):
                        # PRODUCT TAKEN FROM FRIDGE

                        with self.app.app_context():
                            prod = Product.query.filter_by(tag=tag).first()
                            if (prod != None and prod.count > 0):
                                prod.remove(1)

                        with self.app.app_context():
                            allProds = Product.query.all()
                            productMap = {}
                            for product in allProds:
                                productMap[product.tag] = product.count

                        # notify UI
                        sendNotification()
                        notification = {'tag': tag, 'filename': watsonThread.productpicture, 'name': 'nothing',
                                        'action': 'remove',
                                        'productMap': productMap}
                        pusher.trigger('messages', 'new_product', notification)

                    watsonThread.lastaction = tag

        print "Exiting " + self.filename
Exemple #41
0
if statement == 'red':
    comment_list = redditor.redditor()

    for comment in range(len(comment_list)):
        statement = comment_list[comment]
        X_test = tfidf.transform(np.array([statement]))
        predicted = clf.predict(X_test)
        prob = clf.predict_proba(X_test)
        print "Tweet: " + str(l)
        print statement
        print predicted, prob

X_test = tfidf.transform(np.array([statement]))
predicted = clf.predict(X_test)
prob = clf.predict_proba(X_test)
print "Tweet: " + str(l)
print statement
print predicted, prob
n_prob = str(prob[0][0])
p_prob = str(prob[0][1])
push.trigger(
    u'result_channel', u'result_event', {
        u'statement': statement,
        u'prediction': predicted.tolist(),
        u'probabilityn': n_prob,
        u'probabilityp': p_prob
    })

os.system("ruby script.rb")


fn = tfidf.get_feature_names()
stop = tfidf.get_stop_words()

if statement == 'red':
    comment_list = redditor.redditor()


    for comment in range(len(comment_list)):
        statement = comment_list[comment]
        X_test = tfidf.transform(np.array([statement]))
        predicted = clf.predict(X_test)
        prob = clf.predict_proba(X_test)
        print "Tweet: " + str(l)
        print statement
        print predicted, prob

X_test = tfidf.transform(np.array([statement]))
predicted = clf.predict(X_test)
prob = clf.predict_proba(X_test)
print "Tweet: " + str(l)
print statement
print predicted, prob
n_prob = str(prob[0][0])
p_prob = str(prob[0][1])
push.trigger(u'result_channel', u'result_event', {u'statement': statement, u'prediction': predicted.tolist(), u'probabilityn': n_prob, u'probabilityp': p_prob} )

os.system("ruby script.rb")
Exemple #43
0
from picamera import PiCamera
from time import sleep
from datetime import datetime
from pusher import Pusher

seconds_between_photos = 15
pusher_app_id = '<INSERT_YOUR_PUSHER_APP_ID_HERE>'
pusher_key = '<INSERT_YOUR_PUSHER_APP_KEY_HERE>'
pusher_secret = '<INSERT_YOUR_PUSHER_APP_SECRET_HERE>'
hostname =  '<INSERT_YOUR_NGROK_HTTPS_URL_HERE>'

camera = PiCamera()

pusher = Pusher(pusher_app_id, pusher_key, pusher_secret)

# If you need to rotate the camera
# camera.rotation = 180
camera.resolution = (640, 480)

while True:
    try:
        sleep(seconds_between_photos)
        date = datetime.now().strftime('%m-%d-%Y-%H:%M:%S')
        camera.annotate_text = date
        filename = '/photos/' + date + '.jpg'
        camera.capture('/var/www/html' + filename)
        url = hostname + filename
        pusher.trigger('photos', 'new_photo', {'url': url})
    except Exception as e:
        print ('Error:', e)
Exemple #44
0
def rest_messages(request):
    """
    :param request: Django Request Object
    :return: JsonResponse
    :raises: Http404 if not AJAX, not GET, invalid sender, invalid receiver
    Parameter Semantics:
        Must get Javascript Dates encoded by toISOString()
    """

    if request.method == 'POST':
        # The user is creating a message
        form = MessageForm(request.POST)

        log.debug('Message POSTed with parameters {}'.format(request.POST))

        # If this is an AJAX POST request.
        if request.is_ajax():
            log.debug('Message POST is AJAX, parsing JSON.')

            # This is submitted by MessageForm
            try:
                message = ModelFactory.parse(json.dumps(request.POST))
            except ValueError as e:
                raise Http404('Error while parsing JSON: {}'.format(str(e)))
            except AttributeError as e:
                raise Http404('AJAX without Payload: {}'.format(str(e)))


            log.debug('JSON parsed succesfully.  Saving.')

            message.save()

        # If this is a Form-based POST request with valid contents
        elif form.is_valid():
            log.debug('Message POST is form, parsing as Form object.')
            text = form.cleaned_data.get('text')
            sender = form.cleaned_data.get('sender')
            receiver = form.cleaned_data.get('receiver')
            language_code = form.cleaned_data.get('language_code')

            sender_profile = get_object_or_404(Profile, uuid=sender)
            receiver_profile = get_object_or_404(Profile, uuid=receiver)

            message = Message(
                sender=sender_profile,
                receiver=receiver_profile,
                text=text,
                language_code=language_code
            )

            log.debug('Form was valid.  Saving.')

            message.save()

        # If this is a Form-based POST request with invalid contents.
        else:
            # This is a Form-based POST request with invalid values.
            raise Http404('Invalid message: {}'.format(form.errors))

        log.debug('[Pusher] Initializing...')

        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,
        )
        try:
            p.trigger('{}-channel-{}'.format(settings.MACHINE_ROLE, message.sender.uuid), 'Message', message.to_serializable_dict())
            log.debug('[Pusher] Message to sender ({}) triggered successfully.'.format(message.sender))
            p.trigger('{}-channel-{}'.format(settings.MACHINE_ROLE, message.receiver.uuid), 'Message', message.to_serializable_dict())
            log.debug('[Pusher] Message to receiver ({}) triggered successfully.'.format(message.receiver))
        except (requests.exceptions.ConnectionError, requests.exceptions.ReadTimeout) as e:
            log.warning('Connection error at Pusher Message: {}'.format(e))

        return JsonResponse([message.to_serializable_dict()], safe=False)

    # This is a GET Request, seeking a message by uuid.
    else:

        log.debug('Messages requested with parameters: {}'.format(json.dumps(request.GET)))

        # Sender is implicit due to session key
        filter_fields = ['language_code', 'sender', 'receiver', 'uuid', 'bidirectional']

        # TODO Massive security vulnerability, must check who we are giving messages to

        if any([x not in filter_fields + ['date_to', 'date_from'] for x in request.GET.keys()]):
            raise Http404('Invalid GET Parameters.')

        p_date_from_str = request.GET.get('date_from', None)
        p_date_to_str = request.GET.get('date_to', None)

        filterdict = { k:v for k,v in request.GET.items() if k in filter_fields}

        # try:
        #     sender_uuid = ModelFactory.profile_from_request(request).uuid
        # except Http404:
        #     raise Http404('Could not ascertain sender in Message GET.')

        #filterdict['sender'] = sender_uuid

        # This is a nop filter, it might be replaced if there is a 'bidirectional' argument
        q = Q()

        # if bidirectional, then both sender and receiver necessary
        if request.GET.get('bidirectional', 'False').lower() == "true":
            if not ('sender' in request.GET and 'receiver' in request.GET):
                raise Http404('Invalid combination of bidirectional and sender+receiver parameters.')
            else:
                # Because there is no field called bidirectional
                filterdict.pop('bidirectional')
                # Because we will use Q, remove them from the ordinary filterdict
                sender = filterdict.pop('sender')
                receiver = filterdict.pop('receiver')
                # This will get all messages sent between these users
                q = Q(sender=sender, receiver=receiver) | Q(sender=receiver, receiver=sender)
        elif 'bidirectional' in request.GET:
            # Bidirectional was passed as a GET parameter, but was false
            filterdict.pop('bidirectional')

        # filterdict.update({'sender': str(profile.uuid)})
        # TODO Get sender and receiver messages

        if p_date_from_str:
            try:
                # p_date_from = datetime.datetime.strptime(p_date_from_str, '%Y-%m-%dT%H:%M:%S.%fZ%z')
                p_date_from = parser.parse(p_date_from_str.replace('Z', ''))
                filterdict.update({'date_time__gte': p_date_from})
                log.debug('Got date_from_str: {}'.format(p_date_from))
            except ValueError:
                log.debug('Received invalid datetime_from parameters: {}'.format(p_date_from_str))
                raise Http404('Invalid datetime parameters.')

        if p_date_to_str:
            try:
                #p_date_to = datetime.datetime.strptime(p_date_to_str, '%Y-%m-%dT%H:%M:%S.%fZ%z')
                p_date_to = parser.parse(p_date_to_str.replace('Z',''))
                filterdict.update({'date_time__lt': p_date_to})
                log.debug('Got date_to_str: {}'.format(p_date_to))
            except ValueError:
                log.debug('Received invalid datetime_to parameters: {}'.format(p_date_to_str))
                raise Http404('Invalid datetime parameters.')

        # Get Maximum PER_PAGE messages.  And get the largest (time) 10.
        # If bidirectional argument is not passed, q is a nop.
        filtered = Message.objects.filter(q).filter(**filterdict).order_by('date_time')[:PER_PAGE]

        response = list(map(lambda x: x.to_serializable_dict(), filtered))

        # Order of this list matters.
        return JsonResponse(response, safe=False)
Exemple #45
0
class ChatApp(App):
    app_opened = True
    pusher = None
    channel = None
    chatroom = None
    clientPusher = None
    user = None
    users = {"max": "1",
             "max2": '1',
             "sovilaz": "1"}
    sound_msg = SoundLoader.load('src/h.wav')
    friend = False

    def on_pause(self):
        self.app_opened = False
        return True

    def on_resume(self):
        self.app_opened = True
        return True

    def on_stop(self):
        if self.channel:
            message = '$im_out$'
            self.pusher.trigger(self.chatroom, u'newmessage', {'user': self.user, 'message': message})

        return True

    def build(self):
        return

    def login(self):
        if self.root.ids.nickname.text == '':
            self.popup('Sorry', 'Type your name!')
            return

        username = self.root.ids.nickname.text

        if username in self.users:
            self.user = username
        else:
            self.popup('Sorry', 'No such user')
            return

        self.chatroom = 'general'

        self.initPusher()

        self.root.current = 'chatroom'

    def initPusher(self):
        self.pusher = Pusher(app_id=PUSHER_APP_ID, key=PUSHER_APP_KEY, secret=PUSHER_APP_SECRET,
                             cluster=PUSHER_APP_CLUSTER)
        self.clientPusher = pysher.Pusher(PUSHER_APP_KEY, PUSHER_APP_CLUSTER)
        self.clientPusher.connection.bind('pusher:connection_established', self.connectHandler)
        self.clientPusher.connect()

    def connectHandler(self, data):
        self.channel = self.clientPusher.subscribe(self.chatroom)
        self.channel.bind('newmessage', self.pusherCallback)
        # saying hi to chatroom
        message = '$im_in$'
        self.pusher.trigger(self.chatroom, u'newmessage', {'user': self.user, 'message': message})

    def pusherCallback(self, message):
        message = json.loads(message)

        # check if it is a service message
        if message['user'] == self.user:
            if message['message'] == '$im_in$' or message['message'] == '$im_out$' or message['message'] == '$me_too$':
                return
        else:
            if message['message'] == '$im_in$':
                message = '[size=20sp][b][color=A9A9A9]Пользователь {} вошел в сеть[/color][/b][/size]'.format(
                    message['user'])
                self.root.ids.chat_logs.text += message + '\n'
                self.friend = True
                message = '$me_too$'
                self.pusher.trigger(self.chatroom, u'newmessage', {'user': self.user, 'message': message})
                return
            if message['message'] == '$im_out$':
                message = '[size=20sp][b][color=A9A9A9]Пользователь {} вышел из сети[/color][/b][/size]'.format(
                    message['user'])
                self.root.ids.chat_logs.text += message + '\n'
                self.friend = False
                return
            if message['message'] == '$me_too$':
                message = '[size=20sp][b][color=A9A9A9]Ваш собеседник в сети[/color][/b][/size]'
                self.root.ids.chat_logs.text += message + '\n'
                self.friend = True
                return

        if message['user'] != self.user:
            message = '[b][color=2980B9]{}:[/color][/b] {}'.format(message['user'], message['message'])
            self.root.ids.chat_logs.text += message + '\n'
            if self.app_opened:
                try:
                    self.sound_msg.play()
                except:
                    pass

        else:
            message = '[b][color=27db9f]{}:[/color][/b] {}'.format(message['user'], message['message'])
            self.root.ids.chat_logs.text += message + '\n'

    def outsender(self):
        message = self.root.ids.message.text
        try:
            self.pusher.trigger(self.chatroom, u'newmessage', {'user': self.user, 'message': message})
        except:
            self.popup('Sorry', 'No internet connection')
        self.root.ids.message.text = ''

    def send_msg(self):
        my_thread = threading.Thread(target=self.outsender)
        my_thread.start()

    def focus(self, out):
        if os.name != 'posix':
            if out.focus:
                self.root.ids.chatroom.pos_hint = {"center_x": .5, "center_y": .87}
            else:
                self.root.ids.chatroom.pos_hint = {"center_x": .5, "center_y": .5}

    def popup(self, title, text):
        popup = Popup(title=title,
                      content=Label(text=text),
                      size_hint=(0.65, 0.25))
        popup.open()
class PusherThread(RESTThread):
    """
    Thread for sending WeeWX weather data to Pusher.
    """

    DEFAULT_APP_ID = None
    DEFAULT_KEY = None
    DEFAULT_SECRET = None
    DEFAULT_CLUSTER = None
    DEFAULT_CHANNEL = None
    DEFAULT_EVENT = None
    DEFAULT_POST_INTERVAL = 5
    DEFAULT_TIMEOUT = 10
    DEFAULT_MAX_TRIES = 3
    DEFAULT_RETRY_WAIT = 5
    DEFAULT_OBSERVATION_TYPES = [
        'dateTime', 'barometer', 'inTemp', 'outTemp', 'inHumidity',
        'outHumidity', 'windSpeed', 'windDir', 'rain', 'rainRate'
    ]

    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

    def process_record(self, record, dbmanager):
        """Specialized version of process_record that pushes a message to Pusher."""

        # Convert the record to a dictionary
        _datadict = dict(record)

        # Check if there are any observations wanted that are not in the record
        for _observation in self.observation_types:
            if _observation not in _datadict:
                # Get the full record by querying the database ...
                record = self.get_record(record, dbmanager)
                syslog.syslog(
                    syslog.LOG_DEBUG,
                    "pusher: Observation '%s' not found in record. Filling record from database."
                    % _observation)
                break

        # ... convert to Metric if necessary ...
        metric_record = weewx.units.to_METRICWX(record)

        # Instead of sending every observation type, send only those in
        # the list obs_types
        abridged = dict(
            (x, metric_record.get(x)) for x in self.observation_types)

        packet = {}
        for k in abridged:
            packet[k] = abridged[k]

        # Try pushing the packet to Pusher up to max_tries times:
        for _count in range(self.max_tries):
            try:
                self.pusher.trigger(self.channel, self.event, packet)
                return
            except (pusher.errors.PusherError,
                    requests.exceptions.RequestException), e:
                self.handle_exception(e, _count + 1)
            time.sleep(self.retry_wait)
        else:
Exemple #47
0
class StateNotifier(object):


    def __init__(self, app=None, db=None):
        self.app = app
        self.db = db
        self._channel_mapper = lambda: None
        if app is not None:
            self.init_app(app)
        listen(self.db.engine, 'engine_connect', self.receive_engine_connect, named=True)

    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 channel_mapper(self, mapper_func):
        self._channel_mapper = mapper_func

    def get_channel(self):
        return self._channel_mapper()

    def notify_listeners(self, model=None, method=''):
        # print type(model).__name__, model.id, method
        channel = self.get_channel()
        if channel is None:
            return
        event = 'state_notifier'
        state = {}
        state['model'] = type(model).__name__;
        state['method'] = method
        if hasattr(model, 'id'):
            state['id'] = model.id
        if hasattr(model, 'rt_serialize'):
            state['object'] = model.rt_serialize
        elif hasattr(model, 'serialize'):
            state['object'] = model.serialize
        self.pusher_client.trigger(channel, event, state)

    def after_insert(self, **kw):
        self.notify_listeners(kw['target'], 'insert')

    def after_update(self, **kw):
        self.notify_listeners(kw['target'], 'update')

    def after_delete(self, **kw):
        self.notify_listeners(kw['target'], 'delete')

    def receive_engine_connect(self, **kw):

        def get_class_by_tablename(tablename):
            for c in list(self.db.Model._decl_class_registry.values()):
                if hasattr(c, '__tablename__') and c.__tablename__ == tablename:
                    return c

        for table in self.db.metadata.sorted_tables:
            table_class = get_class_by_tablename(table.fullname)
            if not table_class:
                continue
            if hasattr(table_class, '__notifier_skip__') and table_class.__rt_skip__ == True:
                continue
            listen(table_class, 'after_insert', self.after_insert, named=True);
            listen(table_class, 'after_update', self.after_update, named=True);
            listen(table_class, 'after_delete', self.after_delete, named=True);