2016-07-20 19:00:34 +02:00
|
|
|
import functools
|
|
|
|
import json
|
|
|
|
import logging
|
|
|
|
|
|
|
|
from requests import auth
|
|
|
|
from requests_futures import sessions
|
|
|
|
|
2016-10-27 21:18:25 +02:00
|
|
|
from lbrynet.conf import settings
|
2016-07-20 19:00:34 +02:00
|
|
|
from lbrynet.analytics import utils
|
|
|
|
|
|
|
|
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
def log_response(fn):
|
|
|
|
def _log(future):
|
|
|
|
if future.cancelled():
|
|
|
|
log.warning('Request was unexpectedly cancelled')
|
|
|
|
else:
|
|
|
|
response = future.result()
|
|
|
|
log.debug('Response (%s): %s', response.status_code, response.content)
|
|
|
|
|
|
|
|
@functools.wraps(fn)
|
|
|
|
def wrapper(*args, **kwargs):
|
|
|
|
future = fn(*args, **kwargs)
|
|
|
|
future.add_done_callback(_log)
|
|
|
|
return future
|
|
|
|
return wrapper
|
|
|
|
|
|
|
|
|
2016-10-01 17:47:37 +02:00
|
|
|
class Api(object):
|
2016-07-20 19:00:34 +02:00
|
|
|
def __init__(self, session, url, write_key):
|
|
|
|
self.session = session
|
|
|
|
self.url = url
|
|
|
|
self.write_key = write_key
|
|
|
|
|
|
|
|
@property
|
|
|
|
def auth(self):
|
|
|
|
return auth.HTTPBasicAuth(self.write_key, '')
|
|
|
|
|
|
|
|
@log_response
|
|
|
|
def batch(self, events):
|
|
|
|
"""Send multiple events in one request.
|
|
|
|
|
|
|
|
Each event needs to have its type specified.
|
|
|
|
"""
|
|
|
|
data = json.dumps({
|
|
|
|
'batch': events,
|
|
|
|
'sentAt': utils.now(),
|
|
|
|
})
|
|
|
|
log.debug('sending %s events', len(events))
|
|
|
|
log.debug('Data: %s', data)
|
|
|
|
return self.session.post(self.url + '/batch', json=data, auth=self.auth)
|
|
|
|
|
|
|
|
@log_response
|
|
|
|
def track(self, event):
|
|
|
|
"""Send a single tracking event"""
|
|
|
|
log.debug('Sending track event: %s', event)
|
|
|
|
return self.session.post(self.url + '/track', json=event, auth=self.auth)
|
|
|
|
|
|
|
|
@classmethod
|
2016-11-10 21:49:51 +01:00
|
|
|
def new_instance(cls, session=None):
|
2016-09-29 23:51:48 +02:00
|
|
|
"""Initialize an instance using values from the configuration"""
|
2016-07-20 19:00:34 +02:00
|
|
|
if not session:
|
|
|
|
session = sessions.FuturesSession()
|
|
|
|
return cls(
|
|
|
|
session,
|
2016-10-19 06:12:44 +02:00
|
|
|
settings.ANALYTICS_ENDPOINT,
|
|
|
|
utils.deobfuscate(settings.ANALYTICS_TOKEN)
|
2016-07-20 19:00:34 +02:00
|
|
|
)
|