Skip to content

Commit

Permalink
Minor improvements
Browse files Browse the repository at this point in the history
Remove get_time and use time directly, import only used names in a
more places, adjust f2i and use for converting hash payload, remove
unused f2h and d2h, remove unused pi and unhexlify imports, create a
new function for compact cell IDs instead of checking an argument.
  • Loading branch information
Noctem committed Mar 20, 2017
1 parent f528632 commit 15e5625
Show file tree
Hide file tree
Showing 5 changed files with 25 additions and 45 deletions.
2 changes: 1 addition & 1 deletion aiopogo/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import logging

__title__ = 'aiopogo'
__version__ = '1.5.1'
__version__ = '1.5.2'
__author__ = 'David Christenson'
__license__ = 'MIT License'
__copyright__ = 'Copyright (c) 2017 David Christenson <https://github.com/Noctem>'
Expand Down
17 changes: 8 additions & 9 deletions aiopogo/auth.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import logging
from logging import getLogger
from time import time

from .utilities import get_time, get_time_ms, get_format_time_diff
from .utilities import get_time_ms, get_format_time_diff

class Auth:

def __init__(self):
self.log = logging.getLogger(__name__)
self.log = getLogger(__name__)

self._auth_provider = None

self._login = False

# oauth2 uses refresh tokens (which basically never expires)
# oauth2 uses refresh tokens (which basically never expire)
# to get an access_token which is only valid for a certain time)
self._refresh_token = None
self._access_token = None
Expand Down Expand Up @@ -75,11 +76,9 @@ def get_access_token(self, force_refresh = False):
raise NotImplementedError()

def check_access_token(self):
"""
Add few seconds to now so the token get refreshed
before it invalidates in the middle of the request
"""
now_s = get_time() + 120
# Add a couple minutes so the token gets refreshed
# before invalidating in the middle of the request
now_s = time() + 120.0

if self._access_token is not None:
if self._access_token_expiry == 0:
Expand Down
8 changes: 4 additions & 4 deletions aiopogo/auth_ptc.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from urllib.parse import parse_qs, urlsplit
from asyncio import get_event_loop, TimeoutError, CancelledError
from time import time

from aiohttp import TCPConnector, ClientSession, ClientError, DisconnectedError, HttpProcessingError
try:
Expand All @@ -9,7 +10,6 @@ class SocksError(Exception): pass

from .session import socks_connector, CONN_TIMEOUT
from .auth import Auth
from .utilities import get_time
from .exceptions import ActivationRequiredException, AuthConnectionException, AuthException, AuthTimeoutException, InvalidCredentialsException, ProxyException, TimeoutException

try:
Expand Down Expand Up @@ -72,7 +72,7 @@ async def user_login(self, username=None, password=None, retry=True):
self._access_token = None
self.activate_session()
try:
now = get_time()
now = time()
async with self._session.get(self.PTC_LOGIN_URL, timeout=self.timeout, proxy=self.proxy) as resp:
resp.raise_for_status()
data = await resp.json(loads=json.loads)
Expand Down Expand Up @@ -105,7 +105,7 @@ async def user_login(self, username=None, password=None, retry=True):

if self._access_token:
self._login = True
self._access_token_expiry = now + 7200
self._access_token_expiry = now + 7200.0
self.log.info('PTC User Login successful.')
elif self._refresh_token and retry:
return await self.get_access_token()
Expand Down Expand Up @@ -172,7 +172,7 @@ async def get_access_token(self, force_refresh=False):
# three hours, however, the token stops being valid after two hours.
# See issue #86
try:
self._access_token_expiry = token_data['expires'][0] - 3600 + get_time()
self._access_token_expiry = token_data['expires'][0] - 3600 + time()
except (KeyError, IndexError, TypeError):
self._access_token_expiry = 0

Expand Down
7 changes: 4 additions & 3 deletions aiopogo/hash_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from .exceptions import ExpiredHashKeyException, HashingOfflineException, HashingQuotaExceededException, HashingTimeoutException, MalformedHashResponseException, NoHashKeyException, TempHashingBanException, TimeoutException, UnexpectedHashResponseException
from .connector import TimedConnector
from .utilities import f2i

try:
import ujson as json
Expand Down Expand Up @@ -56,9 +57,9 @@ async def hash(self, timestamp, latitude, longitude, accuracy, authticket, sessi

payload = {
'Timestamp': timestamp,
'Latitude64': unpack('<q', pack('<d', latitude))[0],
'Longitude64': unpack('<q', pack('<d', longitude))[0],
'Accuracy64': unpack('<q', pack('<d', accuracy))[0],
'Latitude64': f2i(latitude),
'Longitude64': f2i(longitude),
'Accuracy64': f2i(accuracy),
'AuthTicket': b64encode(authticket),
'SessionData': b64encode(sessiondata),
'Requests': tuple(b64encode(x.SerializeToString()) for x in requests)
Expand Down
36 changes: 8 additions & 28 deletions aiopogo/utilities.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,18 @@
import time
import struct

from time import time
from json import JSONEncoder
from binascii import unhexlify
from math import pi
from array import array
from logging import getLogger
from random import Random
from bisect import bisect
from struct import pack, unpack

import pogeo
from pogeo import get_cell_ids

log = getLogger(__name__)


def f2i(float):
return struct.unpack('<Q', struct.pack('<d', float))[0]


def f2h(float):
return hex(struct.unpack('<Q', struct.pack('<d', float))[0])


def d2h(f):
hex_str = f2h(f)[2:].replace('L','')
hex_str = ("0" * (len(hex_str) % 2)) + hex_str
return unhexlify(hex_str)
def f2i(f):
return unpack('<q', pack('<d', f))[0]


def to_camel_case(value):
Expand All @@ -38,19 +25,12 @@ def default(self, o):
return o.decode('ascii')


def get_cell_ids(lat, lon, radius=500, compact=False):
if compact:
return array('Q', pogeo.get_cell_ids(lat, lon, radius))
else:
return pogeo.get_cell_ids(lat, lon, radius)


def get_time():
return int(time.time())
def get_cell_ids_compact(lat, lon, radius=500):
return array('Q', get_cell_ids(lat, lon, radius))


def get_time_ms():
return int(time.time() * 1000)
return int(time() * 1000)


def get_format_time_diff(low, high, ms=True):
Expand Down

0 comments on commit 15e5625

Please sign in to comment.