Skip to content

Commit

Permalink
Fix balance2 param individual by pkey
Browse files Browse the repository at this point in the history
  • Loading branch information
artyl committed Nov 21, 2022
1 parent 4531ac0 commit 5929005
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 12 deletions.
8 changes: 4 additions & 4 deletions plugin/httpserver_mobile.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ def getbalance_plugin(method, param_source):
param['fplugin'] = param['plugin'] # наш параметр plugin на самом деле fplugin
else:
logging.error(f'Unknown method {method}')
pkey = (param['login'], param['fplugin'])
pkey = store.get_pkey(param['login'], param['fplugin']) # (param['login'], param['fplugin'])
store.options('logginglevel', flush=True) # Запускаем, чтобы сбросить кэш и перечитать ini
phone_items = store.ini('phones.ini').phones().get(pkey, {}).items()
individual = ','.join([f'{k}={v}' for k, v in phone_items if k.lower() in store.settings.ini['Options'].keys()])
Expand Down Expand Up @@ -209,7 +209,7 @@ def getbalance_plugin(method, param_source):
logging.info(f'Jitter {j_time:.2f} seconds')
time.sleep(j_time)
result = module.get_balance(param['login'], param['password'], storename, pkey=pkey)
result = store.correct_result(result)
result = store.correct_result(result, pkey=pkey)
if type(result) != dict or 'Balance' not in result:
raise RuntimeError(f'В result отсутствует баланс')
text = store.result_to_html(result)
Expand Down Expand Up @@ -326,7 +326,7 @@ def pp_field(pkey, he, el, hover, unwanted=False, link=''):
html_table = []
for line in table:
html_line = []
pkey = (line['PhoneNumber'], line['Operator'])
pkey = store.get_pkey(line['PhoneNumber'], line['Operator'])
uslugi = json.loads(responses.get(f"{line['Operator']}_{line['PhoneNumber']}", '{}')).get('UslugiList', '')
subscription_keyword = [i.strip() for i in store.options('subscription_keyword', pkey=pkey).lower().split(',')]
unwanted_kw = [kw for kw in subscription_keyword if kw in uslugi.lower()] # встретившиеся нежелательные
Expand Down Expand Up @@ -454,7 +454,7 @@ def prepare_balance_mobilebalance(filter: str = 'FULL', params: typing.Dict = {}
def prepare_balance_sqlite(filter: str = 'FULL', params: typing.Dict = {}):
'Готовим данные для отчета из sqlite базы'
def alert_suffix(line):
pkey = (line['PhoneNumber'], line['Operator'])
pkey = store.get_pkey(line['PhoneNumber'], line['Operator'])
uslugi = json.loads(responses.get(f"{line['Operator']}_{line['PhoneNumber']}", '{}')).get('UslugiList', '')
if flags.get(f"{line['Operator']}_{line['PhoneNumber']}", '').startswith('error'):
return f'<b> ! последняя попытка получить баланс завершилась ошибкой !</b>'
Expand Down
4 changes: 2 additions & 2 deletions plugin/mbplugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@ def main():
dbengine.flags('setunic', f'{lang}_{plugin}_{login}', 'start') # выставляем флаг о начале запроса
try:
storename = re.sub(r'\W', '_', f'{lang}_{plugin}_{login}')
pkey = (login, f'{lang}_{plugin}') # Пара (номер, оператор)
pkey = store.get_pkey(login, plugin) # Пара (номер, оператор)
result = module.get_balance(login, password, storename, pkey=pkey)
result = store.correct_result(result)
result = store.correct_result(result, pkey=pkey)
if 'Balance' not in result:
raise RuntimeError(f'В result отсутствует баланс')
except Exception:
Expand Down
11 changes: 7 additions & 4 deletions plugin/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,15 +103,15 @@ def fix_num_params(result, int_params):
result[k] = round(v, 2) # Чтобы не было паразитных микрокопеек
return result

def correct_result(result):
def correct_result(result, pkey):
'Дополнительные коррекции после проверки'
if type(result) != dict:
return result
result = fix_num_params(result, int_params=['SMS', 'Min'])
if 'Balance' in result and 'Balance2' in result:
if options('balance2') == 'swap':
if options('balance2', pkey=pkey) == 'swap':
result['Balance'], result['Balance2'] = result['Balance2'], result['Balance']
elif options('balance2') == 'add':
elif options('balance2', pkey=pkey) == 'add':
result['Balance'] = result['Balance'] + result['Balance2']
return result

Expand Down Expand Up @@ -267,8 +267,11 @@ def put(self, url, data=None, **kwargs) -> requests.Response:
return response

def get_pkey(login, plugin_name):
'Все взятия pkey - пары (логин, плагин) через эту функцию, чтобы в случае чего нестыковки исправить здесь '
'''Все взятия pkey - пары (логин, p_плагин) через эту функцию, чтобы в случае чего
нестыковки исправить здесь, если у плагина уже есть префикс p_ то второй раз не прибавляем '''
lang = 'p'
if plugin_name.startswith(f'{lang}_'):
return (login, plugin_name)
return (login, f'{lang}_{plugin_name}')

def options(param, default=None, section='Options', listparam=False, mainparams={}, pkey=None, flush=False):
Expand Down
5 changes: 3 additions & 2 deletions plugin/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -528,7 +528,7 @@ def check_ini(ctx):
if not nn.isdigit():
phones_ini_mess.append(f'Invalid section number [{nn}]')
continue
pkey = (phones_ini.ini[nn]['number'], phones_ini.ini[nn]['region'])
pkey = store.get_pkey(phones_ini.ini[nn]['number'], phones_ini.ini[nn]['region'])
for key in phones_ini.ini[nn].keys():
valid, msg = store.option_validate(key, pkey=pkey)
if not valid:
Expand Down Expand Up @@ -570,7 +570,8 @@ def check_plugin(ctx, bpoint, params, plugin, login, password):
# module.get_balance(login, password, storename)
_ = login, password, storename # dummy linter - use in pdbpdb.run
result = pdbpdb.run("module.get_balance(login, password, storename)", globals(), locals())
result = store.correct_result(result)
pkey = store.get_pkey(login, plugin)
result = store.correct_result(result, pkey)
# res = exec("httpserver_mobile.getbalance_plugin('url', [plugin, login, password, '123'])", globals(), locals())
# breakpoint()
else:
Expand Down

0 comments on commit 5929005

Please sign in to comment.