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)
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()
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()
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))
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)
def main(): global EXIT subscription = Subscriber() subscription.subscribe('/queue/analytics/hour', 'report_', Listener(subscription, action)) while not EXIT: pass
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)
def test_non_ascii_char(self): subscriber = Subscriber() subscriber.lastname = u'Toto°°' subscriber.issues_to_receive = 1 subscriber.save() line = get_first_line() self.assertTrue(line is not None)
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 __init__(self, sub_ip, sub_port, sub_topic, host, port): Subscriber.__init__(self, sub_port, sub_topic, sub_topic) self.address = (host, port) self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.isConnected = False self.img = None self.response = None
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)
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)
def test_email_in_lowercase(self): """Tests that in generated file, the emails are in lower case""" subscriber = Subscriber() subscriber.issues_to_receive = 0 subscriber.email_address = '*****@*****.**' subscriber.save() lines = self.export_and_get_lines() self.assertEqual('*****@*****.**', lines.strip())
def test_remaining_issues_subscriber(self): """Tests when the subscriber has remaining issues""" subs = Subscriber() subs.issues_to_receive = 1 subs.email_address = '*****@*****.**' subs.save() lines = self.export_and_get_lines() self.assertEqual('', lines)
def test_one_email(self): """Test retrieval of one subscriber's email""" subscriber = Subscriber() subscriber.issues_to_receive = 0 subscriber.email_address = '*****@*****.**' subscriber.save() lines = self.export_and_get_lines() self.assertEqual('*****@*****.**', lines.strip())
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)
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 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)
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()
class SubscriberTest(unittest.TestCase): def setUp(self): self.subscriber = Subscriber('asd', 'asd@asd') def test_get_id(self): self.assertEqual(-1, self.subscriber.get_id()) def test_get_name(self): self.assertEqual('asd', self.subscriber.get_name()) def test_get_email(self): self.assertEqual('asd@asd', self.subscriber.get_email())
def test_5_digit_post_code(self): """Checks that the exported post_code is always written with 5 digits, even if the first one is 0.""" sub = Subscriber() sub.issues_to_receive = 1 a = Address() a.post_code = 1300 sub.address = a sub.save() line = self.export_and_get_first_line() splitted_line = line.split('\t') self.assertEqual(splitted_line[8], '01300')
def set_regular_subscriber(self): sub = Subscriber() sub.lastname = 'Nom' sub.firstname = 'Prenom' sub.name_addition = 'NameAddition' a = Address() a.address1 = 'Adresse' a.address2 = 'Addition' a.post_code = 12345 a.city = 'Ville' sub.address = a return sub
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_null_post_code_format(self): """Test the postcode format when a null postcode is in db: 00000 is ugly""" sub = Subscriber() sub.lastname = 'toto' address = Address() address.post_code = 0 sub.address = address sub.save() dict_list = SubscriberAdapter.get_subscribers_from_lastname('toto') new_sub = dict_list[0] self.assertEquals('', new_sub['post_code'])
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)
def test_mail_sent_updated_special_issue(self): sub = Subscriber() sub.lastname = 'toto' sub.issues_to_receive = 0 sub.hors_serie1 = 0 sub.mail_sent = 1 sub.save() self.assertEqual(1, sub.mail_sent) sub.hors_serie1 = 1 sub.save() self.assertEqual(0, sub.mail_sent)
def test_two_email(self): """Tests when we have two emails in generated file""" subscriber = Subscriber() subscriber.email_address = '*****@*****.**' subscriber.issues_to_receive = 0 subscriber.save() subscriber = Subscriber() subscriber.email_address = '*****@*****.**' subscriber.issues_to_receive = 0 subscriber.save() lines = self.export_and_get_lines() self.assertEqual('[email protected]\[email protected]\n', lines)
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'
def test_empty_email(self): """Tests what appens when a subscriber has no email""" subscriber = Subscriber() subscriber.email_address = '*****@*****.**' subscriber.issues_to_receive = 0 subscriber.save() subscriber = Subscriber() subscriber.email_address = '' subscriber.issues_to_receive = 0 subscriber.save() lines = self.export_and_get_lines() self.assertEqual('[email protected]\n', lines)
def test_create_and_delete_subscriber(self): sub = Subscriber() sub.lastname = 'toto' sub.save() ident = sub.identifier SubscriberAdapter.delete_from_id(ident) actual_result_count = len( Subscriber.get_subscribers_from_lastname('toto') ) self.assertEqual(0, actual_result_count)
def test_subscriber_without_remaining_issue(self): """Test if a subscriber that has no issue left will not receive a free number :)""" subscriber = Subscriber() subscriber.lastname = 'toto' subscriber.issues_to_receive = 1 subscriber.save() subscriber = Subscriber() subscriber.lastname = 'tata' subscriber.issues_to_receive = 0 subscriber.save() self.exporter.do_export() self.__test_presence_toto_tata()
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'
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)
def test_field_length(self): """test if the fields in the output file does not exceed character limits""" big_string = ''.join(['b' for i in xrange(1, 40)]) subscriber = Subscriber() subscriber.lastname = big_string subscriber.firstname = big_string subscriber.company = big_string a = Address() a.address1 = big_string a.address2 = big_string a.post_code = 123456 a.city = big_string subscriber.address = a subscriber.issues_to_receive = 10 subscriber.save() line = self.export_and_get_first_line() splitted_line = line.split('\t') self.assertTrue(len(splitted_line[0]) <= 20) self.assertTrue(len(splitted_line[1]) <= 12) self.assertTrue(len(splitted_line[2]) <= 32) self.assertTrue(len(splitted_line[3]) <= 20) self.assertTrue(len(splitted_line[4]) <= 32) self.assertTrue(len(splitted_line[5]) <= 32) self.assertTrue(len(splitted_line[6]) <= 32) self.assertTrue(len(splitted_line[7]) <= 32) self.assertTrue(len(splitted_line[8]) <= 5) self.assertTrue(len(splitted_line[9]) <= 26) self.assertTrue(len(splitted_line[10]) <= 8) self.assertTrue(len(splitted_line[11]) <= 3) self.assertTrue(len(splitted_line[12]) <= 32) self.assertTrue(len(splitted_line[13]) <= 32) self.assertTrue(len(splitted_line[14]) <= 32) self.assertTrue(len(splitted_line[15]) <= 32)
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')
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")
def subscribe_status(self, server, source, target, command): target_nick = self.plugin.nick_extract(source) available = Subscriber.available_statuses() if not command: subscriber = self.wrapper.find_subscriber_with_nick(self.plugin.nick_extract(source)) if subscriber: self.plugin.privmsg(server, target_nick, 'current status: '\ + Subscriber.status_from_int(subscriber.status)) else: self.plugin.privmsg(server, target_nick, 'no subscription') elif command in available: self.wrapper.subscribe_status(target_nick, command) self.plugin.privmsg(server, target_nick, 'subscription status set to ' + command) else: self.plugin.privmsg(server, target_nick, 'invalid command')
def broadcast_to_all_subscribers(self, text, btype): sub = Subscriber() if btype == 'all': subscribers_list = sub.get_all() elif btype == 'notpaid': subscribers_list = sub.get_all_notpaid() elif btype == 'unauthorized': subscribers_list = sub.get_all_unauthorized() elif btype == 'extension': subscribers_list = sub.get_all_5digits() for mysub in subscribers_list: self.send(config['smsc'], mysub[1], text) sms_log.debug('Broadcast message sent to %s' % mysub[1]) time.sleep(1)
def subscribe_status(self, nick, status): nick = nick.lower() subscriber = self.find_subscriber_with_nick(nick) if subscriber: subscriber.update_status(status) else: subscriber = Subscriber(nick, Subscriber.status_from_string(status)) if hasattr(subscriber, 'eid'): self.subscriber_table.update(subscriber.to_dict(), eids=[subscriber.eid]) else: self.subscriber_table.insert(subscriber.to_dict()) self.subscriber_table.all() return subscriber
def add(self, msisdn, pin, balance): # check if subscriber exists try: sub = Subscriber() sub.get(msisdn) except SubscriberException as e: raise ResellerException('Invalid subscriber: %s' % e) # provision the reseller try: cur = db_conn.cursor() cur.execute('INSERT INTO resellers(msisdn,pin,balance) VALUES(%(msisdn)s,%(pin)s,%(balance)s)', {'msisdn': msisdn, 'pin': pin, 'balance': Decimal(str(balance))}) db_conn.commit() except psycopg2.DatabaseError as e: raise ResellerException('PG_HLR error provisioning reseller: %s' % e)
def setUp(self): '''Initialize the object and database''' self.sub = Subscriber() self.conn = sqlite3.Connection('../databases/test.db') self.cursor = self.conn.cursor() self.cursor.execute('DELETE FROM subscribers') self.conn.commit()
def test_end_of_subscribtion_list(self): self.sub.lastname = 'toto' self.sub.issues_to_receive = 1 self.sub.save() self.sub = Subscriber() self.sub.lastname = 'tata' self.sub.issues_to_receive = 0 self.sub.save() self.sub = Subscriber() self.sub.lastname = 'titi' self.sub.issues_to_receive = 10 self.sub.save() ending_sub_list = Subscriber.get_end_of_subscribtion() self.assertEqual(len(ending_sub_list), 2) self.assertEqual(ending_sub_list[0].lastname, 'toto') self.assertEqual(ending_sub_list[1].lastname, 'tata')
def get_subscriber(ws): if ws in subscribers: return subscribers.get(ws) else: sub = Subscriber(ws, app=app) subscribers[ws] = sub return sub
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)
def test_date(self): """Test the format of the date retrieved from the DB""" self.sub.lastname = 'toto' self.sub.subscription_date = datetime.date(2011, 3, 31) self.sub.save() sub = Subscriber.get_subscribers_from_lastname('toto')[0] actual_date = sub.subscription_date self.assertEqual(actual_date.strftime('%d/%m/%Y'), '31/03/2011')
def test_wrong_date(self): """Test what appens when we store a wrong date in the db and try to format it""" self.sub.lastname = 'toto' self.sub.subscription_date = datetime.date(211, 7, 31) self.sub.save() sub = Subscriber.get_subscribers_from_lastname('toto')[0] actual_date = sub.subscription_date
def add_subscriber_callback(self, arguments): list_id = int("".join(arguments)) name = input("name>") email = input("email>") subscriber = Subscriber(name, email) subscriber.save() self.db_path = sqlite3.connect("maillist.db") self.cursor = self.db_path.cursor() self.cursor.execute("""CREATE TABLE IF NOT EXISTS relations (list_id, subscriber_id)""") query = ("""INSERT INTO relations(list_id, subscriber_id) VALUES(?, ?)""") data = [list_id, subscriber.id] print(data) self.cursor.execute(query, data) self.db_path.commit() self.db_path.close()
def add_subscriber_credit(self, amount): res_log.info('Add %s to subscriber %s' % (amount, self.subscriber_msisdn)) try: sub = Subscriber() from credit import Credit, CreditException credit = Credit() res_log.debug('Get current subscriber balance') current_subscriber_balance = sub.get_balance(self.subscriber_msisdn) res_log.debug('Current subscriber balance: %s' % current_subscriber_balance) new_balance = Decimal(str(current_subscriber_balance)) + Decimal(str(amount)) res_log.debug('New balance: %s' % new_balance) credit.add(self.subscriber_msisdn, amount) self.subscriber_balance = new_balance except SubscriberException as e: raise ResellerException('Error getting subscriber balance: %s' % e) except CreditException as e: raise ResellerException('Error adding credit to subscriber: %s' % e)
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
def test_first_line(self): """Test if the first line of generated file is well written""" subs = Subscriber() subs.lastname = 'Debelle' subs.firstname = 'Anne' a = Address() a.address1 = 'rue dupre 63' a.address2 = 'Bruxelles 1090' a.city = 'belgique' subs.address = a subs.issues_to_receive = 1 subs.save() line = self.export_and_get_first_line() self.assertTrue(line is not None) splitted_line = line.split('\t') self.assertEquals(splitted_line[2], u'DEBELLE') self.assertEquals(splitted_line[3], u'ANNE') self.assertEquals(splitted_line[4], u'') self.assertEquals(splitted_line[5], u'') self.assertEquals(splitted_line[6], u'RUE DUPRE 63') self.assertEquals(splitted_line[7], u'BRUXELLES 1090') self.assertEquals(splitted_line[8], u'') self.assertEquals(splitted_line[9], u'BELGIQUE') self.assertEquals(splitted_line[10], u'') self.assertEquals(splitted_line[11], u'') self.assertEquals(splitted_line[12], u'') self.assertEquals(splitted_line[13], u'') self.assertEquals(splitted_line[14], u'') self.assertEquals(splitted_line[15], u'\n')
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
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(), )
def test_get_subs_address_by_lastname(self): """Tests address fields on dict retrieved by the adapter""" sub = Subscriber() sub.lastname = 'toto' address = Address() address.address1 = '42 rue truc' address.address2 = 'bat B' address.post_code = 38100 address.city = 'Paris' sub.address = address sub.save() dict_list = SubscriberAdapter.get_subscribers_from_lastname('toto') new_sub = dict_list[0] self.assertEquals('42 rue truc', new_sub['address']) self.assertEquals('bat B', new_sub['address_addition']) self.assertEquals('38100', new_sub['post_code']) self.assertEquals('Paris', new_sub['city'])
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
def rcv_signal(unique=None, publisher=None): while True: msg = unique.recv_json() if "action" in msg: if msg["action"] == "announcement": s = Subscriber(msg["state"], msg["id"], msg["file"], int(time.time()), msg["cfg"]) msg = {"status": "ok"} if s in subscribers: subscribers.remove(s) else: print("\nNovo trabalhador " + s.id + " online!\n") if not len(s.cfg): if len(cfg): s.cfg = cfg.pop(0) msg["cfg"] = s.cfg subscribers.append(s) unique.send_json(msg) elif msg["action"] == "done": f_name = msg["f_name"] if f_name in files and len(msg["results"]): print("\nArquivo de senha " + f_name + " quebrado!\n") files.remove(f_name) f = open("resultados.txt", "a+") f.write(f_name + "\n") f.write(msg["data"] + "\n") f.write(msg["results"] + "\n\n") f.close() msg = {"action": "stop", "f_name": f_name} publisher.send_json(msg) msg = {"status": "ok"} unique.send_json(msg) else: msg = {"status": "ok"} unique.send_json(msg)
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]))
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
def add(self, msisdn, pin, balance): # check if subscriber exists try: sub = Subscriber() sub.get(msisdn) except SubscriberException as e: raise ResellerException('Invalid subscriber: %s' % e) # provision the reseller try: cur = db_conn.cursor() cur.execute( 'INSERT INTO resellers(msisdn,pin,balance) VALUES(%(msisdn)s,%(pin)s,%(balance)s)', { 'msisdn': msisdn, 'pin': pin, 'balance': Decimal(str(balance)) }) db_conn.commit() except psycopg2.DatabaseError as e: raise ResellerException('PG_HLR error provisioning reseller: %s' % e)
class f2bSubscriberDaemon(daemon): def __sigTERMhandler(self, signum, frame): syslog.syslog("fail2ban-zmq-tools Subscriber: Caught signal %d.\ Initiating shutdown..." % signum) self.quit() 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 quit(self): signal.signal(signal.SIGTERM, signal.SIG_IGN) syslog.syslog("fail2ban-zmq-tools Subscriber: Stopping threads...") self.subscriber.join()