Add a --cached option to list the cards without network access

This commit is contained in:
Andy Teijelo Pérez 2017-10-11 09:28:36 -04:00
parent 1331bc0d3b
commit f7b0efee99

View file

@ -253,12 +253,13 @@ def fetch_usertime(username):
r = session.get("https://secure.etecsa.net:8443/EtecsaQueryServlet?op=getLeftTime&op1={}".format(username)) r = session.get("https://secure.etecsa.net:8443/EtecsaQueryServlet?op=getLeftTime&op1={}".format(username))
return r.text return r.text
def time_left(username, fresh=False): def time_left(username, fresh=False, cached=False):
now = time.time() now = time.time()
with dbm.open(CARDS_DB, "c") as cards_db: with dbm.open(CARDS_DB, "c") as cards_db:
card_info = json.loads(cards_db[username].decode()) card_info = json.loads(cards_db[username].decode())
last_update = card_info.get('last_update', 0) last_update = card_info.get('last_update', 0)
password = card_info['password'] password = card_info['password']
if not cached:
if (now - last_update > 60) or fresh: if (now - last_update > 60) or fresh:
time_left = fetch_usertime(username) time_left = fetch_usertime(username)
last_update = time.time() last_update = time.time()
@ -269,13 +270,14 @@ def time_left(username, fresh=False):
time_left = card_info.get('time_left', '-') time_left = card_info.get('time_left', '-')
return time_left return time_left
def expire_date(username, fresh=False): def expire_date(username, fresh=False, cached=False):
# expire date computation won't depend on last_update # expire date computation won't depend on last_update
# because the expire date will change very infrequently # because the expire date will change very infrequently
# in the case of rechargeable accounts and it will # in the case of rechargeable accounts and it will
# never change in the case of non-rechargeable cards # never change in the case of non-rechargeable cards
with dbm.open(CARDS_DB, "c") as cards_db: with dbm.open(CARDS_DB, "c") as cards_db:
card_info = json.loads(cards_db[username].decode()) card_info = json.loads(cards_db[username].decode())
if not cached:
if (not 'expire_date' in card_info) or fresh: if (not 'expire_date' in card_info) or fresh:
password = card_info['password'] password = card_info['password']
exp_date = fetch_expire_date(username, password) exp_date = fetch_expire_date(username, password)
@ -311,8 +313,8 @@ def cards(args):
print("{}\t{}\t{}\t(expires {})".format( print("{}\t{}\t{}\t(expires {})".format(
card, card,
password, password,
time_left(card, args.fresh), time_left(card, args.fresh, args.cached),
expire_date(card, args.fresh) expire_date(card, args.fresh, args.cached)
)) ))
def cards_add(args): def cards_add(args):