2012-10-01 21:36:44 +02:00
|
|
|
#!/usr/bin/python
|
2012-11-26 16:55:22 +01:00
|
|
|
# Copyright (C) 2012 Humbug, Inc.
|
|
|
|
#
|
|
|
|
# Permission is hereby granted, free of charge, to any person
|
|
|
|
# obtaining a copy of this software and associated documentation files
|
|
|
|
# (the "Software"), to deal in the Software without restriction,
|
|
|
|
# including without limitation the rights to use, copy, modify, merge,
|
|
|
|
# publish, distribute, sublicense, and/or sell copies of the Software,
|
|
|
|
# and to permit persons to whom the Software is furnished to do so,
|
|
|
|
# subject to the following conditions:
|
|
|
|
#
|
|
|
|
# The above copyright notice and this permission notice shall be
|
|
|
|
# included in all copies or substantial portions of the Software.
|
|
|
|
#
|
|
|
|
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
|
|
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
|
|
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
|
|
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
|
|
|
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
|
|
|
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
|
|
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
|
|
# SOFTWARE.
|
|
|
|
|
2012-10-01 21:36:44 +02:00
|
|
|
import simplejson
|
2012-10-04 22:13:47 +02:00
|
|
|
import requests
|
2012-10-01 21:36:44 +02:00
|
|
|
import time
|
2012-10-02 21:47:59 +02:00
|
|
|
import traceback
|
2012-10-18 17:32:58 +02:00
|
|
|
import urlparse
|
2012-10-22 20:31:21 +02:00
|
|
|
import sys
|
2012-11-26 16:45:11 +01:00
|
|
|
import os
|
2012-10-03 23:21:09 +02:00
|
|
|
|
2012-10-05 00:06:54 +02:00
|
|
|
# Check that we have a recent enough version
|
2012-11-01 22:50:38 +01:00
|
|
|
# Older versions don't provide the 'json' attribute on responses.
|
2012-10-05 00:06:54 +02:00
|
|
|
assert(requests.__version__ > '0.12')
|
2012-11-29 15:17:09 +01:00
|
|
|
API_VERSTRING = "/api/v1/"
|
2012-10-05 00:06:54 +02:00
|
|
|
|
2012-12-03 18:24:49 +01:00
|
|
|
class Client(object):
|
2012-11-26 16:45:11 +01:00
|
|
|
def __init__(self, email, api_key=None, api_key_file=None,
|
|
|
|
verbose=False, retry_on_errors=True,
|
2012-10-27 17:36:55 +02:00
|
|
|
site="https://humbughq.com", client="API"):
|
2012-11-26 16:45:11 +01:00
|
|
|
if api_key is None:
|
|
|
|
if api_key_file is None:
|
|
|
|
api_key_file = os.path.join(os.environ["HOME"], ".humbug-api-key")
|
|
|
|
if not os.path.exists(api_key_file):
|
|
|
|
raise RuntimeError("api_key not specified and %s does not exist"
|
|
|
|
% (api_key_file,))
|
2012-11-26 18:21:09 +01:00
|
|
|
with file(api_key_file, 'r') as f:
|
|
|
|
api_key = f.read().strip()
|
2012-11-26 16:45:11 +01:00
|
|
|
|
2012-10-01 21:36:44 +02:00
|
|
|
self.api_key = api_key
|
|
|
|
self.email = email
|
|
|
|
self.verbose = verbose
|
|
|
|
self.base_url = site
|
2012-10-22 20:31:21 +02:00
|
|
|
self.retry_on_errors = retry_on_errors
|
2012-10-23 16:59:42 +02:00
|
|
|
self.client_name = client
|
2012-10-01 21:36:44 +02:00
|
|
|
|
2012-11-29 15:35:30 +01:00
|
|
|
def do_api_query(self, orig_request, url, longpolling = False):
|
|
|
|
request = {}
|
2012-10-05 00:06:54 +02:00
|
|
|
request["email"] = self.email
|
|
|
|
request["api-key"] = self.api_key
|
2012-10-23 16:59:42 +02:00
|
|
|
request["client"] = self.client_name
|
2012-11-07 23:22:19 +01:00
|
|
|
|
2012-11-29 15:35:30 +01:00
|
|
|
for (key, val) in orig_request.iteritems():
|
2012-11-07 23:22:19 +01:00
|
|
|
if not (isinstance(val, str) or isinstance(val, unicode)):
|
|
|
|
request[key] = simplejson.dumps(val)
|
2012-11-29 15:35:30 +01:00
|
|
|
else:
|
|
|
|
request[key] = val
|
2012-11-07 23:22:19 +01:00
|
|
|
|
2012-11-29 15:17:09 +01:00
|
|
|
query_state = {
|
|
|
|
'had_error_retry': False,
|
|
|
|
'request': request,
|
|
|
|
'failures': 0,
|
|
|
|
}
|
|
|
|
|
|
|
|
def error_retry(error_string):
|
|
|
|
if not self.retry_on_errors or query_state["failures"] >= 10:
|
|
|
|
return False
|
|
|
|
if self.verbose:
|
|
|
|
if not query_state["had_error_retry"]:
|
|
|
|
sys.stdout.write("humbug API(%s): connection error%s -- retrying." % \
|
|
|
|
(url.split(API_VERSTRING, 2)[1], error_string,))
|
|
|
|
query_state["had_error_retry"] = True
|
|
|
|
else:
|
|
|
|
sys.stdout.write(".")
|
|
|
|
sys.stdout.flush()
|
|
|
|
query_state["request"]["dont_block"] = simplejson.dumps(True)
|
|
|
|
time.sleep(1)
|
|
|
|
query_state["failures"] += 1
|
|
|
|
return True
|
|
|
|
|
|
|
|
def end_error_retry(succeeded):
|
|
|
|
if query_state["had_error_retry"] and self.verbose:
|
|
|
|
if succeeded:
|
|
|
|
print "Success!"
|
|
|
|
else:
|
|
|
|
print "Failed!"
|
|
|
|
|
2012-10-05 00:06:54 +02:00
|
|
|
while True:
|
|
|
|
try:
|
2012-11-29 15:17:09 +01:00
|
|
|
res = requests.post(urlparse.urljoin(self.base_url, url),
|
|
|
|
data=query_state["request"],
|
2012-11-09 20:16:22 +01:00
|
|
|
verify=True, timeout=55)
|
2012-10-22 20:31:21 +02:00
|
|
|
|
|
|
|
# On 50x errors, try again after a short sleep
|
2012-11-29 15:17:09 +01:00
|
|
|
if str(res.status_code).startswith('5'):
|
|
|
|
if error_retry(" (server %s)" % (res.status_code,)):
|
|
|
|
continue
|
|
|
|
# Otherwise fall through and process the python-requests error normally
|
2012-11-09 21:38:34 +01:00
|
|
|
except (requests.exceptions.Timeout, requests.exceptions.SSLError) as e:
|
|
|
|
# Timeouts are either a Timeout or an SSLError; we
|
|
|
|
# want the later exception handlers to deal with any
|
|
|
|
# non-timeout other SSLErrors
|
|
|
|
if (isinstance(e, requests.exceptions.SSLError) and
|
|
|
|
str(e) != "The read operation timed out"):
|
|
|
|
raise
|
2012-11-09 20:16:22 +01:00
|
|
|
if longpolling:
|
|
|
|
# When longpolling, we expect the timeout to fire,
|
|
|
|
# and the correct response is to just retry
|
|
|
|
continue
|
|
|
|
else:
|
2012-11-29 15:17:09 +01:00
|
|
|
end_error_retry(False)
|
2012-11-09 20:16:22 +01:00
|
|
|
return {'msg': "Connection error:\n%s" % traceback.format_exc(),
|
|
|
|
"result": "connection-error"}
|
2012-10-05 00:06:54 +02:00
|
|
|
except requests.exceptions.ConnectionError:
|
2012-11-29 15:17:09 +01:00
|
|
|
if error_retry(""):
|
2012-10-22 20:31:21 +02:00
|
|
|
continue
|
2012-11-29 15:17:09 +01:00
|
|
|
end_error_retry(False)
|
2012-10-05 00:06:54 +02:00
|
|
|
return {'msg': "Connection error:\n%s" % traceback.format_exc(),
|
|
|
|
"result": "connection-error"}
|
|
|
|
except Exception:
|
2012-10-22 20:31:21 +02:00
|
|
|
# We'll split this out into more cases as we encounter new bugs.
|
2012-10-05 00:06:54 +02:00
|
|
|
return {'msg': "Unexpected error:\n%s" % traceback.format_exc(),
|
|
|
|
"result": "unexpected-error"}
|
|
|
|
|
|
|
|
if res.json is not None:
|
2012-11-29 15:17:09 +01:00
|
|
|
end_error_retry(True)
|
2012-10-05 00:06:54 +02:00
|
|
|
return res.json
|
2012-11-29 15:17:09 +01:00
|
|
|
end_error_retry(False)
|
2012-10-05 00:06:54 +02:00
|
|
|
return {'msg': res.text, "result": "http-error",
|
|
|
|
"status_code": res.status_code}
|
|
|
|
|
2012-11-07 21:48:37 +01:00
|
|
|
@classmethod
|
|
|
|
def _register(cls, name, url=None, make_request=(lambda request={}: request), **query_kwargs):
|
|
|
|
if url is None:
|
|
|
|
url = name
|
|
|
|
def call(self, *args, **kwargs):
|
|
|
|
request = make_request(*args, **kwargs)
|
2012-11-29 15:17:09 +01:00
|
|
|
return self.do_api_query(request, API_VERSTRING + url, **query_kwargs)
|
2012-11-07 21:48:37 +01:00
|
|
|
call.func_name = name
|
|
|
|
setattr(cls, name, call)
|
2012-11-16 20:15:03 +01:00
|
|
|
|
2012-10-12 23:19:49 +02:00
|
|
|
def call_on_each_message(self, callback, options = {}):
|
2012-10-01 21:36:44 +02:00
|
|
|
max_message_id = None
|
|
|
|
while True:
|
2012-10-04 22:13:47 +02:00
|
|
|
if max_message_id is not None:
|
|
|
|
options["last"] = str(max_message_id)
|
|
|
|
res = self.get_messages(options)
|
|
|
|
if 'error' in res.get('result'):
|
2012-10-01 21:36:44 +02:00
|
|
|
if self.verbose:
|
2012-10-05 00:06:54 +02:00
|
|
|
if res["result"] == "http-error":
|
2012-10-22 20:31:21 +02:00
|
|
|
print "HTTP error fetching messages -- probably a server restart"
|
2012-10-04 22:13:47 +02:00
|
|
|
elif res["result"] == "connection-error":
|
2012-10-22 20:31:21 +02:00
|
|
|
print "Connection error fetching messages -- probably server is temporarily down?"
|
2012-10-04 22:13:47 +02:00
|
|
|
else:
|
|
|
|
print "Server returned error:\n%s" % res["msg"]
|
|
|
|
# TODO: Make this back off once it's more reliable
|
2012-10-01 21:36:44 +02:00
|
|
|
time.sleep(1)
|
2012-10-02 21:47:59 +02:00
|
|
|
continue
|
2012-10-10 22:27:22 +02:00
|
|
|
for message in sorted(res['messages'], key=lambda x: int(x["id"])):
|
|
|
|
max_message_id = max(max_message_id, int(message["id"]))
|
2012-10-01 21:36:44 +02:00
|
|
|
callback(message)
|
2012-11-07 21:48:37 +01:00
|
|
|
|
|
|
|
def _mk_subs(streams):
|
|
|
|
return {'subscriptions': streams}
|
|
|
|
|
2012-12-03 18:24:49 +01:00
|
|
|
Client._register('send_message', make_request=(lambda request: request))
|
|
|
|
Client._register('get_messages', longpolling=True)
|
|
|
|
Client._register('get_profile')
|
|
|
|
Client._register('get_public_streams')
|
|
|
|
Client._register('list_subscriptions', url='subscriptions/list')
|
|
|
|
Client._register('add_subscriptions', url='subscriptions/add', make_request=_mk_subs)
|
|
|
|
Client._register('remove_subscriptions', url='subscriptions/remove', make_request=_mk_subs)
|