Beispiel #1
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()
Beispiel #2
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)
class Analytics(object):
    def __init__(self):
        self.sms = SMS()
        self.greenbutton = GreenButton()
        self.duration = 60 * 24 * 3600
        self.start = int(time.time()) - 24 * 3600 - self.duration

    def run(self, user_id):
        user = db.User.get(db.User.id == user_id)
        xml = self.greenbutton.getUsagePointData(user.token, self.start, self.duration)

        soup = BeautifulSoup(xml)

        # Locate the data we care about
        blocks = []
        for entry in soup.find_all('entry'):
            if entry.content and entry.content.find('ns2:intervalblock'):
                blocks = entry.content.find_all('ns2:intervalblock')

        # Group the data by weekday and by hour
        raw = {}
        for block in blocks:
            readings = block.find_all('ns2:intervalreading')
            for reading in readings:
                dt = datetime.fromtimestamp(int(reading.find('ns2:timeperiod').find('ns2:start').get_text()))
                weekday = dt.weekday()
                if weekday not in raw:
                    raw[weekday] = {}
                if dt.hour not in raw[weekday]:
                    raw[weekday][dt.hour] = []
                raw[weekday][dt.hour].append(int(reading.find('ns2:cost').get_text()))

        # Determine the average for each hour on each weekday
        averages = {}
        for weekday in raw.keys():
            averages[weekday] = {}
            for hour in raw[weekday].keys():
                averages[weekday][hour] = sum(raw[weekday][hour]) / len(raw[weekday][hour])

        # Find the peak for whichever weekday tomorrow is
        tomorrow = datetime.today() + timedelta(days=1)
        weekday = (tomorrow.weekday() + 1) % 7
        today_averages = averages[weekday]
        peak_cost = 0
        peak_hour = 0
        for hour in today_averages.keys():
            if today_averages[hour] > peak_cost:
                peak_cost = today_averages[hour]
                peak_hour = hour

        # Send that peak to the user's phone
        message = 'Welcome to Spring Gauge! Your peak usage on %ss is at %s%s. Try turning off some lights at that time.'
        peak = datetime(tomorrow.year, tomorrow.month, tomorrow.day, peak_hour)
        self.sms.send(user.phone, message % (tomorrow.strftime('%A'), int(peak.strftime('%I')), peak.strftime('%p')))

        return {'status': 'success'}
Beispiel #4
0
    def send_subscription_fee_reminder(self, msg):
        try:
            subscribers_list = self.get_unpaid_subscriptions()
        except SubscriptionException as e:
            raise SubscribtionException('ERROR in getting unpaid subscriptions')

        sms = SMS()
        
        for mysub in subscribers_list:
            self.logger.debug("Send sms to %s %s" % (mysub[0], msg))
            sms.send(config['smsc'],mysub[0], msg)
Beispiel #5
0
    def send_subscription_fee_reminder(self, msg):
        try:
            subscribers_list = self.get_unpaid_subscriptions()
        except SubscriptionException as e:
            raise SubscribtionException(
                'ERROR in getting unpaid subscriptions')

        sms = SMS()

        for mysub in subscribers_list:
            self.logger.debug("Send sms to %s %s" % (mysub[0], msg))
            sms.send(config['smsc'], mysub[0], msg)
Beispiel #6
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)
Beispiel #7
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)
Beispiel #8
0
def check_reservations(driver, months, days, times_checked):
    try:
        # Go to reservations and pull up whistler
        reservations_page = "https://www.epicpass.com/plan-your-trip/lift-access/reservations.aspx"
        driver.get(reservations_page)

        resort_selector_id = "PassHolderReservationComponent_Resort_Selection"
        whistler_selector_value = '80'
        check_availability_button_id = "passHolderReservationsSearchButton"

        WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.ID, resort_selector_id)))
        select = Select(driver.find_element_by_id(resort_selector_id))
        select.select_by_value(whistler_selector_value)
        WebDriverWait(driver, 20).until(
                EC.presence_of_element_located((By.ID, check_availability_button_id)))
        check_availability_button = driver.find_element_by_id(check_availability_button_id)
        driver.execute_script("arguments[0].click();", check_availability_button)

        # Get correct month
        # TODO

        # Check for days
        calendar_div_xpath = "//div[@class='passholder_reservations__calendar__days']"
        WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, calendar_div_xpath)))
        time.sleep(1)
        calendar_el = driver.find_element_by_xpath(calendar_div_xpath)
        day_els = calendar_el.find_elements_by_tag_name("button")

        for day_el in day_els:
            if not day_el.get_attribute('disabled'):
                if day_el.text in days:
                    print("Times Checked: %s" % times_checked)
                    print("%s %s is now available!" % (month, day_el.text))
                    print("Found result at %s" % datetime.now().time())
                    if book_day(day_el, driver):
                        sms = SMS(config.phone_number, config.phone_carrier,
                                config.email_address, config.email_password)
                        sms.send("%s %s was attempted to be booked at Whistler Blackcomb.\n" \
                                "Please look for a confirmation email shortly." % (
                                month, day_el.text), "Reservation Found")
                        sys.exit()
                    else:
                        print("Error booking day")

        print("Times Checked: %s" % times_checked, end='\r')
    except TimeoutException:
        traceback.print_exc()
        print("Will try again...")
    finally:
        time.sleep(config.refresh_frequency_seconds)
Beispiel #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')
         count = cur.rowcount
         if count > 0:
             self.logger.info('Found %d subscribers to be deactivated' % count)
             subscribers_list = cur.fetchall()
             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:
             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)
Beispiel #10
0
def sign_up(update: Update, context: CallbackContext) -> None:
    person = update.message.from_user
    phone = unidecode.unidecode(update.message.text)

    print("Phone of {}: {}".format(person.first_name, phone))
    keyboard = [[
        InlineKeyboardButton("📥ارسال مجدد", callback_data='retry'),
        InlineKeyboardButton("↩️بازگشت", callback_data='account')
    ]]
    reply_markup = InlineKeyboardMarkup(keyboard)
    update.message.reply_text("پس از دریافت پیامک کد تایید وارد نمایید: ",
                              reply_markup=reply_markup)
    sms_api = SMS()
    code = sms_api.send(update.message.text)
    context.user_data['v_code'] = code
    context.user_data['phone'] = phone
    return FIFTH
Beispiel #11
0
class Analytics(object):
    def __init__(self):
        self.sms = SMS()
        self.greenbutton = GreenButton()
        self.duration = 60 * 24 * 3600
        self.start = int(time.time()) - 24 * 3600 - self.duration

    def run(self, user_id):
        user = db.User.get(db.User.id == user_id)
        xml = self.greenbutton.getUsagePointData(user.token, self.start,
                                                 self.duration)

        soup = BeautifulSoup(xml)

        # Locate the data we care about
        blocks = []
        for entry in soup.find_all('entry'):
            if entry.content and entry.content.find('ns2:intervalblock'):
                blocks = entry.content.find_all('ns2:intervalblock')

        # Group the data by weekday and by hour
        raw = {}
        for block in blocks:
            readings = block.find_all('ns2:intervalreading')
            for reading in readings:
                dt = datetime.fromtimestamp(
                    int(
                        reading.find('ns2:timeperiod').find(
                            'ns2:start').get_text()))
                weekday = dt.weekday()
                if weekday not in raw:
                    raw[weekday] = {}
                if dt.hour not in raw[weekday]:
                    raw[weekday][dt.hour] = []
                raw[weekday][dt.hour].append(
                    int(reading.find('ns2:cost').get_text()))

        # Determine the average for each hour on each weekday
        averages = {}
        for weekday in raw.keys():
            averages[weekday] = {}
            for hour in raw[weekday].keys():
                averages[weekday][hour] = sum(raw[weekday][hour]) / len(
                    raw[weekday][hour])

        # Find the peak for whichever weekday tomorrow is
        tomorrow = datetime.today() + timedelta(days=1)
        weekday = (tomorrow.weekday() + 1) % 7
        today_averages = averages[weekday]
        peak_cost = 0
        peak_hour = 0
        for hour in today_averages.keys():
            if today_averages[hour] > peak_cost:
                peak_cost = today_averages[hour]
                peak_hour = hour

        # Send that peak to the user's phone
        message = 'Welcome to Spring Gauge! Your peak usage on %ss is at %s%s. Try turning off some lights at that time.'
        peak = datetime(tomorrow.year, tomorrow.month, tomorrow.day, peak_hour)
        self.sms.send(
            user.phone,
            message % (tomorrow.strftime('%A'), int(
                peak.strftime('%I')), peak.strftime('%p')))

        return {'status': 'success'}
Beispiel #12
0
class Bot:
    """The main class"""

    def __init__(self, remote_addr = '', output_dir = '/var/log/bot'):
#        self.active = False
        self.terminated = False
        self.remote_addr = remote_addr
        self.output_dir = output_dir
        self.emergencyAddress = '*****@*****.**'
        
    def start(self, data_dict):

        data = trackingData.TrackingData()
        data.loadFromDict(data_dict)
        data.ip_addr = self.remote_addr
        data.script = os.path.dirname(os.path.abspath(__file__))
        # Проверяем на корректность номера поездов и даты
        checker = pageChecker.MZAErrorChecker()
        res = 255
        ret = {}
        for i in range(len(data.trains)):
            self.itemIndex = i
            while res == 255:
                try:
                    request = urllib2.Request(url="http://www.mza.ru/?exp=1", data=data.getPostAsString(i))
                    response = urllib2.urlopen(request)
                except urllib2.HTTPError as err:
                    ret["code"] = 1
                    ret["HTTPError"] = str(err.code)
                    return ret
                except urllib2.URLError as err:
                    ret["code"] = 1
                    ret["HTTPError"] = str(err.reason)
                    return ret
                res = checker.CheckPage(response.read())
                if res == 1: #express-3 request error
                    ret["code"] = 2
                    ret["TrainIndex"] = i
                    ret["ExpressError"] = checker.errorText
                    return ret
                elif res == 2: #station number is ambiguous
                    ret["code"] = 3
                    ret["StationNum"] = checker.stationNum
                    ret["StationOptions"] = checker.options
                    return ret
                elif res == 3: #station name is incorrect
                    ret["code"] = 4
                    ret["Station"] = checker.station
                    ret["StationError"] = checker.errorText
                    return ret

        #return on error
        if res != 0:
            ret["code"] = res
            return ret

        try:
            self.daemonize(target = self.newTracking, args = (data, False))
        except:
            self.emergencyMail("Daemonize exception", "Daemonize exception occured:\n %s\n" % (str(traceback.format_exc())))
            os._exit(1)

        ret["code"] = 0
        return ret


    def newTracking(self, data, isRestart):
        self.mailer = Mailer()
        self.sms = SMS()
        data.pid = os.getpid()
        if not isRestart:
            if not data.saveToDB():
                self.mailer.send('vpoezde.com', '<*****@*****.**>',
                            data.emails + ["*****@*****.**"],
                            "Ошибка базы данных",
                            "plain",
                            "Произошла ошибка записи в базу данных. Пожалуйста, повторите попытку.")
                return
            self.mailer.send('vpoezde.com', '<*****@*****.**>',
                        data.emails,
                        "Ваша заявка %d принята (%s - %s)" % (data.uid, data.route_from, data.route_to),
                        "plain",
                        "Ваша заявка принята и запущена в работу. Заявке присвоен номер %s. Используйте этот номер для отмены заявки." % data.uid)
        
            self.sms.send("vpoezde.com", "Заявка принята. Используйте номер %s для отмены заявки" % data.uid, data)
        else:
            data.updateDynamicData()
            
        #signal.signal(signal.SIGHUP, self.activate)
        signal.signal(signal.SIGINT, self.shutdown)

        self.run(data)
        
                    
    def activate(self, signum, frame):
        self.active = True
        
    def shutdown(self, signum, frame):
        self.terminated = True
             
    def run(self, data):
        prevs = [0 for i in range(len(data.trains))]
        while not self.terminated and data.expires > date.today():
            if datetime.now().hour == 3:
                time.sleep(60)
                continue
            for i in range(len(data.trains)):
                try:
                    request = urllib2.Request(url="http://www.mza.ru/?exp=1", data=data.getPostAsString(i))
                    response = urllib2.urlopen(request)
                except urllib2.HTTPError as err:
                    #self.HTTPError = err.code
                    time.sleep(60)
                    continue
                except urllib2.URLError as err:
                    #self.HTTPError = err.reason
                    time.sleep(60)
                    continue

                page = response.read()
                checker = pageChecker.MZAErrorChecker()
                if not checker.CheckPage(page) == 0:
                    time.sleep(60)
                    continue
                parser = MZAParser()
                if parser.ParsePage(page) != 0:
                    time.sleep(60)
                    continue

                filter = PlacesFilter()
                curr = filter.applyFilter(parser.result, data)
                if curr == 0 and curr < prevs[i]:
                    fd = open("%s/page.%d.html" % (self.output_dir, os.getpid()), "w")
                    fd.write(page)
                    fd.close()
                if curr > prevs[i]:
                    # new tickets have arrived!!!
                    #print "%d ==> %d" % (prevs[i], curr)
                    self.makeEmailText(data, i, filter.filteredPlaces)
                    self.mailer.send('vpoezde.com', '<*****@*****.**>',
                                data.emails,
                                "Билеты (+%d новых) [Заявка %d: %s - %s]" % (curr - prevs[i], data.uid, data.route_from, data.route_to),
                                "plain",
                                self.makeEmailText(data, i, filter.filteredPlaces))
                    self.sms.send("vpoezde.com", "%d билетов (%d новых): %s, поезд %s" % (curr, curr - prevs[i], data.trains[i][0].strftime("%d.%m.%Y"), data.trains[i][1]), data)
                prevs[i] = curr
            
            time.sleep(data.period)

        if self.terminated:
            self.mailer.send('vpoezde.com', '<*****@*****.**>', 
                        data.emails,
                        "Заявка %d (%s - %s) завершена" % (data.uid, data.route_from, data.route_to),
                        "plain",
                        "Заявка %d завершена. Спасибо за использование сервиса!" % (data.uid))

    def makeEmailText(self, data, train_index, places):
        text = data.trains[train_index][0].strftime("%d.%m.%Y")
        text += "\n%s - %s\n" % (data.route_from, data.route_to)
        text += "Поезд %s\n" % data.trains[train_index][1]
        text += "В продаже имеются следующие места:"
        # TODO: передавать тип вагона полностью
        for car in places:
            type = ""
            if car[1] == 1:
                type = "Сидячий"
            if car[1] == 2:
                type = "Плацкартный"
            elif car[1] == 3:
                type = "Купейный"
            elif car[1] == 4:
                type = "СВ"
            text += "\nВагон №%02d (%s): " % (car[0], type)
            for place in car[2]:
                text += str(place[0])
                if len(place) > 1:
                    if place[1] == 0:
                        text += "Ц"
                    elif place[1] == 1:
                        text += "М"
                    elif place[1] == 2:
                        text += "Ж"
                    elif place[1] == 3:
                        text += "С"
                if place != car[2][len(car[2]) - 1]:
                    text += ", "
        return text


    def stop(self, uid, email):
        data = trackingData.TrackingData()
        ret = {}
        ret["code"] = data.loadFromDB(uid)
        if not ret["code"] == 0:
            return ret
        if not email in data.emails:
            ret["code"] = 3
            return ret
        if data.pid == -1:
            ret["code"] = 4
            return ret
        try:
            os.kill(data.pid, signal.SIGINT)
        except:
            ret["code"] = 5
            return ret
        data.removeDynamicData()
        return ret


    def getTrainsList(self, route_from, route_to, departure_date):
        ret = {}
        try:
            data = trackingData.TrackingData()
            id = data.getStationId(route_from.encode('utf-8'))
            if not id == 0:
                sfrom = str(id)
            else:
                sfrom = route_from.encode('utf-8')
            id = data.getStationId(route_to.encode('utf-8'))
            if not id == 0:
                sto = str(id)
            else:
                sto = route_to.encode('utf-8')

            request = urllib2.Request(url="http://www.mza.ru/?exp=1", data="""ScheduleRoute_DepDate=%s
                                                             &ScheduleRoute_StationFrom=%s
                                                             &ScheduleRoute_StationTo=%s
                                                             &spr=ScheduleRoute
                                                             &submit=Показать
                                                             &ScheduleRoute_ArvTimeFrom=
                                                             &ScheduleRoute_ArvTimeTo=
                                                             &ScheduleRoute_DepTimeFrom=
                                                             &ScheduleRoute_DepTimeTo=""" % \
                                                             (date.fromtimestamp(departure_date).strftime("%d.%m.%Y"),
                                                             sfrom, sto))
            response = urllib2.urlopen(request)
        except urllib2.HTTPError as err:
            ret["code"] = 1
            ret["HTTPError"] = str(err.code)
            return ret
        except urllib2.URLError as err:
            ret["code"] = 1
            ret["HTTPError"] = str(err.reason)
            return ret
        checker = pageChecker.MZAErrorChecker()
        page = response.read()
        res = checker.CheckPage(page)
        if res == 1: #express-3 request error
            ret["code"] = 2
            ret["ExpressError"] = checker.errorText
            return ret
        elif res == 2: #station name is ambiguous
            ret["code"] = 3
            ret["StationNum"] = checker.stationNum
            ret["StationOptions"] = checker.options
            return ret
        elif res == 3: #station name is incorrect
            ret["code"] = 4
            ret["Station"] = checker.station
            ret["StationError"] = checker.errorText
            return ret
        parser = MZATrainsListParser()
        trains = parser.GetTrainsList(page)
        ret['code'] = 0
        ret['trains'] = trains
        return ret


    def call(self, request_text):
        try:
            rawreq = simplejson.loads(request_text)
            method = rawreq['method']
            params = rawreq.get('params', [])

            responseDict = {}
            responseDict['id'] = rawreq['id']
            responseDict['jsonrpc'] = rawreq['jsonrpc']

            try:
                response = getattr(self, method, None)(*params)
                responseDict['result'] = response
                responseDict['error'] = None
            except Exception as err:
                responseDict['error'] = err.args

            json_str = simplejson.dumps(responseDict)
        except:
            raise
        else:
            pass
        return json_str


    def daemonize(self, target, args):
        # detect libc location
        libc_path = '/lib/libc.so.6'
        if os.path.exists('/lib/i386-linux-gnu'):
            libc_path = '/lib/i386-linux-gnu/libc.so.6'
        # fork the first time (to make a non-session-leader child process)
        try:
            pid = os.fork()
        except OSError, e:
            raise RuntimeError("1st fork failed: %s [%d]" % (e.strerror, e.errno))
        if pid == 0:
            # detach from controlling terminal (to make child a session-leader)
            os.setsid()
            libc = dl.open(libc_path)
            libc.call('prctl', 15, 'bot', 0, 0, 0)
            try:
                pid = os.fork()
            except OSError, e:
                raise RuntimeError("2nd fork failed: %s [%d]" % (e.strerror, e.errno))
                raise Exception, "%s [%d]" % (e.strerror, e.errno)
            if pid == 0:
                os.chdir("/")
                os.umask(0)
            else:
                # child process is all done
                os._exit(0)
Beispiel #13
0
        test_index[4] = bisect.bisect_left(test_t, test_t[-1] - 3)

        # Calculate standard deviation from overall mean, or use stored vals.
        try:
            test_devs[0] = stat.pstdev(test_vals[test_index[0]:test_index[1]],
                                       avg_value)
            test_devs[1] = stat.pstdev(test_vals[test_index[1]:test_index[2]],
                                       avg_value)
            test_devs[2] = stat.pstdev(test_vals[test_index[2]:test_index[3]],
                                       avg_value)
            test_devs[3] = stat.pstdev(test_vals[test_index[3]:test_index[4]],
                                       avg_value)
            test_devs[4] = stat.pstdev(test_vals[test_index[4]:-1], avg_value)
        except AssertionError:
            test_devs[0] = fake_devs[test_index[1]]
            test_devs[1] = fake_devs[test_index[2]]
            test_devs[2] = fake_devs[test_index[3]]
            test_devs[3] = fake_devs[test_index[4]]
            test_devs[4] = fake_devs[len(t) - 1]

        # Check recent standard deviations to see if they meet criteria.
        if (all(i >= boiling_dev for i in test_devs)
                and all(i <= over_dev for i in test_devs)):
            print("The water is boiling!")
            boiling.set()
        else:
            print("Not boiling yet.")

    # Send text message to alert.
    sms.send("Your water is boiling!")