Exemple #1
0
def main():
    global EXIT
    
    ##join with the tables
    hour_subscription=Subscriber()
    hour_subscription.subscribe('/topic/enrich/hour', 'join_hour', Listener(hour_subscription,hourly_action))
    day_subscription=Subscriber()
    day_subscription.subscribe('/topic/report/day', 'join_day', Listener(day_subscription,daily_action))
    while not EXIT:
        pass
Exemple #2
0
def do_subscribe(opts):
    LOGGER.info('Starting subscriber...')
    try:
        dsn = 'dbname={} user={} password={} host={} port={}'.format(
            opts.db_name, opts.db_user, opts.db_password, opts.db_host,
            opts.db_port)

        database = Database(dsn)
        database.connect()
        subscriber = Subscriber(opts.connect)
        subscriber.add_handler(get_events_handler(database))
        known_blocks = database.fetch_last_known_blocks(KNOWN_COUNT)
        known_ids = [block['block_id'] for block in known_blocks]
        subscriber.start(known_ids=known_ids)

    except KeyboardInterrupt:
        sys.exit(0)

    except Exception as err:  # pylint: disable=broad-except
        LOGGER.exception(err)
        sys.exit(1)

    finally:
        try:
            database.disconnect()
            subscriber.stop()
        except UnboundLocalError:
            pass

    LOGGER.info('Subscriber shut down successfully')
Exemple #3
0
    def add(self, msisdn, credit):
        sub = Subscriber()
        sms = SMS();
        try:
            mysub = sub.get(msisdn)
        except SubscriberException as e:
            raise CreditException(e)

        current_balance = sub.get_balance(msisdn)
        new_balance = Decimal(str(credit)) + Decimal(str(current_balance))

        # update subscriber balance
        try:
            cur = db_conn.cursor()
            cur.execute('UPDATE subscribers SET balance=%(new_balance)s WHERE msisdn=%(msisdn)s', {'new_balance': Decimal(str(new_balance)), 'msisdn': msisdn})
            sms.send(config['smsc'], msisdn, sms_credit_added % (credit, new_balance))
        except psycopg2.DatabaseError as e:
            raise CreditException('PG_HLR error updating subscriber balance: %s' % e)

        # insert transaction into the credit history
        try:
            cur = db_conn.cursor()
            cur.execute('INSERT INTO credit_history(msisdn,previous_balance,current_balance,amount) VALUES(%s,%s,%s,%s)', (msisdn, current_balance, new_balance, credit))
        except psycopg2.DatabaseError as e:
            db_conn.rollback()
            raise CreditException('PG_HLR error inserting invoice in the history: %s' % e)
        finally:
            db_conn.commit()
Exemple #4
0
 def app_input(self):
     from subscriber import Subscriber
     print("Went in the thread!")
     project_id = "pub-sub132608"
     subscriber = "sub_asdfjfdklsjdjdyebv_V-1"
     sub = Subscriber(project_id, subscriber, "")
     sub.start_server()
Exemple #5
0
def main():
    global EXIT
    subscription = Subscriber()
    subscription.subscribe('/queue/analytics/hour', 'report_',
                           Listener(subscription, action))
    while not EXIT:
        pass
Exemple #6
0
    def broadcast_to_all_subscribers(self, text, btype, location):
        sms_log.debug('Broadcast message to [%s], Location:%s' %
                      (btype, location))
        if location == "all":
            location = False
        sub = Subscriber()
        try:
            if btype == 'authorized':
                subscribers_list = sub.get_all_authorized(location)
            elif btype == 'unauthorized':
                subscribers_list = sub.get_all_unauthorized(location)
            elif btype == 'notpaid':
                subscribers_list = sub.get_all_notpaid(location)
            elif btype == 'extension':
                subscribers_list = sub.get_all_5digits()
            else:
                subscribers_list = []
        except NoDataException as ex:
            return False

        for mysub in subscribers_list:
            self.send(config['smsc'], mysub[1], text)
            time.sleep(1)
            sms_log.debug('Broadcast message sent to [%s] %s' %
                          (btype, mysub[1]))
Exemple #7
0
def get_subscriber(ws):
    if ws in subscribers:
        return subscribers.get(ws)
    else:
        sub = Subscriber(ws, app=app)
        subscribers[ws] = sub
        return sub
 def __init__(self, dbinfo=ct.DB_INFO, redis_host=None):
     self.dbinfo = dbinfo
     self.logger = getLogger(__name__)
     self.index_objs = dict()
     self.stock_objs = dict()
     self.combination_objs = dict()
     self.cal_client = CCalendar(dbinfo, redis_host)
     self.index_info_client = IndexInfo()
     self.comb_info_client = CombinationInfo(dbinfo, redis_host)
     self.stock_info_client = CStockInfo(dbinfo, redis_host)
     self.rindex_stock_data_client = RIndexStock(dbinfo, redis_host)
     self.industry_info_client = IndustryInfo(dbinfo, redis_host)
     self.rindustry_info_client = RIndexIndustryInfo(dbinfo, redis_host)
     self.limit_client = CLimit(dbinfo, redis_host)
     self.animation_client = CAnimation(dbinfo, redis_host)
     self.subscriber = Subscriber()
     self.quote_handler = StockQuoteHandler()
     self.ticker_handler = TickerHandler()
     self.connect_client = StockConnect(market_from=ct.SH_MARKET_SYMBOL,
                                        market_to=ct.HK_MARKET_SYMBOL,
                                        dbinfo=dbinfo,
                                        redis_host=redis_host)
     self.margin_client = Margin(dbinfo=dbinfo, redis_host=redis_host)
     self.emotion_client = Emotion(dbinfo=dbinfo, redis_host=redis_host)
     self.sh_exchange_client = StockExchange(ct.SH_MARKET_SYMBOL)
     self.sz_exchange_client = StockExchange(ct.SZ_MARKET_SYMBOL)
Exemple #9
0
 def deactivate_subscriptions(self, msg):
     try:
         sms = SMS()
         sub = Subscriber()
         cur = db_conn.cursor()
         cur.execute(
             'SELECT msisdn FROM subscribers WHERE subscription_status = 0 AND authorized = 1'
         )
         count = cur.rowcount
         if count > 0:
             self.logger.info('Found %d subscribers to be deactivated' %
                              count)
             subscribers_list = cur.fetchall()
             db_conn.commit()
             for mysub in subscribers_list:
                 self.logger.debug(
                     'Send SMS that account is deactivated to %s' %
                     mysub[0])
                 sms.send(config['smsc'], mysub[0], msg)
                 # disable subscriber
                 try:
                     sub.authorized(mysub[0], 0)
                 except SubscriberException as e:
                     raise SubscriptionException(
                         'PG_HLR error in deactivating subscription: %s' %
                         e)
         else:
             db_conn.commit()
             self.logger.info('No subscribers need to be deactivate')
     except psycopg2.DatabaseError as e:
         raise SubscriptionException(
             'PG_HLR error in checking subscriptions to deactivate: %s' % e)
Exemple #10
0
    def add_subscriber(self, name_, topics):
        j = 0
        name_found = False
        while j < len(self.subscribers):
            if name_ == self.subscribers.get(j).get_name():
                name_found = True
                break
            else:
                j += 1

        if not name_found:
            s = Subscriber(self.sub_id, name_)
            self.subscribers[s.get_id()] = s
            self.sub_id += 1

            i = 0
            while i < len(topics):
                if topics[i] not in self.topic_manager.topics:
                    self.topic_manager.add_sub(
                        s, self.topic_manager.create_topic(topics[i]))
                else:
                    self.topic_manager.add_sub(
                        s, self.topic_manager.find_topic(topics[i]))
                i += 1
            return s
        else:
            raise Exception(
                "There is already a subscriber named \'{0}\' registered to topics \'{1}\'!"
                .format(name_, topics))
Exemple #11
0
    def validate_data(self, pin):
        res_log.debug('Check PIN length')
        if len(pin) > 4 or len(pin) < 4:
            raise ResellerException('PIN invalid length')

        res_log.debug('Check if Reseller exists')
        # check if reseller exists in the database and the PIN is valid
        try:
            cur = db_conn.cursor()
            cur.execute(
                'SELECT msisdn,pin FROM resellers WHERE msisdn=%(msisdn)s',
                {'msisdn': str(self.reseller_msisdn)})
            if cur.rowcount > 0:
                res_log.debug('Valid Reseller found')
                res_log.debug('Auth PIN')
                data = cur.fetchone()
                if data[1] != pin:
                    raise ResellerException('Invalid PIN!')
                res_log.debug('Check if subscriber is valid')
                # check if subscriber exists
                try:
                    sub = Subscriber()
                    sub.get(self.subscriber_msisdn)
                except SubscriberException as e:
                    raise ResellerException('Invalid subscriber')

            else:
                raise ResellerException('Invalid Reseller')
        except psycopg2.DatabaseError as e:
            raise ResellerException(
                'Database error getting reseller msisdn: %s' % e)
Exemple #12
0
 def generate(self):
     cl = Sponsor(self.cfg, self.SponserName, self.befinciaryPlanName)
     allSponsersSubscribersEDIString = ''
     for i in range(self.generateCount):
         sponsorEDIString = cl.edi_string()
         sub = Subscriber(cl, self.ploicyId, self.effectiveDate,
                          self.minAge, self.maxAge)
         subscriberEDIString = sub.edi_string()
         dependentStringPresent = False
         if (self.addSpouse == "Yes"):
             # Spouse as a dependent
             dep = Dependent(sub, spouse=True)
             dependentEDIString = dep.edi_string()
             dependentStringPresent = True
         if (self.childrenCount > 0):
             for i in range(0, self.childrenCount):
                 if sub.age > 23:
                     dep = Dependent(sub)
                     if (dependentStringPresent):
                         dependentEDIString += dep.edi_string()
                     else:
                         dependentEDIString = dep.edi_string()
         if (self.childrenCount > 0 or self.addSpouse == "Yes"):
             subscriberEDIString = subscriberEDIString + dependentEDIString
         sponsorEDIString = sponsorEDIString.replace(
             '{SUBSCRIBER_DETAILS}', subscriberEDIString)
         sponsorEDIString = sponsorEDIString.replace(
             '{SECount}', str(len(sponsorEDIString.split('\n')) - 1))
         allSponsersSubscribersEDIString += sponsorEDIString
     GEEDIstring = self.edi_string.replace('{GECount}',
                                           str(self.generateCount))
     completeEDIString = GEEDIstring.replace(
         '{SPONSOR_DETAILS}', allSponsersSubscribersEDIString)
     self.saveFile(completeEDIString)
     return None
def main():
    global EXIT
    subscription = Subscriber()
    subscription.subscribe('/queue/source', 'clean',
                           Listener(subscription, action))
    while not EXIT:
        pass
    subscription.disconnect()
Exemple #14
0
 def handleBilling(self):
     sb = Subscriber(int(self.txtPhoneNumber.get('1.0', 'end-1c')))
     sms = sb.smsBill()
     originCall = sb.originCallBill()
     destCall = sb.destCallBill()
     text = '______Bill______\nSMS: %drub\nOutgoing Call: %drub\nIncoming Call: %drub\nTotal: %drub\n' \
         % (sms, originCall, destCall, sms+originCall+destCall)
     self.showContent('text', text)
Exemple #15
0
 def handleGetRecords(self):
     sb = Subscriber(int(self.txtPhoneNumber.get('1.0', 'end-1c')))
     table = [
         ['timestamp', 'msisdn_origin', 'msisdn_dest', 'call_duration', 'sms_number']
     ]
     for rc in sb.originRecords + sb.destRecords:
         table.append(rc.toStringArray())
     self.showContent('table', table)
Exemple #16
0
def get_subscriber():
    """Returns Subscriber instance connected to kafka consumer."""
    return Subscriber(
        topic=os.environ["TOPIC"],
        client_id=os.environ["CLIENT_ID"],
        group_id=os.environ["GROUP_ID"],
        auto_offset_reset="earliest",
        **get_kafka_connection_params(),
    )
Exemple #17
0
def setup_subscriber_requester(context):
    requester = Requester(context, ip, port)
    print("Requester ready")
    requester.send_string('SUB_PORT')
    sub_port = requester.recv_string()
    print(sub_port)
    subscriber = Subscriber(context, ip, sub_port)
    print("subscriber ready")
    return requester, subscriber
Exemple #18
0
def main():
    broker = Broker()
    subscriber = Subscriber()

    subscriber.connect_broker(broker)

    topics = ["1", "2", "3", "4", '5', '6', '7', '8', '9']

    subscriber.subscribe_to_topics(topics)
Exemple #19
0
    def onMessage(self, payload, isBinary):
        # echo back message verbatim

        message = json.loads(payload.decode('utf-8'))

        metadata = message.get('metadata')
        event = metadata.get('event')
        queue_name = metadata.get('queue_name')

        if event == "SUBSCRIBE":
            manager = SubscriptionManagerFactory.get_manager(queue_name)
            dependencies = metadata.get('dependencies', [])

            # also ensure all subscribers which this subscriber depends upon
            # are active

            subscriber = Subscriber(self, metadata)
            manager.add_subscription(subscriber)
            setattr(self, 'subscriber', subscriber)

            for subscriber_id in dependencies:
                parent = manager.get_subscriber(subscriber_id)
                if parent is None:
                    print("WARNING: ", "parent subscriber is not found")
                    continue
                print("Parent ", parent)
                parent.add_dependent(subscriber)

                subscriber.add_parent(parent)

            manager.status()

        if event == "PUBLISH":
            payload = message.get('message')
            msg_hash = MessageStore.add(payload)
            handler = MessageBufferHandlerFactory.get_handler(
                queue_name, self.factory.reactor)
            response = handler.handle_message(msg_hash)
            self.sendMessage(response.encode('utf-8'))

        if event == "REQUEST_MESSAGE":
            msg_hash = self.subscriber.get_message()
            message = MessageStore.get(msg_hash)

            payload = {
                'metadata': {
                    'message_hash': msg_hash,
                },
                'message_body': message
            }
            payload = json.dumps(payload)
            self.sendMessage(payload.encode('utf-8'))

        if event == "MESSAGE_PROCESSED_ACK":
            message_hash = metadata.get('message_hash')
            print("ACK received for message_hash", message_hash)
            self.subscriber.notify_dependents(message_hash)
Exemple #20
0
def create_subscribers(num):
    subscribers = []
    for i in range(num):
        subscriber = Subscriber()
        subscriber.name = fake.name()
        subscriber.phone = fake.phone_number()
        subscriber.email = fake.email()
        subscriber.address = fake.address()
        subscribers.append(subscriber)
    Subscriber.objects.insert(subscribers)
Exemple #21
0
 def run(self):
     syslog.syslog("fail2ban-zmq-tools Subscriber starting")
     signal.signal(signal.SIGTERM, self.__sigTERMhandler)
     signal.signal(signal.SIGINT, self.__sigTERMhandler)
     self.subscriber = Subscriber(subscriberconfig=subscriberconfig)
     self.subscriber.start()
     syslog.syslog("fail2ban-zmq-tools Subscriber running.\
                    Main process waiting for termination signal.\
                    Threads working.")
     signal.pause()
     syslog.syslog("fail2ban-zmq-tools Subscriber exiting.")
 def __init__(self, dbinfo):
     self.combination_objs = dict()
     self.stock_objs = dict()
     self.evt = AsyncResult()
     self.dbinfo = dbinfo
     self.cal_client = CCalendar(dbinfo)
     self.comb_info_client = CombinationInfo(dbinfo)
     self.stock_info_client = CStockInfo(dbinfo)
     self.delisted_info_client = CDelisted(dbinfo)
     self.animation_client = CAnimation(dbinfo)
     self.subscriber = Subscriber()
Exemple #23
0
def subscriber():
    URL = request.form['url']
    email = request.form['email']
    threshold = request.form['price']
    product = Subscriber(URL,email,threshold)
    err = product.subscribe()
    if err:
        message = err
    else:
        message = "Thanks for subscribing for updates on product on email-ID "+ email
    return render_template('thanks.html',message=message,url=URL)
Exemple #24
0
    def select_all_subscribers(self):
        query = 'SELECT * FROM `subscriber`;'
        cursor = self.__connection.cursor()

        subscribers = list()

        cursor.execute(query)
        for id, email, subscribed_date in cursor.fetchall():
            subscriber = Subscriber(email, id, subscribed_date)
            subscribers.append(subscriber)

        return subscribers
Exemple #25
0
def main():
    global EXIT
    subscription=Subscriber()
    subscription.subscribe('/queue/source', 'window', Listener(subscription,action))
    threads = []
    for i in range(4):
        t = threading.Thread(target=action)
        threads.append(t)
        t.start()
    while not EXIT:
        pass
    subscription.disconnect()
Exemple #26
0
 def __init__(self, mqueue, identifiers, start_time, end_time, frequency,
              timezone):
     PollingThread.__init__(self)
     self.__queue = mqueue
     self.__start_time = get_today_time(start_time)
     self.__end_time = get_today_time(end_time)
     self.__timezone = timezone
     self.__frequency = frequency
     self.__identifiers = identifiers
     self.__subscriber = Subscriber()
     self.__next_call_time = localnow(self.__timezone)
     self.__last_response_time = localnow(self.__timezone)
def test():
    from subscriber import Subscriber

    account = json.load(open("/var/lib/doublefault/account.json"))
    db = SettingDB(account["db-username"], account["db-password"], table_name="test")
    db.drop_table()
    db.create_table()

    db.put_user_data(Subscriber("user1", address="10.0001,10.0001"))
    db.put_user_data(Subscriber("user2", address="10.0002,10.0002"))
    db.put_user_data(Subscriber("user3", address="10.0003,10.0003"))
    db.put_user_data(Subscriber("user4", address="10.0004,10.0004"))
    db.put_user_data(Subscriber("user5", address="37 Wellington St., Arlington MA"))


    subsc = db.find_user("user1")
    print ("ID: {u.surrogateid}  address: {u.address}, coord: {u.coordinates.latitude},{u.coordinates.longitude}".format(u=subsc))

    db.put_user_data(Subscriber("user1", address="20.0001,20.0001"))

    for user in ["user1", "user2", "user3", "user4", "user5", "user6"]:
        subsc = db.find_user(user)
        if subsc:
            print ("ID: {u.surrogateid}  address: {u.address}, coord: {u.coordinates.latitude},{u.coordinates.longitude}".format(u=subsc))
            pass
        else:
            print ("no %s" % user)
            pass
        pass

    pass
Exemple #28
0
 def subscription_info(self):
     sub = Subscriber()
     unpaid = self.get_unpaid_subscriptions()
     print '---\n\n'
     for number in unpaid:
         print 'PostGres: ' + number[0] + ':'
         info = sub.print_vty_hlr_info(number)
         if "No subscriber found for extension" in info:
             print 'OsmoHLR: ' + info
             print "Checking for 5 digit extension"
             info = sub.print_vty_hlr_info(number[0][-5:])
         print 'OsmoHLR: ' + info
         print '---\n\n'
Exemple #29
0
    def send_subscription_fee_notice(self, msg):
        # get all subscribers
        try:
            sub = Subscriber()
            subscribers_list = sub.get_all()
        except SubscriberException as e:
            raise SubscriptionException('%s' % e)

        sms = SMS()

        for mysub in subscribers_list:
            self.logger.debug("Send sms to %s %s" % (mysub[1], msg))
            sms.send(config['smsc'], mysub[1], msg)
Exemple #30
0
def main():
    subscriber = Subscriber(project_id, subscription_name)
    subscription = subscriber.subscribe()

    while True:
        time.sleep(2)

        subscription.open(callback)
        logger.info("Open Subscriber")

        time.sleep(10)

        subscription.close()
        logger.info("Close Subscriber")