Ejemplo n.º 1
0
def get_balance(login, password, storename=None):
    result = {}
    cardno = login
    session = store.Session(storename, headers={})
    session.update_headers({'X-Requested-With': 'XMLHttpRequest'})
    cardtype = 'virtual-cards' if cardno.startswith('+') else 'cards'
    response = session.get(f'{api_url}{cardtype}/{cardno}?limit=100&rid={random.randint(1000000000,9999999999)}')
    data = response.json()['data']
    logging.debug(data)

    import pprint
    open('..\\log\\sodexo.log','w').write(pprint.PrettyPrinter(indent=4).pformat(data))

    result['Balance'] = 0.001+data['balance']['availableAmount']
    if 'currency' in data['balance']:
        result['Currenc'] = data['balance']['currency']
    if 'validUntil' in data:
        result['TurnOffStr'] = data['validUntil']
    try:
        history = []
        for hist in data['history']:
            t_tz = datetime.datetime.strptime(hist['time'],'%Y-%m-%dT%H:%M:%S.%f%z')
            t_fix = t_tz.replace(tzinfo=None)-datetime.timedelta(hours=3)
            histdate = datetime.datetime.strftime(t_fix,'%Y-%m-%d %H:%M:%S')
            history.append([f"{histdate} {','.join([i.replace('3DI ','').replace('MD00','').replace('EPS*','') for i in hist['locationName']])}",f"{hist['amount']}"])
        result['UslugiOn'] = f'{len(data["history"])}'
        result['UslugiList'] = '\n'.join([f'{a}\t{b}' for a, b in sorted(history)])
    except:
        logging.info(f'Ошибка при получении списка транзакций {"".join(traceback.format_exception(*sys.exc_info()))}')

    return result
Ejemplo n.º 2
0
def get_balance(login, password, storename=None):
    logging.info(f'start get_balance {login}')
    result = {}
    session = store.Session(storename)
    # Проверяем залогинены ли ?
    response3 = session.get('https://my.cardtel.ru/home')
    if len(re.findall(re_balance, response3.content.decode('utf8'))) > 0:
        logging.info('Old session is ok')
    else:  # Нет, логинимся
        data = {
            'op': 'auth',
            'login': login,
            'pwd': password,
            'red': '1',
            'remember': 'false'
        }
        session.drop_and_create()
        response2 = session.post('https://my.cardtel.ru/process', data=data)
        if response3.status_code != 200:
            raise RuntimeError(
                f'Login error: status_code {response2.status_code}!=200')
        response3 = session.get('https://my.cardtel.ru/home')
        if response3.status_code != 200:
            raise RuntimeError(
                f'Get balance page error: status_code {response2.status_code}!=200'
            )
    balance = re.findall(re_balance, response3.content.decode('utf8'))
    if len(balance) == 0:
        raise RuntimeError(f'Balance not found on page')
    result['Balance'] = balance[0]
    session.save_session()
    return result
Ejemplo n.º 3
0
def get_balance(login, password, storename=None):
    logging.info(f'start get_balance {login}')
    result = {}
    url = 'https://user.smile-net.ru/newpa/?handler=Login'
    session = store.Session(storename)
    response = session.get(url)
    if re.search(re_balance, response.text):
        logging.info(f'Already logoned {login}')
    else:
        # Логинимся
        logging.info(f'relogon {login}')
        session.drop_and_create()
        data = {
            'login': login,
            'password': password,
        }
        response = session.post(url, data=data)
        if response.status_code != 200:
            raise RuntimeError(
                f'POST Login page {url} error: status_code {response.status_code}'
            )

    result['Balance'] = re.search(re_balance,
                                  response.text).group(1).replace(',',
                                                                  '.').strip()
    result.update(find_by_regexp(response.text, 'Expired', re_expired))
    result.update(find_by_regexp(response.text, 'UserName', re_userName))
    result.update(find_by_regexp(response.text, 'licSchet', re_licSchet))
    result.update(find_by_regexp(response.text, 'TarifPlan', re_tarifPlan))
    result.update(find_by_regexp(response.text, 'BlockStatus', re_BlockStatus))

    session.save_session()
    return result
Ejemplo n.º 4
0
def get_balance(login, password, storename=None):
    ''' На вход логин и пароль, на выходе словарь с результатами '''
    result = {}
    session = store.Session(storename)
    result = {'Balance': 124.45 + random.randint(1,5),  # double
            'Balance2': 22,  # double
            'Balance3': 33,  # double
            'LicSchet': 'Лицевой счет',
            'UserName': '******',
            'TarifPlan': 'Тарифный план',
            'BlockStatus': 'Статус блокировки',
            'AnyString': 'Любая строка',
            'SpendBalance': 12,  # double Потрачено средств
            'KreditLimit': 23,  # double Кредитный лимит
            'Currenc': 'Валюта',
            'Average': 5,  # double Средний расход в день
            'TurnOffStr': 'Ожидаемая дата отключения',
            'Recomend':	54,  # double Рекомендовано оплатить
            'SMS': 43,  # !!! integer Кол-во оставшихся/потраченных СМС
            'Min': 222,  # !!! integer Кол-во оставшихся минут
            'SpendMin': 32,  # double Кол-во потраченных минут (с секундами)
            'Expired': 'Дата истечения баланса/платежа',
            'ObPlat':	14,   # double Сумма обещанного платежа
            'Internet': 1234,  # double Кол-во оставшегося/потраченного трафика
            # 'ErrorMsg':	'Сообщение об ошибке', # Если оо есть в Reponce то это ошибка
            'UslugiOn': '2/8',
            }
    session.save_session()            
    return result
Ejemplo n.º 5
0
def get_balance(login, password, storename=None):
    logging.info(f'start get_balance {login}')
    result = {}
    headers = {
        'Connection':
        'keep-alive',
        'User-Agent':
        'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
    }
    data = {
        'answer': 'json',
        'email': login,
        'password': password,
    }
    session = store.Session(storename, headers=headers)
    response3 = session.get('https://my.zadarma.com/')
    if re.search(re_balance, response3.text):
        logging.info(f'Already logoned {login}')
    else:
        logging.info(f'Session timeout, relogon {login}')
        session.drop_and_create(headers=headers)
        response1 = session.get('https://my.zadarma.com/auth/')
        _ = response1
        response2 = session.post('https://my.zadarma.com/auth/login/',
                                 data=data)
        _ = response2
        response3 = session.get('https://my.zadarma.com/')

    result['Balance'] = re.search(re_balance,
                                  response3.text).group(1).replace(',', '.')
    try:
        result['TarifPlan'] = re.search(
            re_tariff, response3.text).group(1).replace(' ', '').replace(
                'Текущий тарифный план -', '').strip()
    except Exception:
        logging.info(f"Couldn't take TarifPlan")
    try:
        to_dates = re.findall(r'действует до (\d\d\.\d\d\.\d\d\d\d)',
                              response3.text)
        if len(to_dates) > 0:
            nd = min(
                [time.mktime(time.strptime(d, '%d.%m.%Y')) for d in to_dates])
            result['TurnOff'] = int((nd - time.time()) / 86400)
            result['TurnOffStr'] = time.strftime('%d.%m.%Y',
                                                 time.localtime(nd))
    except Exception:
        logging.info(f"Couldn't take TurnOff")
    try:
        avail_min = re.search(re_min, response3.text)
        if avail_min:
            result['Min'] = avail_min.group(1)
    except Exception:
        logging.info(f"couldn't take Min")
    session.save_session()
    return result
Ejemplo n.º 6
0
def get_balance(login, password, storename=None):
    result = {}
    cardno = login
    session = store.Session(storename)
    session.update_headers({'X-Requested-With': 'XMLHttpRequest'})
    cardtype = 'virtual-cards' if cardno.startswith('+') else 'cards'
    response = session.get(f'https://sodexo.gift-cards.ru/api/1/{cardtype}/{cardno}?limit=100&rid={random.randint(1000000000,9999999999)}')
    data = response.json()['data']
    logging.debug(data)
    result['Balance'] = 0.001+data['balance']['availableAmount']
    result['Currenc'] = data['balance']['currency']
    result['TurnOffStr'] = data['validUntil']
    return result
Ejemplo n.º 7
0
def get_balance(login, password, storename=None):
    requests.packages.urllib3.disable_warnings()  # чтобы не ругался на ошибки сертификатов
    result = {}
    session = store.Session(storename)
    baseurl = 'http://strelkacard.ru'
    url = "https://strelkacard.ru/api/cards/status/?cardnum=" + login + "&cardtypeid=3ae427a1-0f17-4524-acb1-a3f50090a8f3"
    response2 = session.get(url, headers={'Referer': baseurl + '/'}, verify=False)
    # html=u'<html><http-equiv="Content-type" content="text/html; charset=windows-1251" /><p id="Balance">%s<p id="TarifPlan">%s</html>' % (
    result['Balance'] = response2.json()['balance']/100.
    if response2.json().get('emergencyblocked', False):
        result['BlockStatus'] = 'Emergency Blocked'
    if response2.json().get('cardblocked', False):
        result['BlockStatus'] = 'Card Blocked'
    return result
Ejemplo n.º 8
0
def get_balance(login, password, storename=None):
    logging.info(f'start get_balance {login}')
    result = {}
    baseurl = 'https://my.rt.ru/'
    cabinet_url = 'https://my.rt.ru/json/cabinet/'
    headers = {}
    session = store.Session(storename, headers=headers)
    response3 = session.post(cabinet_url, data={})
    # !!! Хоть и возвращает json но 'content-type' - text/html
    if 'accountInfo' in response3.text:
        logging.info(f'Already logoned {login}')
    else:
        # Логинимся
        logging.info(f'relogon {login}')
        session.drop_and_create()
        response1 = session.get(baseurl)
        if response1.status_code != 200:
            raise RuntimeError(f'GET Login page {baseurl} error: status_code {response1.status_code}')
        data = {'_csrf_token': re.findall(re_csrf, response1.text),
                'login': login,
                'password': password,}
        login_url = 'https://my.rt.ru/session/checklogin/'
        response2 = session.post(login_url, data=data)
        if response2.status_code != 200:
            raise RuntimeError(f'POST Login page {login_url} error: status_code {response2.status_code}')
        response3 = session.post(cabinet_url, data={})

    if 'accountInfo' not in response3.text:
        raise RuntimeError(f'Balance (accountInfo) not found on {cabinet_url}')

    result['Balance'] = response3.json().get('accountInfo', {})['balance']
        
    try:
        result['Balance2'] = response3.json().get('bonusAccount',{})['points']
    except Exception:
        logging.info(f'Not found bonusAccount')

    try:
        result['licSchet'] =  response3.json().get('accountInfo', {})['AccountID']
        result['Expired'] =  response3.json().get('accountInfo', {})['daysToLock']
    except Exception:
        logging.info(f'Not found licSchet and Expired')

    try:
        result['anyString'] =  'Статус: ' + response3.json().get('bonusAccount', {})['tier']
    except Exception:
        logging.info(f'Not found anyString (status)')        
    
    session.save_session()
    return result
Ejemplo n.º 9
0
def get_balance(login, password, storename=None):
    result = {}
    session = store.Session(
        storename)  # Используем костылем для хранения предыдущих данных
    # если у нас еще нет переменной для истории - создаем (грязный хак - не делайте так, а если делаете - не пользуйтесь этой сессией для хождения в инет, а только для сохранения):
    session.session.params['history'] = session.session.params.get(
        'history', [])
    data = store.read_stocks(login.lower())
    stocks = data['stocks']
    remain = data['remain']
    currenc = data['currenc']
    res_data = count_all_scocks_multithread(stocks, remain, currenc)
    session.session.params['history'].append({
        'timestamp': time.time(),
        'data': res_data
    })  # Полученное значение сразу добавляем в хвост истории
    if store.options('stock_fulllog'):
        fulllog = '\n'.join(
            f'{time.strftime("%Y.%m.%d %H:%M:%S",time.localtime())}\t{i["security"]}\t{i["price"]}\t{i["currency"]}\t{i["cnt"]}\t{round(i["value"],2)}\t{round(i["value_priv"],2)}'
            for i in res_data)
        with open(
                os.path.join(store.options('loggingfolder'),
                             f'stock_{login}.log'), 'a') as f_log:
            f_log.write(fulllog + '\n')
    # Полная информация по стокам
    result['Stock'] = '\n'.join([
        f'{i["security"]+"("+i["currency"]+")":10} : {round(i["value_priv"],2):9.2f} {currenc}'
        for i in res_data
    ]) + '\n'
    result['UslugiOn'] = len(res_data)
    # Берем два последних элемента, а из них берем первый т.е. [1,2,3][-2:][0] -> 2 а [3][-2:][0] -> 3 чтобы не морочаться с проверкой есть ли предпоследний
    prev_data = session.session.params['history'][-2:][0][
        'data']  # TODO подумать какой из истории брать для вычисления. Пока беру предыдущий
    hst = {i['security']: i['value_priv'] for i in prev_data}
    result['UslugiList'] = '\n'.join([
        f'{i["security"]:5}({i["currency"]}) {i["value_priv"]-hst.get(i["security"],i["value_priv"]):+.2f}\t{i["value_priv"]:.2f}'
        for i in res_data
    ])
    # Полная информация подправленная для показа в balance.html
    result['Balance'] = round(sum([i['value_priv'] for i in res_data]),
                              2)  # Сумма в заданной валюте
    result['Currenc'] = currenc  # Валюта
    session.session.params['history'] = session.session.params['history'][
        -100:]  # оставляем последние 100 значений чтобы не росло бесконечно
    session.save_session()
    return result
Ejemplo n.º 10
0
def get_balance(login, password, storename=None):
    logging.info(f'start get_balance {login}')
    result = {}
    url = 'https://www.sipnet.ru/cabinet/index'
    session = store.Session(storename)
    response1 = session.get(url)
    if re.search(re_balance, response1.text):
        logging.info(f'Already logoned {login}')
    else:
        # Логинимся
        logging.info(f'relogon {login}')
        session.drop_and_create()
        data = {
            'CabinetAction': 'login',
            'view': 'ru',
            'Name': login,
            'Password': password,
        }
        response1 = session.post(url, data=data)
        if response1.status_code != 200:
            raise RuntimeError(
                f'POST Login page {url} error: status_code {response1.status_code}'
            )

    result['Balance'] = re.search(re_balance, response1.text).group(1).replace(
        ',', '.').strip()
    try:
        result['TarifPlan'] = re.search(re_tariff,
                                        response1.text).group(1).replace(
                                            '&nbsp;', '').strip()
    except Exception:
        logging.info(f'Not found TarifPlan')
    try:
        result['licSchet'] = re.search(re_sipid,
                                       response1.text).group(1).replace(
                                           '&nbsp;', '').strip()
    except Exception:
        logging.info(f'Not found licSchet')

    session.save_session()
    return result
Ejemplo n.º 11
0
def get_balance(login, password, storename=None):
    result = {}
    session = store.Session(storename)
    response3 = session.get('https://lk.parking.mos.ru/ru/cabinet')
    if re.findall("(?usi)accountId\":(.*?),", response3.text) != []:
        logging.info('Old session is ok. Step 1')
    else:
        logging.info('Old session is bad? Check 2.')
        #session.drop_and_create()
        response1 = session.get(
            'https://lk.parking.mos.ru/auth/social/sudir?returnTo=/../cabinet')
        if re.search("(?usi)accountId\":(.*?),", response1.text):
            logging.info('Old session is ok. (Step 2)')
        else:
            logging.info('Old session is bad, relogin')
            csrf = re.findall("(?usi)csrf-token-value.*?content='(.*?)'",
                              response1.text)[0]
            bfp = ''.join([hex(random.randrange(15))[-1] for i in range(32)])
            data = {
                'isDelayed': 'false',
                'login': login,
                'password': password,
                'csrftoken_w': csrf,
                'bfp': bfp,
                'alien': 'false',
            }
            response2 = session.post(
                'https://login.mos.ru/sps/login/methods/password', data=data)
            _ = response2
        response3 = session.get('https://lk.parking.mos.ru/ru/cabinet')

    accountId = re.findall("(?usi)accountId\":(.*?),", response3.text)[0]
    response4 = session.put(
        'https://lk.parking.mos.ru/api/2.40/accounts/getbalance',
        data={"accountId": accountId})
    result['Balance'] = response4.json()['balance'] / 100.

    session.save_session()
    return result
Ejemplo n.º 12
0
 def check_or_get_bearer():
     '''Проверяем если сессия отдает баланс, то ок, если нет, то логинимся заново'''
     session = store.Session(storename, headers=headers)
     if 'Authorization' in session.headers:
         response1 = session.get(
             f'https://api.tele2.ru/api/subscribers/7{login}/balance')
         if response1.status_code == 200:
             logging.info('Old session bearer ok')
             return session
     session.drop_and_create(
         headers=headers)  # TODO непонятно как лучше рубить концы или нет
     response2 = session.post(
         f'https://sso.tele2.ru/auth/realms/tele2-b2c/protocol/openid-connect/token?msisdn=7{login}&action=auth&authType=pass',
         data=data)
     if response2.status_code == 200:
         logging.info('New bearer is ok')
         bearer = response2.json()['access_token']
         # !!! TODO теперь session.session.headers подумать как лучше
         session.update_headers({'Authorization': 'Bearer ' + bearer})
         return session
     logging.error(
         f'Bearer get error {response2.status_code} for login {login}')
     raise RuntimeError(f'Bearer get error {response2.status_code}')
Ejemplo n.º 13
0
def get_balance(login, password, storename=None):
    ''' На вход логин и пароль, на выходе словарь с результатами '''
    result = {}
    # Загружаем или создаем сессию
    session = store.Session(storename, headers = {'User-Agent': 'tiehttp', })
    uri = 'https://my.beeline.ru/api/1.0/auth/auth?login='******'&password='******'Login error: status_code {response1.status_code}!=200')

    if 'json' not in response1.headers.get('content-type') or response1.json()['meta']['status'] != 'OK':
        raise RuntimeError(f'Login error: .meta.status!=OK {response1.text}')
    token = response1.json()['token']

    jsonBalance = api(session, token, login, 'info/prepaidBalance')
    if jsonBalance['meta']['status'] == 'ERROR' and jsonBalance['meta']['code'] == 49999:
        jsonBalance = api(session, token, login, 'info/postpaidBalance')
    if jsonBalance['meta']['status'] == 'OK':
        result['Balance'] = round(jsonBalance['balance'], 2)
    else:
        raise RuntimeError(f'Balance not found in {jsonBalance}')

    jsonTariff = api(session, token, login, 'info/pricePlan')
    if jsonTariff['meta']['status'] == 'OK':
        result['TarifPlan'] = jsonTariff['pricePlanInfo']['entityName']

    # список услуг
    jsonSubscr = api(session, token, login, 'info/subscriptions')
    subscr = len(jsonSubscr.get('subscriptions',[]))
    jsonServices = api(session, token, login, 'info/serviceList')
    paid_sum = 0
    ppi = jsonTariff['pricePlanInfo']
    kperiod = 1
    if ppi.get('rcRate', None) != None and ppi.get('rcRatePeriod', None) != None:
        kperiod = 30 if jsonTariff['pricePlanInfo']['rcRatePeriod'].split('.')[-1]=='dayly' else 1
        paid_sum = ppi['rcRate'] * kperiod
    services = []
    for el in jsonServices['services']:
        if el.get('rcRate', None) != None and el.get('rcRatePeriod', None) != None:
            kperiod = 30 if el['rcRatePeriod'].split('.')[-1]=='dayly' else 1
            fee = el['rcRate'] * kperiod
        else:
            fee = 0
        services.append((el['entityName'],fee))
    free = len([a for a, b in services if b == 0])  # бесплатные
    paid = len([a for a, b in services if b != 0])  # платные
    paid_sum = paid_sum+round(sum([b for a, b in services if b != 0]), 2)
    result['UslugiOn'] = f'{free}/{subscr}/{paid}({paid_sum})'
    result['UslugiList'] = '\n'.join([f'{a}\t{b}' for a, b in services])

    jsonStatus = api(session, token, login, 'info/status')
    if jsonStatus['meta']['status'] == 'OK':
        result['BlockStatus'] = jsonStatus['status']
    
    jsonRests = api(session, token, login, 'info/rests')
    if jsonRests['meta']['status'] == 'OK' and 'rests' in jsonRests:
        result['Min'] = 0
        result['Internet'] = 0
        result['SMS'] = 0
        for elem in jsonRests['rests']:
            if elem['unitType'] == 'VOICE':
                result['Min'] += elem['currValue']
            if elem['unitType'] == 'INTERNET':
                result['Internet'] += elem['currValue']
            if elem['unitType'] == 'SMS_MMS':
                result['SMS'] += elem['currValue']

    # похоже теперь у билайна не rests а accumulators, данных мало так что пробуем так
    # и не понятно как определить про что аккумулятор, так что пока ориентируемся на поле unit, у интернета он 'unit': 'KBYTE'
    jsonAcc = api(session, token, login, 'info/accumulators')
    if jsonAcc['meta']['status'] == 'OK' and 'accumulators' in jsonAcc:
        result['Min'] = result.get('Min', 0)
        result['Internet'] = result.get('Internet', 0)
        result['SMS'] = result.get('SMS', 0)
        for elem in jsonAcc['accumulators']:
            if elem['unit'] == 'SECONDS':
                result['Min'] += elem['rest']//60
            if elem['unit'] == 'KBYTE':
                result['Internet'] += elem['rest']*(settings.UNIT['KB']/settings.UNIT.get(store.options('interUnit'), settings.UNIT['KB']))
            if elem['unit'] == 'SMS':
                result['SMS'] += elem['rest']

    session.save_session()
    return result
Ejemplo n.º 14
0
import store

extract = store.Extract('./event_data')
columns = [
    'artist', 'firstName', 'gender', 'itemInSession', 'lastName', 'length',
    'level', 'location', 'sessionId', 'song', 'userId'
]
dropna = ['artist']
extract.save('event_datafile_new.csv', columns, dropna)

print('Session')
session = store.Session()
#session.load('./event_datafile_new.csv')
results = session.where('sessionid = 338 AND itemInSession = 4')
print(results)

print('User Session')
user_session = store.UserSession()
user_session.load('./event_datafile_new.csv')
results = user_session.where('userId = 10 AND sessionId = 182')
print(results)

print('User Listens')
user_listen = store.UserListen()
user_listen.load('./event_datafile_new.csv')
results = user_listen.where("song = 'All Hands Against His Own'")
print(results)
Ejemplo n.º 15
0
def get_balance(login, password, storename=None):
    ''' На вход логин и пароль, на выходе словарь с результатами '''
    result = {}
    # Загружаем или создаем сессию
    session = store.Session(storename, headers={
        'User-Agent': 'tiehttp',
    })
    uri = 'https://my.beeline.ru/api/1.0/auth/auth?login='******'&password='******'Login error: status_code {response1.status_code}!=200')

    if 'json' not in response1.headers.get(
            'content-type') or response1.json()['meta']['status'] != 'OK':
        raise RuntimeError(f'Login error: .meta.status!=OK {response1.text}')
    token = response1.json()['token']

    jsonBalance = api(session, token, login, 'info/prepaidBalance')
    if jsonBalance['meta']['status'] == 'ERROR' and jsonBalance['meta'][
            'code'] == 49999:
        jsonBalance = api(session, token, login, 'info/postpaidBalance')
    if jsonBalance['meta']['status'] == 'OK':
        result['Balance'] = round(jsonBalance['balance'], 2)
    else:
        raise RuntimeError(f'Balance not found in {jsonBalance}')

    jsonTariff = api(session, token, login, 'info/pricePlan')
    if jsonTariff['meta']['status'] == 'OK':
        result['TarifPlan'] = jsonTariff['pricePlanInfo']['entityName']

    # список услуг
    jsonSubscr = api(session, token, login, 'info/subscriptions')
    subscr = len(jsonSubscr.get('subscriptions', []))
    jsonServices = api(session, token, login, 'info/serviceList')
    paid_sum = 0
    ppi = jsonTariff['pricePlanInfo']
    if ppi['rcRate'] is not None and ppi['rcRatePeriod'] is not None:
        kperiod = 30 if jsonTariff['pricePlanInfo']['rcRatePeriod'].split(
            '.')[-1] == 'dayly' else 1
        paid_sum = ppi['rcRate'] * kperiod
    services = []
    for el in jsonServices['services']:
        if el['rcRate'] is not None and el['rcRatePeriod'] is not None:
            kperiod = 30 if el['rcRatePeriod'].split('.')[-1] == 'dayly' else 1
            fee = el['rcRate'] * kperiod
        else:
            fee = 0
        services.append((el['entityName'], fee))
    free = len([a for a, b in services if b == 0])  # бесплатные
    paid = len([a for a, b in services if b != 0])  # платные
    paid_sum = paid_sum + round(sum([b for a, b in services if b != 0]), 2)
    result['UslugiOn'] = f'{free}/{subscr}/{paid}({paid_sum})'
    result['UslugiList'] = '\n'.join([f'{a}\t{b}' for a, b in services])

    jsonStatus = api(session, token, login, 'info/status')
    if jsonStatus['meta']['status'] == 'OK':
        result['BlockStatus'] = jsonStatus['status']

    jsonRests = api(session, token, login, 'info/rests')
    if jsonRests['meta']['status'] == 'OK' and 'rests' in jsonRests:
        result['Min'] = 0
        result['Internet'] = 0
        result['SMS'] = 0
        for elem in jsonRests['rests']:
            if elem['unitType'] == 'VOICE':
                result['Min'] += elem['currValue']
            if elem['unitType'] == 'INTERNET':
                result['Internet'] += elem['currValue']
            if elem['unitType'] == 'SMS_MMS':
                result['SMS'] += elem['currValue']

    session.save_session()
    return result
Ejemplo n.º 16
0
def get_balance(login, password, storename=None):
    ''' На вход логин и пароль, на выходе словарь с результатами '''
    result = {}
    session = store.Session(storename)
    response2 = session.get('https://my.danycom.ru/User/GetBalance/')
    if 'json' in response2.headers.get('content-type'):
        logging.info('Old session is ok')
    else:  # Нет, логинимся
        logging.info('Old session is bad, relogin')
        session.drop_and_create()
        data = {'phone': login, 'email': '', 'password': password}
        response1 = session.post('https://my.danycom.ru/User/SignIn',
                                 data=data)
        if response1.status_code != 200:
            raise RuntimeError(
                f'GET Login page error: status_code {response1.status_code}!=200'
            )
        response2 = session.get('https://my.danycom.ru/User/GetBalance/')
        if response2.status_code != 200:
            raise RuntimeError(
                f'GET GetBalance status_code {response1.status_code}!=200')
        if 'json' not in response2.headers.get('content-type'):
            raise RuntimeError(
                f'GET GetBalance not return json {response2.headers.get("content-type")}'
            )

    result['Balance'] = float('.'.join(response2.json()))  # Баланс

    try:
        url = 'https://my.danycom.ru/User/GetCustomerInfo/'
        response3 = session.get(url)  # ФИО
        if response3.status_code == 200 and 'json' in response3.headers.get(
                'content-type'):
            result['UserName'] = response3.json()
    except Exception:
        logging.info(f"Can't get {url}")

    try:
        url = 'https://my.danycom.ru/User/GetBonusBalance/'
        response4 = session.get(url)  # Бонусы
        if response4.status_code == 200 and 'json' in response4.headers.get(
                'content-type'):
            result['Balance2'] = response4.json()[0]
    except Exception:
        logging.info(f"Can't get {url}")

    try:
        url = 'https://my.danycom.ru/User/GetCurrentTariff/'
        response5 = session.get(url)  # Тариф
        if response5.status_code == 200 and 'json' in response5.headers.get(
                'content-type'):
            result['TarifPlan'] = json.loads(response5.json()).get('Name', '')
    except Exception:
        logging.info(f"Can't get {url}")

    try:
        url = 'https://my.danycom.ru/User/GetCustomerStatus/'
        response6 = session.get(url)  # Статус блокировки
        if response6.status_code == 200 and 'json' in response6.headers.get(
                'content-type'):
            result['BlockStatus'] = response6.json()
    except Exception:
        logging.info(f"Can't get {url}")

    try:
        url = 'https://my.danycom.ru/User/GetRestTraffic/'
        response7 = session.get(url)  # Остатки
        if response7.status_code == 200 and 'json' in response7.headers.get(
                'content-type'):
            rests = json.loads(response7.json())
            result['Min'] = rests.get('CallBalance', 0)
            result['SMS'] = rests.get('SmsBalance', 0)
            k_internet = settings.UNIT.get(
                rests.get('InternetUnit', 'Мб').upper(), 1024) / 1024
            result['Internet'] = rests.get('InternetBalance', 0) * k_internet
            result['Expired'] = rests.get('EndPeriod', '').split('T')[0]
    except Exception:
        logging.info(f"Can't get {url}")

    try:
        url = 'https://my.danycom.ru/Lk/ServicesControl'
        response8 = session.get(url)  # Услуги
        if response8.status_code == 200:  # это просто html
            services = re.findall(
                r'(?usi)"Название">(.*?)<.*?руб">\s*(.*?)\s*/\s*(мес|дн|ден)<',
                response8.text)
            free = len([a for a, b, c in services if b == '0'])  # бесплатные
            paid = len([a for a, b, c in services if b != '0'])  # платные
            paid_sum = round(sum([float(b) for a, b, c in services]), 2)
            result['UslugiOn'] = f'{free}/{paid}({paid_sum})'
            result['UslugiList'] = '\n'.join(
                [f'{a}\t{b}' for a, b, c in services])
    except Exception:
        logging.info(f"Can't get {url}")

    session.save_session()
    return result
Ejemplo n.º 17
0
def get_balance(login, password, storename=None):
    logging.info(f'start get_balance {login}')
    result = {}
    url = 'https://avtodor-tr.ru/account'
    url_ext = 'https://lk.avtodor-tr.ru/api/client/extended'
    session = store.Session(storename)
    response3 = session.get(url_ext)
    if response3.status_code == 200 and 'json' in response3.headers.get(
            'content-type'):
        logging.info('Old session is ok')
    else:
        # Логинимся
        logging.info(f'relogon {login}')
        session.drop_and_create()
        url_login = '******'
        response1 = session.get(url_login)
        if response1.status_code != 200:
            raise RuntimeError(
                f'GET Login page {url_login} error: status_code {response1.status_code}'
            )
        try:
            url_lk = re.search('action="(.*?)"',
                               response1.text).group(1).replace('&amp;', '&')
        except:
            raise RuntimeError(f'No action url on {url_login}')
        data = {'username': login, 'password': password}
        response2 = session.post(url_lk, data=data)
        if response2.status_code not in (200, 301, 302):
            raise RuntimeError(
                f'POST Login page {url_lk} error: status_code {response2.status_code}'
            )
        response3 = session.get(url_ext)
        if response3.status_code != 200:
            raise RuntimeError(
                f'GET Login page {url_ext} error: status_code {response3.status_code}'
            )
        if 'json' not in response3.headers.get('content-type'):
            raise RuntimeError(
                f"{url_ext} not json: {response3.headers.get('content-type')}")

    data = response3.json()
    client = data.get('client', {})
    contracts = data.get('contracts', [])
    # Попытка получить баланс
    result['Balance'] = data['contracts'][0]['account_balance']
    # Если contracts>1 то прибавляем остальное
    result['Balance'] += sum(
        [el['account_balance'] for el in data['contracts'][1:]])

    try:
        result['Balance2'] = data['contracts'][0]['loyalty_member_balance']
    except Exception:
        logging.info(f'Not found bonus')

    try:
        result['userName'] = client['name']
    except Exception:
        logging.info(f'Not found userName')

    try:
        result['licSchet'] = client['id']
    except Exception:
        logging.info(f'Not found licSchet')

    session.save_session()
    return result
Ejemplo n.º 18
0
def get_balance(login, password, storename=None):
    result = {}
    session = store.Session(storename)
    response3 = session.get('https://lk.megafon.ru/api/lk/main/atourexpense')
    if 'json' in response3.headers.get(
            'content-type') and 'balance' in response3.text:
        logging.info('Old session is ok')
    else:  # Нет, логинимся
        logging.info('Old session is bad, relogin')
        session.drop_and_create()
        response1 = session.get('https://lk.megafon.ru/login/')
        if response1.status_code != 200:
            raise RuntimeError(
                f'GET Login page error: status_code {response1.status_code}!=200'
            )
        csrf = re.search('(?usi)name="CSRF" value="([^\"]+)"', response1.text)
        data = {
            'CSRF': csrf,
            'j_username': f'+7{login}',
            'j_password': password
        }
        response2 = session.post('https://lk.megafon.ru/dologin/', data=data)
        if response2.status_code != 200:
            raise RuntimeError(
                f'POST Login page error: status_code {response2.status_code}!=200'
            )
        response3 = session.get(
            'https://lk.megafon.ru/api/lk/main/atourexpense')
        if response3.status_code != 200 or 'json' not in response3.headers.get(
                'content-type'):
            raise RuntimeError(
                f'Get Balance page not return json: status_code={response2.status_code} {response3.headers.get("content-type")}'
            )
        if 'balance' not in response3.text:
            raise RuntimeError(
                f'Get Balance page not return balance: status_code={response2.status_code} {response3.text}'
            )

    result['Balance'] = response3.json().get('balance', 0)
    result['KreditLimit'] = response3.json().get('limit', 0)

    response4 = session.get('https://lk.megafon.ru/api/profile/name')
    if response4.status_code == 200 and 'json' in response4.headers.get(
            'content-type'):
        result['UserName'] = response4.json()['name'].replace('"', '').replace(
            "'", '').replace('&quot;', '')

    response5 = session.get('https://lk.megafon.ru/api/tariff/current')
    if response5.status_code == 200 and 'json' in response5.headers.get(
            'content-type'):
        result['TarifPlan'] = response5.json().get('name', '').replace(
            '&nbsp;', ' ').replace('&mdash;', '-')

    #Старый вариант без получения стоимости платных услуг
    #response6 = session.get('https://lk.megafon.ru/api/lk/mini/options')
    #if response6.status_code == 200 and 'json' in response6.headers.get('content-type'):
    #    servicesDto = response6.json().get('servicesDto', {})
    #    result['UslugiOn'] = f"{servicesDto.get('free','')}/{servicesDto.get('paid','')}"
    response6 = session.get('https://lk.megafon.ru/api/options/list/current')
    if response6.status_code == 200 and 'json' in response6.headers.get(
            'content-type'):
        oList = response6.json()
        services = [(i['optionName'],
                     i['monthRate'] * (1 if i['monthly'] else 30))
                    for i in oList.get('paid', [])]
        services += [(i['optionName'],
                      i['monthRate'] * (1 if i['monthly'] else 30))
                     for i in oList.get('free', [])]
        services.sort(key=lambda i: (-i[1], i[0]))
        free = len([a for a, b in services if b == 0])  # бесплатные
        paid = len([a for a, b in services if b != 0])  # платные
        paid_sum = round(sum([b for a, b in services]), 2)
        result['UslugiOn'] = f'{free}/{paid}({paid_sum})'
        result['UslugiList'] = '\n'.join([f'{a}\t{b}' for a, b in services])

    response7 = session.get('https://lk.megafon.ru/api/options/remaindersMini')
    if response7.status_code == 200 and 'json' in response7.headers.get(
            'content-type'):
        remainders = sum([
            i.get('remainders', [])
            for i in response7.json().get('remainders', [])
        ], [])
        minutes = [
            i['availableValue'] for i in remainders
            if i['unit'].startswith('мин')
        ]
        if len(minutes) > 0:
            result['Min'] = sum([i['value'] for i in minutes])
        internet = [
            i['availableValue'] for i in remainders if i['unit'].endswith('Б')
        ]
        unitDiv = settings.UNIT.get(interUnit, 1)
        if len(internet) > 0:
            result['Internet'] = sum([
                round(i['value'] * settings.UNIT.get(i['unit'], 1) / unitDiv,
                      3) for i in internet
            ])
        sms = [
            i['availableValue'] for i in remainders
            if i['unit'].startswith('шту')
        ]
        if len(sms) > 0:
            result['SMS'] = sum([i['value'] for i in sms])

    session.save_session()
    return result